Repository: hey-api/openapi-ts Branch: main Commit: 725101ab121a Files: 6971 Total size: 37.9 MB Directory structure: gitextract_6gefdnhg/ ├── .changeset/ │ ├── README.md │ ├── changelog.js │ └── config.json ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yml │ │ └── feature_request.yml │ ├── copilot-instructions.md │ └── workflows/ │ ├── ci.yml │ ├── contributors.yml │ ├── coverage.yml │ ├── pullfrog.yml │ └── release.yml ├── .gitignore ├── .husky/ │ └── pre-commit ├── .npmrc ├── .nvmrc ├── .oxfmtrc.json ├── .prettierignore ├── .vscode/ │ ├── extensions.json │ ├── launch.json │ ├── settings.json │ └── tasks.json ├── CLAUDE.md ├── CODE_OF_CONDUCT.md ├── LICENSE.md ├── __tests__/ │ └── changelog.test.ts ├── dev/ │ ├── graph-hotspots.js │ ├── hey-api.ts │ ├── inputs.ts │ ├── json-to-dot.js │ ├── openapi-python.config.ts │ ├── openapi-ts.config.ts │ ├── package.json │ ├── playground.py │ ├── playground.ts │ ├── python/ │ │ └── presets.ts │ ├── tsconfig.json │ ├── turbo.json │ └── typescript/ │ └── presets.ts ├── docs/ │ ├── .contributorsignore │ ├── .contributorssince │ ├── .gitignore │ ├── .vitepress/ │ │ ├── config/ │ │ │ ├── en.ts │ │ │ ├── index.ts │ │ │ ├── scripts/ │ │ │ │ └── optimize-images.ts │ │ │ └── shared.ts │ │ └── theme/ │ │ ├── components/ │ │ │ ├── AuthorsList.vue │ │ │ ├── Examples.vue │ │ │ ├── FeatureStatus.vue │ │ │ ├── Heading.vue │ │ │ ├── Layout.vue │ │ │ ├── VersionLabel.vue │ │ │ └── VersionSwitcher.vue │ │ ├── custom.css │ │ ├── index.ts │ │ └── versions/ │ │ ├── AngularVersionSwitcher.vue │ │ └── ZodVersionSwitcher.vue │ ├── CHANGELOG.md │ ├── data/ │ │ ├── coreTeam.js │ │ ├── hallOfFame.js │ │ └── people.ts │ ├── email-form.md │ ├── embed.ts │ ├── index.md │ ├── openapi-ts/ │ │ ├── clients/ │ │ │ ├── angular/ │ │ │ │ └── v19.md │ │ │ ├── angular.md │ │ │ ├── axios.md │ │ │ ├── custom.md │ │ │ ├── effect.md │ │ │ ├── fetch.md │ │ │ ├── got.md │ │ │ ├── ky.md │ │ │ ├── next-js.md │ │ │ ├── nuxt.md │ │ │ └── ofetch.md │ │ ├── clients.md │ │ ├── community/ │ │ │ ├── contributing/ │ │ │ │ ├── building.md │ │ │ │ ├── developing.md │ │ │ │ └── testing.md │ │ │ ├── contributing.md │ │ │ └── spotlight.md │ │ ├── configuration/ │ │ │ ├── input.md │ │ │ ├── output.md │ │ │ └── parser.md │ │ ├── configuration.md │ │ ├── core.md │ │ ├── get-started.md │ │ ├── integrations.md │ │ ├── license.md │ │ ├── migrating.md │ │ ├── mocks.md │ │ ├── output.md │ │ ├── plugins/ │ │ │ ├── adonis.md │ │ │ ├── ajv.md │ │ │ ├── angular/ │ │ │ │ └── v19.md │ │ │ ├── angular.md │ │ │ ├── arktype.md │ │ │ ├── chance.md │ │ │ ├── concepts/ │ │ │ │ └── resolvers.md │ │ │ ├── custom.md │ │ │ ├── elysia.md │ │ │ ├── express.md │ │ │ ├── faker.md │ │ │ ├── falso.md │ │ │ ├── fastify.md │ │ │ ├── hono.md │ │ │ ├── joi.md │ │ │ ├── koa.md │ │ │ ├── msw.md │ │ │ ├── nest.md │ │ │ ├── nock.md │ │ │ ├── pinia-colada.md │ │ │ ├── schemas.md │ │ │ ├── sdk.md │ │ │ ├── superstruct.md │ │ │ ├── supertest.md │ │ │ ├── swr.md │ │ │ ├── tanstack-query.md │ │ │ ├── transformers.md │ │ │ ├── typebox.md │ │ │ ├── typescript.md │ │ │ ├── valibot.md │ │ │ ├── yup.md │ │ │ ├── zod/ │ │ │ │ ├── mini.md │ │ │ │ └── v3.md │ │ │ ├── zod.md │ │ │ └── zustand.md │ │ ├── state-management.md │ │ ├── validators.md │ │ └── web-frameworks.md │ ├── package.json │ ├── partials/ │ │ ├── contributors-list.md │ │ ├── examples.md │ │ ├── sponsors-list.md │ │ └── sponsors.md │ ├── public/ │ │ └── robots.txt │ └── tsconfig.json ├── eslint.config.js ├── examples/ │ ├── README.md │ ├── openapi-ts-angular/ │ │ ├── .editorconfig │ │ ├── .gitignore │ │ ├── .vscode/ │ │ │ ├── extensions.json │ │ │ ├── launch.json │ │ │ └── tasks.json │ │ ├── README.md │ │ ├── angular.json │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app/ │ │ │ │ ├── app.component.css │ │ │ │ ├── app.component.html │ │ │ │ ├── app.component.spec.ts │ │ │ │ ├── app.component.ts │ │ │ │ ├── app.config.server.ts │ │ │ │ ├── app.config.ts │ │ │ │ ├── app.routes.server.ts │ │ │ │ ├── app.routes.ts │ │ │ │ └── demo/ │ │ │ │ ├── demo.css │ │ │ │ ├── demo.html │ │ │ │ └── demo.ts │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── index.html │ │ │ ├── main.server.ts │ │ │ ├── main.ts │ │ │ ├── server.ts │ │ │ └── styles.css │ │ ├── tsconfig.app.json │ │ ├── tsconfig.json │ │ └── tsconfig.spec.json │ ├── openapi-ts-angular-common/ │ │ ├── .editorconfig │ │ ├── .gitignore │ │ ├── .vscode/ │ │ │ ├── extensions.json │ │ │ ├── launch.json │ │ │ └── tasks.json │ │ ├── README.md │ │ ├── angular.json │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app/ │ │ │ │ ├── app.component.css │ │ │ │ ├── app.component.html │ │ │ │ ├── app.component.spec.ts │ │ │ │ ├── app.component.ts │ │ │ │ ├── app.config.server.ts │ │ │ │ ├── app.config.ts │ │ │ │ ├── app.routes.server.ts │ │ │ │ ├── app.routes.ts │ │ │ │ └── demo/ │ │ │ │ ├── demo.css │ │ │ │ ├── demo.html │ │ │ │ └── demo.ts │ │ │ ├── client/ │ │ │ │ ├── @angular/ │ │ │ │ │ └── common.gen.ts │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── index.html │ │ │ ├── main.server.ts │ │ │ ├── main.ts │ │ │ ├── server.ts │ │ │ └── styles.css │ │ ├── tsconfig.app.json │ │ ├── tsconfig.json │ │ └── tsconfig.spec.json │ ├── openapi-ts-axios/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── index.html │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.css │ │ │ ├── App.tsx │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── main.tsx │ │ │ └── vite-env.d.ts │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-fastify/ │ │ ├── CHANGELOG.md │ │ ├── openapi-ts.config.ts │ │ ├── openapi.json │ │ ├── package.json │ │ ├── src/ │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── fastify.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── handlers.ts │ │ │ ├── index.ts │ │ │ └── server.ts │ │ ├── test/ │ │ │ └── pets.test.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-fetch/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── index.html │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.css │ │ │ ├── App.tsx │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── main.tsx │ │ │ └── vite-env.d.ts │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-ky/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── index.html │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.css │ │ │ ├── App.tsx │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── main.tsx │ │ │ └── vite-env.d.ts │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-nestjs/ │ │ ├── openapi-ts.config.ts │ │ ├── openapi.json │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app.module.ts │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── nestjs.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── main.ts │ │ │ ├── pets/ │ │ │ │ ├── pets.controller.ts │ │ │ │ └── pets.module.ts │ │ │ └── store/ │ │ │ ├── store.controller.ts │ │ │ └── store.module.ts │ │ ├── test/ │ │ │ └── pets.test.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-next/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── app/ │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ ├── page.tsx │ │ │ └── pet/ │ │ │ └── [id]/ │ │ │ └── page.tsx │ │ ├── next.config.ts │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.mjs │ │ ├── src/ │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ └── hey-api.ts │ │ ├── tailwind.config.ts │ │ └── tsconfig.json │ ├── openapi-ts-nuxt/ │ │ ├── .gitignore │ │ ├── .npmrc │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── app.vue │ │ ├── components/ │ │ │ └── home.vue │ │ ├── nuxt.config.ts │ │ ├── package.json │ │ ├── public/ │ │ │ └── robots.txt │ │ ├── server/ │ │ │ └── tsconfig.json │ │ └── tsconfig.json │ ├── openapi-ts-ofetch/ │ │ ├── env.d.ts │ │ ├── index.html │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.vue │ │ │ ├── assets/ │ │ │ │ └── main.css │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ └── main.ts │ │ ├── tailwind.config.ts │ │ ├── tsconfig.app.json │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-openai/ │ │ ├── .gitignore │ │ ├── index.html │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.css │ │ │ ├── App.tsx │ │ │ ├── client/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── main.tsx │ │ │ └── vite-env.d.ts │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-pinia-colada/ │ │ ├── .eslintrc.cjs │ │ ├── .gitignore │ │ ├── .vscode/ │ │ │ └── extensions.json │ │ ├── README.md │ │ ├── env.d.ts │ │ ├── index.html │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.vue │ │ │ ├── assets/ │ │ │ │ └── main.css │ │ │ ├── client/ │ │ │ │ ├── @pinia/ │ │ │ │ │ └── colada.gen.ts │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── main.ts │ │ │ ├── router/ │ │ │ │ └── index.ts │ │ │ └── views/ │ │ │ └── PiniaColadaExample.vue │ │ ├── tailwind.config.ts │ │ ├── tsconfig.app.json │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ ├── tsconfig.vitest.json │ │ ├── vite.config.ts │ │ └── vitest.config.ts │ ├── openapi-ts-tanstack-angular-query-experimental/ │ │ ├── .editorconfig │ │ ├── .eslintignore │ │ ├── .gitignore │ │ ├── .vscode/ │ │ │ ├── extensions.json │ │ │ ├── launch.json │ │ │ └── tasks.json │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── angular.json │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app/ │ │ │ │ ├── app.component.css │ │ │ │ ├── app.component.html │ │ │ │ ├── app.component.ts │ │ │ │ ├── app.config.ts │ │ │ │ ├── app.routes.ts │ │ │ │ └── pet-store/ │ │ │ │ ├── pet-store.component.css │ │ │ │ ├── pet-store.component.html │ │ │ │ └── pet-store.component.ts │ │ │ ├── client/ │ │ │ │ ├── @tanstack/ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── index.html │ │ │ ├── main.ts │ │ │ └── styles.css │ │ ├── tsconfig.app.json │ │ └── tsconfig.json │ ├── openapi-ts-tanstack-react-query/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── index.html │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.css │ │ │ ├── App.tsx │ │ │ ├── client/ │ │ │ │ ├── @tanstack/ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── main.tsx │ │ │ └── vite-env.d.ts │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── openapi-ts-tanstack-svelte-query/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── openapi-ts.config.ts │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app.css │ │ │ ├── app.d.ts │ │ │ ├── app.html │ │ │ ├── client/ │ │ │ │ ├── @tanstack/ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schemas.gen.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ └── routes/ │ │ │ ├── +layout.svelte │ │ │ ├── +page.svelte │ │ │ ├── +page.ts │ │ │ ├── Counter.svelte │ │ │ ├── Header.svelte │ │ │ ├── about/ │ │ │ │ ├── +page.svelte │ │ │ │ └── +page.ts │ │ │ └── sverdle/ │ │ │ ├── +page.server.ts │ │ │ ├── +page.svelte │ │ │ ├── game.test.ts │ │ │ ├── game.ts │ │ │ ├── how-to-play/ │ │ │ │ ├── +page.svelte │ │ │ │ └── +page.ts │ │ │ ├── reduced-motion.ts │ │ │ └── words.server.ts │ │ ├── static/ │ │ │ └── robots.txt │ │ ├── svelte.config.js │ │ ├── tsconfig.json │ │ └── vite.config.ts │ └── openapi-ts-tanstack-vue-query/ │ ├── .eslintrc.cjs │ ├── .gitignore │ ├── .vscode/ │ │ └── extensions.json │ ├── CHANGELOG.md │ ├── README.md │ ├── env.d.ts │ ├── index.html │ ├── openapi-ts.config.ts │ ├── package.json │ ├── postcss.config.js │ ├── src/ │ │ ├── App.vue │ │ ├── assets/ │ │ │ └── main.css │ │ ├── client/ │ │ │ ├── @tanstack/ │ │ │ │ └── vue-query.gen.ts │ │ │ ├── client/ │ │ │ │ ├── client.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── types.gen.ts │ │ │ │ └── utils.gen.ts │ │ │ ├── client.gen.ts │ │ │ ├── core/ │ │ │ │ ├── auth.gen.ts │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ ├── params.gen.ts │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ ├── types.gen.ts │ │ │ │ └── utils.gen.ts │ │ │ ├── index.ts │ │ │ ├── schemas.gen.ts │ │ │ ├── sdk.gen.ts │ │ │ └── types.gen.ts │ │ ├── main.ts │ │ ├── router/ │ │ │ └── index.ts │ │ └── views/ │ │ └── TanstackExample.vue │ ├── tailwind.config.ts │ ├── tsconfig.app.json │ ├── tsconfig.json │ ├── tsconfig.node.json │ ├── tsconfig.vitest.json │ ├── vite.config.ts │ └── vitest.config.ts ├── lint-staged.config.js ├── package.json ├── packages/ │ ├── codegen-core/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── __tests__/ │ │ │ │ ├── data/ │ │ │ │ │ └── file.ts │ │ │ │ ├── exports.test.ts │ │ │ │ ├── files.test.ts │ │ │ │ ├── logger.test.ts │ │ │ │ ├── planner.test.ts │ │ │ │ ├── project.test.ts │ │ │ │ ├── refs.test.ts │ │ │ │ └── symbols.test.ts │ │ │ ├── bindings.ts │ │ │ ├── brands.ts │ │ │ ├── config/ │ │ │ │ ├── interactive.ts │ │ │ │ ├── load.ts │ │ │ │ └── merge.ts │ │ │ ├── extensions.ts │ │ │ ├── files/ │ │ │ │ ├── file.ts │ │ │ │ ├── registry.ts │ │ │ │ ├── rules.ts │ │ │ │ └── types.ts │ │ │ ├── guards.ts │ │ │ ├── index.ts │ │ │ ├── languages/ │ │ │ │ ├── extensions.ts │ │ │ │ ├── modules.ts │ │ │ │ ├── resolvers.ts │ │ │ │ └── types.ts │ │ │ ├── log.ts │ │ │ ├── logger.ts │ │ │ ├── nodes/ │ │ │ │ ├── node.ts │ │ │ │ ├── registry.ts │ │ │ │ └── types.ts │ │ │ ├── output.ts │ │ │ ├── planner/ │ │ │ │ ├── analyzer.ts │ │ │ │ ├── planner.ts │ │ │ │ ├── resolvers.ts │ │ │ │ ├── scope.ts │ │ │ │ └── types.ts │ │ │ ├── project/ │ │ │ │ ├── namespace.ts │ │ │ │ ├── project.ts │ │ │ │ └── types.ts │ │ │ ├── refs/ │ │ │ │ ├── refs.ts │ │ │ │ └── types.ts │ │ │ ├── renderer.ts │ │ │ ├── structure/ │ │ │ │ ├── model.ts │ │ │ │ ├── node.ts │ │ │ │ └── types.ts │ │ │ └── symbols/ │ │ │ ├── registry.ts │ │ │ ├── symbol.ts │ │ │ └── types.ts │ │ ├── tsconfig.json │ │ ├── tsdown.config.ts │ │ └── turbo.json │ ├── custom-client/ │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── package.json │ │ ├── rollup.config.mjs │ │ ├── src/ │ │ │ ├── __tests__/ │ │ │ │ ├── client.test.ts │ │ │ │ └── utils.test.ts │ │ │ ├── client.ts │ │ │ ├── core/ │ │ │ │ ├── auth.ts │ │ │ │ ├── bodySerializer.ts │ │ │ │ ├── params.ts │ │ │ │ ├── pathSerializer.ts │ │ │ │ └── types.ts │ │ │ ├── index.ts │ │ │ ├── plugin.ts │ │ │ ├── types.ts │ │ │ └── utils.ts │ │ ├── tsconfig.base.json │ │ ├── tsconfig.json │ │ └── tsdown.config.ts │ ├── json-schema-ref-parser/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── __tests__/ │ │ │ │ ├── __snapshots__/ │ │ │ │ │ ├── circular-ref-with-description.json │ │ │ │ │ ├── main-with-external-siblings.json │ │ │ │ │ ├── multiple-refs.json │ │ │ │ │ └── redfish-like.json │ │ │ │ ├── bundle.test.ts │ │ │ │ ├── index.test.ts │ │ │ │ ├── pointer.test.ts │ │ │ │ └── utils.ts │ │ │ ├── bundle.ts │ │ │ ├── dereference.ts │ │ │ ├── index.ts │ │ │ ├── options.ts │ │ │ ├── parse.ts │ │ │ ├── parsers/ │ │ │ │ ├── binary.ts │ │ │ │ ├── json.ts │ │ │ │ ├── text.ts │ │ │ │ └── yaml.ts │ │ │ ├── pointer.ts │ │ │ ├── ref.ts │ │ │ ├── refs.ts │ │ │ ├── resolve-external.ts │ │ │ ├── resolvers/ │ │ │ │ ├── file.ts │ │ │ │ └── url.ts │ │ │ ├── types/ │ │ │ │ └── index.ts │ │ │ └── util/ │ │ │ ├── convert-path-to-posix.ts │ │ │ ├── errors.ts │ │ │ ├── is-windows.ts │ │ │ ├── plugins.ts │ │ │ └── url.ts │ │ ├── tsconfig.json │ │ └── tsdown.config.ts │ ├── nuxt/ │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ └── module.ts │ │ ├── tsconfig.base.json │ │ ├── tsconfig.json │ │ └── vitest.config.ts │ ├── openapi-python/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── bin/ │ │ │ ├── run.cmd │ │ │ └── run.js │ │ ├── package.json │ │ ├── src/ │ │ │ ├── __tests__/ │ │ │ │ └── index.test.ts │ │ │ ├── cli/ │ │ │ │ ├── adapter.ts │ │ │ │ ├── index.ts │ │ │ │ └── schema.ts │ │ │ ├── config/ │ │ │ │ ├── expand.ts │ │ │ │ ├── init.ts │ │ │ │ ├── output/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── postprocess.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── plugins.ts │ │ │ │ ├── resolve.ts │ │ │ │ ├── types.ts │ │ │ │ ├── utils.ts │ │ │ │ └── validate.ts │ │ │ ├── createClient.ts │ │ │ ├── generate/ │ │ │ │ ├── client.ts │ │ │ │ └── output.ts │ │ │ ├── generate.ts │ │ │ ├── index.ts │ │ │ ├── plugins/ │ │ │ │ ├── @hey-api/ │ │ │ │ │ ├── client-core/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ └── utils.ts │ │ │ │ │ ├── client-httpx/ │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── client.py │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ └── sdk/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── examples/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── operations/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── resolve.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── shared/ │ │ │ │ │ │ ├── class.ts │ │ │ │ │ │ ├── operation.ts │ │ │ │ │ │ └── signature.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── v1/ │ │ │ │ │ ├── node.ts │ │ │ │ │ └── plugin.ts │ │ │ │ ├── config.ts │ │ │ │ ├── pydantic/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── resolvers.ts │ │ │ │ │ ├── shared/ │ │ │ │ │ │ ├── export.ts │ │ │ │ │ │ ├── field.ts │ │ │ │ │ │ ├── meta.ts │ │ │ │ │ │ ├── processor.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── v2/ │ │ │ │ │ ├── constants.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── processor.ts │ │ │ │ │ ├── toAst/ │ │ │ │ │ │ ├── array.ts │ │ │ │ │ │ ├── boolean.ts │ │ │ │ │ │ ├── enum.ts │ │ │ │ │ │ ├── intersection.ts │ │ │ │ │ │ ├── never.ts │ │ │ │ │ │ ├── null.ts │ │ │ │ │ │ ├── number.ts │ │ │ │ │ │ ├── object.ts │ │ │ │ │ │ ├── string.ts │ │ │ │ │ │ ├── tuple.ts │ │ │ │ │ │ ├── undefined.ts │ │ │ │ │ │ ├── union.ts │ │ │ │ │ │ ├── unknown.ts │ │ │ │ │ │ └── void.ts │ │ │ │ │ └── walker.ts │ │ │ │ ├── shared/ │ │ │ │ │ └── utils/ │ │ │ │ │ └── operation.ts │ │ │ │ └── types.ts │ │ │ ├── py-compiler/ │ │ │ │ ├── __snapshots__/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── nodes/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── declarations/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── class/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── default.py │ │ │ │ │ │ │ ├── with-decorators.py │ │ │ │ │ │ │ ├── with-docstring.py │ │ │ │ │ │ │ ├── with-extends.py │ │ │ │ │ │ │ ├── with-method-docstring.py │ │ │ │ │ │ │ └── with-method.py │ │ │ │ │ │ └── function/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── default.py │ │ │ │ │ │ ├── with-annotations-defaults-return.py │ │ │ │ │ │ ├── with-body.py │ │ │ │ │ │ ├── with-decorators.py │ │ │ │ │ │ └── with-docstring.py │ │ │ │ │ ├── expressions/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── await/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── inside-function.py │ │ │ │ │ │ ├── binary/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── add.py │ │ │ │ │ │ │ └── subtract.py │ │ │ │ │ │ ├── call/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── call.py │ │ │ │ │ │ ├── comprehensions/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── dict/ │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ └── dict.py │ │ │ │ │ │ │ ├── list/ │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ └── list.py │ │ │ │ │ │ │ ├── nested/ │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ └── dict-list.py │ │ │ │ │ │ │ └── set/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── dict.py │ │ │ │ │ │ ├── dict/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── dict.py │ │ │ │ │ │ ├── fString/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── multiple-expressions.py │ │ │ │ │ │ │ └── simple-interpolation.py │ │ │ │ │ │ ├── generator/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── async.py │ │ │ │ │ │ │ ├── simple.py │ │ │ │ │ │ │ └── with-filter.py │ │ │ │ │ │ ├── identifier/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── identifier.py │ │ │ │ │ │ ├── kwarg/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── multiple.py │ │ │ │ │ │ │ ├── number.py │ │ │ │ │ │ │ └── string.py │ │ │ │ │ │ ├── lambda/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── simple.py │ │ │ │ │ │ │ └── with-params-and-default.py │ │ │ │ │ │ ├── list/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── list.py │ │ │ │ │ │ ├── literal/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── primitive.py │ │ │ │ │ │ ├── set/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── set.py │ │ │ │ │ │ ├── subscript/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── index-access.py │ │ │ │ │ │ │ ├── multiple.py │ │ │ │ │ │ │ ├── nested.py │ │ │ │ │ │ │ └── single.py │ │ │ │ │ │ ├── tuple/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── tuple.py │ │ │ │ │ │ └── yield/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── default.py │ │ │ │ │ │ ├── from-iterable.py │ │ │ │ │ │ └── with-value.py │ │ │ │ │ ├── statements/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── assignment/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── annotation-only.py │ │ │ │ │ │ │ ├── annotation-with-value.py │ │ │ │ │ │ │ ├── complex-annotation.py │ │ │ │ │ │ │ ├── optional-annotation.py │ │ │ │ │ │ │ └── primitive.py │ │ │ │ │ │ ├── augmentedAssignment/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── arithmetic.py │ │ │ │ │ │ │ └── bitwise.py │ │ │ │ │ │ ├── block/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── function.py │ │ │ │ │ │ ├── break/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── while.py │ │ │ │ │ │ ├── continue/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── while.py │ │ │ │ │ │ ├── expression/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── simple.py │ │ │ │ │ │ ├── for/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── for-else.py │ │ │ │ │ │ │ └── for.py │ │ │ │ │ │ ├── if/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── if-else.py │ │ │ │ │ │ │ └── if.py │ │ │ │ │ │ ├── import/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── from-with-alias.py │ │ │ │ │ │ │ ├── from-with-asterisk.py │ │ │ │ │ │ │ ├── from-with-name-alias.py │ │ │ │ │ │ │ ├── from-with-name.py │ │ │ │ │ │ │ ├── module-with-alias.py │ │ │ │ │ │ │ └── module.py │ │ │ │ │ │ ├── raise/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── reraise.py │ │ │ │ │ │ │ └── with-exception.py │ │ │ │ │ │ ├── return/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── function.py │ │ │ │ │ │ ├── try/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── with-except-else-finally.py │ │ │ │ │ │ │ ├── with-except-else.py │ │ │ │ │ │ │ ├── with-except-finally.py │ │ │ │ │ │ │ ├── with-except.py │ │ │ │ │ │ │ └── with-finally.py │ │ │ │ │ │ ├── while/ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── while-else.py │ │ │ │ │ │ │ └── while.py │ │ │ │ │ │ └── with/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── with-alias.py │ │ │ │ │ │ ├── with-async.py │ │ │ │ │ │ ├── with-many-items.py │ │ │ │ │ │ ├── with-tuple-alias.py │ │ │ │ │ │ └── with.py │ │ │ │ │ └── structure/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── comment/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ └── simple.py │ │ │ │ │ └── sourceFile/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── simple.py │ │ │ │ │ └── with-docstring.py │ │ │ │ ├── __tests__/ │ │ │ │ │ ├── constants.ts │ │ │ │ │ ├── globalTeardown.ts │ │ │ │ │ └── nodes/ │ │ │ │ │ ├── declarations/ │ │ │ │ │ │ ├── class.test.ts │ │ │ │ │ │ └── function.test.ts │ │ │ │ │ ├── expressions/ │ │ │ │ │ │ ├── await.test.ts │ │ │ │ │ │ ├── binary.test.ts │ │ │ │ │ │ ├── call.test.ts │ │ │ │ │ │ ├── comprehensions/ │ │ │ │ │ │ │ ├── dict.test.ts │ │ │ │ │ │ │ ├── list.test.ts │ │ │ │ │ │ │ ├── nested.test.ts │ │ │ │ │ │ │ └── set.test.ts │ │ │ │ │ │ ├── dict.test.ts │ │ │ │ │ │ ├── fString.test.ts │ │ │ │ │ │ ├── generator.test.ts │ │ │ │ │ │ ├── identifier.test.ts │ │ │ │ │ │ ├── kwarg.test.ts │ │ │ │ │ │ ├── lambda.test.ts │ │ │ │ │ │ ├── list.test.ts │ │ │ │ │ │ ├── literal.test.ts │ │ │ │ │ │ ├── set.test.ts │ │ │ │ │ │ ├── subscript.test.ts │ │ │ │ │ │ ├── tuple.test.ts │ │ │ │ │ │ └── yield.test.ts │ │ │ │ │ ├── statements/ │ │ │ │ │ │ ├── assignment.test.ts │ │ │ │ │ │ ├── augmentedAssignment.test.ts │ │ │ │ │ │ ├── block.test.ts │ │ │ │ │ │ ├── break.test.ts │ │ │ │ │ │ ├── continue.test.ts │ │ │ │ │ │ ├── expression.test.ts │ │ │ │ │ │ ├── for.test.ts │ │ │ │ │ │ ├── if.test.ts │ │ │ │ │ │ ├── import.test.ts │ │ │ │ │ │ ├── raise.test.ts │ │ │ │ │ │ ├── return.test.ts │ │ │ │ │ │ ├── try.test.ts │ │ │ │ │ │ ├── while.test.ts │ │ │ │ │ │ └── with.test.ts │ │ │ │ │ ├── structure/ │ │ │ │ │ │ ├── comment.test.ts │ │ │ │ │ │ └── sourceFile.test.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── index.ts │ │ │ │ ├── nodes/ │ │ │ │ │ ├── base.ts │ │ │ │ │ ├── comprehension.ts │ │ │ │ │ ├── declarations/ │ │ │ │ │ │ ├── class.ts │ │ │ │ │ │ ├── function.ts │ │ │ │ │ │ └── functionParameter.ts │ │ │ │ │ ├── expression.ts │ │ │ │ │ ├── expressions/ │ │ │ │ │ │ ├── async.ts │ │ │ │ │ │ ├── await.ts │ │ │ │ │ │ ├── binary.ts │ │ │ │ │ │ ├── call.ts │ │ │ │ │ │ ├── comprehensions/ │ │ │ │ │ │ │ ├── dict.ts │ │ │ │ │ │ │ ├── list.ts │ │ │ │ │ │ │ └── set.ts │ │ │ │ │ │ ├── dict.ts │ │ │ │ │ │ ├── fString.ts │ │ │ │ │ │ ├── generator.ts │ │ │ │ │ │ ├── identifier.ts │ │ │ │ │ │ ├── keywordArg.ts │ │ │ │ │ │ ├── lambda.ts │ │ │ │ │ │ ├── list.ts │ │ │ │ │ │ ├── literal.ts │ │ │ │ │ │ ├── member.ts │ │ │ │ │ │ ├── set.ts │ │ │ │ │ │ ├── subscript-slice.ts │ │ │ │ │ │ ├── subscript.ts │ │ │ │ │ │ ├── tuple.ts │ │ │ │ │ │ ├── yield.ts │ │ │ │ │ │ └── yieldFrom.ts │ │ │ │ │ ├── factory.ts │ │ │ │ │ ├── kinds.ts │ │ │ │ │ ├── statement.ts │ │ │ │ │ ├── statements/ │ │ │ │ │ │ ├── assignment.ts │ │ │ │ │ │ ├── augmentedAssignment.ts │ │ │ │ │ │ ├── block.ts │ │ │ │ │ │ ├── break.ts │ │ │ │ │ │ ├── continue.ts │ │ │ │ │ │ ├── empty.ts │ │ │ │ │ │ ├── except.ts │ │ │ │ │ │ ├── expression.ts │ │ │ │ │ │ ├── for.ts │ │ │ │ │ │ ├── if.ts │ │ │ │ │ │ ├── import.ts │ │ │ │ │ │ ├── raise.ts │ │ │ │ │ │ ├── return.ts │ │ │ │ │ │ ├── try.ts │ │ │ │ │ │ ├── while.ts │ │ │ │ │ │ ├── with.ts │ │ │ │ │ │ └── withItem.ts │ │ │ │ │ └── structure/ │ │ │ │ │ ├── comment.ts │ │ │ │ │ └── sourceFile.ts │ │ │ │ └── printer.ts │ │ │ ├── py-dsl/ │ │ │ │ ├── base.ts │ │ │ │ ├── decl/ │ │ │ │ │ ├── class.ts │ │ │ │ │ ├── func.ts │ │ │ │ │ └── param.ts │ │ │ │ ├── expr/ │ │ │ │ │ ├── attr.ts │ │ │ │ │ ├── binary.ts │ │ │ │ │ ├── call.ts │ │ │ │ │ ├── dict.ts │ │ │ │ │ ├── expr.ts │ │ │ │ │ ├── identifier.ts │ │ │ │ │ ├── kwarg.ts │ │ │ │ │ ├── list.ts │ │ │ │ │ ├── literal.ts │ │ │ │ │ ├── set.ts │ │ │ │ │ ├── subscript.ts │ │ │ │ │ └── tuple.ts │ │ │ │ ├── index.ts │ │ │ │ ├── layout/ │ │ │ │ │ ├── doc.ts │ │ │ │ │ ├── hint.ts │ │ │ │ │ └── newline.ts │ │ │ │ ├── mixins/ │ │ │ │ │ ├── args.ts │ │ │ │ │ ├── decorator.ts │ │ │ │ │ ├── do.ts │ │ │ │ │ ├── doc.ts │ │ │ │ │ ├── expr.ts │ │ │ │ │ ├── hint.ts │ │ │ │ │ ├── layout.ts │ │ │ │ │ ├── modifiers.ts │ │ │ │ │ ├── operator.ts │ │ │ │ │ ├── param.ts │ │ │ │ │ ├── returns.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── value.ts │ │ │ │ ├── stmt/ │ │ │ │ │ ├── block.ts │ │ │ │ │ ├── break.ts │ │ │ │ │ ├── continue.ts │ │ │ │ │ ├── for.ts │ │ │ │ │ ├── if.ts │ │ │ │ │ ├── import.ts │ │ │ │ │ ├── raise.ts │ │ │ │ │ ├── return.ts │ │ │ │ │ ├── stmt.ts │ │ │ │ │ ├── try.ts │ │ │ │ │ ├── var.ts │ │ │ │ │ ├── while.ts │ │ │ │ │ └── with.ts │ │ │ │ └── utils/ │ │ │ │ ├── __tests__/ │ │ │ │ │ ├── name.test.ts │ │ │ │ │ └── render-utils.test.ts │ │ │ │ ├── context.ts │ │ │ │ ├── factories.ts │ │ │ │ ├── keywords.ts │ │ │ │ ├── lazy.ts │ │ │ │ ├── name.ts │ │ │ │ ├── regexp.ts │ │ │ │ ├── render-utils.ts │ │ │ │ ├── render.ts │ │ │ │ └── reserved.ts │ │ │ └── run.ts │ │ ├── tsconfig.json │ │ ├── tsdown.config.ts │ │ ├── turbo.json │ │ └── vitest.setup.ts │ ├── openapi-python-tests/ │ │ ├── pydantic/ │ │ │ └── v2/ │ │ │ ├── .gitignore │ │ │ ├── __snapshots__/ │ │ │ │ └── 3.1.x/ │ │ │ │ └── opencode/ │ │ │ │ └── pydantic_gen.py │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── opencode.test.ts │ │ │ │ └── utils.ts │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ ├── sdks/ │ │ │ ├── .gitignore │ │ │ ├── __snapshots__/ │ │ │ │ └── opencode/ │ │ │ │ └── default/ │ │ │ │ ├── __init__.py │ │ │ │ ├── client/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── client_gen.py │ │ │ │ ├── pydantic_gen.py │ │ │ │ └── sdk_gen.py │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── opencode.test.ts │ │ │ │ └── utils.ts │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ ├── tsconfig.base.json │ │ └── utils.ts │ ├── openapi-ts/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── bin/ │ │ │ ├── run.cmd │ │ │ └── run.js │ │ ├── package.json │ │ ├── src/ │ │ │ ├── __tests__/ │ │ │ │ ├── cli.test.ts │ │ │ │ ├── index.test.ts │ │ │ │ ├── interactive.test.ts │ │ │ │ └── internal.test.ts │ │ │ ├── cli/ │ │ │ │ ├── adapter.ts │ │ │ │ ├── index.ts │ │ │ │ └── schema.ts │ │ │ ├── config/ │ │ │ │ ├── expand.ts │ │ │ │ ├── init.ts │ │ │ │ ├── output/ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ └── config.test.ts │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── postprocess.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── packages.ts │ │ │ │ ├── plugins.ts │ │ │ │ ├── resolve.ts │ │ │ │ ├── types.ts │ │ │ │ ├── utils.ts │ │ │ │ └── validate.ts │ │ │ ├── createClient.ts │ │ │ ├── generate/ │ │ │ │ ├── client.ts │ │ │ │ └── output.ts │ │ │ ├── generate.ts │ │ │ ├── index.ts │ │ │ ├── internal.ts │ │ │ ├── plugins/ │ │ │ │ ├── @angular/ │ │ │ │ │ └── common/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── httpRequests/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── resolve.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── httpResources/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── resolve.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── shared/ │ │ │ │ │ │ └── node.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── @faker-js/ │ │ │ │ │ └── faker/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── resolvers/ │ │ │ │ │ │ └── types.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── @hey-api/ │ │ │ │ │ ├── client-angular/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── client.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── client-axios/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── client.test.ts │ │ │ │ │ │ │ ├── utils-buildUrl.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── client-core/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── auth.test.ts │ │ │ │ │ │ │ ├── bodySerializer.test.ts │ │ │ │ │ │ │ ├── params.test.ts │ │ │ │ │ │ │ ├── queryKeySerializer.test.ts │ │ │ │ │ │ │ ├── serverSentEvents.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ ├── queryKeySerializer.ts │ │ │ │ │ │ │ ├── serverSentEvents.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── createClientConfig.ts │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ └── utils.ts │ │ │ │ │ ├── client-fetch/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── client.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── client-ky/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── client.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── client-next/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── client.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── client-nuxt/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── client.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── client-ofetch/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── client.test.ts │ │ │ │ │ │ │ └── utils.test.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── schemas/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── sdk/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── examples/ │ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── operations/ │ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── resolve.ts │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ ├── shared/ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ ├── class.ts │ │ │ │ │ │ │ ├── constants.ts │ │ │ │ │ │ │ ├── operation.ts │ │ │ │ │ │ │ ├── signature.ts │ │ │ │ │ │ │ ├── typeOptions.ts │ │ │ │ │ │ │ └── validator.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ └── v1/ │ │ │ │ │ │ ├── node.ts │ │ │ │ │ │ └── plugin.ts │ │ │ │ │ ├── transformers/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── expressions.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ └── typescript/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── resolvers.ts │ │ │ │ │ ├── shared/ │ │ │ │ │ │ ├── clientOptions.ts │ │ │ │ │ │ ├── export.ts │ │ │ │ │ │ ├── meta.ts │ │ │ │ │ │ ├── operation.ts │ │ │ │ │ │ ├── processor.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ └── webhook.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── v1/ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── processor.ts │ │ │ │ │ ├── toAst/ │ │ │ │ │ │ ├── array.ts │ │ │ │ │ │ ├── boolean.ts │ │ │ │ │ │ ├── enum.ts │ │ │ │ │ │ ├── intersection.ts │ │ │ │ │ │ ├── never.ts │ │ │ │ │ │ ├── null.ts │ │ │ │ │ │ ├── number.ts │ │ │ │ │ │ ├── object.ts │ │ │ │ │ │ ├── string.ts │ │ │ │ │ │ ├── tuple.ts │ │ │ │ │ │ ├── undefined.ts │ │ │ │ │ │ ├── union.ts │ │ │ │ │ │ ├── unknown.ts │ │ │ │ │ │ └── void.ts │ │ │ │ │ └── walker.ts │ │ │ │ ├── @pinia/ │ │ │ │ │ └── colada/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── meta.ts │ │ │ │ │ ├── mutationOptions.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── queryKey.ts │ │ │ │ │ ├── queryOptions.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ ├── useType.ts │ │ │ │ │ ├── utils.ts │ │ │ │ │ └── v0/ │ │ │ │ │ └── plugin.ts │ │ │ │ ├── @tanstack/ │ │ │ │ │ ├── angular-query-experimental/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── preact-query/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── query-core/ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ ├── queryKey.ts │ │ │ │ │ │ ├── shared/ │ │ │ │ │ │ │ ├── meta.ts │ │ │ │ │ │ │ └── useType.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ └── v5/ │ │ │ │ │ │ ├── infiniteQueryOptions.ts │ │ │ │ │ │ ├── mutationOptions.ts │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ ├── queryOptions.ts │ │ │ │ │ │ ├── useMutation.ts │ │ │ │ │ │ └── useQuery.ts │ │ │ │ │ ├── react-query/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── solid-query/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── svelte-query/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ └── vue-query/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── arktype/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── constants.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── shared/ │ │ │ │ │ │ ├── export.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── v2/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ └── toAst/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── null.ts │ │ │ │ │ ├── object.ts │ │ │ │ │ └── string.ts │ │ │ │ ├── config.ts │ │ │ │ ├── fastify/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── nestjs/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── orpc/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── contracts/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── node.ts │ │ │ │ │ │ ├── resolve.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── shared/ │ │ │ │ │ │ └── operation.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── v1/ │ │ │ │ │ └── plugin.ts │ │ │ │ ├── shared/ │ │ │ │ │ └── utils/ │ │ │ │ │ ├── coerce.ts │ │ │ │ │ ├── formats.ts │ │ │ │ │ ├── operation.ts │ │ │ │ │ └── schema.ts │ │ │ │ ├── swr/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── v2/ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ └── useSwr.ts │ │ │ │ ├── types.ts │ │ │ │ ├── valibot/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── resolvers.ts │ │ │ │ │ ├── shared/ │ │ │ │ │ │ ├── export.ts │ │ │ │ │ │ ├── meta.ts │ │ │ │ │ │ ├── operation-schema.ts │ │ │ │ │ │ ├── operation.ts │ │ │ │ │ │ ├── pipes.ts │ │ │ │ │ │ ├── processor.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ └── webhook.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── v1/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── constants.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── processor.ts │ │ │ │ │ ├── toAst/ │ │ │ │ │ │ ├── array.ts │ │ │ │ │ │ ├── boolean.ts │ │ │ │ │ │ ├── enum.ts │ │ │ │ │ │ ├── intersection.ts │ │ │ │ │ │ ├── never.ts │ │ │ │ │ │ ├── null.ts │ │ │ │ │ │ ├── number.ts │ │ │ │ │ │ ├── object.ts │ │ │ │ │ │ ├── string.ts │ │ │ │ │ │ ├── tuple.ts │ │ │ │ │ │ ├── undefined.ts │ │ │ │ │ │ ├── union.ts │ │ │ │ │ │ ├── unknown.ts │ │ │ │ │ │ └── void.ts │ │ │ │ │ └── walker.ts │ │ │ │ └── zod/ │ │ │ │ ├── api.ts │ │ │ │ ├── config.ts │ │ │ │ ├── constants.ts │ │ │ │ ├── index.ts │ │ │ │ ├── mini/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── processor.ts │ │ │ │ │ ├── toAst/ │ │ │ │ │ │ ├── array.ts │ │ │ │ │ │ ├── boolean.ts │ │ │ │ │ │ ├── enum.ts │ │ │ │ │ │ ├── never.ts │ │ │ │ │ │ ├── null.ts │ │ │ │ │ │ ├── number.ts │ │ │ │ │ │ ├── object.ts │ │ │ │ │ │ ├── string.ts │ │ │ │ │ │ ├── tuple.ts │ │ │ │ │ │ ├── undefined.ts │ │ │ │ │ │ ├── unknown.ts │ │ │ │ │ │ └── void.ts │ │ │ │ │ └── walker.ts │ │ │ │ ├── plugin.ts │ │ │ │ ├── resolvers.ts │ │ │ │ ├── shared/ │ │ │ │ │ ├── chain.ts │ │ │ │ │ ├── export.ts │ │ │ │ │ ├── meta.ts │ │ │ │ │ ├── module.ts │ │ │ │ │ ├── operation-schema.ts │ │ │ │ │ ├── operation.ts │ │ │ │ │ ├── processor.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── webhook.ts │ │ │ │ ├── types.ts │ │ │ │ ├── v3/ │ │ │ │ │ ├── api.ts │ │ │ │ │ ├── plugin.ts │ │ │ │ │ ├── processor.ts │ │ │ │ │ ├── toAst/ │ │ │ │ │ │ ├── array.ts │ │ │ │ │ │ ├── boolean.ts │ │ │ │ │ │ ├── enum.ts │ │ │ │ │ │ ├── never.ts │ │ │ │ │ │ ├── null.ts │ │ │ │ │ │ ├── number.ts │ │ │ │ │ │ ├── object.ts │ │ │ │ │ │ ├── string.ts │ │ │ │ │ │ ├── tuple.ts │ │ │ │ │ │ ├── undefined.ts │ │ │ │ │ │ ├── unknown.ts │ │ │ │ │ │ └── void.ts │ │ │ │ │ └── walker.ts │ │ │ │ └── v4/ │ │ │ │ ├── api.ts │ │ │ │ ├── plugin.ts │ │ │ │ ├── processor.ts │ │ │ │ ├── toAst/ │ │ │ │ │ ├── array.ts │ │ │ │ │ ├── boolean.ts │ │ │ │ │ ├── enum.ts │ │ │ │ │ ├── intersection.ts │ │ │ │ │ ├── never.ts │ │ │ │ │ ├── null.ts │ │ │ │ │ ├── number.ts │ │ │ │ │ ├── object.ts │ │ │ │ │ ├── string.ts │ │ │ │ │ ├── tuple.ts │ │ │ │ │ ├── undefined.ts │ │ │ │ │ ├── union.ts │ │ │ │ │ ├── unknown.ts │ │ │ │ │ └── void.ts │ │ │ │ └── walker.ts │ │ │ ├── run.ts │ │ │ ├── ts-compiler/ │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── nodes/ │ │ │ │ │ ├── expressions/ │ │ │ │ │ │ ├── identifier/ │ │ │ │ │ │ │ └── identifier.ts │ │ │ │ │ │ └── literal/ │ │ │ │ │ │ └── primitive.ts │ │ │ │ │ └── statements/ │ │ │ │ │ └── var/ │ │ │ │ │ ├── const.ts │ │ │ │ │ ├── let.ts │ │ │ │ │ └── var.ts │ │ │ │ ├── __tests__/ │ │ │ │ │ ├── constants.ts │ │ │ │ │ ├── globalTeardown.ts │ │ │ │ │ └── nodes/ │ │ │ │ │ ├── expressions/ │ │ │ │ │ │ ├── identifier.test.ts │ │ │ │ │ │ └── literal.test.ts │ │ │ │ │ ├── statements/ │ │ │ │ │ │ └── var.test.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── index.ts │ │ │ │ ├── nodes/ │ │ │ │ │ ├── base.ts │ │ │ │ │ ├── expression.ts │ │ │ │ │ ├── expressions/ │ │ │ │ │ │ ├── identifier.ts │ │ │ │ │ │ └── literal.ts │ │ │ │ │ ├── factory.ts │ │ │ │ │ ├── kinds.ts │ │ │ │ │ ├── statement.ts │ │ │ │ │ ├── statements/ │ │ │ │ │ │ ├── assignment.ts │ │ │ │ │ │ └── var.ts │ │ │ │ │ ├── structure/ │ │ │ │ │ │ └── sourceFile.ts │ │ │ │ │ └── type.ts │ │ │ │ └── printer.ts │ │ │ └── ts-dsl/ │ │ │ ├── base.ts │ │ │ ├── decl/ │ │ │ │ ├── class.ts │ │ │ │ ├── decorator.ts │ │ │ │ ├── enum.ts │ │ │ │ ├── field.ts │ │ │ │ ├── func.ts │ │ │ │ ├── getter.ts │ │ │ │ ├── init.ts │ │ │ │ ├── member.ts │ │ │ │ ├── method.ts │ │ │ │ ├── param.ts │ │ │ │ ├── pattern.ts │ │ │ │ └── setter.ts │ │ │ ├── expr/ │ │ │ │ ├── array.ts │ │ │ │ ├── as.ts │ │ │ │ ├── attr.ts │ │ │ │ ├── await.ts │ │ │ │ ├── binary.ts │ │ │ │ ├── call.ts │ │ │ │ ├── expr.ts │ │ │ │ ├── fromValue.ts │ │ │ │ ├── id.ts │ │ │ │ ├── literal.ts │ │ │ │ ├── new.ts │ │ │ │ ├── object.ts │ │ │ │ ├── prefix.ts │ │ │ │ ├── prop.ts │ │ │ │ ├── regexp.ts │ │ │ │ ├── template.ts │ │ │ │ ├── ternary.ts │ │ │ │ └── typeof.ts │ │ │ ├── index.ts │ │ │ ├── layout/ │ │ │ │ ├── doc.ts │ │ │ │ ├── hint.ts │ │ │ │ ├── newline.ts │ │ │ │ └── note.ts │ │ │ ├── mixins/ │ │ │ │ ├── args.ts │ │ │ │ ├── as.ts │ │ │ │ ├── decorator.ts │ │ │ │ ├── do.ts │ │ │ │ ├── doc.ts │ │ │ │ ├── expr.ts │ │ │ │ ├── hint.ts │ │ │ │ ├── layout.ts │ │ │ │ ├── modifiers.ts │ │ │ │ ├── note.ts │ │ │ │ ├── operator.ts │ │ │ │ ├── optional.ts │ │ │ │ ├── param.ts │ │ │ │ ├── pattern.ts │ │ │ │ ├── type-args.ts │ │ │ │ ├── type-expr.ts │ │ │ │ ├── type-params.ts │ │ │ │ ├── type-returns.ts │ │ │ │ ├── types.ts │ │ │ │ └── value.ts │ │ │ ├── stmt/ │ │ │ │ ├── block.ts │ │ │ │ ├── if.ts │ │ │ │ ├── return.ts │ │ │ │ ├── stmt.ts │ │ │ │ ├── throw.ts │ │ │ │ ├── try.ts │ │ │ │ └── var.ts │ │ │ ├── token.ts │ │ │ ├── type/ │ │ │ │ ├── alias.ts │ │ │ │ ├── and.ts │ │ │ │ ├── attr.ts │ │ │ │ ├── expr.ts │ │ │ │ ├── fromValue.ts │ │ │ │ ├── func.ts │ │ │ │ ├── idx-sig.ts │ │ │ │ ├── idx.ts │ │ │ │ ├── literal.ts │ │ │ │ ├── mapped.ts │ │ │ │ ├── object.ts │ │ │ │ ├── operator.ts │ │ │ │ ├── or.ts │ │ │ │ ├── param.ts │ │ │ │ ├── prop.ts │ │ │ │ ├── query.ts │ │ │ │ ├── template.ts │ │ │ │ └── tuple.ts │ │ │ └── utils/ │ │ │ ├── __tests__/ │ │ │ │ ├── name.test.ts │ │ │ │ └── render.test.ts │ │ │ ├── context.ts │ │ │ ├── factories.ts │ │ │ ├── keywords.ts │ │ │ ├── lazy.ts │ │ │ ├── name.ts │ │ │ ├── regexp.ts │ │ │ ├── render-utils.ts │ │ │ ├── render.ts │ │ │ └── reserved.ts │ │ ├── tsconfig.json │ │ ├── tsdown.config.ts │ │ ├── turbo.json │ │ └── vitest.setup.ts │ ├── openapi-ts-tests/ │ │ ├── __snapshots__/ │ │ │ └── plugins/ │ │ │ └── @tanstack/ │ │ │ └── meta/ │ │ │ ├── @tanstack/ │ │ │ │ ├── angular-query-experimental.gen.ts │ │ │ │ ├── preact-query.gen.ts │ │ │ │ ├── react-query.gen.ts │ │ │ │ ├── solid-query.gen.ts │ │ │ │ ├── svelte-query.gen.ts │ │ │ │ └── vue-query.gen.ts │ │ │ ├── client/ │ │ │ │ ├── client.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── types.gen.ts │ │ │ │ └── utils.gen.ts │ │ │ ├── client.gen.ts │ │ │ ├── core/ │ │ │ │ ├── auth.gen.ts │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ ├── params.gen.ts │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ ├── types.gen.ts │ │ │ │ └── utils.gen.ts │ │ │ ├── index.ts │ │ │ ├── sdk.gen.ts │ │ │ └── types.gen.ts │ │ ├── main/ │ │ │ ├── .gitignore │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── 2.0.x.test.ts │ │ │ │ ├── 3.0.x.test.ts │ │ │ │ ├── 3.1.x.test.ts │ │ │ │ ├── __snapshots__/ │ │ │ │ │ ├── 2.0.x/ │ │ │ │ │ │ ├── additional-properties-false/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── additional-properties-true/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── body-response-text-plain/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-PascalCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-SCREAMING_SNAKE_CASE/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-camelCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-preserve/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-snake_case/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-PascalCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-SCREAMING_SNAKE_CASE/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-camelCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-const/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-preserve/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-snake_case/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── exclude-deprecated/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── external/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── form-data/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── plugins/ │ │ │ │ │ │ │ ├── @angular/ │ │ │ │ │ │ │ │ └── common/ │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── default-class/ │ │ │ │ │ │ │ │ ├── @angular/ │ │ │ │ │ │ │ │ │ └── common.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── @hey-api/ │ │ │ │ │ │ │ │ ├── client-fetch/ │ │ │ │ │ │ │ │ │ ├── sdk-nested-classes/ │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── sdk-nested-classes-instance/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── schemas/ │ │ │ │ │ │ │ │ │ └── default/ │ │ │ │ │ │ │ │ │ └── schemas.gen.ts │ │ │ │ │ │ │ │ ├── sdk/ │ │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── instance/ │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── throwOnError/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── typescript/ │ │ │ │ │ │ │ │ ├── transforms-read-write-custom-name/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── transforms-read-write-ignore/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ └── colada/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ │ │ └── colada.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── fetch/ │ │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ │ └── colada.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ ├── angular-query-experimental/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── preact-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── react-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── name-builder/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── useMutation/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── solid-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── svelte-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── vue-query/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── fastify/ │ │ │ │ │ │ │ └── default/ │ │ │ │ │ │ │ ├── fastify.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── ref-deep/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── schema-unknown/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-api-key/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-basic/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-false/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-oauth2/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── servers/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── servers-base-path/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── servers-host/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transforms-read-write/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ └── transforms-schemas-name/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── 3.0.x/ │ │ │ │ │ │ ├── additional-properties-false/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── additional-properties-true/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── additional-properties-undefined/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── array-nested-one-of/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── body-binary-format/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── body-response-text-plain/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── case-PascalCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── case-camelCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── case-preserve/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── case-snake_case/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── components-request-bodies/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── content-binary/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── content-types/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-all-of/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-allof-inline/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-allof-nested/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-any-of/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-mapped-many/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-non-string/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-object-self-mapped/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── discriminator-one-of/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-escape/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-inline/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-inline-javascript/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-inline-name-resolver/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-inline-name-resolver-null/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-inline-typescript/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-PascalCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-SCREAMING_SNAKE_CASE/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-camelCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-ignore-null/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-preserve/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-javascript-snake_case/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-PascalCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-SCREAMING_SNAKE_CASE/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-camelCase/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-const/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-preserve/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-names-values-typescript-snake_case/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── exclude-deprecated/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── external/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── internal-name-conflict/ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── operation-204/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── parameter-explode-false/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── parameter-explode-false-axios/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── plugins/ │ │ │ │ │ │ │ ├── @angular/ │ │ │ │ │ │ │ │ └── common/ │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── default-class/ │ │ │ │ │ │ │ │ ├── @angular/ │ │ │ │ │ │ │ │ │ └── common.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── @hey-api/ │ │ │ │ │ │ │ │ ├── client-fetch/ │ │ │ │ │ │ │ │ │ ├── sdk-nested-classes/ │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── sdk-nested-classes-instance/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── schemas/ │ │ │ │ │ │ │ │ │ └── default/ │ │ │ │ │ │ │ │ │ └── schemas.gen.ts │ │ │ │ │ │ │ │ ├── sdk/ │ │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── instance/ │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── throwOnError/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── typescript/ │ │ │ │ │ │ │ │ ├── transforms-read-write-custom-name/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── transforms-read-write-ignore/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ └── colada/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ │ │ └── colada.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── fetch/ │ │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ │ └── colada.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ ├── angular-query-experimental/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── preact-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── react-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── name-builder/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── useMutation/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── solid-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── svelte-query/ │ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── vue-query/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── fastify/ │ │ │ │ │ │ │ └── default/ │ │ │ │ │ │ │ ├── fastify.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── ref-deep/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-api-key/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-false/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-http-bearer/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-oauth2/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── security-open-id-connect/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── servers/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transformers-all-of/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transformers-allof-response-wrapper/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transformers-any-of-null/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transformers-array/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transformers-recursive/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transforms-properties-required-by-default/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transforms-read-write/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transforms-schemas-name/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── transforms-schemas-name-collision/ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ └── type-invalid/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ └── 3.1.x/ │ │ │ │ │ ├── additional-properties-false/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── additional-properties-true/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── additional-properties-true-any/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── additional-properties-undefined/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── array-nested-one-of/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── body-response-text-plain/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── case-PascalCase/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── case-camelCase/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── case-preserve/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── case-snake_case/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── clients/ │ │ │ │ │ │ ├── @hey-api/ │ │ │ │ │ │ │ ├── client-angular/ │ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── clean-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── import-file-extension-ts/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-required/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── tsconfig-node16-sdk/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── tsconfig-nodenext-sdk/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── client-axios/ │ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── clean-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── import-file-extension-ts/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-required/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── tsconfig-node16-sdk/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── tsconfig-nodenext-sdk/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── client-fetch/ │ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── clean-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── import-file-extension-ts/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-required/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── tsconfig-node16-sdk/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── tsconfig-nodenext-sdk/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── client-ky/ │ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── clean-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── import-file-extension-ts/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-required/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── tsconfig-node16-sdk/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── tsconfig-nodenext-sdk/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── client-next/ │ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── clean-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── import-file-extension-ts/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-required/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── tsconfig-node16-sdk/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── tsconfig-nodenext-sdk/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── client-nuxt/ │ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── clean-false/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── import-file-extension-ts/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── sdk-client-required/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── tsconfig-node16-sdk/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── tsconfig-nodenext-sdk/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── client-ofetch/ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── clean-false/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── import-file-extension-ts/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── sdk-client-required/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── tsconfig-node16-sdk/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── tsconfig-nodenext-sdk/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── client-custom/ │ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ │ ├── custom-client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ │ ├── custom-client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ │ ├── custom-client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ │ ├── custom-client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ ├── custom-client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ │ ├── custom-client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── sdk-client-required/ │ │ │ │ │ │ │ ├── custom-client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ └── my-client/ │ │ │ │ │ │ ├── base-url-false/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── base-url-number/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── base-url-strict/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── base-url-string/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── bundle/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── sdk-client-optional/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ └── sdk-client-required/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ │ └── utils.ts │ │ │ │ │ │ ├── custom.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── components-request-bodies/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── const/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── content-binary/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── content-media-type/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── content-types/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-all-of/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-allof-inline/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-allof-nested/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-any-of/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-mapped-many/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-non-string/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-object-self-mapped/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-one-of/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── discriminator-one-of-read-write/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── duplicate-null/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-escape/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-inline/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-inline-javascript/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-inline-name-resolver/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-inline-name-resolver-null/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-inline-typescript/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-javascript-PascalCase/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-javascript-SCREAMING_SNAKE_CASE/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-javascript-camelCase/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-javascript-ignore-null/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-javascript-preserve/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-javascript-snake_case/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-typescript-PascalCase/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-typescript-SCREAMING_SNAKE_CASE/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-typescript-camelCase/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-typescript-const/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-typescript-preserve/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-names-values-typescript-snake_case/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── exclude-deprecated/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── external/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── headers/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── internal-name-conflict/ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── negative-property-names/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── object-properties-all-of/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── object-properties-any-of/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── object-properties-one-of/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── object-property-names/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── operation-204/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── pagination-ref/ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── parameter-explode-false/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── parameter-explode-false-axios/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── parameter-tuple/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── pattern-properties/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── plugins/ │ │ │ │ │ │ ├── @angular/ │ │ │ │ │ │ │ └── common/ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── default-class/ │ │ │ │ │ │ │ ├── @angular/ │ │ │ │ │ │ │ │ └── common.gen.ts │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── @hey-api/ │ │ │ │ │ │ │ ├── client-fetch/ │ │ │ │ │ │ │ │ ├── sdk-nested-classes/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── sdk-nested-classes-instance/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── schemas/ │ │ │ │ │ │ │ │ └── default/ │ │ │ │ │ │ │ │ └── schemas.gen.ts │ │ │ │ │ │ │ ├── sdk/ │ │ │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── instance/ │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── throwOnError/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── typescript/ │ │ │ │ │ │ │ ├── transforms-read-write-custom-name/ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── transforms-read-write-ignore/ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ └── colada/ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ │ └── colada.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── fetch/ │ │ │ │ │ │ │ ├── @pinia/ │ │ │ │ │ │ │ │ └── colada.gen.ts │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ ├── angular-query-experimental/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── angular-query-experimental.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── preact-query/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── preact-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── react-query/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── name-builder/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── useMutation/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── solid-query/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── solid-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── svelte-query/ │ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── svelte-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── vue-query/ │ │ │ │ │ │ │ ├── asClass/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── axios/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ ├── fetch/ │ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ │ └── name-builder/ │ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ │ └── vue-query.gen.ts │ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ │ └── fastify/ │ │ │ │ │ │ └── default/ │ │ │ │ │ │ ├── fastify.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── ref-deep/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── ref-type/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── required-all-of-ref/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── required-any-of-ref/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── required-one-of-ref/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── schema-const/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── security-api-key/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── security-false/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── security-http-bearer/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── security-oauth2/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── security-open-id-connect/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── servers/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── sse-angular/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── sse-axios/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── sse-fetch/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── sse-next/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── sse-nuxt/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── sse-ofetch/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── sse-tanstack-react-query/ │ │ │ │ │ │ ├── @tanstack/ │ │ │ │ │ │ │ └── react-query.gen.ts │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── string-with-format/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transformers-all-of/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transformers-allof-response-wrapper/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transformers-any-of-null/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transformers-array/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transformers-one-of-discriminated/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transformers-recursive/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transforms-read-write/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transforms-read-write-nested/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transforms-read-write-response/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transforms-read-write-unevaluated/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── transforms-schemas-name/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── type-invalid/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── union-types/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ └── webhooks/ │ │ │ │ │ ├── index.ts │ │ │ │ │ └── types.gen.ts │ │ │ │ ├── cli.test.ts │ │ │ │ ├── clients.test.ts │ │ │ │ ├── custom/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.ts │ │ │ │ │ │ │ ├── bodySerializer.ts │ │ │ │ │ │ │ ├── params.ts │ │ │ │ │ │ │ ├── pathSerializer.ts │ │ │ │ │ │ │ └── types.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── plugin.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ └── utils.ts │ │ │ │ │ └── request.ts │ │ │ │ ├── meta-function.test.ts │ │ │ │ ├── plugins.test.ts │ │ │ │ └── tsconfig/ │ │ │ │ ├── tsconfig.node16.json │ │ │ │ └── tsconfig.nodenext.json │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ ├── nestjs/ │ │ │ └── v11/ │ │ │ ├── __snapshots__/ │ │ │ │ ├── 2.0.x/ │ │ │ │ │ └── default/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── nestjs.gen.ts │ │ │ │ │ └── types.gen.ts │ │ │ │ ├── 3.0.x/ │ │ │ │ │ └── default/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── nestjs.gen.ts │ │ │ │ │ └── types.gen.ts │ │ │ │ └── 3.1.x/ │ │ │ │ └── default/ │ │ │ │ ├── index.ts │ │ │ │ ├── nestjs.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ └── plugins.test.ts │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ ├── orpc/ │ │ │ └── v1/ │ │ │ ├── .gitignore │ │ │ ├── __snapshots__/ │ │ │ │ ├── 3.0.x/ │ │ │ │ │ ├── custom-names/ │ │ │ │ │ │ ├── orpc.gen.ts │ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ │ └── default/ │ │ │ │ │ ├── orpc.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── 3.1.x/ │ │ │ │ ├── contracts-custom-naming/ │ │ │ │ │ ├── orpc.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── contracts-nesting-id/ │ │ │ │ │ ├── orpc.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── contracts-strategy-by-tags/ │ │ │ │ │ ├── orpc.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── contracts-strategy-single/ │ │ │ │ │ ├── orpc.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── custom-names/ │ │ │ │ │ ├── orpc.gen.ts │ │ │ │ │ └── valibot.gen.ts │ │ │ │ └── default/ │ │ │ │ ├── orpc.gen.ts │ │ │ │ └── zod.gen.ts │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── 3.0.x.test.ts │ │ │ │ ├── 3.1.x.test.ts │ │ │ │ ├── constants.ts │ │ │ │ ├── globalTeardown.ts │ │ │ │ └── utils.ts │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ ├── sdks/ │ │ │ ├── .gitignore │ │ │ ├── __snapshots__/ │ │ │ │ ├── method-class-conflict/ │ │ │ │ │ ├── class/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ ├── flat/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ └── types.gen.ts │ │ │ │ │ └── instance/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ └── types.gen.ts │ │ │ │ └── opencode/ │ │ │ │ ├── export-all/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ └── types.gen.ts │ │ │ │ ├── flat/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ └── types.gen.ts │ │ │ │ └── grouped/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ └── types.gen.ts │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── method-class-conflict.test.ts │ │ │ │ ├── opencode.test.ts │ │ │ │ └── utils.ts │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ ├── tsconfig.base.json │ │ ├── utils.ts │ │ ├── valibot/ │ │ │ └── v1/ │ │ │ ├── .gitignore │ │ │ ├── __snapshots__/ │ │ │ │ ├── 3.0.x/ │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ │ └── validators/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ └── 3.1.x/ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── enum-null/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── integer-formats/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── schema-const/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── string-with-format/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── time-format/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── type-format/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators-bigint-min-max/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators-circular-ref/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators-circular-ref-2/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators-metadata/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators-metadata-fn/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators-types/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ ├── validators-union-merge/ │ │ │ │ │ └── valibot.gen.ts │ │ │ │ └── webhooks/ │ │ │ │ └── valibot.gen.ts │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── 3.0.x.test.ts │ │ │ │ ├── 3.1.x.test.ts │ │ │ │ ├── additional-properties.test.ts │ │ │ │ ├── const-values.test.ts │ │ │ │ ├── formats.test.ts │ │ │ │ ├── min-max-constraints.test.ts │ │ │ │ └── utils.ts │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ └── zod/ │ │ ├── v3/ │ │ │ ├── .gitignore │ │ │ ├── __snapshots__/ │ │ │ │ ├── 2.0.x/ │ │ │ │ │ ├── mini/ │ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ └── type-format/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── v3/ │ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ └── type-format/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── v4/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── type-format/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── 3.0.x/ │ │ │ │ │ ├── mini/ │ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── circular/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── type-format/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ └── validators/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── v3/ │ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── circular/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── default/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ ├── type-format/ │ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ │ └── validators/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── v4/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── circular/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── type-format/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── validators/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── 3.1.x/ │ │ │ │ ├── mini/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── enum-resolver-permissive/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── schema-const/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── type-format/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-bigint-min-max/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-circular-ref/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-circular-ref-2/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-dates/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-metadata/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-string-constraints-union/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-types/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── validators-union-merge/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── v3/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── enum-resolver-permissive/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── schema-const/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── type-format/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-bigint-min-max/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-circular-ref/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-circular-ref-2/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-dates/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-metadata/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-string-constraints-union/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── validators-types/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── validators-union-merge/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── v4/ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── default/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── enum-null/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── enum-resolver-permissive/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── schema-const/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── type-format/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-bigint-min-max/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-circular-ref/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-circular-ref-2/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-dates/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-metadata/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-string-constraints-union/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-types/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── validators-union-merge/ │ │ │ │ └── zod.gen.ts │ │ │ ├── package.json │ │ │ ├── test/ │ │ │ │ ├── 3.0.x.test.ts │ │ │ │ ├── 3.1.x.test.ts │ │ │ │ ├── openapi.test.ts │ │ │ │ └── utils.ts │ │ │ ├── tsconfig.json │ │ │ ├── turbo.json │ │ │ └── vitest.setup.ts │ │ └── v4/ │ │ ├── .gitignore │ │ ├── __snapshots__/ │ │ │ ├── 2.0.x/ │ │ │ │ ├── mini/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── type-format/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── v3/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── type-format/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── v4/ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── default/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── type-format/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ ├── transformers.gen.ts │ │ │ │ ├── types.gen.ts │ │ │ │ └── zod.gen.ts │ │ │ ├── 3.0.x/ │ │ │ │ ├── mini/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── circular/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── type-format/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── validators/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── v3/ │ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── circular/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── default/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── enum-null/ │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ ├── type-format/ │ │ │ │ │ │ ├── client/ │ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── core/ │ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── zod.gen.ts │ │ │ │ │ └── validators/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── v4/ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── circular/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── default/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── enum-null/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── type-format/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── validators/ │ │ │ │ └── zod.gen.ts │ │ │ └── 3.1.x/ │ │ │ ├── mini/ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── default/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── defaults-with-ref-and-anyof/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── enum-null/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── enum-resolver-permissive/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── schema-const/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── string-with-format/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── string-with-guid-format/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── type-format/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-bigint-min-max/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-circular-ref/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-circular-ref-2/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-dates/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-metadata/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-metadata-fn/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-string-constraints-union/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-types/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-union-merge/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── webhooks/ │ │ │ │ └── zod.gen.ts │ │ │ ├── v3/ │ │ │ │ ├── array-items-all-of/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── default/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── defaults-with-ref-and-anyof/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── enum-null/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── enum-resolver-permissive/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── schema-const/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── string-with-format/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── string-with-guid-format/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── type-format/ │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── core/ │ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ │ └── utils.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sdk.gen.ts │ │ │ │ │ ├── transformers.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-bigint-min-max/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-circular-ref/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-circular-ref-2/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-dates/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-metadata/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-metadata-fn/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-string-constraints-union/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-types/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ ├── validators-union-merge/ │ │ │ │ │ └── zod.gen.ts │ │ │ │ └── webhooks/ │ │ │ │ └── zod.gen.ts │ │ │ └── v4/ │ │ │ ├── array-items-all-of/ │ │ │ │ └── zod.gen.ts │ │ │ ├── array-items-one-of-length-1/ │ │ │ │ └── zod.gen.ts │ │ │ ├── default/ │ │ │ │ └── zod.gen.ts │ │ │ ├── defaults-with-ref-and-anyof/ │ │ │ │ └── zod.gen.ts │ │ │ ├── enum-null/ │ │ │ │ └── zod.gen.ts │ │ │ ├── enum-resolver-permissive/ │ │ │ │ └── zod.gen.ts │ │ │ ├── schema-const/ │ │ │ │ └── zod.gen.ts │ │ │ ├── string-with-format/ │ │ │ │ └── zod.gen.ts │ │ │ ├── string-with-guid-format/ │ │ │ │ └── zod.gen.ts │ │ │ ├── type-format/ │ │ │ │ ├── client/ │ │ │ │ │ ├── client.gen.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── client.gen.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── auth.gen.ts │ │ │ │ │ ├── bodySerializer.gen.ts │ │ │ │ │ ├── params.gen.ts │ │ │ │ │ ├── pathSerializer.gen.ts │ │ │ │ │ ├── queryKeySerializer.gen.ts │ │ │ │ │ ├── serverSentEvents.gen.ts │ │ │ │ │ ├── types.gen.ts │ │ │ │ │ └── utils.gen.ts │ │ │ │ ├── index.ts │ │ │ │ ├── sdk.gen.ts │ │ │ │ ├── transformers.gen.ts │ │ │ │ ├── types.gen.ts │ │ │ │ └── zod.gen.ts │ │ │ ├── validators/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-bigint-min-max/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-circular-ref/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-circular-ref-2/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-dates/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-metadata/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-metadata-fn/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-string-constraints-union/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-types/ │ │ │ │ └── zod.gen.ts │ │ │ ├── validators-union-merge/ │ │ │ │ └── zod.gen.ts │ │ │ └── webhooks/ │ │ │ └── zod.gen.ts │ │ ├── package.json │ │ ├── test/ │ │ │ ├── 3.0.x.test.ts │ │ │ ├── 3.1.x.test.ts │ │ │ ├── formats.test.ts │ │ │ ├── openapi.test.ts │ │ │ └── utils.ts │ │ ├── tsconfig.json │ │ ├── turbo.json │ │ └── vitest.setup.ts │ ├── shared/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── __tests__/ │ │ │ │ ├── cli.test.ts │ │ │ │ ├── error.test.ts │ │ │ │ └── getSpec.test.ts │ │ │ ├── cli.ts │ │ │ ├── config/ │ │ │ │ ├── engine.ts │ │ │ │ ├── input/ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ ├── input.test.ts │ │ │ │ │ │ └── path.test.ts │ │ │ │ │ ├── input.ts │ │ │ │ │ ├── path.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── logs.ts │ │ │ │ ├── output/ │ │ │ │ │ ├── postprocess.ts │ │ │ │ │ ├── source/ │ │ │ │ │ │ ├── config.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── parser/ │ │ │ │ │ ├── config.ts │ │ │ │ │ ├── filters.ts │ │ │ │ │ ├── patch.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── shared.ts │ │ │ │ └── utils/ │ │ │ │ ├── config.ts │ │ │ │ └── dependencies.ts │ │ │ ├── debug/ │ │ │ │ ├── graph.ts │ │ │ │ ├── index.ts │ │ │ │ └── ir.ts │ │ │ ├── error.ts │ │ │ ├── fs.ts │ │ │ ├── getSpec.ts │ │ │ ├── graph/ │ │ │ │ ├── __tests__/ │ │ │ │ │ └── walk.test.ts │ │ │ │ ├── index.ts │ │ │ │ ├── types/ │ │ │ │ │ ├── graph.ts │ │ │ │ │ └── walk.ts │ │ │ │ └── walk.ts │ │ │ ├── index.ts │ │ │ ├── ir/ │ │ │ │ ├── __tests__/ │ │ │ │ │ ├── graph.test.ts │ │ │ │ │ ├── mediaType.test.ts │ │ │ │ │ ├── pagination.test.ts │ │ │ │ │ └── schema.test.ts │ │ │ │ ├── context.ts │ │ │ │ ├── graph.ts │ │ │ │ ├── intents.ts │ │ │ │ ├── mediaType.ts │ │ │ │ ├── operation.ts │ │ │ │ ├── pagination.ts │ │ │ │ ├── parameter.ts │ │ │ │ ├── schema-processor.ts │ │ │ │ ├── schema-walker.ts │ │ │ │ ├── schema.ts │ │ │ │ ├── types.ts │ │ │ │ └── utils.ts │ │ │ ├── openApi/ │ │ │ │ ├── 2.0.x/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── parser/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── operation.test.ts │ │ │ │ │ │ │ ├── server.test.ts │ │ │ │ │ │ │ └── validate.test.ts │ │ │ │ │ │ ├── filter.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── mediaType.ts │ │ │ │ │ │ ├── operation.ts │ │ │ │ │ │ ├── pagination.ts │ │ │ │ │ │ ├── parameter.ts │ │ │ │ │ │ ├── schema.ts │ │ │ │ │ │ ├── server.ts │ │ │ │ │ │ └── validate.ts │ │ │ │ │ └── types/ │ │ │ │ │ ├── json-schema-draft-4.ts │ │ │ │ │ ├── openapi-spec-extensions.ts │ │ │ │ │ └── spec.ts │ │ │ │ ├── 3.0.x/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── parser/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── operation.test.ts │ │ │ │ │ │ │ └── validate.test.ts │ │ │ │ │ │ ├── filter.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── mediaType.ts │ │ │ │ │ │ ├── operation.ts │ │ │ │ │ │ ├── pagination.ts │ │ │ │ │ │ ├── parameter.ts │ │ │ │ │ │ ├── requestBody.ts │ │ │ │ │ │ ├── schema.ts │ │ │ │ │ │ ├── server.ts │ │ │ │ │ │ └── validate.ts │ │ │ │ │ └── types/ │ │ │ │ │ └── spec.ts │ │ │ │ ├── 3.1.x/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── parser/ │ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ │ ├── operation.test.ts │ │ │ │ │ │ │ └── validate.test.ts │ │ │ │ │ │ ├── filter.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── mediaType.ts │ │ │ │ │ │ ├── operation.ts │ │ │ │ │ │ ├── pagination.ts │ │ │ │ │ │ ├── parameter.ts │ │ │ │ │ │ ├── requestBody.ts │ │ │ │ │ │ ├── schema.ts │ │ │ │ │ │ ├── server.ts │ │ │ │ │ │ ├── validate.ts │ │ │ │ │ │ └── webhook.ts │ │ │ │ │ └── types/ │ │ │ │ │ ├── json-schema-draft-2020-12.ts │ │ │ │ │ ├── spec-extensions.ts │ │ │ │ │ └── spec.ts │ │ │ │ ├── __tests__/ │ │ │ │ │ ├── index.test.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── index.ts │ │ │ │ ├── shared/ │ │ │ │ │ ├── graph/ │ │ │ │ │ │ └── meta.ts │ │ │ │ │ ├── locations/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── operation.ts │ │ │ │ │ ├── transforms/ │ │ │ │ │ │ ├── enums.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── propertiesRequiredByDefault.ts │ │ │ │ │ │ ├── readWrite.ts │ │ │ │ │ │ ├── schemas.ts │ │ │ │ │ │ └── utils.ts │ │ │ │ │ ├── types/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── openapi-spec-extensions.ts │ │ │ │ │ │ ├── schema.ts │ │ │ │ │ │ └── state.ts │ │ │ │ │ └── utils/ │ │ │ │ │ ├── __tests__/ │ │ │ │ │ │ ├── deepEqual.test.ts │ │ │ │ │ │ ├── graph.test.ts │ │ │ │ │ │ ├── operation.test.ts │ │ │ │ │ │ ├── patch.test.ts │ │ │ │ │ │ └── sanitize.test.ts │ │ │ │ │ ├── deepEqual.ts │ │ │ │ │ ├── discriminator.ts │ │ │ │ │ ├── filter.ts │ │ │ │ │ ├── graph.ts │ │ │ │ │ ├── operation.ts │ │ │ │ │ ├── parameter.ts │ │ │ │ │ ├── patch.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ ├── schemaChildRelationships.ts │ │ │ │ │ ├── transforms.ts │ │ │ │ │ └── validator.ts │ │ │ │ └── types.ts │ │ │ ├── parser/ │ │ │ │ └── hooks.ts │ │ │ ├── plugins/ │ │ │ │ ├── shared/ │ │ │ │ │ ├── types/ │ │ │ │ │ │ ├── instance.ts │ │ │ │ │ │ └── schema.ts │ │ │ │ │ └── utils/ │ │ │ │ │ ├── config.ts │ │ │ │ │ └── instance.ts │ │ │ │ ├── symbol.ts │ │ │ │ └── types.ts │ │ │ ├── tsConfig.ts │ │ │ ├── types/ │ │ │ │ ├── logs.ts │ │ │ │ └── watch.ts │ │ │ └── utils/ │ │ │ ├── __tests__/ │ │ │ │ ├── minHeap.test.ts │ │ │ │ ├── path.test.ts │ │ │ │ ├── ref.test.ts │ │ │ │ └── url.test.ts │ │ │ ├── escape.ts │ │ │ ├── exports.ts │ │ │ ├── header.ts │ │ │ ├── input/ │ │ │ │ ├── __tests__/ │ │ │ │ │ ├── readme.test.ts │ │ │ │ │ └── scalar.test.ts │ │ │ │ ├── heyApi.ts │ │ │ │ ├── index.ts │ │ │ │ ├── readme.ts │ │ │ │ └── scalar.ts │ │ │ ├── minHeap.ts │ │ │ ├── naming/ │ │ │ │ ├── __tests__/ │ │ │ │ │ └── naming.test.ts │ │ │ │ ├── naming.ts │ │ │ │ └── types.ts │ │ │ ├── path.ts │ │ │ ├── ref.ts │ │ │ └── url.ts │ │ ├── tsconfig.json │ │ ├── tsdown.config.ts │ │ └── turbo.json │ ├── types/ │ │ ├── CHANGELOG.md │ │ ├── package.json │ │ ├── src/ │ │ │ └── index.ts │ │ └── tsconfig.json │ └── vite-plugin/ │ ├── .gitignore │ ├── CHANGELOG.md │ ├── LICENSE.md │ ├── README.md │ ├── package.json │ ├── src/ │ │ └── index.ts │ ├── tsconfig.base.json │ ├── tsconfig.json │ └── tsdown.config.ts ├── patches/ │ └── vitepress.patch ├── pnpm-workspace.yaml ├── pyproject.toml ├── renovate.json ├── scripts/ │ ├── examples-check.sh │ ├── examples-generate.sh │ ├── publish-preview-packages.sh │ └── update-contributors.sh ├── specs/ │ ├── 2.0.x/ │ │ ├── additional-properties-false.json │ │ ├── additional-properties-true.json │ │ ├── array-items-all-of.yaml │ │ ├── body-response-text-plain.yaml │ │ ├── enum-names-values.json │ │ ├── exclude-deprecated.yaml │ │ ├── external-shared.json │ │ ├── external.yaml │ │ ├── form-data.json │ │ ├── full.yaml │ │ ├── invalid/ │ │ │ └── operationId-unique.yaml │ │ ├── ref-deep.yaml │ │ ├── schema-unknown.yaml │ │ ├── sdk-instance.yaml │ │ ├── sdk-nested-classes.yaml │ │ ├── security-api-key.yaml │ │ ├── security-basic.json │ │ ├── security-oauth2.yaml │ │ ├── servers-base-path.yaml │ │ ├── servers-host.yaml │ │ ├── servers.yaml │ │ ├── transforms-read-write.yaml │ │ ├── transforms-schemas-name.yaml │ │ └── type-format.yaml │ ├── 3.0.x/ │ │ ├── additional-properties-false.json │ │ ├── additional-properties-true.json │ │ ├── additional-properties-undefined.json │ │ ├── array-items-all-of.yaml │ │ ├── array-items-one-of-length-1.yaml │ │ ├── array-nested-one-of.yaml │ │ ├── body-binary-format.yaml │ │ ├── body-response-text-plain.yaml │ │ ├── case.yaml │ │ ├── circular.yaml │ │ ├── components-request-bodies.json │ │ ├── content-binary.json │ │ ├── content-types.yaml │ │ ├── discriminator-all-of.yaml │ │ ├── discriminator-allof-inline.json │ │ ├── discriminator-allof-nested.json │ │ ├── discriminator-any-of.yaml │ │ ├── discriminator-mapped-many.yaml │ │ ├── discriminator-non-string.yaml │ │ ├── discriminator-object-self-mapped.json │ │ ├── discriminator-one-of.yaml │ │ ├── dutchie.json │ │ ├── enum-escape.json │ │ ├── enum-inline.json │ │ ├── enum-names-values.json │ │ ├── enum-null.json │ │ ├── exclude-deprecated.yaml │ │ ├── external-shared.json │ │ ├── external.yaml │ │ ├── full.yaml │ │ ├── internal-name-conflict.json │ │ ├── invalid/ │ │ │ ├── operationId-unique.yaml │ │ │ ├── servers-array.yaml │ │ │ ├── servers-entry.yaml │ │ │ └── servers-required.yaml │ │ ├── operation-204.json │ │ ├── orpc.yaml │ │ ├── parameter-explode-false.json │ │ ├── ref-deep.yaml │ │ ├── ref-duplicate-url.yaml │ │ ├── sdk-instance.yaml │ │ ├── sdk-method-class-conflict.yaml │ │ ├── sdk-nested-classes.yaml │ │ ├── security-api-key.yaml │ │ ├── security-http-bearer.json │ │ ├── security-oauth2.yaml │ │ ├── security-open-id-connect.yaml │ │ ├── servers.yaml │ │ ├── transformers-all-of.yaml │ │ ├── transformers-allof-response-wrapper.json │ │ ├── transformers-any-of-null.json │ │ ├── transformers-array.json │ │ ├── transformers-recursive.json │ │ ├── transforms-read-write.yaml │ │ ├── transforms-schemas-name-collision.yaml │ │ ├── transforms-schemas-name.yaml │ │ ├── type-format.yaml │ │ ├── type-invalid.json │ │ └── validators.json │ ├── 3.1.x/ │ │ ├── additional-properties-false.json │ │ ├── additional-properties-true.json │ │ ├── additional-properties-undefined.json │ │ ├── additional-properties.yaml │ │ ├── array-items-all-of.yaml │ │ ├── array-items-one-of-length-1.yaml │ │ ├── array-nested-one-of.yaml │ │ ├── body-nested-array.yaml │ │ ├── body-response-text-plain.yaml │ │ ├── case.yaml │ │ ├── components-request-bodies.json │ │ ├── const-values.yaml │ │ ├── const.json │ │ ├── content-binary.json │ │ ├── content-media-type.yaml │ │ ├── content-types.yaml │ │ ├── defaults-with-ref-and-anyof.json │ │ ├── discriminator-all-of.yaml │ │ ├── discriminator-allof-inline.json │ │ ├── discriminator-allof-nested.json │ │ ├── discriminator-any-of.yaml │ │ ├── discriminator-mapped-many.yaml │ │ ├── discriminator-non-string.yaml │ │ ├── discriminator-object-self-mapped.json │ │ ├── discriminator-one-of-read-write.yaml │ │ ├── discriminator-one-of.yaml │ │ ├── duplicate-null.json │ │ ├── enum-escape.json │ │ ├── enum-inline.yaml │ │ ├── enum-names-values.yaml │ │ ├── enum-null.json │ │ ├── exclude-deprecated.yaml │ │ ├── external-shared.json │ │ ├── external.yaml │ │ ├── formats.yaml │ │ ├── full.yaml │ │ ├── headers.yaml │ │ ├── integer-formats.yaml │ │ ├── internal-name-conflict.json │ │ ├── invalid/ │ │ │ ├── operationId-unique.yaml │ │ │ ├── servers-array.yaml │ │ │ ├── servers-entry.yaml │ │ │ └── servers-required.yaml │ │ ├── min-max-constraints.yaml │ │ ├── negative-property-names.json │ │ ├── object-properties-all-of.json │ │ ├── object-properties-any-of.json │ │ ├── object-properties-one-of.json │ │ ├── object-property-names.yaml │ │ ├── openai.yaml │ │ ├── opencode.yaml │ │ ├── operation-204.json │ │ ├── orpc.yaml │ │ ├── pagination-ref.yaml │ │ ├── parameter-explode-false.json │ │ ├── parameter-tuple.json │ │ ├── parser-filters.yaml │ │ ├── pattern-properties.json │ │ ├── ref-deep.yaml │ │ ├── ref-type.json │ │ ├── required-all-of-ref.json │ │ ├── required-any-of-ref.json │ │ ├── required-one-of-ref.json │ │ ├── schema-const.yaml │ │ ├── sdk-instance.yaml │ │ ├── sdk-nested-classes.yaml │ │ ├── sdk-nested-conflict.yaml │ │ ├── sdk-signatures.yaml │ │ ├── security-api-key.yaml │ │ ├── security-http-bearer.json │ │ ├── security-oauth2.yaml │ │ ├── security-open-id-connect.yaml │ │ ├── servers.yaml │ │ ├── sse-post.yaml │ │ ├── string-with-format.yaml │ │ ├── string-with-guid-format.yaml │ │ ├── time-format.yaml │ │ ├── transformers-all-of.yaml │ │ ├── transformers-allof-response-wrapper.json │ │ ├── transformers-any-of-null.json │ │ ├── transformers-array.json │ │ ├── transformers-one-of-discriminated.yaml │ │ ├── transformers-recursive.json │ │ ├── transformers.json │ │ ├── transforms-read-write-nested.yaml │ │ ├── transforms-read-write-response.yaml │ │ ├── transforms-read-write-unevaluated.yaml │ │ ├── transforms-read-write.yaml │ │ ├── transforms-schemas-name.yaml │ │ ├── type-format.yaml │ │ ├── type-invalid.json │ │ ├── union-types.json │ │ ├── validators-bigint-min-max.json │ │ ├── validators-circular-ref-2.yaml │ │ ├── validators-circular-ref.json │ │ ├── validators-string-constraints-union.json │ │ ├── validators-union-merge.json │ │ ├── validators.yaml │ │ └── zoom-video-sdk.json │ └── json-schema-ref-parser/ │ ├── ResolutionStep.v1_0_1.yaml │ ├── circular-ref-with-description.json │ ├── external-with-siblings.json │ ├── main-with-external-siblings.json │ ├── multiple-refs.json │ ├── openapi-paths-ref.json │ ├── path-parameter.json │ ├── redfish-like.yaml │ ├── sibling-schema-collision-other.json │ ├── sibling-schema-collision-root.json │ ├── sibling-schema-collision-versioned.json │ ├── sibling-schema-collision-wrapper.json │ ├── sibling-schema-direct-root.json │ ├── sibling-schema-extended-root.json │ ├── sibling-schema-extended-wrapper.json │ ├── sibling-schema-multi-root.json │ ├── sibling-schema-multi-versioned.json │ ├── sibling-schema-multi-wrapper.json │ ├── sibling-schema-root.json │ ├── sibling-schema-versioned.json │ ├── sibling-schema-wrapper.json │ └── test-siblings.yaml ├── tsconfig.base.json ├── tsconfig.json ├── turbo.json ├── vercel.json └── vitest.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .changeset/README.md ================================================ # Changesets Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) ================================================ FILE: .changeset/changelog.js ================================================ import { getInfo, getInfoFromPullRequest } from '@changesets/get-github-info'; /** * @returns {string} */ function getRepo() { return 'hey-api/openapi-ts'; } /** @type {import("@changesets/types").ChangelogFunctions} */ export default { getDependencyReleaseLine: async (_, dependenciesUpdated) => { if (!dependenciesUpdated.length) { return ''; } const list = dependenciesUpdated.map( (dependency) => ` - ${dependency.name}@${dependency.newVersion}`, ); return ['### Updated Dependencies:', ...list].join('\n'); }, getReleaseLine: async (changeset) => { const repo = getRepo(); /** @type number | undefined */ let prFromSummary; /** @type string | undefined */ let commitFromSummary; /** @type string[] */ const usersFromSummary = []; // Remove PR, commit, author/user lines from summary const replacedChangelog = changeset.summary .replace(/^\s*(?:pr|pull|pull\s+request):\s*#?(\d+)/im, (_, pr) => { const num = Number(pr); if (!Number.isNaN(num)) { prFromSummary = num; } return ''; }) .replace(/^\s*commit:\s*([^\s]+)/im, (_, commit) => { commitFromSummary = commit; return ''; }) .replace(/^\s*(?:author|user):\s*@?([^\s]+)/gim, (_, user) => { usersFromSummary.push(user); return ''; }) .trim(); const links = await (async () => { if (prFromSummary !== undefined) { let { links } = await getInfoFromPullRequest({ pull: prFromSummary, repo, }); if (commitFromSummary) { const shortCommitId = commitFromSummary.slice(0, 7); links = { ...links, commit: `[\`${shortCommitId}\`](https://github.com/${repo}/commit/${commitFromSummary})`, }; } return links; } const commitToFetchFrom = commitFromSummary || changeset.commit; if (commitToFetchFrom) { let { links } = await getInfo({ commit: commitToFetchFrom, repo }); const shortCommitId = commitToFetchFrom.slice(0, 7); links = { ...links, commit: `[\`${shortCommitId}\`](https://github.com/${repo}/commit/${commitToFetchFrom})`, }; return links; } return { commit: null, pull: null, user: null, }; })(); const users = usersFromSummary.length ? usersFromSummary .map((userFromSummary) => `[@${userFromSummary}](https://github.com/${userFromSummary})`) .join(', ') : links.user; const metadata = [ links.pull === null ? '' : ` (${links.pull})`, links.commit === null ? '' : ` (${links.commit})`, users === null ? '' : ` by ${users}`, ].join(''); // Split summary into first line and the rest const [firstLine, ...rest] = replacedChangelog.split('\n'); const restSummary = rest.join('\n').trim(); // No code block conversion: preserve original triple backtick code blocks and indentation let releaseLine = `\n- ${firstLine}${metadata}`; if (restSummary) { releaseLine += '\n\n' + restSummary; } return releaseLine; }, }; ================================================ FILE: .changeset/config.json ================================================ { "$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json", "access": "public", "baseBranch": "main", "changelog": "./changelog.js", "commit": false, "fixed": [], "ignore": [], "linked": [], "updateInternalDependencies": "minor", "___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": { "onlyUpdatePeerDependentsWhenOutOfRange": true } } ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf indent_size = 2 indent_style = space insert_final_newline = true trim_trailing_whitespace = true ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf bun.lockb linguist-generated=true package-lock.json linguist-generated=true pnpm-lock.yaml linguist-generated=true yarn.lock linguist-generated=true ================================================ FILE: .github/FUNDING.yml ================================================ github: - hey-api ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.yml ================================================ name: Bug report description: Report an issue with the project. labels: - bug 🔥 body: - type: markdown attributes: value: | Thanks for taking the time to fill out this bug report! Please do your best to fill out as much information as possible. - type: textarea id: description attributes: label: Description description: Please check if there is an existing bug report before creating a new issue. If you intend to submit a pull request to fix this issue, let us know in the description. placeholder: Bug description validations: required: true - type: textarea id: config attributes: label: Reproducible example or configuration description: Please provide a reproducible StackBlitz example, your configuration file, or CLI command used to recreate the issue. placeholder: https://stackblitz.com/edit/hey-api-client-fetch-example value: https://stackblitz.com/edit/hey-api-client-fetch-example - type: textarea id: openapi-spec attributes: label: OpenAPI specification (optional) description: Minimal OpenAPI specification needed to recreate the issue. placeholder: OpenAPI Specification - type: textarea id: system-info attributes: label: System information (optional) description: Any additional relevant system information. This may include OS, browser, NPM version, Node.js version, etc. placeholder: System information ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.yml ================================================ name: Feature Request description: Suggest a new feature for the project. labels: - feature 🚀 body: - type: markdown attributes: value: | Thanks for taking the time to request a new feature! Please ensure your feature request has enough information so maintainers can decide if it will be worked on. - type: textarea id: description attributes: label: Description description: Please provide a clear and concise description of the proposed feature. The more information you can provide, the better. placeholder: Feature description validations: required: true ================================================ FILE: .github/copilot-instructions.md ================================================ # Hey API OpenAPI TypeScript Codegen OpenAPI TypeScript is a CLI tool and library for generating TypeScript clients, SDKs, validators, and schemas from OpenAPI specifications. This is a monorepo built with pnpm workspaces, Turbo build orchestration, and TypeScript. **ALWAYS reference these instructions first and fallback to search or bash commands only when you encounter unexpected information that does not match the info here.** ## Working Effectively ### Prerequisites and Setup - Install Node.js (see `.nvmrc` for recommended version) - Install pnpm globally: `npm install -g pnpm@10.15.1` - Clone the repository and run setup commands ### Bootstrap, Build, and Test ```bash # Install dependencies (takes ~1m 20s) pnpm install # Build packages only (NEVER CANCEL - takes ~2m 15s - set timeout to 180+ seconds) pnpm build --filter="@hey-api/**" # Build all including examples (NEVER CANCEL - takes ~5+ minutes - set timeout to 360+ seconds) pnpm build # Run tests (takes ~1m 5s - set timeout to 120+ seconds) # NOTE: Some network-dependent tests may fail in sandboxed environments pnpm test # Run linting (takes ~35s) pnpm lint # Run type checking (NEVER CANCEL - takes ~1m 20s - set timeout to 120+ seconds) pnpm typecheck # Format code (takes ~35s) pnpm format ``` ### Development Workflow ```bash # Start development mode for main package (watches for changes) pnpm --filter @hey-api/openapi-ts dev # Start development server for examples (e.g., fetch example) pnpm --filter @example/openapi-ts-fetch dev # Server starts on http://localhost:5173/ # Run CLI tool directly node packages/openapi-ts/dist/run.js --help # or after building npx @hey-api/openapi-ts --help ``` ## Build and Test Details ### **CRITICAL BUILD TIMING** - **NEVER CANCEL BUILD COMMANDS** - They may take 2-5+ minutes - `pnpm build --filter="@hey-api/**"`: ~2m 15s (packages only) - `pnpm build`: ~5+ minutes (includes docs and examples) - `pnpm install`: ~1m 20s - `pnpm test`: ~1m 5s - `pnpm typecheck`: ~1m 20s - `pnpm lint`: ~35s - `pnpm format`: ~35s ### Build Issues and Workarounds - **Docs build may fail** due to pnpm version mismatch in VitePress - this is expected in some environments - Use `pnpm build --filter="@hey-api/**"` to build packages without docs - **Some tests may fail** in sandboxed environments due to network restrictions (OpenAPI spec downloads) - **Generated test files** in `packages/openapi-ts-tests/` contain auto-generated snapshots that may have linting warnings - this is expected - **Linting issues** in `.gen/snapshots/` directories are expected for generated code ## Validation ### Manual Testing Scenarios After making changes, ALWAYS validate with these scenarios: 1. **CLI Functionality Test**: ```bash # Test CLI help node packages/openapi-ts/dist/run.js --help # Test CLI version node packages/openapi-ts/dist/run.js --version # Test basic code generation with a simple OpenAPI spec # Create a minimal test spec and generate client code node packages/openapi-ts/dist/run.js -i path/to/spec.json -o ./test-output --plugins "@hey-api/client-fetch" "@hey-api/typescript" ``` 2. **Example Application Test**: ```bash # Start fetch example and verify it loads pnpm --filter @example/openapi-ts-fetch dev # Should start on http://localhost:5173/ ``` 3. **Development Mode Test**: ```bash # Start dev mode and make a small change to verify rebuilding pnpm --filter @hey-api/openapi-ts dev ``` ### Pre-commit Validation ALWAYS run these commands before committing or the CI will fail: ```bash # Use lint:fix to auto-fix issues (some warnings in generated test files are expected) pnpm lint:fix # Run typecheck (can target specific packages with --filter) pnpm typecheck # Run tests (some network tests may fail in sandboxed environments) pnpm test ``` **NOTE**: Some linting warnings in generated test snapshot files (`.gen/snapshots/`) are expected and should be ignored. The `lint:fix` command will resolve actual source code issues. ## Repository Structure ### Key Packages - `packages/openapi-ts/` - Main CLI tool and library - `packages/codegen-core/` - Core code generation utilities - `packages/custom-client/` - Custom HTTP client implementations - `packages/nuxt/` - Nuxt.js integration - `packages/vite-plugin/` - Vite plugin ### Examples - `examples/openapi-ts-fetch/` - Fetch client example (React + Vite) - `examples/openapi-ts-angular/` - Angular client example - `examples/openapi-ts-tanstack-react-query/` - TanStack React Query integration - `examples/openapi-ts-vue/` - Vue.js integration - Plus many more framework-specific examples ### Configuration Files - `pnpm-workspace.yaml` - Workspace configuration - `turbo.json` - Turbo build configuration - `package.json` - Root package with workspace scripts - `.nvmrc` - Node.js version specification ## Common Tasks ### Working with the Main Package ```bash # Install deps for main package pnpm --filter @hey-api/openapi-ts install # Build main package only pnpm --filter @hey-api/openapi-ts build # Test main package only pnpm --filter @hey-api/openapi-ts test # Start dev mode for main package pnpm --filter @hey-api/openapi-ts dev ``` ### Working with Examples ```bash # List all example packages ls examples/ # Run specific example pnpm --filter @example/openapi-ts-fetch dev # Build all examples pnpm build --filter="@example/**" ``` ### Debugging and Troubleshooting - Check `turbo.json` for task dependencies and configuration - Use `pnpm list` to see installed packages - Use `pnpm why ` to understand dependency chains - Check individual package `package.json` files for available scripts ## CI/CD Pipeline The repository uses GitHub Actions (`.github/workflows/ci.yml`): - Tests on multiple Node.js versions - Tests on multiple OS (macOS, Ubuntu, Windows) - Runs build, lint, typecheck, and test commands - Publishes preview packages on PRs ## Performance Expectations - **Cold install**: ~1m 20s - **Cold build**: ~2-5m depending on scope - **Incremental builds**: ~30s in dev mode - **Test suite**: ~1m 5s - **Linting**: ~35s - **Type checking**: ~1m 20s Remember: This is a complex monorepo with many dependencies. Be patient with build times and always use appropriate timeouts for long-running commands. ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: push: branches: - main pull_request: workflow_dispatch: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: setup: name: Setup runs-on: ubuntu-latest outputs: node-version: ${{ steps.nvmrc.outputs.node-version }} steps: - uses: actions/checkout@v6.0.2 - id: nvmrc run: echo "node-version=$(cat .nvmrc)" >> $GITHUB_OUTPUT ci: name: Build, Lint, Test needs: setup runs-on: ${{ matrix.os }} env: TURBO_TEAM: ${{ secrets.TURBO_TEAM }} TURBO_TELEMETRY_DISABLED: 1 TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} strategy: matrix: include: # All Node versions on Ubuntu (fast, catches Node issues) - os: ubuntu-latest node-version: '20.19.0' - os: ubuntu-latest node-version: '22.12.0' - os: ubuntu-latest node-version: ${{ needs.setup.outputs.node-version }} is-primary: true # Primary runner for examples/previews # Latest Node on other OSes (catches platform issues) - os: macos-latest node-version: ${{ needs.setup.outputs.node-version }} - os: windows-latest node-version: ${{ needs.setup.outputs.node-version }} steps: - uses: actions/checkout@v6.0.2 with: fetch-depth: 0 - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v6 with: node-version: ${{ matrix.node-version }} cache: pnpm - uses: astral-sh/setup-uv@v7 with: enable-cache: true - name: Install dependencies run: pnpm install --frozen-lockfile - name: Build packages run: pnpm tb "@hey-api/**" - name: Check examples generated code if: matrix.is-primary run: pnpm examples:check - name: Build examples if: matrix.is-primary run: pnpm tb "@example/**" - name: Run linter run: pnpm turbo run lint - name: Run type check run: pnpm ty "!@test/openapi-ts" - name: Run type check (heavy tests) run: pnpm ty "@test/openapi-ts" - name: Run tests run: pnpm test - name: Publish preview packages if: matrix.is-primary && github.event_name == 'pull_request' run: ./scripts/publish-preview-packages.sh env: TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} ================================================ FILE: .github/workflows/contributors.yml ================================================ name: Update Contributors on: schedule: - cron: '0 0 * * *' # Every day at 00:00 UTC workflow_dispatch: jobs: update: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6.0.2 - name: Install dependencies run: sudo apt-get update && sudo apt-get install -y jq curl - name: Run update contributors script env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | chmod +x ./scripts/update-contributors.sh ./scripts/update-contributors.sh - name: Commit and push if updated run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" git add ./docs/partials/contributors-list.md git diff --cached --quiet || git commit -m "chore(docs): update contributors list" git push ================================================ FILE: .github/workflows/coverage.yml ================================================ name: Coverage on: push: branches: - main paths-ignore: - docs/** pull_request: paths-ignore: - docs/** concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: upload: name: Upload runs-on: ubuntu-latest env: TURBO_TEAM: ${{ secrets.TURBO_TEAM }} TURBO_TELEMETRY_DISABLED: 1 TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} steps: - uses: actions/checkout@v6.0.2 - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v6 with: node-version-file: '.nvmrc' cache: pnpm - name: Install dependencies run: pnpm install --frozen-lockfile - name: Run test coverage run: pnpm test:coverage - name: Upload code coverage to codecov.io uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} directory: ./coverage flags: unittests fail_ci_if_error: true ================================================ FILE: .github/workflows/pullfrog.yml ================================================ # PULLFROG ACTION — DO NOT EDIT EXCEPT WHERE INDICATED name: Pullfrog run-name: ${{ inputs.name || github.workflow }} on: workflow_dispatch: inputs: prompt: type: string description: Agent prompt name: type: string description: Run name permissions: id-token: write contents: write pull-requests: write issues: write actions: read checks: read jobs: pullfrog: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v6 with: fetch-depth: 1 - name: Run agent uses: pullfrog/pullfrog@v0 with: prompt: ${{ inputs.prompt }} env: # add any additional keys your agent(s) need # optionally, comment out any you won't use ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }} MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }} DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} ================================================ FILE: .github/workflows/release.yml ================================================ name: Release on: push: branches: - main permissions: contents: write id-token: write issues: write packages: write pull-requests: write concurrency: ${{ github.workflow }}-${{ github.ref }} jobs: release: name: Release runs-on: ubuntu-latest env: TURBO_TEAM: ${{ secrets.TURBO_TEAM }} TURBO_TELEMETRY_DISABLED: 1 TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} steps: - uses: actions/checkout@v6.0.2 - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v6 with: node-version-file: '.nvmrc' cache: pnpm - name: Install Dependencies run: pnpm install --frozen-lockfile - name: Build packages run: pnpm tb "@hey-api/**" - name: Generate GitHub App Token id: app-token uses: actions/create-github-app-token@v3.0.0 with: app-id: ${{ secrets.GIT_APP_CLIENT_ID }} private-key: ${{ secrets.GIT_APP_PRIVATE_KEY }} - name: Create Release Pull Request uses: changesets/action@v1.7.0 with: commit: 'ci: release' publish: pnpm changeset publish title: 'ci: release' version: pnpm changeset version env: GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} NPM_CONFIG_PROVENANCE: true - name: Get current branch run: echo "CURRENT_BRANCH=$(git branch --show-current)" >> $GITHUB_ENV - name: Update lock file if: env.CURRENT_BRANCH == 'changeset-release/main' run: pnpm install --lockfile-only - name: Commit lock file if: env.CURRENT_BRANCH == 'changeset-release/main' uses: stefanzweifel/git-auto-commit-action@v7.1.0 with: branch: ${{ env.CURRENT_BRANCH }} commit_message: 'chore: update lock file' snapshot: name: Snapshot Release runs-on: ubuntu-latest needs: release if: github.ref == 'refs/heads/main' env: TURBO_TEAM: ${{ secrets.TURBO_TEAM }} TURBO_TELEMETRY_DISABLED: 1 TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} steps: - uses: actions/checkout@v6.0.2 - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v6 with: node-version-file: '.nvmrc' cache: pnpm - name: Install Dependencies run: pnpm install --frozen-lockfile - name: Build packages run: pnpm tb "@hey-api/**" - name: Publish snapshot run: | pnpm changeset version --snapshot next pnpm changeset publish --tag next env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} NPM_CONFIG_PROVENANCE: true ================================================ FILE: .gitignore ================================================ .DS_Store .cache .mypy_cache .idea .tmp junit.xml node_modules npm-debug.log* temp yarn-debug.log* yarn-error.log* *.tsbuildinfo *.iml dist coverage .env .venv .next .nuxt .output .svelte-kit .turbo # test files .gen/ dev/gen/ test/generated # debug files openapi-ts-debug-* # error files logs openapi-ts-error-* # But DO NOT ignore generated snapshots! !test/__snapshots__/test/generated !test/__snapshots__/test/generated/** ================================================ FILE: .husky/pre-commit ================================================ pnpm lint-staged ================================================ FILE: .npmrc ================================================ engine-strict=true save-exact=true ================================================ FILE: .nvmrc ================================================ 24.14.0 ================================================ FILE: .oxfmtrc.json ================================================ { "$schema": "./node_modules/oxfmt/configuration_schema.json", "singleQuote": true, "ignorePatterns": [ "**/.tsdown/", "**/dist/", "**/node_modules/", "temp/", "dev/.gen/", "examples/openapi-ts-openai/src/client/**/*.ts", "**/test/generated/", "**/__snapshots__/", "**/.next/", "**/.nuxt/", "**/.output/", "**/.svelte-kit/", "**/.vitepress/cache", "**/.vitepress/dist", "**/.angular" ] } ================================================ FILE: .prettierignore ================================================ **/.changeset/*.md **/node_modules **/templates **/dist **/.next **/.nuxt **/.output **/.svelte-kit **/.vitepress/cache **/.vitepress/dist **/test/generated **/__snapshots__ **/CHANGELOG.md pnpm-lock.yaml ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "dbaeumer.vscode-eslint", "EditorConfig.EditorConfig", "hilleer.yaml-plus-json", "oxc.oxc-vscode", "streetsidesoftware.code-spell-checker", "usernamehw.errorlens" ] } ================================================ FILE: .vscode/launch.json ================================================ { "version": "0.2.0", "configurations": [ { "type": "node", "request": "attach", "name": "Attach", "port": 9229, "skipFiles": ["/**"] }, { "name": "TS: Debug", "type": "node", "request": "launch", "preLaunchTask": "build:openapi-ts", "program": "${workspaceFolder}/packages/openapi-ts/dist/run.mjs", "cwd": "${workspaceFolder}/dev" }, { "name": "Python: Debug", "type": "node", "request": "launch", "preLaunchTask": "build:openapi-python", "program": "${workspaceFolder}/packages/openapi-python/dist/run.mjs", "cwd": "${workspaceFolder}/dev" } ] } ================================================ FILE: .vscode/settings.json ================================================ { "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }, "editor.defaultFormatter": "oxc.oxc-vscode", "editor.quickSuggestions": { "other": "on", "strings": "on" }, "eslint.format.enable": true, "eslint.nodePath": "./node_modules", "eslint.workingDirectories": [{ "pattern": "./packages/*/" }], "oxc.fmt.configPath": ".oxfmtrc.json", "search.exclude": { "**/*-lock.yaml": true, "**/*-lock.json": true, "**/*.log": true, "**/*.map": true, "**/*.mjs": true, "**/*.mts": true, "**/.vitepress/dist": true, "**/dist": true, "**/.mypy_cache": true, "**/__snapshots__": true, "**/coverage": true, "**/openapi-python-tests/**/.gen": true, "**/openapi-ts-tests/**/generated": true, "**/openapi-ts-tests/**/.gen": true, "**/*.tsbuildinfo": true }, "typescript.experimental.useTsgo": true, "typescript.preferences.autoImportFileExcludePatterns": ["dist/**"], "typescript.preferences.autoImportSpecifierExcludeRegexes": ["^(node:)?os$"], "typescript.tsdk": "node_modules/typescript/lib", "vitest.rootConfig": "vitest.config.ts", "[javascript]": { "editor.defaultFormatter": "oxc.oxc-vscode" }, "[typescript]": { "editor.defaultFormatter": "oxc.oxc-vscode" } } ================================================ FILE: .vscode/tasks.json ================================================ { "version": "2.0.0", "tasks": [ { "label": "build:openapi-ts", "type": "shell", "command": "pnpm", "args": ["turbo", "run", "build", "--filter=@hey-api/openapi-ts"], "group": "build", "problemMatcher": ["$tsc"], "presentation": { "reveal": "silent", "close": true } }, { "label": "build:openapi-python", "type": "shell", "command": "pnpm", "args": ["turbo", "run", "build", "--filter=@hey-api/openapi-python"], "group": "build", "problemMatcher": ["$tsc"], "presentation": { "reveal": "silent", "close": true } } ] } ================================================ FILE: CLAUDE.md ================================================ # CLAUDE.md OpenAPI TypeScript is a CLI tool and library for generating TypeScript clients, SDKs, validators, and schemas from OpenAPI specifications. This is a monorepo built with pnpm workspaces, Turbo build orchestration, and TypeScript. ## Quick Reference ```bash pnpm install # Install dependencies pnpm build --filter="@hey-api/**" # Build packages only pnpm build # Build everything (packages + examples + docs) pnpm test # Run all tests pnpm typecheck # Type check all packages pnpm lint # Check formatting (oxfmt) + linting (eslint) pnpm lint:fix # Auto-fix formatting and linting pnpm format # Format with oxfmt ``` ### Shortcuts ```bash pnpm tt -- @hey-api/openapi-ts # Test specific package pnpm tw -- @hey-api/openapi-ts # Test watch specific package pnpm tu -- @hey-api/openapi-ts # Update test snapshots pnpm tb -- @hey-api/openapi-ts # Build specific package pnpm ty -- @hey-api/openapi-ts # Typecheck specific package ``` ### Development ```bash pnpm dev:ts # Watch mode for openapi-ts (runs from dev/) pnpm dev:py # Watch mode for openapi-python (runs from dev/) ``` ## Build Timing **Do not cancel build commands** - they take significant time: - `pnpm install`: ~1m 20s - `pnpm build --filter="@hey-api/**"`: ~2m 15s - `pnpm build` (full): ~5+ minutes - `pnpm test`: ~1m 5s - `pnpm typecheck`: ~1m 20s - `pnpm lint`: ~35s Set timeouts accordingly (180s+ for builds, 120s+ for tests/typecheck). ## Repository Structure ``` packages/ openapi-ts/ # Main CLI tool and library openapi-python/ # Python DSL generation codegen-core/ # Core code generation utilities shared/ # Cross-package utilities (migrating out) types/ # Shared type definitions custom-client/ # Custom HTTP client implementations nuxt/ # Nuxt.js integration vite-plugin/ # Vite plugin config-vite-base/ # Shared Vite base configuration openapi-ts-tests/ # Test utilities and snapshots examples/ # 16+ framework-specific examples docs/ # VitePress documentation site dev/ # Development environment (CLI testing configs) specs/ # OpenAPI test specifications scripts/ # Build and test scripts ``` ## Tooling - **Package manager**: pnpm 10.28.2 (strict engine, exact versions) - **Node**: >=20.19.0 (see .nvmrc for exact version) - **Build**: Turbo 2.8.0 + tsdown + Rollup - **Language**: TypeScript 5.9.3, ESM only - **Formatter**: oxfmt 0.27.0 (single quotes via .oxfmtrc.json) - **Linter**: ESLint 9 flat config with typescript-eslint, simple-import-sort, sort-destructure-keys, typescript-sort-keys - **Tests**: Vitest 3.2.4 - **Pre-commit**: Husky + lint-staged (runs `pnpm format` + `pnpm lint:fix`) - **Python** (for openapi-python): Python >=3.10, mypy, ruff, line length 120 - **Releases**: Changesets ## Code Conventions - ESM modules only (`.mts`/`.mjs` extensions in builds) - UTF-8, LF line endings, 2-space indentation - Single quotes (enforced by oxfmt) - Imports sorted by eslint-plugin-simple-import-sort - Object/interface keys sorted alphabetically - Destructured keys sorted alphabetically ## Refactoring Guidelines When refactoring existing code: - **Preserve all JSDoc comments** - Read the original file first and keep all existing documentation - **Match existing code patterns** - Look at similar files in the codebase for conventions - **Prefer `edit` over `write`** - Making targeted edits preserves comments better than rewriting files - **Check reference implementations** - For plugin work, use Valibot as a reference for proper patterns ## Pre-commit Checklist Run before committing (Husky runs format + lint automatically, but also verify): ```bash pnpm lint:fix # Auto-fix formatting and linting pnpm typecheck # Type check pnpm test # Run tests ``` Some linting warnings in `.gen/snapshots/` directories are expected for generated code. ## Git Conventions - **Branch naming**: `feat/`, `fix/`, `chore/`, `refactor/`, `docs/` prefixes - **Commit messages**: Conventional Commits (`feat:`, `fix:`, `chore:`, `refactor:`, `ci:`, `docs:`) - **Releases**: Changesets-based, auto-publish on merge to main ## Known Issues - Docs build may fail due to pnpm version mismatch in VitePress - use `--filter="@hey-api/**"` to skip - Some tests may fail in sandboxed environments due to network restrictions (OpenAPI spec downloads) - Generated test files in `packages/openapi-ts-tests/` may have expected linting warnings ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at https://github.com/hey-api/openapi-ts. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq ================================================ FILE: LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: __tests__/changelog.test.ts ================================================ import type * as getGitHubInfo from '@changesets/get-github-info'; import parse from '@changesets/parse'; import type { ModCompWithPackage, NewChangesetWithCommit, VersionType } from '@changesets/types'; import { describe, expect, it, vi } from 'vitest'; import changelog from '../.changeset/changelog.js'; type GetGitHubInfo = typeof getGitHubInfo; const data = { commit: 'a085003', pull: 1613, repo: 'hey-api/openapi-ts', user: 'someone', }; vi.mock( '@changesets/get-github-info', (): GetGitHubInfo => ({ async getInfo({ commit, repo }) { const { pull, user } = data; const links = { commit: `[\`${commit}\`](https://github.com/${repo}/commit/${commit})`, pull: `[#${pull}](https://github.com/${repo}/pull/${pull})`, user: `[@${user}](https://github.com/${user})`, }; return { links, pull, user, }; }, async getInfoFromPullRequest({ pull, repo }) { const { commit, user } = data; const links = { commit: `[\`${commit}\`](https://github.com/${repo}/commit/${commit})`, pull: `[#${pull}](https://github.com/${repo}/pull/${pull})`, user: `[@${user}](https://github.com/${user})`, }; return { commit, links, user, }; }, }), ); const getChangeset = ( content: string, commit: string | undefined, ): [NewChangesetWithCommit, VersionType, null | Record] => [ { ...parse( `--- pkg: "minor" --- something ${content} `, ), commit, id: 'some-id', }, 'minor', { repo: data.repo }, ]; describe('changelog', () => { it('formats dependency release lines', async () => { const changesets: NewChangesetWithCommit[] = [ { commit: 'abc123', id: 'fake-id', releases: [], summary: 'update deps', }, ]; const deps: ModCompWithPackage[] = [ { changesets: ['fake-id'], dir: '/fake/path', name: '@hey-api/openapi-ts', newVersion: '0.0.2', oldVersion: '0.0.1', packageJson: { name: '@hey-api/openapi-ts', version: '0.0.1', }, type: 'patch', }, ]; const line = await changelog.getDependencyReleaseLine(changesets, deps, { repo: 'org/repo', }); expect(line).toEqual('### Updated Dependencies:\n - @hey-api/openapi-ts@0.0.2'); }); it('formats regular release lines', async () => { const changeset: NewChangesetWithCommit = { commit: 'abc123', id: 'fake-id', releases: [], summary: 'Fixed bug in parser', }; const line = await changelog.getReleaseLine(changeset, 'patch', { repo: 'org/repo', }); expect(line).toContain('Fixed bug in parser'); expect(line).toContain('abc123'); }); it('with multiple authors', async () => { expect( await changelog.getReleaseLine( ...getChangeset(['author: @one', 'author: @two'].join('\n'), data.commit), ), ).toEqual( `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@one](https://github.com/one), [@two](https://github.com/two)`, ); }); it('places metadata on the first line and preserves markdown code blocks', async () => { const summary = [ 'refactor(config): replace `off` with null to disable options', '', '### Updated `output` options', '', 'We made the `output` configuration more consistent by using `null` to represent disabled options. [This change](https://heyapi.dev/openapi-ts/migrating#updated-output-options) does not affect boolean options.', '', '```js', 'export default {', ' input: "hey-api/backend", // sign up at app.heyapi.dev', ' output: {', ' format: null,', ' lint: null,', ' path: "src/client",', ' tsConfigPath: null,', ' },', '};', '```', ].join('\n'); const changeset = { commit: 'fcdd73b816d74babf47e6a1f46032f5b8ebb4b48', id: 'fake-id', releases: [], summary, }; const line = await changelog.getReleaseLine(changeset, 'minor', { repo: 'hey-api/openapi-ts', }); // Metadata should be on the first line expect(line).toMatch( /^\n- refactor\(config\): replace `off` with null to disable options \(\[#1613\]\(https:\/\/github.com\/hey-api\/openapi-ts\/pull\/1613\)\) \(\[`fcdd73b`\]\(https:\/\/github.com\/hey-api\/openapi-ts\/commit\/fcdd73b816d74babf47e6a1f46032f5b8ebb4b48\)\) by \[@someone\]\(https:\/\/github.com\/someone\)/, ); // Should not contain quadruple backticks expect(line).not.toContain('````'); // Should contain a markdown code block expect(line).toContain('```js\nexport default {'); expect(line).toContain(' input: "hey-api/backend", // sign up at app.heyapi.dev'); expect(line).toContain(' output: {'); expect(line).toContain(' format: null,'); expect(line).toContain(' lint: null,'); expect(line).toContain(' path: "src/client",'); expect(line).toContain(' tsConfigPath: null,'); expect(line).toContain(' },'); expect(line).toContain('};'); expect(line).toContain('```'); }); it('converts multiple code blocks and preserves non-code content', async () => { const summary = [ 'feat: add foo', '', '```js', 'console.log(1);', '```', '', 'Some text.', '', '```ts', 'console.log(2);', '```', ].join('\n'); const changeset = { commit: 'abc123', id: 'fake-id', releases: [], summary, }; const line = await changelog.getReleaseLine(changeset, 'minor', { repo: 'hey-api/openapi-ts', }); expect(line).toContain('```js\nconsole.log(1);\n```'); expect(line).toContain('```ts\nconsole.log(2);\n```'); expect(line).toContain('Some text.'); }); describe.each(['author', 'user'])('override author with %s keyword', (keyword) => { it.each(['with @', 'without @'])('%s', async (kind) => { expect( await changelog.getReleaseLine( ...getChangeset(`${keyword}: ${kind === 'with @' ? '@' : ''}other`, data.commit), ), ).toEqual( `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@other](https://github.com/other)`, ); }); }); describe.each([data.commit, 'wrongcommit', undefined])( 'with commit from changeset of %s', (commitFromChangeset) => { describe.each(['pr', 'pull request', 'pull'])('override pr with %s keyword', (keyword) => { it.each(['with #', 'without #'])('%s', async (kind) => { expect( await changelog.getReleaseLine( ...getChangeset( `${keyword}: ${kind === 'with #' ? '#' : ''}${data.pull}`, commitFromChangeset, ), ), ).toEqual( `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@someone](https://github.com/someone)`, ); }); }); it('override commit with commit keyword', async () => { expect( await changelog.getReleaseLine( ...getChangeset(`commit: ${data.commit}`, commitFromChangeset), ), ).toEqual( `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@someone](https://github.com/someone)`, ); }); }, ); }); ================================================ FILE: dev/graph-hotspots.js ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Load your exported graph const nodes = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'graph.json'), 'utf-8')); // Annotate nodes with children count const annotatedNodes = nodes.map((n) => ({ childrenCount: n.childrenPointers?.length ?? 0, pointer: n.pointer, })); // Sort by childrenCount descending annotatedNodes.sort((a, b) => b.childrenCount - a.childrenCount); // Print top 20 hotspots console.log('Top 20 potential bottleneck nodes:\n'); annotatedNodes.slice(0, 20).forEach((n) => { console.log(`${n.pointer} — children: ${n.childrenCount}`); }); ================================================ FILE: dev/hey-api.ts ================================================ // @ts-ignore import type { CreateClientConfig } from './.gen/typescript/client.gen'; // @ts-ignore export const createClientConfig: CreateClientConfig = (config) => ({ ...config, // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); ================================================ FILE: dev/inputs.ts ================================================ import path from 'node:path'; const specsPath = path.join(__dirname, '..', 'specs'); export const inputs = { circular: path.resolve(specsPath, '3.0.x', 'circular.yaml'), full: path.resolve(specsPath, '3.1.x', 'full.yaml'), local: 'http://localhost:8000/openapi.json', opencode: path.resolve(specsPath, '3.1.x', 'opencode.yaml'), petstore: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', redfish: 'https://raw.githubusercontent.com/DMTF/Redfish-Publications/refs/heads/main/openapi/openapi.yaml', scalar: 'scalar:@scalar/access-service', transformers: path.resolve(specsPath, '3.1.x', 'transformers.json'), validators: path.resolve(specsPath, '3.1.x', 'validators.yaml'), } as const; export type InputKey = keyof typeof inputs; export function getInput(key: InputKey = (process.env.INPUT as InputKey) || 'opencode') { const input = inputs[key] || key; if (!input) { throw new Error(`Unknown input: ${key}. Available: ${Object.keys(inputs).join(', ')}`); } return input; } ================================================ FILE: dev/json-to-dot.js ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const nodes = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'graph.json'), 'utf-8')); // --- Filter nodes for readability --- const threshold = 10; // high-fanout threshold const filteredSet = new Set(); // Include nodes with children > threshold and their immediate children for (const n of nodes) { const childCount = n.childrenPointers?.length ?? 0; if (childCount > threshold) { filteredSet.add(n.pointer); for (const child of n.childrenPointers || []) { filteredSet.add(child); } } } // Filtered nodes list const filteredNodes = nodes.filter((n) => filteredSet.has(n.pointer)); // Start the .dot file let dot = 'digraph OpenAPIGraph {\nrankdir=LR;\nnode [style=filled];\n'; // Add nodes with color based on fanout for (const n of filteredNodes) { const childCount = n.childrenPointers?.length ?? 0; const color = childCount > 50 ? 'red' : childCount > 20 ? 'orange' : 'lightgray'; dot += `"${n.pointer}" [label="${n.pointer}\\n${childCount} children", fillcolor=${color}];\n`; } // Add edges: node -> its children for (const n of filteredNodes) { for (const child of n.childrenPointers || []) { if (filteredSet.has(child)) { dot += `"${n.pointer}" -> "${child}";\n`; } } } dot += '}\n'; // Write to a file fs.writeFileSync(path.resolve(__dirname, 'graph.dot'), dot); console.log('graph.dot created!'); // Instructions: // Render with Graphviz: // dot -Tpng graph.dot -o graph.png // or // dot -Tsvg graph.dot -o graph.svg ================================================ FILE: dev/openapi-python.config.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { parseEnv } from 'node:util'; import { defineConfig } from '@hey-api/openapi-python'; import { getInput } from './inputs'; import { getPreset } from './python/presets'; process.env = { ...process.env, ...parseEnv(fs.readFileSync(path.resolve(__dirname, '.env'), 'utf-8')), }; export default defineConfig(() => [ { input: getInput(), logs: { path: './logs', }, output: { path: path.resolve(__dirname, 'gen', 'python'), }, plugins: getPreset(), }, ]); ================================================ FILE: dev/openapi-ts.config.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { parseEnv } from 'node:util'; import { defineConfig } from '@hey-api/openapi-ts'; import { getInput } from './inputs'; import { getPreset } from './typescript/presets'; process.env = { ...process.env, ...parseEnv(fs.readFileSync(path.resolve(__dirname, '.env'), 'utf-8')), }; export default defineConfig(() => [ { input: getInput(), logs: { path: './logs', }, output: { path: path.resolve(__dirname, 'gen', 'typescript'), }, plugins: getPreset(), }, ]); ================================================ FILE: dev/package.json ================================================ { "name": "@test/playground", "version": "0.0.0", "private": true, "type": "module", "scripts": { "dev": "tsx ./playground.ts" }, "devDependencies": { "@angular/common": "21.1.2", "@angular/core": "21.1.2", "@hey-api/codegen-core": "workspace:*", "@hey-api/openapi-python": "workspace:*", "@hey-api/openapi-ts": "workspace:*", "@opencode-ai/sdk": "1.2.27", "@orpc/contract": "1.13.4", "@pinia/colada": "0.19.1", "@tanstack/angular-query-experimental": "5.90.25", "@tanstack/preact-query": "5.93.0", "@tanstack/react-query": "5.90.21", "@tanstack/solid-query": "5.90.26", "@tanstack/svelte-query": "5.90.2", "@tanstack/vue-query": "5.92.9", "arktype": "2.2.0", "nuxt": "3.21.0", "swr": "2.4.1", "tsx": "4.21.0", "typescript": "5.9.3", "valibot": "1.2.0", "vue": "3.5.25", "zod": "4.3.6" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: dev/playground.py ================================================ # import httpx from gen.python import OpenCode # def log_request(request): # print(request.method, request.url, request.headers, request.content) # client = httpx.Client(event_hooks={"request": [log_request]}) def run(): client = OpenCode() client.tui.publish( body={ "properties": { "message": "Hello from Hey API OpenAPI Python Playground!", "variant": "success", }, "type": "tui.toast.show", }, directory="main", ) run() ================================================ FILE: dev/playground.ts ================================================ import type { DefinePlugin, IR } from '@hey-api/openapi-ts'; // import { createOpencode } from '@opencode-ai/sdk'; import { client } from './gen/typescript/client.gen'; import { OpenCode } from './gen/typescript/sdk.gen'; type MyPluginConfig = { readonly name: 'myplugin' }; type MyPlugin = DefinePlugin; export function f(schema: IR.SchemaObject, plugin: MyPlugin['Instance']) { plugin.context.resolveIrRef(schema.$ref!); } export const handler: MyPlugin['Handler'] = ({ plugin }) => { plugin.forEach('schema', 'operation', (event) => { console.log(event); }); }; async function run() { // const { client, server } = await createOpencode(); // console.log(client, server); client.setConfig({ baseUrl: 'https://api.example.com', }); const sdk = new OpenCode({ client }); sdk.tui.publish({ body: { properties: { message: 'Hello from Hey API OpenAPI TypeScript Playground!', variant: 'success', }, type: 'tui.toast.show', }, directory: 'main', }); } run(); ================================================ FILE: dev/python/presets.ts ================================================ import type { UserConfig } from '@hey-api/openapi-python'; export type PluginConfig = NonNullable[number]>; export const presets = { sdk: () => [ /** SDK */ { name: '@hey-api/python-sdk', operations: { containerName: 'OpenCode', strategy: 'single', }, paramsStructure: 'flat', }, ], validated: () => [ /** SDK + Pydantic validation */ { name: '@hey-api/python-sdk', paramsStructure: 'flat', }, 'pydantic', ], } as const satisfies Record ReadonlyArray>; export type PresetKey = keyof typeof presets; export function getPreset(key: PresetKey = (process.env.PRESET as PresetKey) || 'sdk') { const preset = presets[key]; if (!preset) { throw new Error(`Unknown preset: ${key}. Available: ${Object.keys(presets).join(', ')}`); } return preset(); } ================================================ FILE: dev/tsconfig.json ================================================ { "extends": "../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true, "module": "ESNext", "moduleResolution": "bundler", "noEmit": true, "resolveJsonModule": true } } ================================================ FILE: dev/turbo.json ================================================ { "$schema": "../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: dev/typescript/presets.ts ================================================ import type { UserConfig } from '@hey-api/openapi-ts'; export type PluginConfig = NonNullable[number]>; export const presets = { angular: () => [ { httpRequests: 'flat', name: '@angular/common', }, ], full: () => [ /** Full kitchen sink for comprehensive testing */ '@hey-api/typescript', { name: '@hey-api/sdk', paramsStructure: 'flat', }, { name: '@hey-api/transformers', }, { metadata: true, name: 'zod', }, { name: '@tanstack/react-query', queryKeys: { tags: true, }, }, ], rpc: () => [ /** RPC-style SDK with Zod validation */ 'orpc', 'zod', ], sdk: () => [ /** SDK with types */ '@hey-api/typescript', { name: '@hey-api/sdk', operations: { containerName: 'OpenCode', strategy: 'single', }, paramsStructure: 'flat', }, ], tanstack: () => [ /** SDK + TanStack Query */ '@hey-api/typescript', '@hey-api/sdk', { name: '@tanstack/react-query', queryKeys: { tags: true, }, }, ], types: () => [ /** Just types, nothing else */ '@hey-api/typescript', ], validated: () => [ /** SDK + Zod validation */ '@hey-api/typescript', { name: '@hey-api/sdk', validator: 'zod', }, { metadata: true, name: 'valibot', }, { metadata: true, name: 'zod', }, ], } as const satisfies Record ReadonlyArray>; export type PresetKey = keyof typeof presets; export function getPreset(key: PresetKey = (process.env.PRESET as PresetKey) || 'sdk') { const preset = presets[key]; if (!preset) { throw new Error(`Unknown preset: ${key}. Available: ${Object.keys(presets).join(', ')}`); } return preset(); } ================================================ FILE: docs/.contributorsignore ================================================ dependabot-preview[bot] dependabot[bot] github-actions[bot] renovate[bot] Copilot ================================================ FILE: docs/.contributorssince ================================================ 2025-04-20T08:08:34Z ================================================ FILE: docs/.gitignore ================================================ .vitepress/cache .vitepress/dist ================================================ FILE: docs/.vitepress/config/en.ts ================================================ import { defineConfig } from 'vitepress'; export default defineConfig({ description: '🌀 OpenAPI to TypeScript codegen. Production-ready SDKs, Zod schemas, TanStack Query hooks, and 20+ plugins. Used by Vercel, OpenCode, and PayPal.', lang: 'en-US', themeConfig: { editLink: { pattern: 'https://github.com/hey-api/openapi-ts/edit/main/docs/:path', text: 'Edit', }, footer: { message: 'Released under the MIT License.', }, nav: [ { link: 'https://github.com/sponsors/hey-api', text: 'Sponsor Hey API', }, ], outline: { label: 'Table of Contents', level: 2, }, sidebar: [ { items: [ { link: '/openapi-ts/get-started', text: 'Get Started', }, { collapsed: true, items: [ { link: '/openapi-ts/configuration/input', text: 'Input', }, { link: '/openapi-ts/configuration/output', text: 'Output', }, { link: '/openapi-ts/configuration/parser', text: 'Parser', }, ], link: '/openapi-ts/configuration', text: 'Configuration', }, { link: '/openapi-ts/output', text: 'Output', }, ], text: 'Introduction', }, { items: [ { collapsed: true, items: [ { link: '/openapi-ts/plugins/typescript', text: 'TypeScript', }, { link: '/openapi-ts/plugins/sdk', text: 'SDK', }, { link: '/openapi-ts/plugins/transformers', text: 'Transformers', }, { link: '/openapi-ts/plugins/schemas', text: 'Schemas', }, ], link: '/openapi-ts/core', text: 'Core', }, { collapsed: true, items: [ { link: '/openapi-ts/clients/fetch', text: 'Fetch API', }, { link: '/openapi-ts/clients/angular', text: 'Angular', }, { link: '/openapi-ts/clients/axios', text: 'Axios', }, { link: '/openapi-ts/clients/ky', text: 'Ky', }, { link: '/openapi-ts/clients/next-js', text: 'Next.js', }, { link: '/openapi-ts/clients/nuxt', text: 'Nuxt', }, { link: '/openapi-ts/clients/ofetch', text: 'OFetch', }, { link: '/openapi-ts/clients/effect', text: 'Effect soon', }, { link: '/openapi-ts/clients/got', text: 'Got soon', }, ], link: '/openapi-ts/clients', text: 'Clients', }, { collapsed: true, items: [ { link: '/openapi-ts/plugins/valibot', text: 'Valibot', }, { link: '/openapi-ts/plugins/zod', text: 'Zod', }, { link: '/openapi-ts/plugins/ajv', text: 'Ajv soon', }, { link: '/openapi-ts/plugins/arktype', text: 'Arktype soon', }, { link: '/openapi-ts/plugins/joi', text: 'Joi soon', }, { link: '/openapi-ts/plugins/superstruct', text: 'Superstruct soon', }, { link: '/openapi-ts/plugins/typebox', text: 'TypeBox soon', }, { link: '/openapi-ts/plugins/yup', text: 'Yup soon', }, ], link: '/openapi-ts/validators', text: 'Validators', }, { collapsed: true, items: [ { link: '/openapi-ts/plugins/pinia-colada', text: 'Pinia Colada', }, { link: '/openapi-ts/plugins/tanstack-query', text: 'TanStack Query', }, { link: '/openapi-ts/plugins/swr', text: 'SWR soon', }, { link: '/openapi-ts/plugins/zustand', text: 'Zustand soon', }, ], link: '/openapi-ts/state-management', text: 'State Management', }, { collapsed: true, items: [ { link: '/openapi-ts/plugins/chance', text: 'Chance soon', }, { link: '/openapi-ts/plugins/faker', text: 'Faker soon', }, { link: '/openapi-ts/plugins/falso', text: 'Falso soon', }, { link: '/openapi-ts/plugins/msw', text: 'MSW soon', }, { link: '/openapi-ts/plugins/nock', text: 'Nock soon', }, { link: '/openapi-ts/plugins/supertest', text: 'Supertest soon', }, ], link: '/openapi-ts/mocks', text: 'Mocks', }, { collapsed: true, items: [ { link: '/openapi-ts/plugins/angular', text: 'Angular', }, { link: '/openapi-ts/plugins/fastify', text: 'Fastify', }, { link: '/openapi-ts/plugins/nest', text: 'Nest', }, { link: '/openapi-ts/plugins/adonis', text: 'Adonis soon', }, { link: '/openapi-ts/plugins/elysia', text: 'Elysia soon', }, { link: '/openapi-ts/plugins/express', text: 'Express soon', }, { link: '/openapi-ts/plugins/hono', text: 'Hono soon', }, { link: '/openapi-ts/plugins/koa', text: 'Koa soon', }, ], link: '/openapi-ts/web-frameworks', text: 'Web Frameworks', }, { collapsed: true, items: [ { link: '/openapi-ts/plugins/concepts/resolvers', text: 'Resolvers', }, ], text: 'Concepts', }, { collapsed: true, items: [ { link: '/openapi-ts/plugins/custom', text: 'Plugin', }, { link: '/openapi-ts/clients/custom', text: 'Client', }, ], text: 'Custom', }, ], text: 'Plugins', }, { items: [ { link: '/openapi-ts/community/spotlight', text: 'Spotlight', }, { collapsed: true, items: [ { link: '/openapi-ts/community/contributing/building', text: 'Building', }, { link: '/openapi-ts/community/contributing/developing', text: 'Developing', }, { link: '/openapi-ts/community/contributing/testing', text: 'Testing', }, ], link: '/openapi-ts/community/contributing', text: 'Contributing', }, ], text: 'Community', }, { items: [ { link: '/openapi-ts/integrations', text: 'GitHub', }, ], text: 'Integrations', }, { items: [ { link: '/openapi-ts/migrating', text: 'Migrating', }, { link: '/openapi-ts/license', text: 'License', }, { link: 'https://github.com/orgs/hey-api/discussions/1495', text: 'Roadmap', }, ], text: '@hey-api/openapi-ts', }, ], }, title: 'Hey API', }); ================================================ FILE: docs/.vitepress/config/index.ts ================================================ import { defineConfig } from 'vitepress'; import en from './en.js'; import shared from './shared.js'; export default defineConfig({ ...shared, locales: { ...shared.locales, root: { label: 'English', ...en }, }, }); ================================================ FILE: docs/.vitepress/config/scripts/optimize-images.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import type { FormatEnum } from 'sharp'; import sharp from 'sharp'; const allowedImageExtensions = ['.png', '.jpg', '.jpeg', '.webp', '.svg'] as const; const images: ReadonlyArray<{ formats?: ReadonlyArray; sizes: ReadonlyArray<{ formats: ReadonlyArray; width: number; }>; source: string; }> = [ { sizes: [ { formats: ['png'], width: 300, }, { formats: ['png'], width: 640, }, { formats: ['png'], width: 920, }, ], source: 'hero.png', }, { sizes: [ { formats: ['jpeg', 'webp'], width: 480, }, { formats: ['webp'], width: 768, }, { formats: ['png', 'webp'], width: 1200, }, ], source: 'kinde-logo-wordmark.png', }, { sizes: [ { formats: ['jpeg', 'webp'], width: 480, }, { formats: ['webp'], width: 768, }, { formats: ['png', 'webp'], width: 1200, }, ], source: 'kinde-logo-wordmark-dark.png', }, { sizes: [ { formats: ['png'], width: 300, }, ], source: 'logo-astronaut.png', }, { sizes: [ { formats: ['png'], width: 300, }, { formats: ['png'], width: 640, }, { formats: ['png'], width: 1280, }, ], source: 'openapi-ts-hero.png', }, { sizes: [ { formats: ['jpeg', 'webp'], width: 480, }, { formats: ['webp'], width: 768, }, { formats: ['png', 'webp'], width: 1200, }, ], source: 'stainless-logo-wordmark.png', }, ]; const outputDir = 'public/assets/.gen'; if (fs.existsSync(outputDir)) { fs.rmSync(outputDir, { force: true, recursive: true }); } fs.mkdirSync(outputDir, { recursive: true }); export async function processImages() { for (const image of images) { const inputPath = path.join('public', 'assets', 'raw', image.source); const ext = path.extname(image.source).toLowerCase(); const name = path.basename(image.source, ext); if (!allowedImageExtensions.includes(ext as (typeof allowedImageExtensions)[number])) { continue; } for (const imageSize of image.sizes) { const size = typeof imageSize === 'object' ? imageSize.width : imageSize; const formats = typeof imageSize === 'object' ? imageSize.formats || image.formats : image.formats; for (const format of formats) { const outputFileName = `${name}-${size}w.${format}`; const outputPath = path.join(outputDir, outputFileName); let image = sharp(inputPath).resize(size).toFormat(format, { quality: 80, }); if (format === 'jpeg') { image = image.flatten({ background: '#ffffff' }); } await image.toFile(outputPath); } } } } ================================================ FILE: docs/.vitepress/config/shared.ts ================================================ import path from 'node:path'; import { defineConfig, type HeadConfig } from 'vitepress'; import llmstxt from 'vitepress-plugin-llms'; import { processImages } from './scripts/optimize-images.js'; const domain = process.env.SITE_DOMAIN || 'http://localhost:5173'; export default defineConfig({ cleanUrls: true, head: [ [ 'link', { href: '/assets/icons/dark.svg', media: '(prefers-color-scheme: dark)', rel: 'icon', sizes: '16x16', type: 'image/svg', }, ], [ 'link', { href: '/assets/icons/light.svg', media: '(prefers-color-scheme: light)', rel: 'icon', sizes: '16x16', type: 'image/svg', }, ], process.env.NODE_ENV === 'production' && [ 'script', { 'data-website-id': '4dffba2d-03a6-4358-9d90-229038c8575d', defer: '', src: 'https://cloud.umami.is/script.js', }, ], ].filter(Boolean) as Array, lastUpdated: true, sitemap: { hostname: domain, lastmodDateOnly: true, // filter out everything but index and `openapi-ts` pages transformItems: (items) => items.filter((item) => !item.url || item.url.startsWith('openapi-ts')), }, themeConfig: { externalLinkIcon: true, logo: { alt: 'Hey API logo', dark: '/assets/icons/dark.svg', light: '/assets/icons/light.svg', }, search: { options: { apiKey: '2565c35b4ad91c2f8f8ae32cf9bbe899', appId: 'OWEH2O8E50', disableUserPersonalization: false, indexName: 'openapi-ts docs', insights: true, }, provider: 'algolia', }, socialLinks: [ { icon: 'linkedin', link: 'https://linkedin.com/company/heyapi' }, { icon: 'bluesky', link: 'https://bsky.app/profile/heyapi.dev' }, { icon: 'x', link: 'https://x.com/mrlubos' }, { icon: 'github', link: 'https://github.com/hey-api/openapi-ts' }, ], }, transformPageData: (pageData, context) => { pageData.frontmatter.head ??= []; const canonicalUrl = pageData.relativePath .replace(/index\.md$/, '') .replace(/\.md$/, context.siteConfig.cleanUrls ? '' : '.html'); const url = `${domain}/${canonicalUrl}`; const head: Array = pageData.frontmatter.head; head.unshift( ['link', { href: url, rel: 'canonical' }], ['meta', { content: 'website', property: 'og:type' }], ['meta', { content: 'en_US', property: 'og:locale' }], ['meta', { content: 'Hey API', property: 'og:site_name' }], [ 'meta', { content: `${domain}/assets/.gen/openapi-ts-hero-640w.png`, property: 'og:image', }, ], ['meta', { content: url, property: 'og:url' }], [ 'meta', { content: pageData.frontmatter.description || '🌀 OpenAPI to TypeScript codegen. Production-ready SDKs, Zod schemas, TanStack Query hooks, and 20+ plugins. Used by Vercel, OpenCode, and PayPal.', property: 'og:description', }, ], [ 'meta', { content: pageData.frontmatter.title || 'OpenAPI TypeScript', property: 'og:title', }, ], ); }, vite: { plugins: [ { async buildStart() { try { await processImages(); } catch (error) { console.error('❌ Error optimizing images:', error); } }, name: 'generate-images', }, llmstxt({ experimental: { depth: 2, }, }), ], resolve: { alias: [ { find: '@components', replacement: path.resolve(__dirname, '..', 'theme', 'components'), }, { find: '@data', replacement: path.resolve(__dirname, '..', '..', 'data'), }, { find: '@versions', replacement: path.resolve(__dirname, '..', 'theme', 'versions'), }, ], preserveSymlinks: true, }, }, }); ================================================ FILE: docs/.vitepress/theme/components/AuthorsList.vue ================================================ ================================================ FILE: docs/.vitepress/theme/components/Examples.vue ================================================ ================================================ FILE: docs/.vitepress/theme/components/FeatureStatus.vue ================================================ ================================================ FILE: docs/.vitepress/theme/components/Heading.vue ================================================ ================================================ FILE: docs/.vitepress/theme/components/Layout.vue ================================================ ================================================ FILE: docs/.vitepress/theme/components/VersionLabel.vue ================================================ ================================================ FILE: docs/.vitepress/theme/components/VersionSwitcher.vue ================================================ ================================================ FILE: docs/.vitepress/theme/custom.css ================================================ :root { --c-gradient-start: #d486b8; --vp-c-brand-1: #a37ab4; --vp-c-brand-2: #d486b8; --vp-c-brand-3: #a37ab4; --github-mark-fill-color: #24292f; --vp-home-hero-name-color: transparent; --vp-home-hero-name-background: -webkit-linear-gradient( 120deg, var(--c-gradient-start) 30%, var(--vp-c-brand-3) ); } html.dark { --c-gradient-start: #86b9b0; --vp-c-bg: #001b2e; --vp-c-bg-alt: #041421; --vp-c-bg-soft: #041421; --vp-c-brand-1: #b3cde4; --vp-c-brand-2: #b3cde4; --vp-c-brand-3: #537692; --github-mark-fill-color: #fff; --vp-home-hero-image-background-image: linear-gradient( -45deg, var(--vp-c-brand-3) 50%, var(--c-gradient-start) 50% ); --vp-home-hero-image-filter: blur(144px); } html.mac { --vs-background-color: var(--vp-input-switch-bg-color); --vs-border: 1px solid var(--vp-input-border-color); --vs-menu-border: 1px solid var(--vp-input-border-color); --vs-menu-box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; --vs-option-background-color: var(--vp-sidebar-bg-color); --vs-option-disabled-background-color: var(--vp-sidebar-bg-color); --vs-option-focused-background-color: var(--vp-sidebar-bg-color); --vs-option-focused-text-color: var(--vp-c-brand-1); --vs-option-hover-background-color: var(--vp-sidebar-bg-color); --vs-option-hover-text-color: var(--vp-c-brand-1); --vs-option-selected-background-color: var(--vp-sidebar-bg-color); --vs-option-selected-text-color: var(--vp-c-brand-1); --vs-option-text-color: var(--vp-c-text-2); --vs-padding-x: 8px; --vs-padding-y: 4px; --vs-padding: var(--vs-padding-y) var(--vs-padding-x); --vs-text-color: var(--vp-c-text-1); --vs-width: auto; } [data-soon] { background-color: var(--vp-button-brand-bg); border-radius: 1em; color: var(--vp-button-brand-text); font-size: 0.6em; padding: 0.05em 0.4em 0.2em; position: relative; text-transform: lowercase; top: -1em; } iframe { background-color: var(--vp-sidebar-bg-color); border: none; margin: 0; } .VPFeatures.VPHomeFeatures > .container { max-width: initial; } .VPFeatures.VPHomeFeatures > .container > .items { gap: 1rem; justify-content: center; margin: 0; padding: 0.2rem 0; } .VPFeatures.VPHomeFeatures > .container > .items > .item { flex-shrink: 0; max-width: 390px; padding: 0; width: 100%; } .authors-list { display: flex; flex-wrap: wrap; font-size: 1rem; gap: 1em; padding: 0 !important; } .authors-list img { border-radius: 50%; display: block; height: 2rem; width: 2rem; } .authors-list a { align-items: center; border: 1px solid transparent; border-radius: 10px; display: flex; column-gap: 0.4em; padding: 0.4em 0.6em; text-decoration: none; transition: border-color ease-out 300ms; } .authors-list h3 { color: var(--vp-c-text-1); font-size: inherit; margin: 0; } .authors-list a::after { display: none !important; } .authors-list li { margin: 0 !important; } h3#demo + iframe, h3#demo + button { margin: 1rem 0 0; } .buttonLink { color: var(--vp-c-brand-1); font-size: 16px; font-weight: 500; text-decoration: underline; text-underline-offset: 2px; transition: color 0.25s, opacity 0.25s; } .buttonLink:hover { color: var(--vp-c-brand-2); } .home-list { text-align: center; } .authors-list li, .home-list li, .sponsors-list li { list-style: none; } .home-list.sponsors-list > ul { justify-content: center; } .home-list > ul { align-items: center; justify-content: center; } .home-list > ul, .sponsors-list > ul { display: flex; flex-direction: column; flex-wrap: wrap; padding: 0; } .home-list > ul:not(:last-child), .sponsors-list > ul:not(:last-child) { padding-bottom: 1rem; } .home-list > h3 { color: var(--vp-c-text-2); display: inline-block; font-size: 0.9rem; margin-top: 2rem; text-transform: uppercase; } .sponsors-list li { align-items: center; border: 1px solid transparent; border-radius: 10px; display: flex; flex-direction: column; row-gap: 0.5rem; justify-content: center; max-width: 240px; padding: 1rem; transition: border-color ease-out 300ms; width: 100%; } .sponsors-list li a:first-of-type { height: 66px; } .sponsors-list li a:first-of-type picture, .sponsors-list li a:first-of-type img { height: 100%; } .sponsors-list li p { margin: 0; font-size: 0.86rem; line-height: 120%; } .sponsors-list li a:last-of-type { font-size: 0.86rem; line-height: 100%; } .sponsors-list > ul.gold { row-gap: 2rem; column-gap: 3rem; } .sponsors-list > ul.gold li { max-width: 240px; } .sponsors-list > ul.silver { row-gap: 2rem; column-gap: 3rem; } .sponsors-list > ul.silver li { max-width: 180px; } .sponsors-list > ul li svg { color: var(--vp-c-text-1) !important; height: 100% !important; } /* Cella */ html.dark .sponsors-list > ul li.cella svg > path:nth-child(2), html.dark .sponsors-list > ul li.cella svg > path:nth-child(3) { filter: invert(); } /* FastAPI */ .sponsors-list > ul li.fastapi svg > g > path { fill: white !important; } html.dark .sponsors-list > ul li.fastapi svg > g > path { fill: var(--vp-button-brand-bg) !important; } /* OpenStatus */ .sponsors-list > ul li.openstatus svg > g > g > path:not(:first-of-type) { fill: white !important; } html.dark .sponsors-list > ul li.openstatus svg > g > g > path:not(:first-of-type) { fill: var(--vp-button-brand-bg) !important; } .sponsors-list > ul.bronze { row-gap: 2rem; column-gap: 1rem; } .sponsors-list > ul.bronze li { max-width: 100px; } .sponsors-list > ul.friends { row-gap: 2rem; column-gap: 1rem; } .sponsors-list > ul.friends li { max-width: 70px; } .sponsors-list li + li { margin-top: 0; } .sponsors-list li > a { align-items: center; display: flex; justify-content: center; text-decoration: none; width: 100%; } html.dark .authors-list li > a, html.dark .sponsors-list li { background-color: var(--vp-button-brand-bg); } .sponsors-list li > :is(.vp-doc a[href*='://'], .vp-doc a[target='_blank'])::after { display: none; } .authors-list li > a:hover, .authors-list li > a:focus, .sponsors-list li:has(> a:hover), .sponsors-list li:has(> a:focus) { border-color: var(--vp-c-brand-1); } /* .sponsors-list-new currently unused, keep in case we want to reuse it again */ .sponsors-list-new > a { border: 1px solid currentColor; color: var(--vp-c-text-2); text-transform: lowercase; } .migration { background-color: var(--vp-c-brand-3); border-radius: 10px; border: 1px solid transparent; color: var(--vp-button-brand-text); column-gap: 3rem; display: flex; flex-direction: column; justify-content: space-between; margin: 0 auto 1rem; max-width: 392px; padding: 1rem; row-gap: 1rem; transition: border-color ease-out 250ms; width: auto; } a.migration:hover, a.migration:focus { border-color: var(--vp-c-brand-1); } .contributors-list ul { margin-bottom: 1.3rem; margin-top: 1.3rem; } .vue-select .control { cursor: pointer; transition: border-color 0.25s; } .vue-select .control:hover { border-color: var(--vp-c-brand-1); } .vue-select .control .indicators-container { padding: 0; } .vue-select .control .value-container.has-value:has(.single-value) { padding-inline-end: 0; } .vue-select .control .indicators-container button.dropdown-icon { height: 100%; padding: var(--vs-padding); width: calc(var(--vs-indicator-icon-size) + var(--vs-padding-x) + var(--vs-padding-x)); } .vue-select .menu { width: fit-content !important; } .vue-select .menu .menu-option { border-left: 2px solid transparent; border-right: 2px solid transparent; white-space: nowrap; transition: background-color 0.25s, border-color 0.25s, color 0.25s, opacity 0.25s; } .vue-select .menu:hover .menu-option.focused:not(:hover) { border-left: 2px solid transparent; } .vue-select .menu .menu-option:hover, .vue-select .menu:not(:hover) .menu-option.focused { border-left: 2px solid var(--vp-c-brand-1); } @media (min-width: 640px) { h1.heading .name { max-width: 600px; } .VPFeatures.VPHomeFeatures > .container > .items { gap: 1rem; padding: 0.4rem 0; } .home-list > ul, .sponsors-list > ul { flex-direction: row; } .contributors-list ul { columns: 2; } } @media (min-width: 892px) { .migration { flex-direction: row; max-width: 798px; } } @media (min-width: 960px) { .VPFeatures.VPHomeFeatures > .container > .items { gap: 1rem; padding: 0.5rem 0; } .VPNavBar.has-sidebar > .wrapper > .container > .title { background-color: var(--vp-sidebar-bg-color); } } footer.VPDocFooter > .edit-info > .last-updated { /* don't render last updated date */ display: none; } .DocSearch-Modal { display: flex; } .DocSearch-Footer { position: initial; } .sr-only { border: 0; clip: rect(0, 0, 0, 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; white-space: nowrap; width: 1px; } .VPNavBarTitle a.title { column-gap: 4px; } .VPImage.logo { margin-right: 0; } .VPNavBarTitle { color: var(--vp-c-text-1); } ================================================ FILE: docs/.vitepress/theme/index.ts ================================================ // eslint-disable-next-line simple-import-sort/imports import type { Theme } from 'vitepress'; import DefaultTheme from 'vitepress/theme'; // custom CSS must be imported after default theme to correctly apply styles import './custom.css'; import Layout from './components/Layout.vue'; export default { Layout, enhanceApp: () => {}, extends: DefaultTheme, } satisfies Theme; ================================================ FILE: docs/.vitepress/theme/versions/AngularVersionSwitcher.vue ================================================ ================================================ FILE: docs/.vitepress/theme/versions/ZodVersionSwitcher.vue ================================================ ================================================ FILE: docs/CHANGELOG.md ================================================ # docs ## 0.10.4 ### Patch Changes - docs: add bigint section to transformers ([#2865](https://github.com/hey-api/openapi-ts/pull/2865)) ([`ba4d9bf`](https://github.com/hey-api/openapi-ts/commit/ba4d9bf603d8c897016fd1775d13e184111ace17)) by [@wn-mitch](https://github.com/wn-mitch) ## 0.10.3 ### Patch Changes - chore: clarify TanStack Query reactivity in Vue ([#2745](https://github.com/hey-api/openapi-ts/pull/2745)) ([`5d06dbd`](https://github.com/hey-api/openapi-ts/commit/5d06dbdf8c2a834ecefdd7305b59572470f45a7e)) by [@9M6](https://github.com/9M6) ## 0.10.2 ### Patch Changes - [#2117](https://github.com/hey-api/openapi-ts/pull/2117) [`a1435b9`](https://github.com/hey-api/openapi-ts/commit/a1435b915a272d9ffa599c194ee52c2a33f77fcd) Thanks [@johnny-mh](https://github.com/johnny-mh)! - docs: add docs for `input.patch` feature ## 0.10.1 ### Patch Changes - [#1774](https://github.com/hey-api/openapi-ts/pull/1774) [`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: announce Hey API platform ## 0.10.0 ### Minor Changes - [#1568](https://github.com/hey-api/openapi-ts/pull/1568) [`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: change the default parser ## 0.9.0 ### Minor Changes - [#1511](https://github.com/hey-api/openapi-ts/pull/1511) [`4e8064d`](https://github.com/hey-api/openapi-ts/commit/4e8064d9a589e14b42d2b1a329e2436f242884da) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add watch mode ## Watch Mode ::: warning Watch mode currently supports only remote files via URL. ::: If your schema changes frequently, you may want to automatically regenerate the output during development. To watch your input file for changes, enable `watch` mode in your configuration or pass the `--watch` flag to the CLI. ### Config ```js export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', watch: true, }; ``` ### CLI ```sh npx @hey-api/openapi-ts \ -c @hey-api/client-fetch \ -i path/to/openapi.json \ -o src/client \ -w ``` ### Patch Changes - [#1496](https://github.com/hey-api/openapi-ts/pull/1496) [`1e418ba`](https://github.com/hey-api/openapi-ts/commit/1e418ba760b9903326ec37009651c32e195e24a9) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: split output section into multiple pages ## 0.8.0 ### Minor Changes - [#1447](https://github.com/hey-api/openapi-ts/pull/1447) [`200821b`](https://github.com/hey-api/openapi-ts/commit/200821b3ceea8ffca7656fe3f6e2ef98b7110a2a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: revert license to MIT ### Patch Changes - [#1430](https://github.com/hey-api/openapi-ts/pull/1430) [`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add validators page ## 0.7.4 ### Patch Changes - [#1420](https://github.com/hey-api/openapi-ts/pull/1420) [`8010dbb`](https://github.com/hey-api/openapi-ts/commit/8010dbb1ab8b91d1d49d5cf16276183764a63ff3) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add buildUrl() method to Axios client page ## 0.7.3 ### Patch Changes - [#1316](https://github.com/hey-api/openapi-ts/pull/1316) [`a79fac8`](https://github.com/hey-api/openapi-ts/commit/a79fac8919ed29eec7195cbd441ffa38b559d63c) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add Plugins page ## 0.7.2 ### Patch Changes - [#1253](https://github.com/hey-api/openapi-ts/pull/1253) [`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update sponsorship links ## 0.7.1 ### Patch Changes - [#1222](https://github.com/hey-api/openapi-ts/pull/1222) [`ceb4363`](https://github.com/hey-api/openapi-ts/commit/ceb4363d52893ebe947e21aac402b868ff2820d4) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add support for @tanstack/angular-query-experimental package ## 0.7.0 ### Minor Changes - [#1201](https://github.com/hey-api/openapi-ts/pull/1201) [`972a93a`](https://github.com/hey-api/openapi-ts/commit/972a93a91a945cc9ead73c08bb0fa9ee120433ba) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: make plugins first-class citizens This release makes plugins first-class citizens. In order to achieve that, the following breaking changes were introduced. ### Removed CLI options The `--types`, `--schemas`, and `--services` CLI options have been removed. You can list which plugins you'd like to use explicitly by passing a list of plugins as `--plugins ` ### Removed `*.export` option Previously, you could explicitly disable export of certain artifacts using the `*.export` option or its shorthand variant. These were both removed. You can now disable export of specific artifacts by manually defining an array of `plugins` and excluding the unwanted plugin. ::: code-group ```js [shorthand] export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', schemas: false, // [!code --] plugins: ['@hey-api/types', '@hey-api/services'], // [!code ++] }; ``` ```js [*.export] export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', schemas: { export: false, // [!code --] }, plugins: ['@hey-api/types', '@hey-api/services'], // [!code ++] }; ``` ::: ### Renamed `schemas.name` option Each plugin definition contains a `name` field. This was conflicting with the `schemas.name` option. As a result, it has been renamed to `nameBuilder`. ```js export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', schemas: { name: (name) => `${name}Schema`, // [!code --] }, plugins: [ // ...other plugins { nameBuilder: (name) => `${name}Schema`, // [!code ++] name: '@hey-api/schemas', }, ], }; ``` ### Removed `services.include` shorthand option Previously, you could use a string value as a shorthand for the `services.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', services: '^MySchema', // [!code --] plugins: [ // ...other plugins { include: '^MySchema', // [!code ++] name: '@hey-api/services', }, ], }; ``` ### Renamed `services.name` option Each plugin definition contains a `name` field. This was conflicting with the `services.name` option. As a result, it has been renamed to `serviceNameBuilder`. ```js export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', services: { name: '{{name}}Service', // [!code --] }, plugins: [ // ...other plugins { serviceNameBuilder: '{{name}}Service', // [!code ++] name: '@hey-api/services', }, ], }; ``` ### Renamed `types.dates` option Previously, you could set `types.dates` to a boolean or a string value, depending on whether you wanted to transform only type strings into dates, or runtime code too. Many people found these options confusing, so they have been simplified to a boolean and extracted into a separate `@hey-api/transformers` plugin. ```js export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', types: { dates: 'types+transform', // [!code --] }, plugins: [ // ...other plugins { dates: true, // [!code ++] name: '@hey-api/transformers', }, ], }; ``` ### Removed `types.include` shorthand option Previously, you could use a string value as a shorthand for the `types.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', types: '^MySchema', // [!code --] plugins: [ // ...other plugins { include: '^MySchema', // [!code ++] name: '@hey-api/types', }, ], }; ``` ### Renamed `types.name` option Each plugin definition contains a `name` field. This was conflicting with the `types.name` option. As a result, it has been renamed to `style`. ```js export default { client: '@hey-api/client-fetch', input: 'path/to/openapi.json', output: 'src/client', types: { name: 'PascalCase', // [!code --] }, plugins: [ // ...other plugins { name: '@hey-api/types', style: 'PascalCase', // [!code ++] }, ], }; ``` ## 0.6.2 ### Patch Changes - [#1162](https://github.com/hey-api/openapi-ts/pull/1162) [`1c85c24`](https://github.com/hey-api/openapi-ts/commit/1c85c24af514e9781aab1960298caa28effef5d3) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add Zod plugin page ## 0.6.1 ### Patch Changes - [#1151](https://github.com/hey-api/openapi-ts/pull/1151) [`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update website domain, add license documentation ## 0.6.0 ### Minor Changes - [#1009](https://github.com/hey-api/openapi-ts/pull/1009) [`c6b044d`](https://github.com/hey-api/openapi-ts/commit/c6b044d0bc9dc54cb0eb58d23438f4e1d050cb38) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: change schemas name pattern, add schemas.name option ## 0.5.11 ### Patch Changes - [#978](https://github.com/hey-api/openapi-ts/pull/978) [`2e051a5`](https://github.com/hey-api/openapi-ts/commit/2e051a596302c2e103dca25951a07b4aae1e9e23) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add basic TanStack Query plugin description ## 0.5.10 ### Patch Changes - [#830](https://github.com/hey-api/openapi-ts/pull/830) [`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: split clients documentation into separate pages - [#830](https://github.com/hey-api/openapi-ts/pull/830) [`323d0a0`](https://github.com/hey-api/openapi-ts/commit/323d0a03c6560f27d0ce5eee1708ee16dc395532) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: remove interceptors page in favour of per-client sections - [#830](https://github.com/hey-api/openapi-ts/pull/830) [`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add v0.52.0 migration ## 0.5.9 ### Patch Changes - [#828](https://github.com/hey-api/openapi-ts/pull/828) [`82a4696`](https://github.com/hey-api/openapi-ts/commit/82a4696b0b209ea2d9147f47f213479e61aed3d7) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add migration guide for v0.51.0 ## 0.5.8 ### Patch Changes - [#613](https://github.com/hey-api/openapi-ts/pull/613) [`b3786dc`](https://github.com/hey-api/openapi-ts/commit/b3786dc6749d8d4ae26bb63322e124663f881741) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add Axios client documentation ## 0.5.7 ### Patch Changes - [#632](https://github.com/hey-api/openapi-ts/pull/632) [`9c16bc7`](https://github.com/hey-api/openapi-ts/commit/9c16bc71cde48c0cb700b7e720a9e2ad56ec5f02) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add output page ## 0.5.6 ### Patch Changes - docs: add fetch client documentation ([#602](https://github.com/hey-api/openapi-ts/pull/602)) - docs: add migration notes for v0.46.0 ([#602](https://github.com/hey-api/openapi-ts/pull/602)) ## 0.5.5 ### Patch Changes - docs: add migration for v0.45.0 ([#569](https://github.com/hey-api/openapi-ts/pull/569)) ## 0.5.4 ### Patch Changes - docs: add format and lint migration for 0.44.0 ([#546](https://github.com/hey-api/openapi-ts/pull/546)) ## 0.5.3 ### Patch Changes - docs: add links to homepage ([#489](https://github.com/hey-api/openapi-ts/pull/489)) - feat: remove enum postfix, use typescript enums in types when generated, export enums from types.gen.ts ([#498](https://github.com/hey-api/openapi-ts/pull/498)) - docs: add examples ([#476](https://github.com/hey-api/openapi-ts/pull/476)) ## 0.5.2 ### Patch Changes - docs: add github action to integrations ([#451](https://github.com/hey-api/openapi-ts/pull/451)) ## 0.5.1 ### Patch Changes - docs: add tanstack-query and http clients sections ([#436](https://github.com/hey-api/openapi-ts/pull/436)) ## 0.5.0 ### Minor Changes - feat: allow choosing naming convention for types ([#402](https://github.com/hey-api/openapi-ts/pull/402)) ## 0.4.0 ### Minor Changes - docs: add integrations ([#394](https://github.com/hey-api/openapi-ts/pull/394)) - feat: rename generated files ([#363](https://github.com/hey-api/openapi-ts/pull/363)) ### Patch Changes - docs: add enums migration ([#358](https://github.com/hey-api/openapi-ts/pull/358)) ## 0.3.0 ### Minor Changes - fix: rename write to dryRun and invert value ([#326](https://github.com/hey-api/openapi-ts/pull/326)) ### Patch Changes - docs: update contributing guidelines ([#347](https://github.com/hey-api/openapi-ts/pull/347)) ## 0.2.2 ### Patch Changes - docs: add migration notes ([#306](https://github.com/hey-api/openapi-ts/pull/306)) ## 0.2.1 ### Patch Changes - fix(config): rename exportSchemas to schemas ([#288](https://github.com/hey-api/openapi-ts/pull/288)) ## 0.2.0 ### Minor Changes - docs: add support for localization of docs ([#251](https://github.com/hey-api/openapi-ts/pull/251)) ### Patch Changes - docs: add logo ([#250](https://github.com/hey-api/openapi-ts/pull/250)) ================================================ FILE: docs/data/coreTeam.js ================================================ export const coreTeam = [ { avatar: 'https://github.com/mrlubos.png', links: [{ icon: 'github', link: 'https://github.com/mrlubos' }], name: 'Lubos', title: 'Hey API', }, ]; ================================================ FILE: docs/data/hallOfFame.js ================================================ export const hallOfFame = [ { avatar: 'https://github.com/ferdikoomen.png', links: [{ icon: 'github', link: 'https://github.com/ferdikoomen' }], name: 'Ferdi Koomen', title: 'OpenAPI TypeScript Codegen', }, { avatar: 'https://github.com/nicolas-chaulet.png', links: [{ icon: 'github', link: 'https://github.com/nicolas-chaulet' }], name: 'Nicolas Chaulet', title: 'Made the Hey API fork', }, { avatar: 'https://github.com/jordanshatford.png', links: [{ icon: 'github', link: 'https://github.com/jordanshatford' }], name: 'Jordan Shatford', title: 'Maintainer and Contributor', }, ]; ================================================ FILE: docs/data/people.ts ================================================ type Person = { github: string; name: string; }; export const dmitriyBrolnickij: Person = { github: 'https://github.com/brolnickij', name: 'Dmitriy Brolnickij', }; export const jacobCohen: Person = { github: 'https://github.com/jacobinu', name: 'Jacob Cohen', }; export const joshHemphill: Person = { github: 'https://github.com/josh-hemphill', name: 'Josh Hemphill', }; export const maxScopp: Person = { github: 'https://github.com/max-scopp', name: 'Max Scopp', }; export const sebastiaanWouters: Person = { github: 'https://github.com/SebastiaanWouters', name: 'Sebastiaan Wouters', }; export const yuriMikhin: Person = { github: 'https://github.com/mikhin', name: 'Yuri Mikhin', }; ================================================ FILE: docs/email-form.md ================================================
### Newsletter
    Subscribe to product updates.
    ================================================ FILE: docs/embed.ts ================================================ import sdk from '@stackblitz/sdk'; // https://api.npmjs.org/versions/@hey-api%2Fopenapi-ts/last-week export const embedProject = (projectId: string) => async (event: Event) => { const container = document.createElement('div'); if (event.target) { const node = event.target as HTMLElement; node.replaceWith(container); } switch (projectId) { case 'hey-api-client-axios-example': return await sdk.embedProjectId(container, projectId, { height: 700, openFile: 'openapi-ts.config.ts,src/client/schemas.gen.ts,src/client/sdk.gen.ts,src/client/types.gen.ts,src/App.tsx', view: 'editor', }); case 'hey-api-client-fetch-example': return await sdk.embedProjectId(container, projectId, { height: 700, openFile: 'openapi-ts.config.ts,src/client/schemas.gen.ts,src/client/sdk.gen.ts,src/client/types.gen.ts,src/App.tsx', view: 'editor', }); case 'hey-api-client-fetch-plugin-fastify-example': return await sdk.embedProjectId(container, projectId, { height: 700, openFile: 'openapi-ts.config.ts,src/client/fastify.gen.ts,src/client/types.gen.ts,src/server.ts', view: 'editor', }); case 'hey-api-client-fetch-plugin-tanstack-react-query-example': return await sdk.embedProjectId(container, projectId, { height: 700, openFile: 'openapi-ts.config.ts,src/client/@tanstack/react-query.gen.ts,src/client/types.gen.ts,src/App.tsx', view: 'editor', }); case 'hey-api-client-fetch-plugin-zod-example': return await sdk.embedProjectId(container, projectId, { height: 700, openFile: 'openapi-ts.config.ts,src/client/zod.gen.ts,src/App.tsx', view: 'editor', }); case 'hey-api-example': return await sdk.embedProjectId(container, projectId, { height: 700, openFile: 'openapi-ts.config.ts,src/client/schemas.gen.ts,src/client/sdk.gen.ts,src/client/types.gen.ts', view: 'editor', }); } }; ================================================ FILE: docs/index.md ================================================ --- layout: home hero: name: OpenAPI to TypeScript in seconds. tagline: Generate production-ready SDKs and validators from your OpenAPI spec. Used by Vercel, OpenCode, and PayPal. actions: - link: /openapi-ts/get-started text: Get Started theme: brand - link: https://stackblitz.com/edit/hey-api-example?file=openapi-ts.config.ts,src%2Fclient%2Fschemas.gen.ts,src%2Fclient%2Fsdk.gen.ts,src%2Fclient%2Ftypes.gen.ts text: View Demo theme: alt - link: https://github.com/orgs/hey-api/discussions/3159 text: Roadmap theme: alt image: alt: Two people looking at the TypeScript logo src: /assets/.gen/hero-920w.png features: - icon: title: OpenAPI to TypeScript details: Generate production-ready TypeScript from any OpenAPI specification. link: /openapi-ts/get-started linkText: Get started - icon: title: Instant SDKs details: Highly customizable SDKs and types with sensible defaults that compile out of the box. link: /openapi-ts/output linkText: See output - icon: title: HTTP Clients details: Pluggable HTTP clients for Fetch API, Angular, Axios, Next.js, Nuxt, and more. link: /openapi-ts/clients linkText: Explore clients - icon: title: Plugin Ecosystem details: Zod, TanStack Query, and 20+ plugins to reduce third-party boilerplate. link: /openapi-ts/core linkText: Explore plugins - icon: 🧩 title: Custom Extensions details: Build custom plugins for proprietary or advanced use cases. link: /openapi-ts/plugins/custom linkText: Build a custom plugin - icon: title: Integrations details: Sync specs, automate workflows, and integrate with the Hey API Platform. link: /openapi-ts/integrations linkText: Learn about integrations ---
    ### Sponsors
    ================================================ FILE: docs/openapi-ts/clients/angular/v19.md ================================================ --- title: Angular v19 Client description: Generate a type-safe Angular v19 client from OpenAPI with the Angular client for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Angular v19

    ::: warning Angular client is currently in beta. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ### About [Angular](https://angular.dev/) is a web framework that empowers developers to build fast, reliable applications. The Angular client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Collaborators ## Features - Angular v19 support - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - support for [`@Injectable()`](https://angular.dev/api/core/Injectable) decorators - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/client-angular` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-angular'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-angular # [!code ++] ``` ::: ### Providers You can use the Angular client in your application by adding `provideHeyApiClient` to your providers. ```ts import { provideHeyApiClient, client } from './client/client.gen'; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(withFetch()), provideHeyApiClient(client), // [!code ++] ], }; ``` ## Configuration The Angular client is built as a thin wrapper on top of Angular, extending its functionality to work with Hey API. If you're already familiar with Angular, configuring your client will feel like working directly with Angular. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any `HttpRequest` configuration option to `setConfig()`, and even your own [`httpClient`](#custom-httpclient) implementation. ```js import { client } from 'client/client.gen'; client.setConfig({ baseUrl: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, you might need to use the second approach. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-angular', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseUrl: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. If needed, you can still use `setConfig()` to update the client configuration later. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseUrl: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseUrl: 'https://example.com', // <-- override default configuration }); ``` ## `@Injectable` If you prefer to use the [`@Injectable()`](https://angular.dev/api/core/Injectable) decorators, set the `asClass` option in your SDK plugin to `true`. ::: code-group ```ts [example] @Injectable({ providedIn: 'root' }) export class FooService { // class methods } ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ '@hey-api/client-angular', { name: '@hey-api/sdk', asClass: true, // [!code ++] }, ], }; ``` ::: ## Interceptors ::: warning This section is under construction. We appreciate your patience. ::: ## Auth ::: warning This section is under construction. We appreciate your patience. ::: ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `httpClient` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import { client } from 'client/client.gen'; client.setConfig({ httpClient: inject(CustomHttpClient), }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## Plugins You might be also interested in the [Angular](/openapi-ts/plugins/angular/v19) plugin. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-angular/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients/angular.md ================================================ --- title: Angular v20 Client description: Generate a type-safe Angular v20 client from OpenAPI with the Angular client for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Angular v20

    ::: warning Angular client is currently in beta. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ### About [Angular](https://angular.dev/) is a web framework that empowers developers to build fast, reliable applications. The Angular client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Collaborators ## Features - Angular v20 support - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - support for [`@Injectable()`](https://angular.dev/api/core/Injectable) decorators - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/client-angular` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-angular'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-angular # [!code ++] ``` ::: ### Providers You can use the Angular client in your application by adding `provideHeyApiClient` to your providers. ```ts import { provideHeyApiClient, client } from './client/client.gen'; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(withFetch()), provideHeyApiClient(client), // [!code ++] ], }; ``` ## Configuration The Angular client is built as a thin wrapper on top of Angular, extending its functionality to work with Hey API. If you're already familiar with Angular, configuring your client will feel like working directly with Angular. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any `HttpRequest` configuration option to `setConfig()`, and even your own [`httpClient`](#custom-instance) implementation. ```js import { client } from 'client/client.gen'; client.setConfig({ baseUrl: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, you might need to use the second approach. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-angular', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseUrl: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. If needed, you can still use `setConfig()` to update the client configuration later. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseUrl: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseUrl: 'https://example.com', // <-- override default configuration }); ``` ## `@Injectable` If you prefer to use the [`@Injectable()`](https://angular.dev/api/core/Injectable) decorators, set the `asClass` option in your SDK plugin to `true`. ::: code-group ```ts [example] @Injectable({ providedIn: 'root' }) export class FooService { // class methods } ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ '@hey-api/client-angular', { name: '@hey-api/sdk', asClass: true, // [!code ++] }, ], }; ``` ::: ## Interceptors ::: warning This section is under construction. We appreciate your patience. ::: ## Auth ::: warning This section is under construction. We appreciate your patience. ::: ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `httpClient` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import { client } from 'client/client.gen'; client.setConfig({ httpClient: inject(CustomHttpClient), }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## Plugins You might be also interested in the [Angular](/openapi-ts/plugins/angular) plugin. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-angular/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients/axios.md ================================================ --- title: Axios v1 Client description: Generate a type-safe Axios v1 client from OpenAPI with the Axios client for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Axios v1

    ### About [Axios](https://axios-http.com) is a simple promise based HTTP client for the browser and Node.js. Axios provides a simple to use library in a small package with a very extensible interface. The Axios client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Demo ## Features - Axios v1 support - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/client-axios` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-axios'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-axios # [!code ++] ``` ::: ## Configuration The Axios client is built as a thin wrapper on top of Axios, extending its functionality to work with Hey API. If you're already familiar with Axios, configuring your client will feel like working directly with Axios. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any Axios configuration option to `setConfig()` (except for `auth`), and even your own [Axios](#custom-instance) implementation. ```js import { client } from 'client/client.gen'; client.setConfig({ baseURL: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, you might need to use the second approach. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-axios', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseURL: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. If needed, you can still use `setConfig()` to update the client configuration later. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseURL: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseURL: 'https://example.com', // <-- override default configuration }); ``` ## Interceptors Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to your application. Axios provides interceptors, please refer to their documentation on [interceptors](https://axios-http.com/docs/interceptors). We expose the Axios instance through the `instance` field. ```js import { client } from 'client/client.gen'; client.instance.interceptors.request.use((config) => { // do something return config; }); ``` ## Auth The SDKs include auth mechanisms for every endpoint. You will want to configure the `auth` field to pass the right token for each request. The `auth` field can be a string or a function returning a string representing the token. The returned value will be attached only to requests that require auth. ```js import { client } from 'client/client.gen'; client.setConfig({ auth: () => '', // [!code ++] baseURL: 'https://example.com', }); ``` If you're not using SDKs or generating auth, using interceptors is a common approach to configuring auth for each request. ```js import { client } from 'client/client.gen'; client.instance.interceptors.request.use((config) => { config.headers.set('Authorization', 'Bearer '); // [!code ++] return config; }); ``` ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `axios` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import axios from 'axios'; import { client } from 'client/client.gen'; // Customize the default axios instance axios.defaults.baseURL = 'https://example.com'; client.setConfig({ axios: axios, }); ``` or you can pass an `AxiosInstance` created with `axios.create()`: ```js import axios from 'axios'; import { client } from 'client/client.gen'; const customAxiosInstance = axios.create({ baseURL: 'https://example.com', }); client.setConfig({ axios: customAxiosInstance, }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-axios/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients/custom.md ================================================ --- title: Custom Client description: Learn how to create your own Hey API client. --- # Custom Client ::: warning Client API is in development. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues/1213). ::: You may need to write your own client if the available clients do not suit your needs or you're working on a proprietary use case. This can be easily achieved using the Client API. But don't take our word for it – all Hey API clients are written this way! ::: warning Custom clients documentation will be finalized after further testing. Simplified [instructions](https://github.com/hey-api/openapi-ts/issues/1213#issuecomment-2765206344) can be found in the GitHub thread. ::: ================================================ FILE: docs/openapi-ts/clients/effect.md ================================================ --- title: Effect client description: Effect client for Hey API. Compatible with all our features. --- # Effect soon ### About [Effect](https://effect.website/) is a powerful TypeScript library designed to help developers easily create complex, synchronous, and asynchronous programs. ================================================ FILE: docs/openapi-ts/clients/fetch.md ================================================ --- title: Fetch API Client description: Generate a type-safe Fetch API client from OpenAPI with the Fetch API client for openapi-ts. Fully compatible with validators, transformers, and all core features. --- # Fetch API ### About The [Fetch API](https://developer.mozilla.org/docs/Web/API/Fetch_API) provides an interface for fetching resources (including across the network). It is a more powerful and flexible replacement for XMLHttpRequest. The Fetch API client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Demo ## Features - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/client-fetch` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-fetch'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-fetch # [!code ++] ``` ::: ::: tip This step is optional because Fetch is the default client. ::: ## Configuration The Fetch client is built as a thin wrapper on top of Fetch API, extending its functionality to work with Hey API. If you're already familiar with Fetch, configuring your client will feel like working directly with Fetch API. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any Fetch API configuration option to `setConfig()`, and even your own [Fetch](#custom-instance) implementation. ```js import { client } from 'client/client.gen'; client.setConfig({ baseUrl: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, you might need to use the second approach. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-fetch', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseUrl: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. If needed, you can still use `setConfig()` to update the client configuration later. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseUrl: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseUrl: 'https://example.com', // <-- override default configuration }); ``` ## Interceptors Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to your application. They can be added with `use`, removed with `eject`, and updated wth `update`. The `use` and `update` methods will return the ID of the interceptor for use with `eject` and `update`. Fetch API does not have the interceptor functionality, so we implement our own. ### Example: Request interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(request) { // do something return request; } interceptorId = client.interceptors.request.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.request.eject(interceptorId); // eject by reference client.interceptors.request.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(request) { // do something return request; } // update by ID client.interceptors.request.update(interceptorId, myNewInterceptor); // update by reference client.interceptors.request.update(myInterceptor, myNewInterceptor); ``` ::: ### Example: Response interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(response) { // do something return response; } interceptorId = client.interceptors.response.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.response.eject(interceptorId); // eject by reference client.interceptors.response.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(response) { // do something return response; } // update by ID client.interceptors.response.update(interceptorId, myNewInterceptor); // update by reference client.interceptors.response.update(myInterceptor, myNewInterceptor); ``` ::: ::: tip To eject, you must provide the ID or reference of the interceptor passed to `use()`, the ID is the value returned by `use()` and `update()`. ::: ## Auth The SDKs include auth mechanisms for every endpoint. You will want to configure the `auth` field to pass the right token for each request. The `auth` field can be a string or a function returning a string representing the token. The returned value will be attached only to requests that require auth. ```js import { client } from 'client/client.gen'; client.setConfig({ auth: () => '', // [!code ++] baseUrl: 'https://example.com', }); ``` If you're not using SDKs or generating auth, using interceptors is a common approach to configuring auth for each request. ```js import { client } from 'client/client.gen'; client.interceptors.request.use((request, options) => { request.headers.set('Authorization', 'Bearer '); // [!code ++] return request; }); ``` ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `fetch` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import { client } from 'client/client.gen'; client.setConfig({ fetch: () => { /* custom `fetch` method */ }, }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-fetch/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients/got.md ================================================ --- title: Got client description: Got client for Hey API. Compatible with all our features. --- # Got soon ### About [Got](https://github.com/sindresorhus/got) is a human-friendly and powerful HTTP request library for Node.js. ================================================ FILE: docs/openapi-ts/clients/ky.md ================================================ --- title: Ky v1 Client description: Generate a type-safe Ky v1 client from OpenAPI with the Ky client for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Ky v1

    ### About [Ky](https://github.com/sindresorhus/ky) is a tiny and elegant JavaScript HTTP client based on the Fetch API. The Ky client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Collaborators ## Features - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/client-ky` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-ky'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-ky # [!code ++] ``` ::: ## Configuration The Ky client is built as a thin wrapper on top of Ky, extending its functionality to work with Hey API. If you're already familiar with Ky, configuring your client will feel like working directly with Ky. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any Ky configuration option to `setConfig()`, and even your own [`ky`](#custom-instance) instance. ```js import { client } from 'client/client.gen'; client.setConfig({ baseUrl: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, you might need to use the second approach. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-ky', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseUrl: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. If needed, you can still use `setConfig()` to update the client configuration later. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseUrl: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseUrl: 'https://example.com', // <-- override default configuration }); ``` ## Interceptors Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to your application. They can be added with `use`, removed with `eject`, and updated wth `update`. The `use` and `update` methods will return the ID of the interceptor for use with `eject` and `update`. Ky does not have the interceptor functionality, so we implement our own. ### Example: Request interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(request) { // do something return request; } interceptorId = client.interceptors.request.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.request.eject(interceptorId); // eject by reference client.interceptors.request.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(request) { // do something return request; } // update by ID client.interceptors.request.update(interceptorId, myNewInterceptor); // update by reference client.interceptors.request.update(myInterceptor, myNewInterceptor); ``` ::: ### Example: Response interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(response) { // do something return response; } interceptorId = client.interceptors.response.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.response.eject(interceptorId); // eject by reference client.interceptors.response.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(response) { // do something return response; } // update by ID client.interceptors.response.update(interceptorId, myNewInterceptor); // update by reference client.interceptors.response.update(myInterceptor, myNewInterceptor); ``` ::: ::: tip To eject, you must provide the ID or reference of the interceptor passed to `use()`, the ID is the value returned by `use()` and `update()`. ::: ## Auth The SDKs include auth mechanisms for every endpoint. You will want to configure the `auth` field to pass the right token for each request. The `auth` field can be a string or a function returning a string representing the token. The returned value will be attached only to requests that require auth. ```js import { client } from 'client/client.gen'; client.setConfig({ auth: () => '', // [!code ++] baseUrl: 'https://example.com', }); ``` If you're not using SDKs or generating auth, using interceptors is a common approach to configuring auth for each request. ```js import { client } from 'client/client.gen'; client.interceptors.request.use((request, options) => { request.headers.set('Authorization', 'Bearer '); // [!code ++] return request; }); ``` ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `ky` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import { client } from 'client/client.gen'; client.setConfig({ ky: ky.create({ /* custom `ky` instance */ }), }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-ky/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients/next-js.md ================================================ --- title: Next.js Client description: Generate a type-safe Next.js client from OpenAPI with the Next.js client for openapi-ts. Fully compatible with validators, transformers, and all core features. --- # Next.js ### About [Next.js](https://nextjs.org) is the React framework for the web. Used by some of the world's largest companies, Next.js enables you to create high-quality web applications with the power of React components. The Next.js client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ## Features - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/client-next` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-next'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-next # [!code ++] ``` ::: ## Configuration The Next.js client is built as a thin wrapper on top of [fetch](https://nextjs.org/docs/app/api-reference/functions/fetch), extending its functionality to work with Hey API. If you're already familiar with Fetch, configuring your client will feel like working directly with Fetch API. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-next', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseUrl: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. This is the recommended approach because it guarantees the client will be initialized in both server and client environment. If needed, you can still use `setConfig()` to update the client configuration later. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any Fetch API configuration option to `setConfig()`, and even your own [Fetch](#custom-instance) implementation. ```js import { client } from 'client/client.gen'; client.setConfig({ baseUrl: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, this might be an acceptable trade-off. However, our Next.js users usually want to use the first approach. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseUrl: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseUrl: 'https://example.com', // <-- override default configuration }); ``` ## Interceptors Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to your application. They can be added with `use`, removed with `eject`, and updated wth `update`. The `use` and `update` methods will return the ID of the interceptor for use with `eject` and `update`. Fetch API does not have the interceptor functionality, so we implement our own. ### Example: Request interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(request) { // do something return request; } interceptorId = client.interceptors.request.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.request.eject(interceptorId); // eject by reference client.interceptors.request.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(request) { // do something return request; } // update by ID client.interceptors.request.update(interceptorId, myNewInterceptor); // update by reference client.interceptors.request.update(myInterceptor, myNewInterceptor); ``` ::: ### Example: Response interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(response) { // do something return response; } interceptorId = client.interceptors.response.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.response.eject(interceptorId); // eject by reference client.interceptors.response.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(response) { // do something return response; } // update by ID client.interceptors.response.update(interceptorId, myNewInterceptor); // update by reference client.interceptors.response.update(myInterceptor, myNewInterceptor); ``` ::: ::: tip To eject, you must provide the ID or reference of the interceptor passed to `use()`, the ID is the value returned by `use()` and `update()`. ::: ## Auth The SDKs include auth mechanisms for every endpoint. You will want to configure the `auth` field to pass the right token for each request. The `auth` field can be a string or a function returning a string representing the token. The returned value will be attached only to requests that require auth. ```js import { client } from 'client/client.gen'; client.setConfig({ auth: () => '', // [!code ++] baseUrl: 'https://example.com', }); ``` If you're not using SDKs or generating auth, using interceptors is a common approach to configuring auth for each request. ```js import { client } from 'client/client.gen'; client.interceptors.request.use((options) => { options.headers.set('Authorization', 'Bearer '); // [!code ++] }); ``` ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `fetch` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import { client } from 'client/client.gen'; client.setConfig({ fetch: () => { /* custom `fetch` method */ }, }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-next/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients/nuxt.md ================================================ --- title: Nuxt v3 Client description: Generate a type-safe Nuxt v3 client from OpenAPI with the Nuxt client for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Nuxt v3

    ::: warning Nuxt client is currently in beta. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ### About [Nuxt](https://nuxt.com) is an open source framework that makes web development intuitive and powerful. The Nuxt client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ## Features - Nuxt v3 support - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation Start by adding `@hey-api/nuxt` to your dependencies. ::: code-group ```sh [npm] npm install @hey-api/nuxt ``` ```sh [pnpm] pnpm add @hey-api/nuxt ``` ```sh [yarn] yarn add @hey-api/nuxt ``` ```sh [bun] bun add @hey-api/nuxt ``` ::: In your [configuration](/openapi-ts/get-started), add `@hey-api/client-nuxt` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-nuxt'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-nuxt # [!code ++] ``` ::: ::: tip If you add `@hey-api/nuxt` to your Nuxt modules, this step is not needed. ::: ## Configuration The Nuxt client is built as a thin wrapper on top of Nuxt, extending its functionality to work with Hey API. If you're already familiar with Nuxt, configuring your client will feel like working directly with Nuxt. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any Nuxt configuration option to `setConfig()`, and even your own [`$fetch`](#custom-instance) implementation. ```js import { client } from 'client/client.gen'; client.setConfig({ baseURL: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, you might need to use the second approach. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-nuxt', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseURL: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. If needed, you can still use `setConfig()` to update the client configuration later. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseURL: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseURL: 'https://example.com', // <-- override default configuration }); ``` ## Interceptors Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to your application. Nuxt provides interceptors through ofetch, please refer to their documentation on [$fetch](https://nuxt.com/docs/api/utils/dollarfetch). You can pass any Nuxt/ofetch arguments to the client instance. ::: tip If you omit `composable`, `$fetch` is used by default. ::: ```js import { client } from 'client/client.gen'; const result = await client.get({ composable: '$fetch', onRequest: (context) => { // do something }, url: '/foo', }); ``` ## Auth The SDKs include auth mechanisms for every endpoint. You will want to configure the `auth` field to pass the right token for each request. The `auth` field can be a string or a function returning a string representing the token. The returned value will be attached only to requests that require auth. ```js import { client } from 'client/client.gen'; client.setConfig({ auth: () => '', // [!code ++] baseURL: 'https://example.com', }); ``` If you're not using SDKs or generating auth, using interceptors is a common approach to configuring auth for each request. ```js import { client } from 'client/client.gen'; client.setConfig({ onRequest: ({ options }) => { options.headers.set('Authorization', 'Bearer '); // [!code ++] }, }); ``` ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `$fetch` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import { client } from 'client/client.gen'; client.setConfig({ $fetch: () => { /* custom `$fetch` method */ }, }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-nuxt/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients/ofetch.md ================================================ --- title: OFetch Client description: Generate a type-safe ofetch client from OpenAPI with the ofetch client for openapi-ts. Fully compatible with validators, transformers, and all core features. --- # OFetch ### About [`ofetch`](https://github.com/unjs/ofetch) is a better Fetch API that adds useful defaults and features such as automatic response parsing, request/response hooks, and it works in Node, browser, and workers. The `ofetch` client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Collaborators ## Features - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/client-ofetch` to your plugins and you'll be ready to generate client artifacts. :tada: ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-ofetch'], // [!code ++] }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -c @hey-api/client-ofetch # [!code ++] ``` ::: ## Configuration The `ofetch` client is built as a thin wrapper on top of `ofetch`, extending its functionality to work with Hey API. If you're already familiar with `ofetch`, configuring your client will feel like working directly with `ofetch`. When we installed the client above, it created a [`client.gen.ts`](/openapi-ts/output#client) file. You will most likely want to configure the exported `client` instance. There are two ways to do that. ### `setConfig()` This is the simpler approach. You can call the `setConfig()` method at the beginning of your application or anytime you need to update the client configuration. You can pass any `ofetch` configuration option to `setConfig()`, and even your own [`ofetch`](#custom-instance) instance. ```js import { client } from 'client/client.gen'; client.setConfig({ baseUrl: 'https://example.com', }); ``` The disadvantage of this approach is that your code may call the `client` instance before it's configured for the first time. Depending on your use case, you might need to use the second approach. ### Runtime API Since `client.gen.ts` is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying the `runtimeConfigPath` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-ofetch', runtimeConfigPath: './src/hey-api.ts', // [!code ++] }, ], }; ``` In our custom file, we need to export a `createClientConfig()` method. This function is a simple wrapper allowing us to override configuration values. ::: code-group ```ts [hey-api.ts] import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, baseUrl: 'https://example.com', }); ``` ::: With this approach, `client.gen.ts` will call `createClientConfig()` before initializing the `client` instance. If needed, you can still use `setConfig()` to update the client configuration later. ### `createClient()` You can also create your own client instance. You can use it to manually send requests or point it to a different domain. ```js import { createClient } from './client/client'; const myClient = createClient({ baseUrl: 'https://example.com', }); ``` You can also pass this instance to any SDK function through the `client` option. This will override the default instance from `client.gen.ts`. ```js const response = await getFoo({ client: myClient, }); ``` ### SDKs Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases. ```js const response = await getFoo({ baseUrl: 'https://example.com', // <-- override default configuration }); ``` ## Interceptors Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to your application. The `ofetch` client supports two complementary options: - built-in Hey API interceptors exposed via `client.interceptors` - native `ofetch` hooks passed through config (e.g., `onRequest`) ### Example: Request interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(request) { // do something return request; } interceptorId = client.interceptors.request.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.request.eject(interceptorId); // eject by reference client.interceptors.request.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(request) { // do something return request; } // update by ID client.interceptors.request.update(interceptorId, myNewInterceptor); // update by reference client.interceptors.request.update(myInterceptor, myNewInterceptor); ``` ::: ### Example: Response interceptor ::: code-group ```js [use] import { client } from 'client/client.gen'; async function myInterceptor(response) { // do something return response; } interceptorId = client.interceptors.response.use(myInterceptor); ``` ```js [eject] import { client } from 'client/client.gen'; // eject by ID client.interceptors.response.eject(interceptorId); // eject by reference client.interceptors.response.eject(myInterceptor); ``` ```js [update] import { client } from 'client/client.gen'; async function myNewInterceptor(response) { // do something return response; } // update interceptor by interceptor ID client.interceptors.response.update(interceptorId, myNewInterceptor); // update interceptor by reference to interceptor function client.interceptors.response.update(myInterceptor, myNewInterceptor); ``` ::: ::: tip To eject, you must provide the ID or reference of the interceptor passed to `use()`, the ID is the value returned by `use()` and `update()`. ::: ### Example: `ofetch` hooks ```js import { client } from 'client/client.gen'; client.setConfig({ onRequest: ({ options }) => { // mutate ofetch options (headers, query, etc.) }, onResponse: ({ response }) => { // inspect/transform the raw Response }, onRequestError: (ctx) => { // handle request errors }, onResponseError: (ctx) => { // handle response errors }, }); ``` ## Auth The SDKs include auth mechanisms for every endpoint. You will want to configure the `auth` field to pass the right token for each request. The `auth` field can be a string or a function returning a string representing the token. The returned value will be attached only to requests that require auth. ```js import { client } from 'client/client.gen'; client.setConfig({ auth: () => '', // [!code ++] baseUrl: 'https://example.com', }); ``` If you're not using SDKs or generating auth, using interceptors is a common approach to configuring auth for each request. ```js import { client } from 'client/client.gen'; client.interceptors.request.use((request, options) => { request.headers.set('Authorization', 'Bearer '); // [!code ++] return request; }); ``` You can also use the `ofetch` hooks. ```js import { client } from 'client/client.gen'; client.setConfig({ onRequest: ({ options }) => { options.headers.set('Authorization', 'Bearer '); // [!code ++] }, }); ``` ## Build URL If you need to access the compiled URL, you can use the `buildUrl()` method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint. ```ts type FooData = { path: { fooId: number; }; query?: { bar?: string; }; url: '/foo/{fooId}'; }; const url = client.buildUrl({ path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }); console.log(url); // prints '/foo/1?bar=baz' ``` ## Custom Instance You can provide a custom `ofetch` instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether. ```js import { ofetch } from 'ofetch'; import { client } from 'client/client.gen'; const customOFetchInstance = ofetch.create({ onRequest: ({ options }) => { // customize request }, onResponse: ({ response }) => { // customize response }, }); client.setConfig({ ofetch: customOFetchInstance, }); ``` You can use any of the approaches mentioned in [Configuration](#configuration), depending on how granular you want your custom instance to be. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/client-ofetch/types.ts) interface. ================================================ FILE: docs/openapi-ts/clients.md ================================================ --- title: Clients description: HTTP clients for Hey API. Compatible with all our features. --- # HTTP Clients We all send HTTP requests in a slightly different way. Hey API doesn't force you to use any specific technology. What we do, however, is support your choice with great clients. All seamlessly integrated with our other features. ## Features - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output ## Options Hey API natively supports the following clients. - [Fetch API](/openapi-ts/clients/fetch) - [Angular](/openapi-ts/clients/angular) - [Axios](/openapi-ts/clients/axios) - [Ky](/openapi-ts/clients/ky) - [Next.js](/openapi-ts/clients/next-js) - [Nuxt](/openapi-ts/clients/nuxt) - [OFetch](/openapi-ts/clients/ofetch) - [Effect](/openapi-ts/clients/effect) Soon - [Got](/openapi-ts/clients/got) Soon Don't see your client? [Build your own](/openapi-ts/clients/custom) or let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ================================================ FILE: docs/openapi-ts/community/contributing/building.md ================================================ --- title: Building description: Learn how to contribute to Hey API. --- # Building ::: warning This page is under construction. We appreciate your patience. ::: ## Prerequisites You should have a working knowledge of [git](https://git-scm.com), [node](https://nodejs.org/en), and [pnpm](https://pnpm.io). ## Guidelines Your [pull request](https://help.github.com/articles/using-pull-requests) must: - address a single issue or add a single item of functionality - contain a clean history of small, incremental, logically separate commits, with no merge commits - use clear commit messages - be possible to merge automatically ## Start `@hey-api/openapi-ts` Run `pnpm --filter @hey-api/openapi-ts dev`. ================================================ FILE: docs/openapi-ts/community/contributing/developing.md ================================================ --- title: Developing description: Learn how to contribute to Hey API. --- # Developing ::: warning This page is under construction. We appreciate your patience. ::: ## Working with Examples The `examples` folder contains various integration examples that demonstrate how to use `@hey-api/openapi-ts` with different frameworks and libraries. These examples are kept in sync with the codebase through automated checks. ### Generating Example Code When you make changes to the core packages that affect code generation, you need to regenerate the client code in all examples: ```bash pnpm examples:generate ``` This command will: - Find all examples with an `openapi-ts` script - Run the OpenAPI code generator for each example - Update the generated client code in each example ### Checking Example Code Before committing changes, ensure that all generated example code is up-to-date: ```bash pnpm examples:check ``` This command will: - Regenerate all example code - Check if any files were modified - Exit with an error if generated code is out of sync This check is also run automatically in CI to ensure examples stay in sync with the main codebase. ### Example Workflow 1. Make changes to core packages 2. Build the packages: `pnpm build --filter="@hey-api/**"` 3. Regenerate examples: `pnpm examples:generate` 4. Commit all changes including the updated generated code 5. The CI will verify that examples are in sync ::: tip Think of generated example code as snapshot tests - they should always reflect the current state of the code generator. ::: ================================================ FILE: docs/openapi-ts/community/contributing/testing.md ================================================ --- title: Testing description: Learn how to contribute to Hey API. --- # Testing ::: warning This page is under construction. We appreciate your patience. ::: ================================================ FILE: docs/openapi-ts/community/contributing.md ================================================ --- title: Contributing description: Learn how to contribute to Hey API. --- # Contributor Manual ## Foreword Hey API is building an OpenAPI to TypeScript code generator ecosystem. It's trusted by thousands of companies – from YC startups to Fortune 500 enterprises – and powers products used by millions worldwide. We welcome contributors of all backgrounds and experience levels. Whether you're fixing a typo or building a new feature, your input matters. If you need guidance, help with technical writing, or want to bring a feature idea to life, we're here to support you. ::: tip New to open source? Take a look at the [Open Source](https://opensource.guide/) or [First Contributions](https://github.com/firstcontributions/first-contributions) guides for helpful information on contributing to open source projects. ::: ## First Steps There are many ways to contribute to Hey API. Most of them don't involve writing any code! - **Read the documentation**. Start with the [Get Started](/openapi-ts/get-started) guide. If you find anything broken or confusing, you can suggest improvements by clicking "Edit" at the bottom of any page. - **Browse open issues**. Help others by providing workarounds, asking for clarification, triaging, or suggesting labels on [open issues](https://github.com/hey-api/openapi-ts/issues). If you see something you would like to work on, consider opening a pull request. - **Participate in discussions**. Ask or [answer questions](https://github.com/orgs/hey-api/discussions), provide feedback, or suggest new ideas. Every idea is welcome, no matter how big or small. - **Engage on social media**. Help others discover Hey API by engaging with our posts on [LinkedIn](https://linkedin.com/company/heyapi), [Bluesky](https://bsky.app/profile/heyapi.dev), or [X](https://x.com/mrlubos). Share your experiences with Hey API on Reddit, Slack, or in your own communities and group chats. - **Create a new issue**. If you can't find a solution, [open an issue](https://github.com/hey-api/openapi-ts/issues). The issue template will guide you through the process. - **Open a pull request**. If you find an issue you would like to fix, open a pull request. If you need help, tag [`@mrlubos`](https://github.com/mrlubos) on GitHub, provide enough relevant information, and we will do our best to assist you. These are some of the best ways not only to contribute to Hey API, but also to learn, connect with others, and share ideas. ## Pull Requests Ready to write some code? We have dedicated guides to help you [build](/openapi-ts/community/contributing/building), [develop](/openapi-ts/community/contributing/developing), and [test](/openapi-ts/community/contributing/testing) your feature before it's released. We are excited to see what you'll contribute! ================================================ FILE: docs/openapi-ts/community/spotlight.md ================================================ --- title: Spotlight description: Meet the people behind Hey API. --- # Spotlight Meet the people behind Hey API. To join this list, please refer to the [contributing](/openapi-ts/community/contributing) guide. ## Core Team These people actively maintain Hey API. Do you want to join the core team? Send us a short [email](mailto:lubos@heyapi.dev?subject=Join%20Core%20Team) describing your interest in Hey API, any relevant experience, and what you're hoping to work on. ## Hall of Fame These are the people with significant contributions to Hey API. A special thank you goes to [Ferdi Koomen](https://madebyferdi.com) for allowing us to use the original source code from OpenAPI TypeScript Codegen. None of this would've been possible without you! ## Contributors The complete list of contributors to Hey API.
    A sincere thank you for your contributions. ================================================ FILE: docs/openapi-ts/configuration/input.md ================================================ --- title: Input description: Configure @hey-api/openapi-ts. --- # Input You must provide an input so we can load your OpenAPI specification. ## Input The input can be a string path, URL, [API registry](#api-registry), an object containing any of these, or an object representing an OpenAPI specification. Hey API supports all valid OpenAPI versions and file formats. ::: code-group ```js [path] export default { input: './path/to/openapi.json', // [!code ++] }; ``` ```js [url] export default { input: 'https://get.heyapi.dev/hey-api/backend', // sign up at app.heyapi.dev // [!code ++] }; ``` ```js [registry] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev // [!code ++] }; ``` ```js [object] export default { input: { // [!code ++] path: 'hey-api/backend', // sign up at app.heyapi.dev // [!code ++] // ...other options // [!code ++] }, // [!code ++] }; ``` ```js [spec] export default { input: { // [!code ++] openapi: '3.1.1', // [!code ++] // ...rest of your spec // [!code ++] }, // [!code ++] }; ``` ::: You can learn more about complex use cases in the [Advanced](/openapi-ts/configuration#advanced) section. ::: info If you use an HTTPS URL with a self-signed certificate in development, you will need to set [`NODE_TLS_REJECT_UNAUTHORIZED=0`](https://github.com/hey-api/openapi-ts/issues/276#issuecomment-2043143501) in your environment. ::: ### Request options You can pass any valid Fetch API [options](https://developer.mozilla.org/docs/Web/API/RequestInit) to the request for fetching your specification. This is useful if your file is behind auth for example. ```js export default { input: { path: 'https://secret.com/protected-spec', fetch: { // [!code ++] headers: { // [!code ++] Authorization: 'Bearer xxx', // [!code ++] }, // [!code ++] }, // [!code ++] }, }; ``` ## API Registry You can store your specifications in an API registry to serve as a single source of truth. This helps prevent drift, improves discoverability, enables version tracking, and more. ### Hey API You can learn more about [Hey API Platform](https://app.heyapi.dev) on the [Integrations](/openapi-ts/integrations) page. ```js [uuid] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev // [!code ++] }; ``` The `input` object lets you provide additional options to construct the correct URL. ```js export default { input: { path: 'hey-api/backend', // sign up at app.heyapi.dev branch: 'main', // [!code ++] }, }; ``` We also provide shorthands for other registries: ::: details Scalar Prefix your input with `scalar:` to use the Scalar API Registry. ```js [long] export default { input: 'scalar:@scalar/access-service', // [!code ++] }; ``` ::: ::: details ReadMe Prefix your input with `readme:` to use the ReadMe API Registry. ::: code-group ```js [uuid] export default { input: 'readme:nysezql0wwo236', // [!code ++] }; ``` ```js [long] export default { input: 'readme:@developers/v2.0#nysezql0wwo236', // [!code ++] }; ``` ::: ## Watch Mode ::: warning Watch mode currently supports only remote files via URL. ::: If your schema changes frequently, you may want to automatically regenerate the output during development. To watch your input file for changes, enable `input.watch` mode in your configuration or pass the `--watch` flag to the CLI. ::: code-group ```js [config] export default { input: { path: 'hey-api/backend', // sign up at app.heyapi.dev watch: true, // [!code ++] }, }; ``` ```sh [cli] npx @hey-api/openapi-ts \ -i hey-api/backend \ -o src/client \ -w # [!code ++] ``` ::: ================================================ FILE: docs/openapi-ts/configuration/output.md ================================================ --- title: Output description: Configure @hey-api/openapi-ts. --- # Output You must set the output so we know where to generate your files. ## Output Output can be a path to the destination folder or an object containing the destination folder path and optional settings. ::: code-group ```js [path] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', // [!code ++] }; ``` ```js [object] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { // [!code ++] path: 'src/client', // [!code ++] // ...other options // [!code ++] }, // [!code ++] }; ``` ::: You can learn more about complex use cases in the [Advanced](/openapi-ts/configuration#advanced) section. ## File Control how files are named and annotated in the generated output. ### File Name You can customize the naming and casing pattern for files using the `fileName` option. ::: code-group ```js [default] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { fileName: '{{name}}', // [!code ++] path: 'src/client', }, }; ``` ```js [snake_case] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { fileName: { case: 'snake_case', // [!code ++] }, path: 'src/client', }, }; ``` ::: By default, we append every file name with a `.gen` suffix to highlight it's automatically generated. You can customize or disable this suffix using the `fileName.suffix` option. ::: code-group ```js [default] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { fileName: { suffix: '.gen', // [!code ++] }, path: 'src/client', }, }; ``` ```js [disabled] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { fileName: { suffix: null, // [!code ++] }, path: 'src/client', }, }; ``` ```js [custom] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { fileName: { suffix: '.generated', // [!code ++] }, path: 'src/client', }, }; ``` ::: ### File Header The generated output includes a notice in every file warning that any modifications will be lost when the files are regenerated. You can customize or disable this notice using the `header` option. ::: code-group ```js [example] /* eslint-disable */ // This file is auto-generated by @hey-api/openapi-ts /** ... */ ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { header: (ctx) => [ // [!code ++] '/* eslint-disable */', // [!code ++] ...ctx.defaultValue, // [!code ++] ], // [!code ++] path: 'src/client', }, }; ``` ::: ## Module Control how module specifiers are generated in the output. ### Module Extension Set `module.extension` to define the file extension used in import specifiers. This is useful when targeting environments that require fully specified imports (e.g., Node ESM or certain bundlers). ::: code-group ```js [example] import foo from './foo.js'; import bar from './bar.js'; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { module: { extension: '.js', // [!code ++] }, path: 'src/client', }, }; ``` ::: ### Module Path Use `module.resolve` for full control over how module specifiers are generated. This lets you override specific modules or redirect them to custom locations (e.g., CDNs or internal aliases). ::: code-group ```js [example] import * as z from 'https://esm.sh/zod'; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { module: { resolve(path) { // [!code ++] if (path === 'zod') { // [!code ++] return 'https://esm.sh/zod'; // [!code ++] } // [!code ++] }, // [!code ++] }, path: 'src/client', }, }; ``` ::: ## Source Source is a copy of the input specification used to generate your output. It can be used to power documentation tools or to persist a stable snapshot alongside your generated files. Enabling the `source` option with `true` creates a `source.json` file in your output folder. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', source: true, // [!code ++] }, }; ``` You can customize the file name and location using `fileName` and `path`. For example, this configuration will create an `openapi.json` file inside `src/client/source` directory. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', source: { fileName: 'openapi', // [!code ++] path: './source', // [!code ++] }, }, }; ``` To use the source without writing it to disk, you can provide a `callback` function. This is useful for logging or integrating with external systems. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', source: { callback: (source) => console.log(source), // [!code ++] path: null, // [!code ++] }, }, }; ``` ## Post Process Post-processing allows you to run commands on the generated output folder after files are written. This is typically used to run formatters, linters, or other cleanup tools. Commands are executed in order, and each command receives the output path via the `path` placeholder. ### Presets You can use built-in presets for common tools: ::: code-group ```js [biome:format] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', postProcess: ['biome:format'], // [!code ++] }, }; ``` ```js [biome:lint] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', postProcess: ['biome:lint'], // [!code ++] }, }; ``` ```js [eslint] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', postProcess: ['eslint'], // [!code ++] }, }; ``` ```js [oxfmt] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', postProcess: ['oxfmt'], // [!code ++] }, }; ``` ```js [oxlint] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', postProcess: ['oxlint'], // [!code ++] }, }; ``` ```js [prettier] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', postProcess: ['prettier'], // [!code ++] }, }; ``` ::: ### Custom You can also provide custom post processors: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', postProcess: [{ // [!code ++] command: 'dprint', // [!code ++] args: ['fmt', '{{path}}'], // [!code ++] }], // [!code ++] }, }; ``` You can skip processing by adding the output path to the tool's ignore file (for example `.eslintignore` or `.prettierignore`). ## Name Conflicts As your project grows, the chances of name conflicts increase. We use a simple conflict resolver that appends numeric suffixes to duplicate identifiers. If you prefer a different strategy, you can provide your own `nameConflictResolver` function. ::: code-group ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { nameConflictResolver({ attempt, baseName }) { // [!code ++] return attempt === 0 ? baseName : `${baseName}_N${attempt + 1}`; // [!code ++] }, // [!code ++] path: 'src/client', }, }; ``` ```ts [example] export type ChatCompletion = string; export type ChatCompletion_N2 = number; ``` ::: ## TSConfig Path We use the [TSConfig file](https://www.typescriptlang.org/tsconfig/) to generate output matching your project's settings. By default, we attempt to find a TSConfig file starting from the location of the `@hey-api/openapi-ts` configuration file and traversing up. ::: code-group ```js [default] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', tsConfigPath: undefined, // [!code ++] }, }; ``` ```js [custom] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', tsConfigPath: './config/tsconfig.custom.json', // [!code ++] }, }; ``` ```js [disabled] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', tsConfigPath: null, // [!code ++] }, }; ``` ::: ## Custom Files By default, you can't keep custom files in the `path` folder because it's emptied on every run. If you're sure you need to disable this behavior, set `clean` to `false`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { clean: false, // [!code ++] path: 'src/client', }, }; ``` ::: warning Setting `clean` to `false` may result in broken output. Ensure you typecheck your code. ::: ================================================ FILE: docs/openapi-ts/configuration/parser.md ================================================ --- title: Parser description: Configure @hey-api/openapi-ts. --- # Parser We parse your input before making it available to plugins. Configuring the parser is optional, but it provides an ideal opportunity to modify or validate your input as needed. ## Patch Sometimes you need to modify raw input before it's processed further. A common use case is fixing an invalid specification or adding a missing field. For this reason, custom patches are applied before any parsing takes place. You can add custom patches with `patch`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { patch: { schemas: { Foo: (schema) => { // [!code ++] // convert date-time format to timestamp // [!code ++] delete schema.properties.updatedAt.format; // [!code ++] schema.properties.updatedAt.type = 'number'; // [!code ++] }, // [!code ++] Bar: (schema) => { // [!code ++] // add missing property // [!code ++] schema.properties.meta = { // [!code ++] additionalProperties: true, // [!code ++] type: 'object', // [!code ++] }; // [!code ++] schema.required = ['meta']; // [!code ++] }, // [!code ++] Baz: (schema) => { // [!code ++] // remove property // [!code ++] delete schema.properties.internalField; // [!code ++] }, // [!code ++] }, }, }, }; ``` ## Validate ::: warning The validator feature is very limited. You can help improve it by submitting more [use cases](https://github.com/hey-api/openapi-ts/issues/1970#issuecomment-2933189789). ::: If you don't control or trust your input, you might want to validate it. Any detected errors in your input will exit `@hey-api/openapi-ts` and no plugins will be executed. To validate your input, set `validate_EXPERIMENTAL` to `true`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { validate_EXPERIMENTAL: true, // [!code ++] }, }; ``` ## Filters Filters allow you to trim your input before it's processed further, so your output contains only relevant resources. ### Operations Set `include` to match operations to be included or `exclude` to match operations to be excluded. Both exact keys and regular expressions are supported. When both rules match the same operation, `exclude` takes precedence over `include`. ::: code-group ```js [include] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { operations: { include: ['GET /api/v1/foo', '/^[A-Z]+ /api/v1//'], // [!code ++] }, }, }, }; ``` ```js [exclude] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { operations: { exclude: ['GET /api/v1/foo', '/^[A-Z]+ /api/v1//'], // [!code ++] }, }, }, }; ``` ::: ### Tags Set `include` to match tags to be included or `exclude` to match tags to be excluded. When both rules match the same tag, `exclude` takes precedence over `include`. ::: code-group ```js [include] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { tags: { include: ['v2'], // [!code ++] }, }, }, }; ``` ```js [exclude] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { tags: { exclude: ['v1'], // [!code ++] }, }, }, }; ``` ::: ### Deprecated You can filter out deprecated resources by setting `deprecated` to `false`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { deprecated: false, // [!code ++] }, }, }; ``` ### Schemas Set `include` to match schemas to be included or `exclude` to match schemas to be excluded. Both exact keys and regular expressions are supported. When both rules match the same schema, `exclude` takes precedence over `include`. ::: code-group ```js [include] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { schemas: { include: ['Foo', '/^Bar/'], // [!code ++] }, }, }, }; ``` ```js [exclude] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { schemas: { exclude: ['Foo', '/^Bar/'], // [!code ++] }, }, }, }; ``` ::: ### Parameters Set `include` to match parameters to be included or `exclude` to match parameters to be excluded. Both exact keys and regular expressions are supported. When both rules match the same parameter, `exclude` takes precedence over `include`. ::: code-group ```js [include] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { parameters: { include: ['QueryParameter', '/^MyQueryParameter/'], // [!code ++] }, }, }, }; ``` ```js [exclude] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { parameters: { exclude: ['QueryParameter', '/^MyQueryParameter/'], // [!code ++] }, }, }, }; ``` ::: ### Request Bodies Set `include` to match request bodies to be included or `exclude` to match request bodies to be excluded. Both exact keys and regular expressions are supported. When both rules match the same request body, `exclude` takes precedence over `include`. ::: code-group ```js [include] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { requestBodies: { include: ['Payload', '/^SpecialPayload/'], // [!code ++] }, }, }, }; ``` ```js [exclude] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { requestBodies: { exclude: ['Payload', '/^SpecialPayload/'], // [!code ++] }, }, }, }; ``` ::: ### Responses Set `include` to match responses to be included or `exclude` to match responses to be excluded. Both exact keys and regular expressions are supported. When both rules match the same response, `exclude` takes precedence over `include`. ::: code-group ```js [include] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { responses: { include: ['Foo', '/^Bar/'], // [!code ++] }, }, }, }; ``` ```js [exclude] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { responses: { exclude: ['Foo', '/^Bar/'], // [!code ++] }, }, }, }; ``` ::: ### Orphaned resources If you only want to exclude orphaned resources, set `orphans` to `false`. This is the default value when combined with any other filters. If this isn't the desired behavior, you may want to set `orphans` to `true` to always preserve unused resources. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { orphans: false, // [!code ++] }, }, }; ``` ### Order For performance reasons, we don't preserve the original order when filtering out resources. If maintaining the original order is important to you, set `preserveOrder` to `true`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { filters: { preserveOrder: true, // [!code ++] }, }, }; ``` ## Transforms You can think of transforms as deterministic [patches](#patch). They provide an easy way to apply the most commonly used input transformations. ### Enums Your input might contain two types of enums: - enums defined as reusable components (root enums) - non-reusable enums nested within other schemas (inline enums) You may want all enums to be reusable. This is because only root enums are typically exported by plugins. Inline enums will never be directly importable since they're nested inside other schemas. ::: code-group ```js [root] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { enums: 'root', // [!code ++] }, }, }; ``` ```js [inline] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { enums: 'inline', // [!code ++] }, }, }; ``` ::: You can customize the naming and casing pattern for `enums` schemas using the `.name` and `.case` options. ### Properties required by default By default, any object schema with a missing `required` keyword is interpreted as "no properties are required." This is the correct behavior according to the OpenAPI standard. However, some specifications interpret a missing `required` keyword as "all properties should be required." This option allows you to change the default behavior so that properties are required by default unless explicitly marked as optional. ::: code-group ```js [default] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { propertiesRequiredByDefault: false, // [!code ++] }, }, }; ``` ```js [required] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { propertiesRequiredByDefault: true, // [!code ++] }, }, }; ``` ::: ### Read-write Your schemas might contain read-only or write-only fields. Using such schemas directly could mean asking the user to provide a read-only field in requests, or expecting a write-only field in responses. We separate schemas for requests and responses if direct usage would result in such scenarios. ::: code-group ```js [default] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { readWrite: { requests: '{{name}}Writable', // [!code ++] responses: '{{name}}', // [!code ++] }, }, }, }; ``` ```js [disabled] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { readWrite: false, // [!code ++] }, }, }; ``` ::: You can customize the naming and casing pattern for `requests` and `responses` schemas using the `.name` and `.case` options. ### Schema Name Sometimes your schema names are auto-generated or follow a naming convention that produces verbose or awkward type names. You can rename schema component keys throughout the specification, automatically updating all `$ref` pointers. For example, stripping version markers from schema names, removing vendor prefixes, converting naming conventions, or shortening deeply qualified names. ::: code-group ```js [function] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { schemaName: (name) => { // [!code ++] // Strip version markers: ServiceRoot_v1_20_0_ServiceRoot → ServiceRoot // [!code ++] let clean = name.replace(/([A-Za-z\d]+)_v\d+_\d+_\d+_([A-Za-z\d]*)/g, (_, p1, p2) => // [!code ++] p2.startsWith(p1) ? p2 : p1 + p2, // [!code ++] ); // [!code ++] // Deduplicate prefixes: Foo_Foo → Foo // [!code ++] const m = clean.match(/^([A-Za-z\d]+)_\1([A-Za-z\d]*)$/); // [!code ++] if (m) clean = m[1] + m[2]; // [!code ++] return clean; // [!code ++] }, // [!code ++] }, }, }; ``` ```js [template] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { transforms: { schemaName: 'Api{{name}}', // [!code ++] }, }, }; ``` ::: ::: tip Name Collisions If a transformed schema name conflicts with an existing schema, the rename is skipped for that schema to prevent overwrites. The original name is preserved. ::: ## Pagination Paginated operations are detected by having a pagination keyword in its parameters or request body. By default, we consider the following to be pagination keywords: `after`, `before`, `cursor`, `offset`, `page`, and `start`. You can provide custom pagination keywords using `pagination.keywords`. ::: code-group ```js [extend] import { defaultPaginationKeywords } from '@hey-api/openapi-ts'; export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { pagination: { keywords: [ ...defaultPaginationKeywords, // [!code ++] 'extra', // [!code ++] 'pagination', // [!code ++] 'keywords', // [!code ++] ], }, }, }; ``` ```js [override] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { pagination: { keywords: [ 'custom', // [!code ++] 'pagination', // [!code ++] 'keywords', // [!code ++] ], }, }, }; ``` ::: ## Hooks Hooks affect runtime behavior but aren't tied to any single plugin. They can be configured globally via `hooks` or per plugin through the `~hooks` property. ::: code-group ```js [parser] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { hooks: {}, // configure global hooks // [!code ++] }, }; ``` ```js [plugin] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@tanstack/react-query', '~hooks': {}, // configure plugin hooks // [!code ++] }, ], }; ``` ::: We always use the first hook that returns a value. If a hook returns no value, we fall back to less specific hooks until one does. ### Operations {#hooks-operations} Each operation has a list of classifiers that can include `query`, `mutation`, both, or none. Plugins may use these values to decide whether to generate specific output. For example, you usually don't want to generate [TanStack Query options](/openapi-ts/plugins/tanstack-query#queries) for PATCH operations. #### Query operations {#hooks-query-operations} By default, GET operations are classified as `query` operations. #### Mutation operations {#hooks-mutation-operations} By default, DELETE, PATCH, POST, and PUT operations are classified as `mutation` operations. #### Example: POST search query Imagine your API has a POST `/search` endpoint that accepts a large payload. By default, it's classified as a `mutation`, but in practice it behaves like a `query`, and your [state management](/openapi-ts/state-management) plugin should generate query hooks. You can achieve this by classifying the operation as `query` in a matcher. ::: code-group ```js [isQuery] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { hooks: { operations: { isQuery: (op) => { if (op.method === 'post' && op.path === '/search') { // [!code ++] return true; // [!code ++] } // [!code ++] }, }, }, }, }; ``` ```js [getKind] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { hooks: { operations: { getKind: (op) => { if (op.method === 'post' && op.path === '/search') { // [!code ++] return ['query']; // [!code ++] } // [!code ++] }, }, }, }, }; ``` ::: ### Symbols {#hooks-symbols} Each symbol can have a placement function deciding its output location. #### Example: Alphabetic sort While we work on a better example, let's imagine a world where it's desirable to place every symbol in a file named after its initial letter. For example, a function named `Foo` should end up in the file `f.ts`. You can achieve this by using the symbol's name. ```js [getKind] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { hooks: { symbols: { getFilePath: (symbol) => { // [!code ++] if (symbol.name) { // [!code ++] return symbol.name[0]?.toLowerCase(); // [!code ++] } // [!code ++] }, // [!code ++] }, }, }, }; ``` Most plugins expose configuration options that allow you to rename many of the generated symbols. If you need even more control, use the `getName()` hook. #### Example: Enum naming By default, generated enums use the same name for both the type and the runtime value. ::: code-group ```ts [example] export const Flags = { ALPHA: 'alpha', BETA: 'beta', } as const; export type Flags = (typeof Flags)[keyof typeof Flags]; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { enums: 'javascript', name: '@hey-api/typescript', }, ], }; ``` ::: While this code works perfectly fine due to TypeScript's declaration merging, let's say we want to use a different name for the type. We can accomplish this with the `getName()` hook. ::: code-group ```ts [example] export const Flags = { ALPHA: 'alpha', BETA: 'beta', } as const; export type FlagsType = (typeof Flags)[keyof typeof Flags]; // [!code ++] ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { enums: 'javascript', name: '@hey-api/typescript', '~hooks': { symbols: { getName({ meta, name, schema }) { // [!code ++] if (schema?.type === 'enum' && meta.category === 'type') { // [!code ++] return `${name}Type`; // [!code ++] } // [!code ++] }, // [!code ++] }, }, }, ], }; ``` ::: ================================================ FILE: docs/openapi-ts/configuration.md ================================================ --- title: Configuration description: Configure @hey-api/openapi-ts. --- # Configuration `@hey-api/openapi-ts` supports loading configuration from any file inside your project root folder supported by [jiti loader](https://github.com/unjs/c12?tab=readme-ov-file#-features). Below are the most common file formats. ::: code-group ```js [openapi-ts.config.ts] import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }); ``` ```js [openapi-ts.config.cjs] /** @type {import('@hey-api/openapi-ts').UserConfig} */ module.exports = { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ```js [openapi-ts.config.mjs] /** @type {import('@hey-api/openapi-ts').UserConfig} */ export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ::: Alternatively, you can use `openapi-ts.config.js` and configure the export statement depending on your project setup. ## Input You must provide an input so we can load your OpenAPI specification. The input can be a string path, URL, [API registry](/openapi-ts/configuration/input#api-registry) shorthand, an object containing any of these, or an object representing an OpenAPI specification. Hey API supports all valid OpenAPI versions and file formats. You can learn more on the [Input](/openapi-ts/configuration/input) page. ::: code-group ```js [path] export default { input: './path/to/openapi.json', // [!code ++] }; ``` ```js [url] export default { input: 'https://get.heyapi.dev/hey-api/backend', // sign up at app.heyapi.dev // [!code ++] }; ``` ```js [registry] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev // [!code ++] }; ``` ```js [object] export default { input: { // [!code ++] path: 'hey-api/backend', // sign up at app.heyapi.dev // [!code ++] // ...other options // [!code ++] }, // [!code ++] }; ``` ```js [spec] export default { input: { // [!code ++] openapi: '3.1.1', // [!code ++] // ...rest of your spec // [!code ++] }, // [!code ++] }; ``` ::: ::: info If you use an HTTPS URL with a self-signed certificate in development, you will need to set [`NODE_TLS_REJECT_UNAUTHORIZED=0`](https://github.com/hey-api/openapi-ts/issues/276#issuecomment-2043143501) in your environment. ::: ## Output You must set the output so we know where to generate your files. It can be a path to the destination folder or an object containing the destination folder path and optional settings. You can learn more on the [Output](/openapi-ts/configuration/output) page. ::: code-group ```js [path] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', // [!code ++] }; ``` ```js [object] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { // [!code ++] path: 'src/client', // [!code ++] // ...other options // [!code ++] }, // [!code ++] }; ``` ::: ::: tip You should treat the output folder as a dependency. Do not directly modify its contents as your changes might be erased when you run `@hey-api/openapi-ts` again. ::: ## Parser We parse your input before making it available to plugins. Configuring the parser is optional, but it provides an ideal opportunity to modify or validate your input as needed. You can learn more on the [Parser](/openapi-ts/configuration/parser) page. ## Plugins Plugins are responsible for generating artifacts from your input. By default, Hey API will generate TypeScript interfaces and SDK from your OpenAPI specification. You can add, remove, or customize any of the plugins. In fact, we highly encourage you to do so! You can learn more on the [Output](/openapi-ts/output) page. ## Advanced More complex configuration scenarios can be handled by providing an array of inputs, outputs, or configurations. ### Multiple jobs Throughout this documentation, we generally reference single job configurations. However, you can easily run multiple jobs by providing an array of configuration objects. ::: code-group ```js [config] export default [ { input: 'foo.yaml', output: 'src/foo', }, { input: 'bar.yaml', output: 'src/bar', }, ]; ``` ```txt [example] src/ ├── foo/ │ ├── client/ │ ├── core/ │ ├── client.gen.ts │ ├── index.ts │ ├── sdk.gen.ts │ └── types.gen.ts └── bar/ ├── client/ ├── core/ ├── client.gen.ts ├── index.ts ├── sdk.gen.ts └── types.gen.ts ``` ::: ### Job matrix Reusing configuration across multiple jobs is possible by defining a job matrix. You can create a job matrix by providing `input` and `output` arrays of matching length. ::: code-group ```js [config] export default { input: ['foo.yaml', 'bar.yaml'], output: ['src/foo', 'src/bar'], }; ``` ```txt [example] src/ ├── foo/ │ ├── client/ │ ├── core/ │ ├── client.gen.ts │ ├── index.ts │ ├── sdk.gen.ts │ └── types.gen.ts └── bar/ ├── client/ ├── core/ ├── client.gen.ts ├── index.ts ├── sdk.gen.ts └── types.gen.ts ``` ::: ### Merging inputs You can merge inputs by defining multiple inputs and a single output. ::: code-group ```js [config] export default { input: ['foo.yaml', 'bar.yaml'], output: 'src/client', }; ``` ```txt [example] src/ └── client/ ├── client/ ├── core/ ├── client.gen.ts ├── index.ts ├── sdk.gen.ts └── types.gen.ts ``` ::: ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/config/types.ts) interface. ================================================ FILE: docs/openapi-ts/core.md ================================================ --- title: Core Plugins description: Learn about the core plugins provided by Hey API. --- # Core Apart from being responsible for the default output, core plugins are the foundation for other plugins. Instead of creating their own primitives, other plugins can reuse the artifacts from core plugins. This results in a smaller output size and a better user experience. ## Options Hey API provides the following core plugins. - [TypeScript](/openapi-ts/plugins/typescript) - [SDK](/openapi-ts/plugins/sdk) - [Transformers](/openapi-ts/plugins/transformers) - [Schemas](/openapi-ts/plugins/schemas) Need another core plugin? Let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ================================================ FILE: docs/openapi-ts/get-started.md ================================================ --- title: Get Started description: Get started with @hey-api/openapi-ts. --- # Get Started [@hey-api/openapi-ts](https://github.com/hey-api/openapi-ts) generates TypeScript code from OpenAPI specifications. Point it at your spec, pick your plugins, and get production-ready code in seconds. Used by companies like Vercel, OpenCode, and PayPal. > _“OpenAPI codegen that just works.”_ > > — Guillermo Rauch, CEO of Vercel ### Demo ## Features - production-ready code that compiles - runs in any Node.js 20+ environment - accepts any OpenAPI specification - core plugins for SDKs, types, and schemas - HTTP clients for Fetch API, Angular, Axios, Next.js, Nuxt, and more - 20+ plugins to reduce third-party boilerplate - highly customizable via plugins - [sync with Hey API Registry](/openapi-ts/integrations) for spec management ## Quick Start The fastest way to use `@hey-api/openapi-ts` is via npx ```sh npx @hey-api/openapi-ts -i hey-api/backend -o src/client ``` Congratulations on creating your first client! 🎉 You can learn more about the generated files on the [Output](/openapi-ts/output) page. ## Installation You can download `@hey-api/openapi-ts` from npm using your favorite package manager. ::: code-group ```sh [npm] npm install @hey-api/openapi-ts -D -E ``` ```sh [pnpm] pnpm add @hey-api/openapi-ts -D -E ``` ```sh [yarn] yarn add @hey-api/openapi-ts -D -E ``` ```sh [bun] bun add @hey-api/openapi-ts -D -E ``` ::: ### Versioning This package is in [initial development](https://semver.org/#spec-item-4). Please pin an exact version so you can safely upgrade when you're ready. We publish [migration notes](/openapi-ts/migrating) for every breaking release. You might not be impacted by a breaking change if you don't use the affected features. ## Usage ### CLI Most people run `@hey-api/openapi-ts` via CLI. To do that, add a script to your `package.json` file which will make `openapi-ts` executable through script. ```json "scripts": { "openapi-ts": "openapi-ts" } ``` The above script can be executed by running `npm run openapi-ts` or equivalent command in other package managers. Next, we will create a [configuration](/openapi-ts/configuration) file and move our options from Quick Start to it. ### Node.js You can also generate output programmatically by calling `createClient()` in a JavaScript/TypeScript file. ::: code-group ```ts [script.ts] import { createClient } from '@hey-api/openapi-ts'; createClient({ input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }); ``` ::: ### Configuration It's a good practice to extract your configuration into a separate file. Learn how to do that and discover available options on the [Configuration](/openapi-ts/configuration) page. ================================================ FILE: docs/openapi-ts/integrations.md ================================================ --- title: Hey API Platform description: Automate your client generation with our OpenAPI specifications storage. --- # Hey API Platform ::: warning This feature is in development! :tada: Try it out and provide feedback on [GitHub](https://github.com/orgs/hey-api/discussions/1773). ::: You can automate your client generation with Hey API Platform thanks to reproducible builds. Create dependency links between your clients and APIs, and watch the magic unfold. It's completely language and codegen agnostic. ## Features - API version history - real-time updates - reproducible builds - language and codegen agnostic (TypeScript/Python/Go/Java/etc codegens are welcome) ## Upload Specifications Before you can generate clients, you must publish your OpenAPI specifications to Hey API. ### Prerequisites 1. Create a **free account** with [Hey API](https://app.heyapi.dev). 1. Create a new **organization** and **project** for your API provider. We recommend your naming matches your GitHub structure as it will be referenced by API clients. For example, we are using **hey-api/backend** for the platform. 1. Inside your project, go to _Integrations_ > _APIs_ and generate an **API key**. Keep this value secret, it will be used to upload files. ### Add GitHub CI workflow Once you have your API key, you can start uploading OpenAPI specifications on every API build. We'll use our [GitHub Action](https://github.com/marketplace/actions/upload-openapi-spec-by-hey-api), but you can also make the API call manually if you're not using GitHub. Create a new GitHub workflow or add an upload step to an existing workflow inside your API codebase. The example below will upload your OpenAPI specification to Hey API on every pull request and push to the `main` branch. ```yaml name: Upload OpenAPI Specification on: push: branches: - main pull_request: jobs: upload-openapi-spec: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Upload OpenAPI spec uses: hey-api/upload-openapi-spec@v1.3.0 with: path-to-file: path/to/openapi.json tags: optional,custom,tags env: API_KEY: ${{ secrets.HEY_API_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` ### Inputs To successfully upload an OpenAPI specification, you need to provide the following inputs (see `with` in the example above) #### `path-to-file` A relative path to your OpenAPI file within the repository. Note that you might need an additional step in your GitHub workflow to generate this file (see [FastAPI example](https://fastapi.tiangolo.com/how-to/extending-openapi/#generate-the-openapi-schema)). #### `tags` (optional) A comma-separated string value representing any custom tags you wish to add to your OpenAPI specification. ### Environment Variables In addition to the required `path-to-file` input, you must provide the following environment variables. #### `API_KEY` This is the project API key you obtained from [Hey API](https://app.heyapi.dev). ::: warning Personal API keys can't be used to upload specifications. ::: #### `GITHUB_TOKEN` This variable will be available inside your workflow by default. It's used to fetch information about your repository, i.e. default branch. ## Generate Clients You can generate clients from public projects or any private projects you can access. The setup is largely the same, you want to configure the input path used by your codegen. ::: code-group ```sh [Hey API] npx @hey-api/openapi-ts -i hey-api/backend -o src/client ``` ```sh [OpenAPI TypeScript] npx openapi-typescript \ https://get.heyapi.dev/hey-api/backend \ -o schema.ts ``` ```sh [Orval] npx orval \ --input https://get.heyapi.dev/hey-api/backend \ --output ./src/client.ts ``` ```sh [Other] other-cli \ --input https://get.heyapi.dev/hey-api/backend \ # [!code ++] --output refer/to/other/tools/docs ``` ::: By default, we preserve the current behavior and return the latest specification. Let's have a closer look at the input path and change that. ## Get API As you can deduce from the examples above, the default command for fetching OpenAPI specifications looks like this. ``` https://get.heyapi.dev// ``` If you created an organization `foo` with project `bar` earlier, your URL would look like this. ``` https://get.heyapi.dev/foo/bar ``` ### Auth Projects are private by default, you will need to be authenticated to download OpenAPI specifications. We recommend using [project API keys](#prerequisites) in CI workflows and [personal API keys](https://app.heyapi.dev/settings/user/apis) for local development. Once you have your API key, you can authenticate the request using the `Authorization` header or `api_key` query parameter. ``` https://get.heyapi.dev/foo/bar?api_key= ``` Congratulations on fetching your first OpenAPI specification! 🎉 ### Filters The default behavior returns the last uploaded specification. This might not be what you want. You can use a range of filters to narrow down the possible specifications, or pin your builds to an exact version. #### `branch` You can fetch the last build from branch by providing the `branch` query parameter. ``` https://get.heyapi.dev/foo/bar?branch=production ``` #### `commit_sha` You can fetch an exact specification by providing the `commit_sha` query parameter. This will always return the same file. ``` https://get.heyapi.dev/foo/bar?commit_sha=0eb34c2024841ce95620f3ec02a2fea164ea4e9d ``` #### `tags` If you're tagging your specifications with [custom tags](#tags-optional), you can use them to filter the results. When you provide multiple tags, only the first match will be returned. ``` https://get.heyapi.dev/foo/bar?tags=optional,custom,tags ``` #### `version` Every OpenAPI document contains a required version field. You can use this value to fetch the last uploaded specification matching the value. ``` https://get.heyapi.dev/foo/bar?version=1.0.0 ``` ## Feedback We'd love your feedback! You can contact us on social media (search Hey API), [email](mailto:lubos@heyapi.dev), or [GitHub](https://github.com/orgs/hey-api/discussions/1773). ## Pricing The platform is currently in beta with our focus being on delivering a great experience. We plan to announce pricing once we have gathered enough data around usage patterns. However, we can guarantee there will always be a free plan available. Our mission to bring the finest tooling for working with APIs remains unchanged. ================================================ FILE: docs/openapi-ts/license.md ================================================ --- title: License description: License FAQ. --- # License ### MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: docs/openapi-ts/migrating.md ================================================ --- title: Migrating description: Migrating to @hey-api/openapi-ts. --- # Migrating While we try to avoid breaking changes, sometimes it's unavoidable in order to offer you the latest features. This page lists changes that require updates to your code. If you run into a problem with migration, please [open an issue](https://github.com/hey-api/openapi-ts/issues). ## v0.93.0 ### Removed resolver node Valibot and Zod plugins no longer expose the `enum.nodes.nullable` node. Both plugins were refactored so that nullable values are handled outside of resolvers. ## v0.92.0 ### Updated Symbol interface The `exportFrom` property has been replaced with the `getExportFromFilePath()` function. This allows you to dynamically determine export paths based on symbol properties. This is a low-level feature, so you're most likely unaffected. ## v0.91.0 ### Removed CommonJS (CJS) support `@hey-api/openapi-ts` is now ESM-only. This change simplifies the codebase, improves tree-shaking, and enables better integration with modern bundlers and TypeScript tooling. CommonJS entry points (`require()`, `module.exports`) are no longer supported. If you are in a CJS environment, you can still load the package dynamically using `import()` like: ```js const { defineConfig } = await import('@hey-api/openapi-ts'); ``` If you have previously written: ```js const { defineConfig } = require('@hey-api/openapi-ts'); ``` Migrate by updating your static imports: ```js import { defineConfig } from '@hey-api/openapi-ts'; ``` If your environment cannot use ESM, pin to a previous version. ## v0.90.0 ### Resolvers API The [Resolvers API](/openapi-ts/plugins/concepts/resolvers) has been simplified and expanded to provide a more consistent behavior across plugins. You can view a few common examples on the [Resolvers](/openapi-ts/plugins/concepts/resolvers) page. ### Structure API The [SDK plugin](/openapi-ts/plugins/sdk) and [Angular plugin](/openapi-ts/plugins/angular) now implement the Structure API, enabling more complex structures and fixing several known issues. Some Structure APIs are incompatible with the previous configuration, most notably the `methodNameBuilder` function, which accepted the operation object as an argument. You can read the [SDK Output](/openapi-ts/plugins/sdk#output) section to familiarize yourself with the Structure API. Please [open an issue](https://github.com/hey-api/openapi-ts/issues) if you're unable to migrate your configuration to the new syntax. ## v0.89.0 ### Prefer named exports This release changes the default for `index.ts` to prefer named exports. Named exports may lead to better IDE and bundler performance compared to asterisk (`*`) as your tooling doesn't have to inspect the underlying module to discover exports. While this change is merely cosmetic, you can set `output.preferExportAll` to `true` if you prefer to use the asterisk. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', preferExportAll: true, // [!code ++] }, }; ``` ### Removed `symbol:setValue:*` events These events have been removed in favor of `node:set:*` events. ## v0.88.0 ### Removed `compiler` and `tsc` exports This release removes the `compiler` utility functions. Instead, it introduces a new TypeScript DSL exposed under the `$` symbol. All plugins now use this interface, so you may notice slight changes in the generated output. ## v0.87.0 ### Removed legacy clients This release removes support for legacy clients and plugins. Please migrate to the new clients if you haven't done so yet. If you're unable to do so due to a missing feature, let us know on [GitHub](https://github.com/hey-api/openapi-ts/issues). ## v0.86.0 ### Removed Node 18 support This release bumps the minimum required Node version to 20.19. ## v0.85.0 ### Updated `output` options We made the `output` configuration more consistent by using `null` to represent disabled options. This change does not affect boolean options. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { format: false, // [!code --] format: null, // [!code ++] lint: false, // [!code --] lint: null, // [!code ++] path: 'src/client', tsConfigPath: 'off', // [!code --] tsConfigPath: null, // [!code ++] }, }; ``` ### Updated Pinia Colada query options Pinia Colada query options now use `defineQueryOptions` to improve reactivity support. Instead of calling the query options function, you can use one of the following approaches. ::: code-group ```ts [no params] useQuery(getPetsQuery); ``` ```ts [constant] useQuery(getPetByIdQuery, () => ({ path: { petId: 1, }, })); ``` ```ts [reactive] const petId = ref(1); useQuery(getPetByIdQuery, () => ({ path: { petId: petId.value, }, })); ``` ```ts [properties] const petId = ref(1); useQuery(() => ({ ...getPetByIdQuery({ path: { petId: petId.value as number }, }), enabled: () => petId.value != null, })); ``` ::: ## v0.84.0 ### Symbol API This release improves the Symbol API, which adds the capability to place symbols in arbitrary files. We preserved the previous output structure for all plugins except Angular. You can preserve the previous Angular output by writing your own [placement function](/openapi-ts/configuration/parser#hooks-symbols). ### TypeScript renderer We ship a dedicated TypeScript renderer for `.ts` files. This release improves the renderer's ability to group and sort imported modules, resulting in a more polished output. ### Removed `output` plugin option Due to the Symbol API release, this option has been removed from the Plugin API. ## v0.83.0 ### Symbol API This release adds the Symbol API, which significantly reduces the risk of naming collisions. While the generated output should only include formatting changes, this feature introduces breaking changes to the Plugin API that affect custom plugins. We will update the [custom plugin guide](/openapi-ts/plugins/custom) once the Plugin API becomes more stable. ### Removed `groupByTag` Pinia Colada option This option has been removed to provide a more consistent API across plugins. We plan to bring it back in a future release. ## v0.82.0 ### Hooks API This release adds the [Hooks API](/openapi-ts/configuration/parser#hooks), giving you granular control over which operations generate queries and mutations. As a result, we tightened the previous behavior and POST operations no longer generate queries by default. To preserve the old behavior, add a custom matcher. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', parser: { hooks: { operations: { isQuery: (op) => (op.method === 'post' ? true : undefined), // [!code ++] }, }, }, }; ``` ## v0.81.0 ### Server-Sent Events (SSE) This release adds support for server-sent events (SSE). Instead of treating `text/event-stream` content types as regular HTTP methods, we now generate SSE streams. In practice, you will want to update your affected endpoints to process streamed events. ::: code-group ```js [before] const { data } = await foo(); console.log(data.type); ``` ```js [after] const { stream } = await foo(); for await (const event of stream) { console.log(event.type); } ``` ::: ## v0.80.0 ### Added Zod 4 and Zod Mini This release adds support for Zod 4 and Zod Mini. By default, the `zod` plugin will generate output for Zod 4. If you want to preserve the previous output for Zod 3 or use Zod Mini, set `compatibilityVersion` to `3` or `mini`. ::: code-group ```js [Zod 3] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, // [!code ++] }, ], }; ``` ```js [Zod Mini] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', // [!code ++] }, ], }; ``` ::: ## v0.79.0 ### Removed `typescript+namespace` enums mode Due to a simpler TypeScript plugin implementation, the `typescript+namespace` enums mode is no longer necessary. This mode was used in the past to group inline enums under the same namespace. With the latest changes, this behavior is no longer supported. You can either choose to ignore inline enums (default), or use the `enums` transform (added in v0.78.0) to convert them into reusable components which will get exported as usual. ## v0.78.0 ### Added `parser` options Previously, `@hey-api/typescript` would generate correct types, but the validator plugins would have to re-implement the same logic or generate schemas that didn't match the generated types. Since neither option was ideal, this release adds a dedicated place for `parser` options. Parser is responsible for preparing the input so plugins can generate more accurate output with less effort. You can learn more about configuring parser on the [Parser](/openapi-ts/configuration/parser) page. ### Moved `input` options The following options were moved to the new `parser` group. - `input.filters` moved to `parser.filters` - `input.pagination` moved to `parser.pagination` - `input.patch` moved to `parser.patch` - `input.validate_EXPERIMENTAL` moved to `parser.validate_EXPERIMENTAL` ### Updated `typescript` options The following options were renamed. - `enumsCase` moved to `enums.case` - `enumsConstantsIgnoreNull` moved to `enums.constantsIgnoreNull` ### Moved `typescript` options The following options were moved to the new `parser` group. - `exportInlineEnums` moved to `parser.transforms.enums` - `readOnlyWriteOnlyBehavior` moved to `parser.transforms.readWrite.enabled` - `readableNameBuilder` moved to `parser.transforms.readWrite.responses.name` - `writableNameBuilder` moved to `parser.transforms.readWrite.requests.name` ### Updated `readWrite.responses` name Additionally, the naming pattern for response schemas has changed from `{name}Readable` to `{name}`. This is to prevent your code from breaking by default when using a schema that gets updated with a write-only field. ## v0.77.0 ### Updated `sdk.validator` option Clients can now validate both request and response data. As a result, passing a boolean or string to `validator` will control both of these options. To preserve the previous behavior, set `validator.request` to `false` and `validator.response` to your previous configuration. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', validator: true, // [!code --] validator: { // [!code ++] request: false, // [!code ++] response: true, // [!code ++] }, // [!code ++] }, ], }; ``` ### Updated Plugin API Please refer to the [custom plugin](/openapi-ts/plugins/custom) tutorial for the latest guide. ## v0.76.0 ### Single Valibot schema per request Previously, we generated a separate schema for each endpoint parameter and request body. In v0.76.0, a single request schema is generated for the whole endpoint. It may contain a request body, parameters, and headers. ```ts const vData = v.object({ body: v.optional( v.object({ foo: v.optional(v.string()), bar: v.optional(v.union([v.number(), v.null()])), }), ), headers: v.optional(v.never()), path: v.object({ baz: v.string(), }), query: v.optional(v.never()), }); ``` If you need to access individual fields, you can do so using the [`.entries`](https://valibot.dev/api/object/) API. For example, we can get the request body schema with `vData.entries.body`. ## v0.75.0 ### Updated TanStack Query options The TanStack Query plugin options have been expanded to support more naming and casing patterns. As a result, the following options have been renamed. - `queryOptionsNameBuilder` renamed to `queryOptions` - `infiniteQueryOptionsNameBuilder` renamed to `infiniteQueryOptions` - `mutationOptionsNameBuilder` renamed to `mutationOptions` - `queryKeyNameBuilder` renamed to `queryKeys` - `infiniteQueryKeyNameBuilder` renamed to `infiniteQueryKeys` ### Added `plugin.forEach()` method This method replaces the `.subscribe()` method. Additionally, `.forEach()` is executed immediately, which means we don't need the `before` and `after` events – simply move your code before and after the `.forEach()` block. ```ts plugin.subscribe('operation', (event) => { // [!code --] // do something with event // [!code --] }); // [!code --] plugin.subscribe('schema', (event) => { // [!code --] plugin.forEach('operation', 'schema', (event) => { // [!code ++] // do something with event }); ``` ## v0.74.0 ### Single Zod schema per request Previously, we generated a separate schema for each endpoint parameter and request body. In v0.74.0, a single request schema is generated for the whole endpoint. It may contain a request body, parameters, and headers. ```ts const zData = z.object({ body: z .object({ foo: z.string().optional(), bar: z.union([z.number(), z.null()]).optional(), }) .optional(), headers: z.never().optional(), path: z.object({ baz: z.string(), }), query: z.never().optional(), }); ``` If you need to access individual fields, you can do so using the [`.shape`](https://zod.dev/api?id=shape) API. For example, we can get the request body schema with `zData.shape.body`. ## v0.73.0 ### Bundle `@hey-api/client-*` plugins In previous releases, you had to install a separate client package to generate a fully working output, e.g., `npm install @hey-api/client-fetch`. This created a few challenges: getting started was slower, upgrading was sometimes painful, and bundling too. Beginning with v0.73.0, all Hey API clients are bundled by default and don't require installing any additional dependencies. You can remove any installed client packages and re-run `@hey-api/openapi-ts`. ```sh npm uninstall @hey-api/client-fetch ``` ## v0.72.0 ### Added `sdk.classStructure` option When generating class-based SDKs, we now try to infer the ideal structure using `operationId` keywords. If you'd like to preserve the previous behavior, set `classStructure` to `off`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { classStructure: 'off', // [!code ++] name: '@hey-api/sdk', }, ], }; ``` ## v0.71.0 ### Renamed `sdk.serviceNameBuilder` option This option has been renamed to `sdk.classNameBuilder` to better represent its functionality. Additionally, it's no longer set by default. To preserve the previous behavior, update your configuration. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { classNameBuilder: '{{name}}Service', // [!code ++] name: '@hey-api/sdk', serviceNameBuilder: '{{name}}Service', // [!code --] }, ], }; ``` ## v0.68.0 ### Upgraded input filters Input filters now avoid generating invalid output without requiring you to specify every missing schema as in the previous releases. As part of this release, we changed the way filters are configured and removed the support for regular expressions. Let us know if regular expressions are still useful for you and want to bring them back! ::: code-group ```js [include] export default { input: { // match only the schema named `foo` and `GET` operation for the `/api/v1/foo` path filters: { operations: { include: ['GET /api/v1/foo'], // [!code ++] }, schemas: { include: ['foo'], // [!code ++] }, }, include: '^(#/components/schemas/foo|#/paths/api/v1/foo/get)$', // [!code --] path: 'hey-api/backend', // sign up at app.heyapi.dev }, output: 'src/client', plugins: ['@hey-api/client-fetch'], }; ``` ```js [exclude] export default { input: { // match everything except for the schema named `foo` and `GET` operation for the `/api/v1/foo` path exclude: '^(#/components/schemas/foo|#/paths/api/v1/foo/get)$', // [!code --] filters: { operations: { exclude: ['GET /api/v1/foo'], // [!code ++] }, schemas: { exclude: ['foo'], // [!code ++] }, }, path: 'hey-api/backend', // sign up at app.heyapi.dev }, output: 'src/client', plugins: ['@hey-api/client-fetch'], }; ``` ::: ## v0.67.0 ### Respecting `moduleResolution` value in `tsconfig.json` This release introduces functionality related to your `tsconfig.json` file. The initial feature properly respects the value of your `moduleResolution` field. If you're using `nodenext`, the relative module paths in your output will be appended with `.js`. To preserve the previous behavior where we never appended `.js` to relative module paths, set `output.tsConfigPath` to `off`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { path: 'src/client', tsConfigPath: 'off', // [!code ++] }, }; ``` ## v0.66.0 ### Read-only and write-only fields Starting with v0.66.0, `@hey-api/typescript` will generate separate types for payloads and responses if it detects any read-only or write-only fields. To preserve the previous behavior and generate a single type regardless, set `readOnlyWriteOnlyBehavior` to `off`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/typescript', readOnlyWriteOnlyBehavior: 'off', // [!code ++] }, ], }; ``` ## v0.64.0 ### Added `ClientOptions` interface The `Config` interface now accepts an optional generic extending `ClientOptions` instead of `boolean` type `ThrowOnError`. ```ts type Foo = Config; // [!code --] type Foo = Config<{ throwOnError: false }>; // [!code ++] ``` ### Added `client.baseUrl` option You can use this option to configure the default base URL for the generated client. By default, we will attempt to resolve the first defined server or infer the base URL from the input path. If you'd like to preserve the previous behavior, set `baseUrl` to `false`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { baseUrl: false, // [!code ++] name: '@hey-api/client-fetch', }, ], }; ``` ## v0.63.0 ### Client plugins Clients are now plugins generating their own `client.gen.ts` file. There's no migration needed if you're using CLI. If you're using the configuration file, move `client` options to `plugins`. ```js export default { client: '@hey-api/client-fetch', // [!code --] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: ['@hey-api/client-fetch'], // [!code ++] }; ``` ### Added `client.gen.ts` file Related to above, the internal `client` instance previously located in `sdk.gen.ts` is now defined in `client.gen.ts`. If you're importing it in your code, update the import module. ```js import { client } from 'client/sdk.gen'; // [!code --] import { client } from 'client/client.gen'; // [!code ++] ``` ### Moved `sdk.throwOnError` option This SDK configuration option has been moved to the client plugins where applicable. Not every client can be configured to throw on error, so it didn't make sense to expose the option when it didn't have any effect. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ { name: '@hey-api/client-fetch', throwOnError: true, // [!code ++] }, { name: '@hey-api/sdk', throwOnError: true, // [!code --] }, ], }; ``` ## v0.62.0 ### Changed parser Formerly known as the experimental parser, this is now the default parser. This change should not impact the generated output's functionality. However, there might be cases where this results in breaking changes due to different handling of certain scenarios. If you need to revert to the legacy parser, set the `experimentalParser` flag to `false`. ```js export default { client: '@hey-api/client-fetch', experimentalParser: false, // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` Note that the legacy parser is no longer supported and will be removed in the v1 release. ## v0.61.0 ### Added `auth` option Client package functions `accessToken` and `apiKey` were replaced with a single `auth` function for fetching auth tokens. If your API supports multiple auth mechanisms, you can use the `auth` argument to return the appropriate token. ```js import { client } from 'client/sdk.gen'; client.setConfig({ accessToken: () => '', // [!code --] apiKey: () => '', // [!code --] auth: (auth) => '', // [!code ++] }); ``` Due to conflict with the Axios native `auth` option, we removed support for configuring Axios auth. Please let us know if you require this feature added back. ### Added `watch` option While this is a new feature, supporting it involved replacing the `@apidevtools/json-schema-ref-parser` dependency with our own implementation. Since this was a big change, we're applying caution and marking this as a breaking change. ### Changed `parseAs: 'auto'` behavior The Fetch API client will return raw response body as `ReadableStream` when `Content-Type` response header is undefined and `parseAs` is `auto`. ## v0.60.0 ### Added `sdk.transformer` option When generating SDKs, you now have to specify `transformer` in order to modify response data. By default, adding `@hey-api/transformers` to your plugins will only produce additional output. To preserve the previous functionality, set `sdk.transformer` to `true`. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { dates: true, name: '@hey-api/transformers', }, { name: '@hey-api/sdk', transformer: true, // [!code ++] }, ], }; ``` ## v0.59.0 ### Added `logs.level` option You can now configure different log levels. As part of this feature, we had to introduce a breaking change by moving the `debug` option to `logs.level`. This will affect you if you're calling `@hey-api/openapi-ts` from Node.js (not CLI) or using the configuration file. ```js export default { client: '@hey-api/client-fetch', debug: true, // [!code --] input: 'hey-api/backend', // sign up at app.heyapi.dev logs: { level: 'debug', // [!code ++] }, output: 'src/client', }; ``` ### Updated default `plugins` `@hey-api/schemas` has been removed from the default plugins. To continue using it, add it to your plugins array. ```js export default { client: '@hey-api/client-fetch', experimentalParser: true, input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@hey-api/schemas', // [!code ++] ], }; ``` ## v0.58.0 ### Removed `schemas.gen.ts` re-export `index.ts` will no longer re-export `schemas.gen.ts` to reduce the chance of producing broken output. Please update your code to import from `schemas.gen.ts` directly. ```js import { mySchema } from 'client'; // [!code --] import { mySchema } from 'client/schemas.gen'; // [!code ++] ``` ### Removed `transformers.gen.ts` re-export `index.ts` will no longer re-export `transformers.gen.ts` to reduce the chance of producing broken output. Please update your code to import from `transformers.gen.ts` directly. ```js import { myTransformer } from 'client'; // [!code --] import { myTransformer } from 'client/transformers.gen'; // [!code ++] ``` ### Added `output.clean` option By default, the `output.path` folder will be emptied on every run. To preserve the previous behavior, set `output.clean` to `false`. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: { clean: false, // [!code ++] path: 'src/client', }, }; ``` ### Added `typescript.identifierCase` option **This change affects only the experimental parser.** By default, the generated TypeScript interfaces will follow the PascalCase naming convention. In the previous versions, we tried to preserve the original name as much as possible. To keep the previous behavior, set `typescript.identifierCase` to `preserve`. ```js export default { client: '@hey-api/client-fetch', experimentalParser: true, input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { identifierCase: 'preserve', // [!code ++] name: '@hey-api/typescript', }, ], }; ``` ## v0.57.0 ### Renamed `@hey-api/services` plugin This plugin has been renamed to `@hey-api/sdk`. ### Changed `sdk.output` value To align with the updated name, the `@hey-api/sdk` plugin will generate an `sdk.gen.ts` file. This will result in a breaking change if you're importing from `services.gen.ts`. Please update your imports to reflect this change. ```js import { client } from 'client/services.gen'; // [!code --] import { client } from 'client/sdk.gen'; // [!code ++] ``` ### Renamed `@hey-api/types` plugin This plugin has been renamed to `@hey-api/typescript`. ### Added `typescript.exportInlineEnums` option By default, inline enums (enums not defined as reusable components in the input file) will be generated only as inlined union types. You can set `exportInlineEnums` to `true` to treat inline enums as reusable components. When `true`, the exported enums will follow the style defined in `enums`. This is a breaking change since in the previous versions, inline enums were always treated as reusable components. To preserve your current output, set `exportInlineEnums` to `true`. This feature works only with the experimental parser. ```js export default { client: '@hey-api/client-fetch', experimentalParser: true, input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { exportInlineEnums: true, // [!code ++] name: '@hey-api/typescript', }, ], }; ``` ## v0.56.0 ### Deprecated `tree` in `@hey-api/types` This config option is deprecated and will be removed when the experimental parser becomes the default. ## v0.55.0 This release adds the ability to filter your OpenAPI specification before it's processed. This feature will be useful if you are working with a large specification and are interested in generating output only from a small subset. This feature is available only in the experimental parser. In the future, this will become the default parser. To opt-in to the experimental parser, set the `experimentalParser` flag in your configuration to `true`. ### Deprecated `include` in `@hey-api/types` This config option is deprecated and will be removed when the experimental parser becomes the default. ### Deprecated `filter` in `@hey-api/services` This config option is deprecated and will be removed when the experimental parser becomes the default. ### Added `input.include` option This config option can be used to replace the deprecated options. It accepts a regular expression string matching against references within the bundled specification. ```js export default { client: '@hey-api/client-fetch', experimentalParser: true, input: { include: '^(#/components/schemas/foo|#/paths/api/v1/foo/get)$', // [!code ++] path: 'hey-api/backend', // sign up at app.heyapi.dev }, output: 'src/client', }; ``` The configuration above will process only the schema named `foo` and `GET` operation for the `/api/v1/foo` path. ## v0.54.0 This release makes plugins first-class citizens. In order to achieve that, the following breaking changes were introduced. ### Removed CLI options The `--types`, `--schemas`, and `--services` CLI options have been removed. You can list which plugins you'd like to use explicitly by passing a list of plugins as `--plugins ` ### Removed `*.export` option Previously, you could explicitly disable export of certain artifacts using the `*.export` option or its shorthand variant. These were both removed. You can now disable export of specific artifacts by manually defining an array of `plugins` and excluding the unwanted plugin. ::: code-group ```js [shorthand] export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', schemas: false, // [!code --] plugins: ['@hey-api/types', '@hey-api/services'], // [!code ++] }; ``` ```js [*.export] export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', schemas: { export: false, // [!code --] }, plugins: ['@hey-api/types', '@hey-api/services'], // [!code ++] }; ``` ::: ### Renamed `schemas.name` option Each plugin definition contains a `name` field. This was conflicting with the `schemas.name` option. As a result, it has been renamed to `nameBuilder`. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', schemas: { name: (name) => `${name}Schema`, // [!code --] }, plugins: [ // ...other plugins { nameBuilder: (name) => `${name}Schema`, // [!code ++] name: '@hey-api/schemas', }, ], }; ``` ### Removed `services.include` shorthand option Previously, you could use a string value as a shorthand for the `services.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', services: '^MySchema', // [!code --] plugins: [ // ...other plugins { include: '^MySchema', // [!code ++] name: '@hey-api/services', }, ], }; ``` ### Renamed `services.name` option Each plugin definition contains a `name` field. This was conflicting with the `services.name` option. As a result, it has been renamed to `serviceNameBuilder`. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', services: { name: '{{name}}Service', // [!code --] }, plugins: [ // ...other plugins { serviceNameBuilder: '{{name}}Service', // [!code ++] name: '@hey-api/services', }, ], }; ``` ### Renamed `types.dates` option Previously, you could set `types.dates` to a boolean or a string value, depending on whether you wanted to transform only type strings into dates, or runtime code too. Many people found these options confusing, so they have been simplified to a boolean and extracted into a separate `@hey-api/transformers` plugin. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', types: { dates: 'types+transform', // [!code --] }, plugins: [ // ...other plugins { dates: true, // [!code ++] name: '@hey-api/transformers', }, ], }; ``` ### Removed `types.include` shorthand option Previously, you could use a string value as a shorthand for the `types.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', types: '^MySchema', // [!code --] plugins: [ // ...other plugins { include: '^MySchema', // [!code ++] name: '@hey-api/types', }, ], }; ``` ### Renamed `types.name` option Each plugin definition contains a `name` field. This was conflicting with the `types.name` option. As a result, it has been renamed to `style`. ```js export default { client: '@hey-api/client-fetch', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', types: { name: 'PascalCase', // [!code --] }, plugins: [ // ...other plugins { name: '@hey-api/types', style: 'PascalCase', // [!code ++] }, ], }; ``` ## v0.53.0 ### Changed schemas name pattern Previously, generated schemas would have their definition names prefixed with `$`. This was problematic when using them with Svelte due to reserved keyword conflicts. The new naming pattern for schemas suffixes their definition names with `Schema`. You can continue using the previous pattern by setting the `schemas.name` configuration option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', schemas: { name: (name) => `$${name}`, // [!code ++] }, }; ``` ### Renamed legacy clients Legacy clients were renamed to signal they are deprecated more clearly. To continue using legacy clients, you will need to update your configuration and prefix them with `legacy/`. ::: code-group ```js [fetch] export default { client: 'fetch', // [!code --] client: 'legacy/fetch', // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ```js [axios] export default { client: 'axios', // [!code --] client: 'legacy/axios', // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ```js [angular] export default { client: 'angular', // [!code --] client: 'legacy/angular', // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ```js [node] export default { client: 'node', // [!code --] client: 'legacy/node', // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ```js [xhr] export default { client: 'xhr', // [!code --] client: 'legacy/xhr', // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ::: ## v0.52.0 ### Removed internal `client` export Previously, client packages would create a default client which you'd then import and configure. ```js import { client, createClient } from '@hey-api/client-fetch'; createClient({ baseUrl: 'https://example.com', }); console.log(client.getConfig().baseUrl); // <-- 'https://example.com' ``` This client instance was used internally by services unless overridden. Apart from running `createClient()` twice, people were confused about the meaning of `global` configuration option. Starting with v0.52.0, client packages will not create a default client. Instead, services will define their own client. You can now achieve the same configuration by importing `client` from services and using the new `setConfig()` method. ```js import { client } from 'client/services.gen'; client.setConfig({ baseUrl: 'https://example.com', }); console.log(client.getConfig().baseUrl); // <-- 'https://example.com' ``` ## v0.51.0 ### Required `client` option Client now has to be explicitly specified and `@hey-api/openapi-ts` will no longer generate a legacy Fetch API client by default. To preserve the previous default behavior, set the `client` option to `fetch`. ```js export default { client: 'fetch', // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ## v0.48.0 ### Changed `methodNameBuilder()` signature The `services.methodNameBuilder()` function now provides a single `operation` argument instead of multiple cherry-picked properties from it. ```js import { createClient } from '@hey-api/openapi-ts'; createClient({ input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', services: { methodNameBuilder: (service, name) => name, // [!code --] methodNameBuilder: (operation) => operation.name, // [!code ++] }, }); ``` ## v0.46.0 ### Tree-shakeable services By default, your services will now support [tree-shaking](https://developer.mozilla.org/docs/Glossary/Tree_shaking). You can either use wildcard imports ```js import { DefaultService } from 'client/services.gen'; // [!code --] import * as DefaultService from 'client/services.gen'; // [!code ++] DefaultService.foo(); // only import needs to be changed ``` or update all references to service classes ```js import { DefaultService } from 'client/services.gen'; // [!code --] import { foo } from 'client/services.gen'; // [!code ++] foo(); // all references need to be changed ``` If you want to preserve the old behavior, you can set the newly exposed `services.asClass` option to `true.` ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', services: { asClass: true, // [!code ++] }, }; ``` ## v0.45.0 ### Removed `client` inference `@hey-api/openapi-ts` will no longer infer which client you want to generate. By default, we will create a `fetch` client. If you want a different client, you can specify it using the `client` option. ```js export default { client: 'axios', // [!code ++] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` ## v0.44.0 ### Moved `format` This config option has been moved. You can now configure formatter using the `output.format` option. ```js export default { format: 'prettier', // [!code --] input: 'hey-api/backend', // sign up at app.heyapi.dev output: { format: 'prettier', // [!code ++] path: 'src/client', }, }; ``` ### Moved `lint` This config option has been moved. You can now configure linter using the `output.lint` option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev lint: 'eslint', // [!code --] output: { lint: 'eslint', // [!code ++] path: 'src/client', }, }; ``` ## v0.43.0 ### Removed `enums.gen.ts` This file has been removed. Instead, enums are exported from `types.gen.ts`. If you use imports from `enums.gen.ts`, you should be able to easily find and replace all instances. ```js import { Foo } from 'client/enums.gen'; // [!code --] import { Foo } from 'client/types.gen'; // [!code ++] ``` ### Removed `Enum` postfix Generated enum names are no longer postfixed with `Enum`. You can either alias your imports ```js import { FooEnum } from 'client/types.gen'; // [!code --] import { Foo as FooEnum } from 'client/types.gen'; // [!code ++] console.log(FooEnum.value); // only import needs to be changed ``` or update all references to enums ```js import { FooEnum } from 'client/types.gen'; // [!code --] import { Foo } from 'client/types.gen'; // [!code ++] console.log(Foo.value); // all references need to be changed ``` ### Moved `enums` This config option has been moved. You can now configure enums using the `types.enums` option. ```js export default { enums: 'javascript', // [!code --] input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', types: { enums: 'javascript', // [!code ++] }, }; ``` ## v0.42.0 ### Changed `format` This config option has changed. You now need to specify a value (`biome` or `prettier`) to format the output (default: `false`). ```js{2} export default { format: 'prettier', input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', } ``` ### Changed `lint` This config option has changed. You now need to specify a value (`biome` or `eslint`) to lint the output (default: `false`). ```js{3} export default { input: 'hey-api/backend', // sign up at app.heyapi.dev lint: 'eslint', output: 'src/client', } ``` ### Moved `operationId` This config option has been moved. You can now configure it using the `services.operationId` option. ```js{5} export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', services: { operationId: true, }, } ``` ## v0.41.0 ### Removed `postfixServices` This config option has been removed. You can now transform service names using the string pattern parameter. ```js{5} export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', services: { name: 'myAwesome{{name}}Api', }, } ``` ### Removed `serviceResponse` This config option has been removed. You can now configure service responses using the `services.response` option. ```js{5} export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', services: { response: 'body', }, } ``` ### Removed `useDateType` This config option has been removed. You can now configure date type using the `types.dates` option. ```js{5} export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', type: { dates: true, }, } ``` ## v0.40.0 ### Renamed `models.gen.ts` file `models.gen.ts` is now called `types.gen.ts`. If you use imports from `models.gen.ts`, you should be able to easily find and replace all instances. ```js import type { Model } from 'client/models.gen' // [!code --] import type { Model } from 'client/types.gen' // [!code ++] ``` ### Renamed `exportModels` This config option is now called `types`. ### PascalCase for types You can now choose to export types using the PascalCase naming convention. ```js{5} export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', types: { name: 'PascalCase', }, } ``` ### Exported `enums.gen.ts` file Enums are now re-exported from the main `index.ts` file. ## v0.39.0 ### Single `enums.gen.ts` file Enums are now exported from a separate file. If you use imports from `models.ts`, you can change them to `enums.gen.ts`. ```js import { Enum } from 'client/models'; // [!code --] import { Enum } from 'client/enums.gen'; // [!code ++] ``` ### Renamed `models.ts` file `models.ts` is now called `models.gen.ts`. If you use imports from `models.ts`, you should be able to easily find and replace all instances. ```js import type { Model } from 'client/models' // [!code --] import type { Model } from 'client/models.gen' // [!code ++] ``` ### Renamed `schemas.ts` file `schemas.ts` is now called `schemas.gen.ts`. If you use imports from `schemas.ts`, you should be able to easily find and replace all instances. ```js import { $Schema } from 'client/schemas'; // [!code --] import { $Schema } from 'client/schemas.gen'; // [!code ++] ``` ### Renamed `services.ts` file `services.ts` is now called `services.gen.ts`. If you use imports from `services.ts`, you should be able to easily find and replace all instances. ```js import { DefaultService } from 'client/services'; // [!code --] import { DefaultService } from 'client/services.gen'; // [!code ++] ``` ### Deprecated exports from `index.ts` Until this release, `index.ts` file exported all generated artifacts. Starting from this release, enums are no longer exported from `index.ts`. Models, schemas, and services will continue to be exported from `index.ts` to avoid a huge migration lift, but we recommend migrating to import groups per artifact type. ```js import { Enum, type Model, $Schema, DefaultService } from 'client' // [!code --] import { Enum } from 'client/enums.gen' // [!code ++] import type { Model } from 'client/models.gen' // [!code ++] import { $Schema } from 'client/schemas.gen' // [!code ++] import { DefaultService } from 'client/services.gen' // [!code ++] ``` ### Prefer `unknown` Types that cannot be determined will now be generated as `unknown` instead of `any`. To dismiss any errors, you can cast your variables back to `any`, but we recommend updating your code to work with `unknown` types. ```js const foo = bar as any ``` ## v0.38.0 ### Renamed `write` This config option is now called `dryRun` (file) or `--dry-run` (CLI). To restore existing functionality, invert the value, ie. `write: true` is `dryRun: false` and `write: false` is `dryRun: true`. ## v0.36.0 ### JSON Schema 2020-12 Schemas are exported directly from OpenAPI specification. This means your schemas might change depending on which OpenAPI version you're using. If this release caused a field to be removed, consult the JSON Schema documentation on how to obtain the same value from JSON Schema (eg. [required properties](https://json-schema.org/understanding-json-schema/reference/object#required)). ### Renamed `exportSchemas` This config option is now called `schemas`. ## v0.35.0 ### Removed `postfixModels` This config option has been removed. ## v0.34.0 ### Single `services.ts` file Services are now exported from a single file. If you used imports from individual service files, these will need to be updated to refer to the single `services.ts` file. ## v0.31.1 ### Merged enums options `useLegacyEnums` config option is now `enums: 'typescript'` and existing `enums: true` option is now `enums: 'javascript'`. ## v0.31.0 ### Single `models.ts` file TypeScript interfaces are now exported from a single file. If you used imports from individual model files, these will need to be updated to refer to the single `models.ts` file. ### Single `schemas.ts` file Schemas are now exported from a single file. If you used imports from individual schema files, these will need to be updated to refer to the single `schemas.ts` file. ## v0.27.38 ### `useOptions: true` By default, generated clients will use a single object argument to pass values to API calls. This is a significant change from the previous default of unspecified array of arguments. If migrating your application in one go isn't feasible, we recommend deprecating your old client and generating a new client. ```ts import { DefaultService } from 'client/services'; // <-- old client with array arguments import { DefaultService } from 'client_v2/services'; // <-- new client with options argument ``` This way, you can gradually switch over to the new syntax as you update parts of your code. Once you've removed all instances of `client` imports, you can safely delete the old `client` folder and find and replace all `client_v2` calls to `client`. ## v0.27.36 ### `exportSchemas: true` By default, we will create schemas from your OpenAPI specification. Use `exportSchemas: false` to preserve the old behavior. ## v0.27.32 ### Renamed `Config` interface This interface is now called `UserConfig`. ## v0.27.29 ### Renamed `openapi` CLI command This command is now called `openapi-ts`. ## v0.27.26 ### Removed `indent` This config option has been removed. Use a [code formatter](/openapi-ts/configuration/output#post-process) to modify the generated files code style according to your preferences. ## v0.27.24 ### Removed `useUnionTypes` This config option has been removed. Generated types will behave the same as `useUnionTypes: true` before. ## OpenAPI TypeScript Codegen `@hey-api/openapi-ts` was originally forked from Ferdi Koomen's [openapi-typescript-codegen](https://github.com/ferdikoomen/openapi-typescript-codegen). Therefore, we want you to be able to migrate your projects. Migration should be relatively straightforward if you follow the release notes on this page. Start on [v0.27.24](#v0-27-24) and scroll to the release you're migrating to. ================================================ FILE: docs/openapi-ts/mocks.md ================================================ --- title: Mocks description: Learn about mocking HTTP servers with @hey-api/openapi-ts. --- # Mocks Realistic mock data is an important component of every robust development process, testing strategy, and product presentation. ## Options Hey API natively supports the following mocking frameworks. - [Chance](/openapi-ts/plugins/chance) Soon - [Faker](/openapi-ts/plugins/faker) Soon - [Falso](/openapi-ts/plugins/falso) Soon - [MSW](/openapi-ts/plugins/msw) Soon - [Nock](/openapi-ts/plugins/nock) Soon - [Supertest](/openapi-ts/plugins/supertest) Soon Don't see your framework? Let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ================================================ FILE: docs/openapi-ts/output.md ================================================ --- title: Output description: Learn about files generated with @hey-api/openapi-ts. --- # Output Every generated file in your output folder is created by a plugin. This page describes the default output, but similar logic applies to all plugins. ## Overview If you use the default configuration, your [project](https://stackblitz.com/edit/hey-api-example?file=openapi-ts.config.ts,src%2Fclient%2Fschemas.gen.ts,src%2Fclient%2Fsdk.gen.ts,src%2Fclient%2Ftypes.gen.ts) might look like this. ```txt my-app/ ├── node_modules/ ├── src/ │ ├── client/ │ │ ├── client/ │ │ ├── core/ │ │ ├── client.gen.ts │ │ ├── index.ts │ │ ├── sdk.gen.ts │ │ └── types.gen.ts │ └── index.ts └── package.json ``` Your actual output depends on your Hey API configuration. It may contain a different number of files and their contents might differ. Let's go through each file in the `src/client` folder and explain what it looks like, what it does, and how to use it. ## Client `client.gen.ts` is generated by [client plugins](/openapi-ts/clients). If you choose to generate SDKs (enabled by default), we use the Fetch client unless specified otherwise. ::: code-group ```ts [client.gen.ts] import { createClient, createConfig } from './client'; export const client = createClient(createConfig()); ``` ::: The contents of this file are consumed by SDKs, but you can also import `client` in your application to perform additional configuration or send manual requests. ### Bundle Client plugins provide their bundles inside `client` and `core` folders. The contents of these folders don't depend on the provided input. Everything inside these folders serves as a scaffolding so the generated code can make HTTP requests. ## TypeScript You can learn more on the [TypeScript](/openapi-ts/plugins/typescript) page. ## SDK You can learn more on the [SDK](/openapi-ts/plugins/sdk) page. ## Entry File `index.ts` is not generated by any specific plugin. It's meant for convenience and by default, it re-exports every artifact generated by default plugins (TypeScript and SDK). ::: code-group ```ts [index.ts] export * from './sdk.gen'; export * from './types.gen'; ``` ::: ### Disable entry file We recommend importing artifacts from their respective files to avoid ambiguity, but we leave this choice up to you. ```ts import type { Pet } from './client'; // or import type { Pet } from './client/types.gen'; ``` If you're not importing artifacts from the entry file, you can skip generating it altogether by setting the `output.entryFile` option to `false`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: { entryFile: false, // [!code ++] path: 'src/client', }, }; ``` ### Re-export artifacts You can choose which artifacts should be re-exported from the entry file using the `includeInEntry` option on any plugin. For example, we can re-export all [Zod](/openapi-ts/plugins/zod) plugin artifacts by setting `includeInEntry` to `true`: ::: code-group ```ts [example] export { zAddPetData, zAddPetResponse, zApiResponse, zCategory, // ...more exports } from './zod.gen'; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { includeInEntry: true, // [!code ++] name: 'zod', }, ], }; ``` ::: Or we can re-export only specific artifacts by providing a predicate function: ::: code-group ```ts [example] export { zTag } from './zod.gen'; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { includeInEntry: (symbol) => symbol.name === 'zTag', // [!code ++] name: 'zod', }, ], }; ``` ::: ================================================ FILE: docs/openapi-ts/plugins/adonis.md ================================================ --- title: AdonisJS description: AdonisJS plugin for Hey API. Compatible with all our features. --- # AdonisJS soon ### About [AdonisJS](https://adonisjs.com) is a TypeScript-first web framework for building web apps and API servers. It comes with support for testing, modern tooling, an ecosystem of official packages, and more. ================================================ FILE: docs/openapi-ts/plugins/ajv.md ================================================ --- title: Ajv description: Ajv plugin for Hey API. Compatible with all our features. --- # Ajv soon ### About [Ajv](https://ajv.js.org) is the fastest JSON validator for Node.js and browser. ================================================ FILE: docs/openapi-ts/plugins/angular/v19.md ================================================ --- title: Angular v19 Plugin description: Generate Angular v19 HTTP requests and resources from OpenAPI with the Angular plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Angular v19

    ::: warning Angular client is currently in beta. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ### About [Angular](https://angular.dev/) is a web framework that empowers developers to build fast, reliable applications. The Angular plugin for Hey API generates HTTP requests and resources from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Collaborators ## Features - Angular v19 support - seamless integration with `@hey-api/openapi-ts` ecosystem - generate HTTP requests - generate HTTP resources - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `@angular/common` to your plugins and you'll be ready to generate Angular artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@angular/common', // [!code ++] ], }; ``` ## Output The Angular plugin will generate the following artifacts, depending on the input specification. ## Requests A single function is generated for each endpoint. It returns an [`HttpRequest`](https://v19.angular.dev/api/common/http/HttpRequest) result. ::: code-group ```ts [example] export const addPetRequest = (options) => client.requestOptions({ method: 'POST', responseStyle: 'data', url: '/pet', ...options, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@angular/common', httpRequests: true, // [!code ++] }, ], }; ``` ::: ## Resources A single function is generated for each endpoint. It returns a result from [`httpResource`](https://v19.angular.dev/api/common/http/httpResource) call. ::: code-group ```ts [example] export const addPetResource = (options) => httpResource(() => addPetRequest(options())); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@angular/common', httpResources: true, // [!code ++] }, ], }; ``` ::: ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@angular/common/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/angular.md ================================================ --- title: Angular v20 Plugin description: Generate Angular v20 HTTP requests and resources from OpenAPI with the Angular plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Angular v20

    ::: warning Angular client is currently in beta. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ### About [Angular](https://angular.dev/) is a web framework that empowers developers to build fast, reliable applications. The Angular plugin for Hey API generates HTTP requests and resources from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ### Collaborators ## Features - Angular v20 support - seamless integration with `@hey-api/openapi-ts` ecosystem - generate HTTP requests - generate HTTP resources - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `@angular/common` to your plugins and you'll be ready to generate Angular artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@angular/common', // [!code ++] ], }; ``` ## Output The Angular plugin will generate the following artifacts, depending on the input specification. ## Requests A single function is generated for each endpoint. It returns an [`HttpRequest`](https://angular.dev/api/common/http/HttpRequest) result. ::: code-group ```ts [example] export const addPetRequest = (options) => client.requestOptions({ method: 'POST', responseStyle: 'data', url: '/pet', ...options, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@angular/common', httpRequests: true, // [!code ++] }, ], }; ``` ::: ## Resources A single function is generated for each endpoint. It returns a result from [`httpResource`](https://angular.dev/api/common/http/httpResource) call. ::: code-group ```ts [example] export const addPetResource = (options) => httpResource(() => addPetRequest(options())); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@angular/common', httpResources: true, // [!code ++] }, ], }; ``` ::: ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@angular/common/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/arktype.md ================================================ --- title: Arktype description: Arktype plugin for Hey API. Compatible with all our features. --- # Arktype soon ### About [Arktype](https://arktype.io) is a TypeScript's 1:1 validator, optimized from editor to runtime. ================================================ FILE: docs/openapi-ts/plugins/chance.md ================================================ --- title: Chance description: Chance plugin for Hey API. Compatible with all our features. --- # Chance soon ### About [Chance](https://chancejs.com/) is a minimalist generator of random strings, numbers, etc. to help reduce some monotony particularly while writing automated tests or anywhere else you need anything random. ================================================ FILE: docs/openapi-ts/plugins/concepts/resolvers.md ================================================ --- title: Resolvers description: Understand the concepts behind plugins. --- # Resolvers Sometimes the default plugin behavior isn't what you need or expect. Resolvers let you patch plugins in a safe and performant way, without forking or reimplementing core logic. Currently available for [TypeScript](/openapi-ts/plugins/typescript), [Valibot](/openapi-ts/plugins/valibot), and [Zod](/openapi-ts/plugins/zod). ## Examples This page demonstrates resolvers through a few common scenarios. 1. [Handle arbitrary schema formats](#example-1) 2. [Validate high precision numbers](#example-2) 3. [Replace default base](#example-3) 4. [Create permissive enums](#example-4) ## Terminology Before we look at examples, let's go through the resolvers API to help you understand how they work. Plugins that support resolvers expose them through the `~resolvers` option. Each resolver is a function that receives context and returns an implemented node (or patches existing ones). The resolver context will usually contain: - `$` - The node builder interface. Use it to build your custom logic. - `nodes` - Parts of the plugin logic. You can use these to avoid reimplementing the functionality, or replace them with custom implementation. - `plugin` - The plugin instance. You'll most likely use it to register new symbols. - `symbols` - Frequently used symbols. These are effectively shorthands for commonly used `plugin.referenceSymbol()` calls. Other fields may include the current schema or relevant utilities. ## Example 1 ### Handle arbitrary schema formats By default, the Valibot plugin may produce the following schemas for `date` and `date-time` strings. ```js export const vDates = v.object({ created: v.pipe(v.string(), v.isoDate()), modified: v.pipe(v.string(), v.isoTimestamp()), }); ``` We can override this behavior by patching the `nodes.format` function only for strings with `date` or `date-time` formats. ```js { name: 'valibot', '~resolvers': { string(ctx) { const { $, schema, symbols } = ctx; const { v } = symbols; if (schema.format === 'date' || schema.format === 'date-time') { ctx.nodes.format = () => $(v).attr('isoDateTime').call(); } } } } ``` This applies custom logic with surgical precision, without affecting the rest of the default behavior. ::: code-group ```js [after] export const vDates = v.object({ created: v.pipe(v.string(), v.isoDateTime()), modified: v.pipe(v.string(), v.isoDateTime()), }); ``` ```js [before] export const vDates = v.object({ created: v.pipe(v.string(), v.isoDate()), modified: v.pipe(v.string(), v.isoTimestamp()), }); ``` ::: ## Example 2 ### Validate high precision numbers Let's say you're dealing with very large or unsafe numbers. ```js export const vAmount = v.number(); ``` In this case, you'll want to use a third-party library to validate your values. We can use big.js to validate all numbers by replacing the whole resolver. ```js { name: 'valibot', '~resolvers': { number(ctx) { const { $, plugin, symbols } = ctx; const { v } = symbols; const big = plugin.symbolOnce('Big', { external: 'big.js', importKind: 'default', }); return $(v).attr('instance').call(big); } } } ``` We're calling `plugin.symbolOnce()` to ensure we always use the same symbol reference. ::: code-group ```js [after] import Big from 'big.js'; export const vAmount = v.instance(Big); ``` ```js [before] export const vAmount = v.number(); ``` ::: ## Example 3 ### Replace default base You might want to replace the default base schema, e.g., `v.object()`. ```js export const vUser = v.object({ age: v.number(), }); ``` Let's say we want to interpret any schema without explicitly defined additional properties as a loose object. ```js { name: 'valibot', '~resolvers': { object(ctx) { const { $, symbols } = ctx; const { v } = symbols; const additional = ctx.nodes.additionalProperties(ctx); if (additional === undefined) { const shape = ctx.nodes.shape(ctx); ctx.nodes.base = () => $(v).attr('looseObject').call(shape); } } } } ``` Above we demonstrate patching a node based on the result of another node. ::: code-group ```js [after] export const vUser = v.looseObject({ age: v.number(), }); ``` ```js [before] export const vUser = v.object({ age: v.number(), }); ``` ::: ## Example 4 ### Create permissive enums By default, enum schemas are strict and will reject unknown values. ```js export const zStatus = z.enum(['active', 'inactive', 'pending']); ``` You might want to accept unknown enum values, for example when the API adds new values that haven't been added to the spec yet. You can use the enum resolver to create a permissive union. ```js { name: 'zod', '~resolvers': { enum(ctx) { const { $, symbols } = ctx; const { z } = symbols; const { allStrings, enumMembers, literalMembers } = ctx.nodes.items(ctx); if (!allStrings || !enumMembers.length) { return; } const enumSchema = $(z).attr('enum').call($.array(...enumMembers)); return $(z).attr('union').call( $.array(enumSchema, $(z).attr('string').call()) ); } } } ``` This resolver creates a union that accepts both the known enum values and any other string. ::: code-group ```js [after] export const zStatus = z.union([z.enum(['active', 'inactive', 'pending']), z.string()]); ``` ```js [before] export const zStatus = z.enum(['active', 'inactive', 'pending']); ``` ::: ## Feedback We welcome feedback on the Resolvers API. [Open a GitHub issue](https://github.com/hey-api/openapi-ts/issues) to request support for additional plugins. ================================================ FILE: docs/openapi-ts/plugins/custom.md ================================================ --- title: Custom Plugin description: Learn how to create your own Hey API plugin. --- # Custom Plugin ::: warning Plugin API is in development. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ::: warning This page is out of date as of [v0.83.0](/openapi-ts/migrating#v0-83-0). If you have an existing custom plugin, we recommend waiting for a more stable Plugin API to avoid multiple plugin rewrites. ::: You may need to write your own plugin if the available plugins do not suit your needs or you're working on a proprietary use case. This can be easily achieved using the Plugin API. But don't take our word for it – all Hey API plugins are written this way! ## File Structure We recommend following the design pattern of the native plugins. You can browse the code on [GitHub](https://github.com/hey-api/openapi-ts/tree/main/packages/openapi-ts/src/plugins) as you follow this tutorial. First, create a `my-plugin` folder for your plugin files. Inside, create a barrel file `index.ts` exporting the plugin. ::: code-group ```ts [index.ts] export { defaultConfig, defineConfig } from './config'; export type { MyPlugin } from './types'; ``` ::: ## TypeScript `index.ts` references two files, so we need to create them. `types.ts` contains the TypeScript interface for your plugin options. It must have the reserved `name` and `output` fields, everything else will become user-configurable options. ::: code-group ```ts [types.ts] import type { DefinePlugin } from '@hey-api/openapi-ts'; export type UserConfig = { /** * Plugin name. Must be unique. */ name: 'my-plugin'; /** * Name of the generated file. * * @default 'my-plugin' */ output?: string; /** * User-configurable option for your plugin. * * @default false */ myOption?: boolean; }; export type MyPlugin = DefinePlugin; ``` ::: ## Configuration `config.ts` contains the runtime configuration for your plugin. It must implement the `MyPlugin` interface we created above and define the `handler()` function from the `MyPlugin['Config']` interface. ::: code-group ```ts [config.ts] import { definePluginConfig } from '@hey-api/openapi-ts'; import { handler } from './plugin'; import type { MyPlugin } from './types'; export const defaultConfig: MyPlugin['Config'] = { config: { myOption: false, // implements default value from types }, dependencies: ['@hey-api/typescript'], handler, name: 'my-plugin', }; /** * Type helper for `my-plugin` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ``` ::: In the file above, we define a `my-plugin` plugin which will generate a `my-plugin.gen.ts` file. We also demonstrate declaring `@hey-api/typescript` as a dependency for our plugin, so we can safely import artifacts from `types.gen.ts`. By default, your plugin output won't be re-exported from the `index.ts` file. To enable this feature, add `includeInEntry: true` to your `config.ts` file. ::: warning Re-exporting your plugin from index file may result in broken output due to naming conflicts. Ensure your exported identifiers are unique. ::: ## Handler Notice we defined `handler` in our `config.ts` file. This method is responsible for generating the actual output. We recommend implementing it in `plugin.ts`. ::: code-group ```ts [plugin.ts] import type { MyPlugin } from './types'; export const handler: MyPlugin['Handler'] = ({ plugin }) => { // create an output file. it will not be // generated until it contains nodes const file = plugin.createFile({ id: plugin.name, path: plugin.output, }); plugin.forEach('operation', 'schema', (event) => { if (event.type === 'operation') { // do something with the operation model } else if (event.type === 'schema') { // do something with the schema model } }); // we're using the TypeScript Compiler API const stringLiteral = ts.factory.createStringLiteral('Hello, world!'); const variableDeclaration = ts.factory.createVariableDeclaration( 'foo', undefined, undefined, stringLiteral, ); const node = ts.factory.createVariableStatement( [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], ts.factory.createVariableDeclarationList([variableDeclaration], ts.NodeFlags.Const), ); // add a node to our file file.add(node); }; ``` ::: ### Legacy Handler You can also define an optional `handlerLegacy` function in `config.ts`. This method is responsible for generating the output when using the legacy parser. We do not recommend implementing this method unless you must use the legacy parser. You can use one of our [`plugin-legacy.ts`](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/%40hey-api/typescript/plugin-legacy.ts) files as an inspiration for potential implementation. ## Usage Once we're satisfied with our plugin, we can register it in the [configuration](/openapi-ts/configuration) file. ```js import { defineConfig } from 'path/to/my-plugin'; export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ defineConfig({ myOption: true, }), ], }; ``` ## Output Putting all of this together will generate the following `my-plugin.gen.ts` file. ::: code-group ```ts [my-plugin.gen.ts] export const foo = 'Hello, world!'; ``` ::: Congratulations! You've successfully created your own plugin! :tada: ================================================ FILE: docs/openapi-ts/plugins/elysia.md ================================================ --- title: Elysia description: Elysia plugin for Hey API. Compatible with all our features. --- # Elysia soon ### About [Elysia](https://elysiajs.com/) is an ergonomic framework for humans. TypeScript with end-to-end type safety, type integrity, and exceptional developer experience. Supercharged by Bun. ================================================ FILE: docs/openapi-ts/plugins/express.md ================================================ --- title: Express description: Express plugin for Hey API. Compatible with all our features. --- # Express soon ### About [Express](https://expressjs.com) is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. ================================================ FILE: docs/openapi-ts/plugins/faker.md ================================================ --- title: Faker description: Faker plugin for Hey API. Compatible with all our features. --- # Faker soon ### About [Faker](https://fakerjs.dev) is a popular library that generates fake (but reasonable) data that can be used for things such as unit testing, performance testing, building demos, and working without a completed backend. ================================================ FILE: docs/openapi-ts/plugins/falso.md ================================================ --- title: Falso description: Falso plugin for Hey API. Compatible with all our features. --- # Falso soon ### About [Falso](https://ngneat.github.io/falso/) creates massive amounts of fake data in the browser and NodeJS. Tree shakeable & fully typed. ================================================ FILE: docs/openapi-ts/plugins/fastify.md ================================================ --- title: Fastify v5 Plugin description: Generate Fastify v5 route handlers from OpenAPI with the Fastify plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Fastify v5

    ::: warning Fastify plugin is currently in beta. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ### About [Fastify](https://fastify.dev) is a fast and low overhead web framework for Node.js. The Fastify plugin for Hey API generates route handlers from your OpenAPI spec, fully compatible with all core features. ### Collaborators ## Features - Fastify v5 support - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe route handlers - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `fastify` to your plugins and you'll be ready to generate Fastify artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins 'fastify', // [!code ++] ], }; ``` ## Output The Fastify plugin will generate the following artifacts, depending on the input specification. ## Route Handlers Route handlers are generated from all endpoints. The generated interface follows the naming convention of SDK functions. ::: code-group ```ts [example] const fastify = Fastify(); const serviceHandlers: RouteHandlers = { createPets(request, reply) { reply.code(201).send(); }, listPets(request, reply) { reply.code(200).send([]); }, showPetById(request, reply) { reply.code(200).send({ id: Number(request.params.petId), name: 'Kitty', }); }, }; fastify.register(glue, { serviceHandlers }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'fastify', }, ], }; ``` ::: ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/fastify/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/hono.md ================================================ --- title: Hono description: Hono plugin for Hey API. Compatible with all our features. --- # Hono soon ### About [Hono](https://hono.dev) is a small, simple, and ultrafast web framework built on Web Standards. It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Netlify, AWS Lambda, Lambda@Edge, and Node.js. ================================================ FILE: docs/openapi-ts/plugins/joi.md ================================================ --- title: Joi description: Joi plugin for Hey API. Compatible with all our features. --- # Joi soon ### About [Joi](https://joi.dev) is the most powerful schema description language and data validator for JavaScript. ================================================ FILE: docs/openapi-ts/plugins/koa.md ================================================ --- title: Koa description: Koa plugin for Hey API. Compatible with all our features. --- # Koa soon ### About [Koa](https://koajs.com) is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. ================================================ FILE: docs/openapi-ts/plugins/msw.md ================================================ --- title: MSW description: MSW plugin for Hey API. Compatible with all our features. --- # MSW soon ### About [MSW](https://mswjs.io) is an API mocking library that allows you to write client-agnostic mocks and reuse them across any frameworks, tools, and environments. ================================================ FILE: docs/openapi-ts/plugins/nest.md ================================================ --- title: NestJS v11 Plugin description: Generate NestJS v11 controller methods from OpenAPI with the NestJS plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    NestJS v11

    ::: warning NestJS plugin is currently in beta. The interface might change before it becomes stable. We encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ### About [Nest](https://nestjs.com) is a progressive Node.js framework for building efficient, reliable and scalable server-side applications. The NestJS plugin for Hey API generates type-safe controller method signatures from your OpenAPI spec, fully compatible with all core features. ### Collaborators ## Features - NestJS v11 support - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe controller methods - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `nestjs` to your plugins and you'll be ready to generate NestJS artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins 'nestjs', // [!code ++] ], }; ``` ## Output The NestJS plugin will generate the following artifacts, depending on the input specification. ## Controller Methods Operations are grouped by their first tag into separate types. ::: code-group ```ts [example] export type PetsControllerMethods = { createPet: (body: CreatePetData['body']) => Promise; listPets: (query?: ListPetsData['query']) => Promise; showPetById: (path: ShowPetByIdData['path']) => Promise; }; export type StoreControllerMethods = { getInventory: () => Promise; }; ``` ```ts [usage] import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common'; import type { PetsControllerMethods } from '../client/nestjs.gen'; import type { CreatePetData, ListPetsData, ShowPetByIdData } from '../client/types.gen'; @Controller('pets') export class PetsController implements Pick< PetsControllerMethods, 'createPet' | 'listPets' | 'showPetById' > { @Post() async createPet(@Body() body: CreatePetData['body']) {} @Get() async listPets(@Query() query?: ListPetsData['query']) {} @Get(':petId') async showPetById(@Param() path: ShowPetByIdData['path']) {} } ``` ::: ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/nestjs/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/nock.md ================================================ --- title: Nock description: Nock plugin for Hey API. Compatible with all our features. --- # Nock soon ### About [Nock](https://github.com/nock/nock) is an HTTP server mocking and expectations library for Node.js. ================================================ FILE: docs/openapi-ts/plugins/pinia-colada.md ================================================ --- title: Pinia Colada v0 Plugin description: Generate Pinia Colada v0 functions and query keys from OpenAPI with the Pinia Colada plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Pinia Colada v0

    ### About [Pinia Colada](https://pinia-colada.esm.dev) is the perfect companion to Pinia to handle async state management in your Vue applications. The Pinia Colada plugin for Hey API generates functions and query keys from your OpenAPI spec, fully compatible with SDKs, transformers, and all core features. ### Collaborators ## Features - Pinia Colada v0 support - seamless integration with `@hey-api/openapi-ts` ecosystem - create query keys following the best practices - type-safe query options and mutation options - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `@pinia/colada` to your plugins and you'll be ready to generate Pinia Colada artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@pinia/colada', // [!code ++] ], }; ``` ::: tip When using this plugin in a Nuxt app, prefer the [ofetch client](/openapi-ts/clients/ofetch) for universal compatibility. The [nuxt client](/openapi-ts/clients/nuxt) is tailored for working directly with Nuxt composables (`$fetch` / `useFetch` / `useAsyncData`) and is not intended as a universal HTTP client for libraries like `@pinia/colada`. ::: ## Output The Pinia Colada plugin will generate the following artifacts, depending on the input specification. ## Queries Queries are generated from [query operations](/openapi-ts/configuration/parser#hooks-query-operations). The generated query functions follow the naming convention of SDK functions and by default append `Query`, e.g., `getPetByIdQuery()`. ::: code-group ```ts [example] const query = useQuery(getPetByIdQuery, () => ({ path: { petId: 1, }, })); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@pinia/colada', queryOptions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `queryOptions` functions using the `.name` and `.case` options. ## Query Keys Query keys contain normalized SDK function parameters and additional metadata. ::: code-group ```ts [example] const queryKey = [ { _id: 'getPetById', baseUrl: 'https://app.heyapi.dev', path: { petId: 1, }, }, ]; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@pinia/colada', queryKeys: true, // [!code ++] }, ], }; ``` ::: ### Tags You can include operation tags in your query keys by setting `tags` to `true`. This will make query keys larger but provides better cache invalidation capabilities. ::: code-group ```ts [example] const key = [ { _id: 'getPetById', baseUrl: 'https://app.heyapi.dev', path: { petId: 1, }, tags: ['pets', 'one', 'get'], // [!code ++] }, ]; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@pinia/colada', queryKeys: { tags: true, // [!code ++] }, }, ], }; ``` ::: ### Accessing Query Keys If you have access to the result of query options function, you can get the query key from the `key` field. ::: code-group ```ts [example] const { key } = getPetByIdQuery({ path: { petId: 1, }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@pinia/colada', queryOptions: true, // [!code ++] }, ], }; ``` ::: Alternatively, you can access the same query key by calling query key functions. The generated query key functions follow the naming convention of SDK functions and by default append `QueryKey`, e.g., `getPetByIdQueryKey()`. ::: code-group ```ts [example] const key = getPetByIdQueryKey({ path: { petId: 1, }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@pinia/colada', queryKeys: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `queryKeys` functions using the `.name` and `.case` options. ## Mutations Mutations are generated from [mutation operations](/openapi-ts/configuration/parser#hooks-mutation-operations). The generated mutation functions follow the naming convention of SDK functions and by default append `Mutation`, e.g., `addPetMutation()`. ::: code-group ```ts [example] const addPet = useMutation({ ...addPetMutation(), onError: (error) => { console.log(error); }, }); addPet.mutate({ body: { name: 'Kitty', }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@pinia/colada', mutationOptions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `mutationOptions` functions using the `.name` and `.case` options. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@pinia/colada/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/schemas.md ================================================ --- title: JSON Schema description: Learn about files generated with @hey-api/openapi-ts. --- # JSON Schemas Schemas are located in the `schemas.gen.ts` file. This file contains runtime schemas generated from your OpenAPI specification definitions located in `#/components/schemas`. If you're using OpenAPI 3.1, your schemas are fully JSON Schema compliant and can be used with other tools supporting JSON Schema. ## Configuration You can modify the contents of `schemas.gen.ts` by configuring the `@hey-api/schemas` plugin. Note that you must specify the default plugins to preserve the default output. ::: code-group ```js [json] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/schemas', type: 'json', // [!code ++] }, ], }; ``` ```js [form] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/schemas', type: 'form', // [!code ++] }, ], }; ``` ```js [disabled] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@hey-api/schemas', // [!code --] ], }; ``` ::: ## Output Below is an example output generated in the `type: 'form'` style. Disabling schemas will not generate the `schemas.gen.ts` file. ```ts export const PetSchema = { required: ['name'], properties: { id: { type: 'integer', format: 'int64', example: 10, }, name: { type: 'string', example: 'doggie', }, }, type: 'object', } as const; ``` ## Usage A great use case for schemas is client-side form input validation. ```ts import { $Schema } from './client/schemas.gen'; const maxInputLength = $Schema.properties.text.maxLength; if (userInput.length > maxInputLength) { throw new Error(`Text length can't exceed ${maxInputLength} characters!`); } ``` ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/schemas/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/sdk.md ================================================ --- title: SDK Plugin description: Generate SDKs from OpenAPI with the SDK plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. --- # SDK ### About The SDK plugin generates a high-level, ergonomic API layer on top of the low-level HTTP client. It exposes typed functions or methods for each operation, with built-in auth handling, configurable request and response validation, and ready-to-use code examples. ## Features - high-level SDK layer on top of the HTTP client - typed functions or methods per operation - built-in authentication handling - request and response validation - ready-to-use code examples ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/sdk` to your plugins and you'll be ready to generate SDK artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@hey-api/sdk', // [!code ++] ], }; ``` ## Output The SDK plugin supports a wide range of configuration options. This guide focuses on two main SDK formats: tree-shakeable functions and instantiable classes, but you can apply the same concepts to create more advanced configurations. ## Flat This is the default setting. Flat SDKs support tree-shaking, which can lead to a reduced bundle size. You select flat mode by setting `operations.strategy` to `flat`. ::: code-group ```ts [example] import type { AddPetData } from './types.gen'; export const addPet = (options: Options) => { /** ... */ }; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', operations: { strategy: 'flat', // [!code ++] }, }, ], }; ``` ::: ## Instance Class SDKs do not support tree-shaking, which results in a larger bundle size, but you may prefer their syntax. You select class mode by setting `operations.strategy` to `single`. ::: code-group ```ts [example] import type { AddPetData } from './types.gen'; export class Sdk extends HeyApiClient { public addPet(options: Options) { /** ... */ } } ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', operations: { strategy: 'single', // [!code ++] }, }, ], }; ``` ::: ### Name As shown above, by default our SDK class is called `Sdk`. The first thing you'll likely want to do is change this to your preferred name, which you can do using `operation.containerName`. ::: code-group ```ts [example] import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses } from './types.gen'; export class PetStore extends HeyApiClient { // [!code ++] /** ... */ } ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', operations: { containerName: 'PetStore', // [!code ++] strategy: 'single', }, }, ], }; ``` ::: ### Structure While we try to infer the SDK structure from `operationId` fields, you'll likely want to customize it further. You can do this using `operations.nesting`. Similar to the `operations.strategy` option, we provide a few presets. However, you gain the most control by providing your own function. To demonstrate the power of this feature, let's nest a few endpoints inside a `Pet` class and rename them. Our original `addPet()` method will now become `pet.add()`. Notice that we use the built-in `OperationPath.fromOperationId()` helper to handle the remaining operations. ::: code-group ```ts [example] import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses } from './types.gen'; export class Pet extends HeyApiClient { public add(options: Options) { // [!code ++] /** ... */ } } export class PetStore extends HeyApiClient { get pet(): Pet { // [!code ++] /** ... */ } } ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', operations: { containerName: 'PetStore', nesting(operation) { if (operation.path === '/pet/{petId}' || operation.path === '/pet') { // [!code ++] return ['pet', operation.operationId?.replace(/Pet/, '') // [!code ++] || operation.method.toLocaleLowerCase()]; // [!code ++] } // [!code ++] return OperationPath.fromOperationId()(operation); // [!code ++] }, strategy: 'single', }, }, ], }; ``` ::: ## Auth Most APIs require some form of authentication, which is why the SDK plugin provides built-in auth mechanisms by default. All you need to do is return the data from the `auth()` function, and the SDK will handle serialization and encoding for you. There are several ways to do this, for example on the client instance. ::: code-group ```ts [example] import { client } from './client.gen'; client.setConfig({ auth() { return ''; }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { auth: true, // [!code ++] name: '@hey-api/sdk', }, ], }; ``` ::: ::: info The SDK plugin currently supports only the `bearer` and `basic` auth schemes. [Open an issue](https://github.com/hey-api/openapi-ts/issues) if you'd like support for additional mechanisms. ::: ## Validators Validating data at runtime comes with a performance cost, which is why it's not enabled by default. To enable validation, set `validator` to `zod` or one of the available [validator plugins](/openapi-ts/validators). This will implicitly add the selected plugin with default values. For a more granular approach, manually add a validator plugin and set `validator` to the plugin name or `true` to automatically select a compatible plugin. Until you customize the validator plugin, both approaches will produce the same default output. ::: code-group ```ts [example] import * as v from 'valibot'; export const addPet = (options: Options) => (options.client ?? client).post({ requestValidator: async (data) => // [!code ++] await v.parseAsync(vAddPetData, data), // [!code ++] responseValidator: async (data) => // [!code ++] await v.parseAsync(vAddPetResponse, data), // [!code ++] /** ... */ }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', validator: true, // or 'valibot' // [!code ++] }, { name: 'valibot', // customize (optional) // [!code ++] // other options }, ], }; ``` ::: You can choose to validate only requests or responses. ::: code-group ```js [requests] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', validator: { request: 'zod', // [!code ++] }, }, ], }; ``` ```js [responses] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@hey-api/sdk', validator: { response: 'zod', // [!code ++] }, }, ], }; ``` ::: Learn more about available validators on the [Validators](/openapi-ts/validators) page. ## Code Examples The SDK plugin can generate ready-to-use code examples for each operation, showing how to call the SDK methods with proper parameters and setup. Examples are not generated by default, but you can enable and customize them through the `examples` option. With the default settings, an example might look like this. ::: code-group ```ts [example] import { PetStore } from 'your-package'; await new PetStore().addPet(); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { examples: true, // [!code ++] name: '@hey-api/sdk', operations: { containerName: 'PetStore', strategy: 'single', }, }, ], }; ``` ::: ### Module and Setup To make examples more practical, configure `moduleName` to specify the package from which users import your SDK. Next, set `setupName` to indicate how users should instantiate the SDK, typically only once per application. ::: code-group ```ts [example] import { PetStore } from '@petstore/client'; // [!code ++] const client = new PetStore(); // [!code ++] await client.addPet(); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { examples: { moduleName: '@petstore/client', // [!code ++] setupName: 'client', // [!code ++] }, name: '@hey-api/sdk', operations: { containerName: 'PetStore', strategy: 'single', }, }, ], }; ``` ::: ### Initialization Often, your SDK needs to be instantiated with an API key or other configuration. In examples, `importSetup` lets you control how the SDK is initialized. ::: code-group ```ts [example] import { PetStore } from '@petstore/client'; const client = new PetStore({ // [!code ++] apiKey: 'YOUR_API_KEY', // [!code ++] }); // [!code ++] await client.addPet(); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { examples: { importSetup: ({ $, node }) => // [!code ++] $.new( // [!code ++] node.name, // [!code ++] $.object() // [!code ++] .pretty() // [!code ++] .prop('apiKey', $.literal('YOUR_API_KEY')), // [!code ++] ), // [!code ++] moduleName: '@petstore/client', setupName: 'client', }, name: '@hey-api/sdk', operations: { containerName: 'PetStore', strategy: 'single', }, }, ], }; ``` ::: ### Import Style If you re-export the generated SDK from your own module, you can adjust `importName` and `importKind` to match your actual import style. ::: code-group ```ts [example] import CatStore from '@petstore/client'; // [!code ++] const client = new CatStore({ // [!code ++] apiKey: 'YOUR_API_KEY', }); await client.addPet(); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { examples: { importKind: 'default', // [!code ++] importName: 'CatStore', // [!code ++] importSetup: ({ $, node }) => $(node.name).call($.object().pretty().prop('apiKey', $.literal('YOUR_API_KEY'))), moduleName: '@petstore/client', setupName: 'client', }, name: '@hey-api/sdk', operations: { containerName: 'PetStore', strategy: 'single', }, }, ], }; ``` ::: ### Payload You can customize the example request using the `payload` option. Requests can also be customized selectively. For example, we can provide a default payload only for the `addPet()` method. ::: code-group ```ts [example] import CatStore from '@petstore/client'; const client = new CatStore({ apiKey: 'YOUR_API_KEY', }); await client.addPet({ // [!code ++] petId: 1234, // [!code ++] }); // [!code ++] ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { examples: { importKind: 'default', importName: 'CatStore', importSetup: ({ $, node }) => $(node.name).call( $.object().pretty().prop('apiKey', $.literal('YOUR_API_KEY')), ), moduleName: '@petstore/client', payload(operation, ctx) { // [!code ++] const { $ } = ctx; // [!code ++] if (operation.path === '/pet/{petId}' || operation.path === '/pet') { // [!code ++] return $.object().pretty().prop('petId', $.literal(1234)); // [!code ++] } // [!code ++] }, // [!code ++] setupName: 'client', }, name: '@hey-api/sdk', operations: { containerName: 'PetStore', strategy: 'single', }, }, ], }; ``` ::: ### Display Enabling examples does not produce visible output on its own. Examples are written into the source specification and can be consumed by documentation tools such as [Mintlify](https://kutt.to/6vrYy9) or [Scalar](https://kutt.to/skQUVd). To persist that specification, enable [Source](/openapi-ts/configuration/output#source) generation. ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/sdk/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/superstruct.md ================================================ --- title: Superstruct description: Superstruct plugin for Hey API. Compatible with all our features. --- # Superstruct soon ### About [Superstruct](https://docs.superstructjs.org) makes it easy to define interfaces and then validate JavaScript data against them. ================================================ FILE: docs/openapi-ts/plugins/supertest.md ================================================ --- title: Supertest description: Supertest plugin for Hey API. Compatible with all our features. --- # Supertest soon ### About [Supertest](https://github.com/ladjs/supertest) is a super-agent driven library for testing node.js HTTP servers using a fluent API. ================================================ FILE: docs/openapi-ts/plugins/swr.md ================================================ --- title: SWR description: SWR plugin for Hey API. Compatible with all our features. --- # SWR soon ### About [SWR](https://swr.vercel.app) is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data. ================================================ FILE: docs/openapi-ts/plugins/tanstack-query.md ================================================ --- title: TanStack Query v5 Plugin description: Generate TanStack Query v5 functions and query keys from OpenAPI with the TanStack Query plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    TanStack Query v5

    ### About [TanStack Query](https://tanstack.com/query) is a powerful asynchronous state management solution for TypeScript/JavaScript, React, Solid, Vue, Svelte, Angular, and Preact. The TanStack Query plugin for Hey API generates functions and query keys from your OpenAPI spec, fully compatible with SDKs, transformers, and all core features. ### Demo ## Features - TanStack Query v5 support - seamless integration with `@hey-api/openapi-ts` ecosystem - create query keys following the best practices - type-safe query options, infinite query options, and mutation options - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add TanStack Query to your plugins and you'll be ready to generate TanStack Query artifacts. :tada: ::: code-group ```js [react] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@tanstack/react-query', // [!code ++] ], }; ``` ```js [vue] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@tanstack/vue-query', // [!code ++] ], }; ``` ```js [angular] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@tanstack/angular-query-experimental', // [!code ++] ], }; ``` ```js [svelte] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@tanstack/svelte-query', // [!code ++] ], }; ``` ```js [solid] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@tanstack/solid-query', // [!code ++] ], }; ``` ```js [preact] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@tanstack/preact-query', // [!code ++] ], }; ``` ::: ## Output The TanStack Query plugin will generate the following artifacts, depending on the input specification. ## Queries Queries are generated from [query operations](/openapi-ts/configuration/parser#hooks-query-operations). The generated query functions follow the naming convention of SDK functions and by default append `Options`, e.g., `getPetByIdOptions()`. ::: code-group ```ts [example] const query = useQuery({ ...getPetByIdOptions({ path: { petId: 1, }, }), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', queryOptions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `queryOptions` functions using the `.name` and `.case` options. ### Meta You can use the `meta` field to attach arbitrary information to a query. To generate metadata for `queryOptions`, provide a function to the `.meta` option. ::: code-group ```ts [example] queryOptions({ // ...other fields meta: { id: 'getPetById', }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', queryOptions: { meta: (operation) => ({ id: operation.id }), // [!code ++] }, }, ], }; ``` ::: ## Query Keys Query keys contain normalized SDK function parameters and additional metadata. ::: code-group ```ts [example] const queryKey = [ { _id: 'getPetById', baseUrl: 'https://app.heyapi.dev', path: { petId: 1, }, }, ]; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', queryKeys: true, // [!code ++] }, ], }; ``` ::: ### Tags You can include operation tags in your query keys by setting `tags` to `true`. This will make query keys larger but provides better cache invalidation capabilities. ::: code-group ```ts [example] const queryKey = [ { _id: 'getPetById', baseUrl: 'https://app.heyapi.dev', path: { petId: 1, }, tags: ['pets', 'one', 'get'], // [!code ++] }, ]; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', queryKeys: { tags: true, // [!code ++] }, }, ], }; ``` ::: ### Accessing Query Keys If you have access to the result of query options function, you can get the query key from the `queryKey` field. ::: code-group ```ts [example] const { queryKey } = getPetByIdOptions({ path: { petId: 1, }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', queryOptions: true, // [!code ++] }, ], }; ``` ::: Alternatively, you can access the same query key by calling query key functions. The generated query key functions follow the naming convention of SDK functions and by default append `QueryKey`, e.g., `getPetByIdQueryKey()`. ::: code-group ```ts [example] const queryKey = getPetByIdQueryKey({ path: { petId: 1, }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', queryKeys: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `queryKeys` functions using the `.name` and `.case` options. ## Infinite Queries Infinite queries are generated from [query operations](/openapi-ts/configuration/parser#hooks-query-operations) if we detect a [pagination](/openapi-ts/configuration/parser#pagination) parameter. The generated infinite query functions follow the naming convention of SDK functions and by default append `InfiniteOptions`, e.g., `getFooInfiniteOptions()`. ::: code-group ```ts [example] const query = useInfiniteQuery({ ...getFooInfiniteOptions({ path: { fooId: 1, }, }), getNextPageParam: (lastPage, pages) => lastPage.nextCursor, initialPageParam: 0, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', infiniteQueryOptions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `infiniteQueryOptions` functions using the `.name` and `.case` options. ### Meta You can use the `meta` field to attach arbitrary information to a query. To generate metadata for `infiniteQueryOptions`, provide a function to the `.meta` option. ::: code-group ```ts [example] infiniteQueryOptions({ // ...other fields meta: { id: 'getPetById', }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', infiniteQueryOptions: { meta: (operation) => ({ id: operation.id }), // [!code ++] }, }, ], }; ``` ::: ## Infinite Query Keys Infinite query keys contain normalized SDK function parameters and additional metadata. ::: code-group ```ts [example] const queryKey = [ { _id: 'getPetById', _infinite: true, baseUrl: 'https://app.heyapi.dev', path: { petId: 1, }, }, ]; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', infiniteQueryKeys: true, // [!code ++] }, ], }; ``` ::: ### Tags You can include operation tags in your infinite query keys by setting `tags` to `true`. This will make query keys larger but provides better cache invalidation capabilities. ::: code-group ```ts [example] const queryKey = [ { _id: 'getPetById', _infinite: true, baseUrl: 'https://app.heyapi.dev', path: { petId: 1, }, tags: ['pets', 'one', 'get'], // [!code ++] }, ]; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', infiniteQueryKeys: { tags: true, // [!code ++] }, }, ], }; ``` ::: ### Accessing Infinite Query Keys If you have access to the result of infinite query options function, you can get the query key from the `queryKey` field. ::: code-group ```ts [example] const { queryKey } = getPetByIdInfiniteOptions({ path: { petId: 1, }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', infiniteQueryOptions: true, // [!code ++] }, ], }; ``` ::: Alternatively, you can access the same query key by calling query key functions. The generated query key functions follow the naming convention of SDK functions and by default append `InfiniteQueryKey`, e.g., `getPetByIdInfiniteQueryKey()`. ::: code-group ```ts [example] const queryKey = getPetByIdInfiniteQueryKey({ path: { petId: 1, }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', infiniteQueryKeys: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `infiniteQueryKeys` functions using the `.name` and `.case` options. ## Mutations Mutations are generated from [mutation operations](/openapi-ts/configuration/parser#hooks-mutation-operations). The generated mutation functions follow the naming convention of SDK functions and by default append `Mutation`, e.g., `addPetMutation()`. ::: code-group ```ts [example] const addPet = useMutation({ ...addPetMutation(), onError: (error) => { console.log(error); }, }); addPet.mutate({ body: { name: 'Kitty', }, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', mutationOptions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `mutationOptions` functions using the `.name` and `.case` options. ### Meta You can use the `meta` field to attach arbitrary information to a mutation. To generate metadata for `mutationOptions`, provide a function to the `.meta` option. ::: code-group ```ts [example] const mutationOptions = { // ...other fields meta: { id: 'getPetById', }, }; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@tanstack/react-query', mutationOptions: { meta: (operation) => ({ id: operation.id }), // [!code ++] }, }, ], }; ``` ::: ## Reactivity In Vue applications, you need to wrap the options functions in [`computed()`](https://vuejs.org/guide/essentials/computed) to make them reactive. Otherwise, TanStack Query won't know it should execute the query when its dependencies change. ::: code-group ```js [reactive] // ✅ Query will execute on `petId` change const query = useQuery( computed(() => getPetByIdOptions({ path: { petId: petId.value, }, }), ), ); ``` ```js [static] // ❌ Query will execute only once const query = useQuery( getPetByIdOptions({ path: { petId: petId.value, }, }), ); ``` ::: ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@tanstack/react-query/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/transformers.md ================================================ --- title: Transformers description: Learn about transforming data with @hey-api/openapi-ts. --- # Transformers JSON is the most commonly used data format in REST APIs. However, it does not map well to complex data types. For example, both regular strings and date strings become simple strings in JSON. One approach to this problem is using a [JSON superset](https://github.com/blitz-js/superjson). For most people, switching formats is not feasible. That's why we provide the `@hey-api/transformers` plugin. ::: warning Transformers currently handle only the most common use cases. If your data isn't being transformed as expected, we encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ::: ## Considerations Before deciding whether transformers are right for you, let's explain how they work. Transformers generate a runtime file, therefore they impact the bundle size. We generate a single transformer per operation response for the most efficient result, just like a human engineer would. ### Limitations Transformers handle only the most common scenarios. Some of the known limitations are: - union types are not transformed (e.g., if you have multiple possible response shapes) - only types defined through `$ref` are transformed - error responses are not transformed If your data isn't being transformed as expected, we encourage you to leave feedback on [GitHub](https://github.com/hey-api/openapi-ts/issues). ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/transformers` to your plugins and you'll be ready to generate transformers. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@hey-api/transformers', // [!code ++] ], }; ``` ## SDKs To automatically transform response data in your SDKs, set `sdk.transformer` to `true`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@hey-api/transformers', { name: '@hey-api/sdk', // [!code ++] transformer: true, // [!code ++] }, ], }; ``` ## Dates To convert date strings into `Date` objects, use the `dates` configuration option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { dates: true, // [!code ++] name: '@hey-api/transformers', }, ], }; ``` This will generate types that use `Date` instead of `string` and appropriate transformers. Note that third-party date packages are not supported at the moment. ## BigInt The `@hey-api/transformers` plugin will natively type all BigInts as `bigint` instead of `number`, which can affect arithmetic operations if your application previously used `number`. To force BigInts to be numbers, use the `bigint` configuration option. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { bigint: true, // [!code ++] name: '@hey-api/transformers', }, ], }; ``` ## Example A generated response transformer might look something like this. Please note the example has been edited for brevity. ::: code-group ```ts [transformers.gen.ts] import type { GetFooResponse } from './types.gen'; const quxSchemaResponseTransformer = (data: any) => { if (data.baz) { data.baz = new Date(data.baz); } return data; }; const bazSchemaResponseTransformer = (data: any) => { data = quxSchemaResponseTransformer(data); data.bar = new Date(data.bar); return data; }; export const getFooResponseTransformer = async (data: any): Promise => { data = bazSchemaResponseTransformer(data); return data; }; ``` ```ts [types.gen.ts] export type Baz = Qux & { id: 'Baz'; } & { foo: number; bar: Date; baz: 'foo' | 'bar' | 'baz'; qux: number; }; export type Qux = { foo: number; bar: number; baz?: Date; id: string; }; export type GetFooResponse = Baz; ``` ::: ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/transformers/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/typebox.md ================================================ --- title: TypeBox description: TypeBox plugin for Hey API. Compatible with all our features. --- # TypeBox soon ### About [TypeBox](https://github.com/sinclairzx81/typebox) is a JSON Schema type builder with static type resolution for TypeScript. ================================================ FILE: docs/openapi-ts/plugins/typescript.md ================================================ --- title: TypeScript description: Learn about files generated with @hey-api/openapi-ts. --- # TypeScript TypeScript interfaces are located in the `types.gen.ts` file. This is the only file that does not impact your bundle size and runtime performance. It will get discarded during build time, unless you configured to emit runtime [enums](#enums). ## Installation In your [configuration](/openapi-ts/get-started), add `@hey-api/typescript` to your plugins and you'll be ready to generate TypeScript artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@hey-api/typescript', // [!code ++] ], }; ``` :::tip The `@hey-api/typescript` plugin might be implicitly added to your `plugins` if another plugin depends on it. ::: ## Output The TypeScript plugin will generate the following artifacts, depending on the input specification. ## Requests A single request type is generated for each endpoint. It may contain a request body, parameters, and headers. ```ts export type AddPetData = { body: { id?: number; name: string; }; path?: never; query?: never; url: '/pets'; }; ``` You can customize the naming and casing pattern for `requests` types using the `.name` and `.case` options. ## Responses A single type is generated for all endpoint's responses. ```ts export type AddPetResponses = { 200: { id?: number; name: string; }; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; ``` You can customize the naming and casing pattern for `responses` types using the `.name` and `.case` options. ## Definitions A type is generated for every reusable definition from your input. ```ts export type Pet = { id?: number; name: string; }; ``` You can customize the naming and casing pattern for `definitions` types using the `.name` and `.case` options. ## Enums By default, `@hey-api/typescript` will emit enums only as types. You may want to generate runtime artifacts. A good use case is iterating through possible field values without manually typing arrays. To emit runtime enums, set `enums` to a valid option. ::: code-group ```js [disabled] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { enums: false, // default // [!code ++] name: '@hey-api/typescript', }, ], }; ``` ```js [javascript] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { enums: 'javascript', // [!code ++] name: '@hey-api/typescript', }, ], }; ``` ```js [typescript] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { enums: 'typescript', // [!code ++] name: '@hey-api/typescript', }, ], }; ``` ::: We recommend exporting enums as plain JavaScript objects. [TypeScript enums](https://www.typescriptlang.org/docs/handbook/enums.html) are not a type-level extension of JavaScript and pose [typing challenges](https://dev.to/ivanzm123/dont-use-enums-in-typescript-they-are-very-dangerous-57bh). ## Comments By default, `@hey-api/typescript` will include comments in the generated code based on descriptions from your OpenAPI specification. If you want to reduce the size of your generated files or prefer cleaner output, you can disable comments. ::: code-group ```js [enabled] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { comments: true, // default // [!code ++] name: '@hey-api/typescript', }, ], }; ``` ```js [disabled] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { comments: false, // [!code ++] name: '@hey-api/typescript', }, ], }; ``` ::: ## Resolvers You can further customize this plugin's behavior using [resolvers](/openapi-ts/plugins/concepts/resolvers). ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/@hey-api/typescript/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/valibot.md ================================================ --- title: Valibot v1 Plugin description: Generate Valibot v1 schemas from OpenAPI with the Valibot plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Valibot v1

    ### About [Valibot](https://valibot.dev) is the open source schema library for TypeScript with bundle size, type safety and developer experience in mind. The Valibot plugin for Hey API generates schemas from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ## Features - Valibot v1 support - seamless integration with `@hey-api/openapi-ts` ecosystem - Valibot schemas for requests, responses, and reusable definitions - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `valibot` to your plugins and you'll be ready to generate Valibot artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins 'valibot', // [!code ++] ], }; ``` ### SDKs To add data validators to your SDKs, set `sdk.validator` to `true`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins 'valibot', { name: '@hey-api/sdk', // [!code ++] validator: true, // [!code ++] }, ], }; ``` Learn more about data validators in your SDKs on the [SDKs](/openapi-ts/plugins/sdk#validators) page. ## Output The Valibot plugin will generate the following artifacts, depending on the input specification. ## Requests A single request schema is generated for each endpoint. It may contain a request body, parameters, and headers. ::: code-group ```ts [example] const vData = v.object({ body: v.optional( v.object({ foo: v.optional(v.string()), bar: v.optional(v.union([v.number(), v.null()])), }), ), path: v.object({ baz: v.string(), }), query: v.optional(v.never()), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'valibot', requests: true, // [!code ++] }, ], }; ``` ::: ::: tip If you need to access individual fields, you can do so using the [`.entries`](https://valibot.dev/api/object/) API. For example, we can get the request body schema with `vData.entries.body`. ::: You can customize the naming and casing pattern for `requests` schemas using the `.name` and `.case` options. ## Responses A single Valibot schema is generated for all endpoint's responses. If the endpoint describes multiple responses, the generated schema is a union of all possible response shapes. ::: code-group ```ts [example] const vResponse = v.union([ v.object({ foo: v.optional(v.string()), }), v.object({ bar: v.optional(v.number()), }), ]); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'valibot', responses: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `responses` schemas using the `.name` and `.case` options. ## Definitions A Valibot schema is generated for every reusable definition from your input. ::: code-group ```ts [example] const vFoo = v.pipe(v.number(), v.integer()); const vBar = v.object({ bar: v.optional(v.array(v.pipe(v.number(), v.integer()))), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'valibot', definitions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `definitions` schemas using the `.name` and `.case` options. ## Metadata It's often useful to associate a schema with some additional [metadata](https://valibot.dev/api/metadata/) for documentation, code generation, AI structured outputs, form validation, and other purposes. You can set `metadata` to `true` to attach descriptions to schemas when available. ::: code-group ```ts [example] export const vFoo = v.pipe( v.string(), v.metadata({ description: 'Additional metadata', }), ); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'valibot', metadata: true, // [!code ++] }, ], }; ``` ::: For more control over metadata, you can provide your own function. It receives the source `schema`, the target `node` object, and the `$` builder for populating metadata. ::: code-group ```ts [example] export const vFoo = v.pipe( v.string(), v.metadata({ hasTitle: false, createdAt: 1735732800000, }), ); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'valibot', metadata({ $, node, schema }) { // [!code ++] node.prop('hasTitle', $.literal(Boolean(schema.title))); // [!code ++] node.prop('createdAt', $.literal(Date.now())); // [!code ++] }, // [!code ++] }, ], }; ``` ::: ## Resolvers You can further customize this plugin's behavior using [resolvers](/openapi-ts/plugins/concepts/resolvers). ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/valibot/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/yup.md ================================================ --- title: Yup description: Yup plugin for Hey API. Compatible with all our features. --- # Yup soon ### About [Yup](https://github.com/jquense/yup) is a schema builder for runtime value parsing and validation. ================================================ FILE: docs/openapi-ts/plugins/zod/mini.md ================================================ --- title: Zod Mini Plugin description: Generate Zod Mini schemas from OpenAPI with the Zod plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Zod Mini

    ### About [Zod](https://zod.dev) is a TypeScript-first schema validation library with static type inference. The Zod plugin for Hey API generates schemas from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ## Features - Zod Mini support - seamless integration with `@hey-api/openapi-ts` ecosystem - Zod schemas for requests, responses, and reusable definitions - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `zod` to your plugins and you'll be ready to generate Zod artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', // [!code ++] compatibilityVersion: 'mini', // [!code ++] }, ], }; ``` ### SDKs To add data validators to your SDKs, set `sdk.validator` to `true`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', }, { name: '@hey-api/sdk', // [!code ++] validator: true, // [!code ++] }, ], }; ``` Learn more about data validators in your SDKs on the [SDKs](/openapi-ts/plugins/sdk#validators) page. ## Output The Zod plugin will generate the following artifacts, depending on the input specification. ## Requests A single request schema is generated for each endpoint. It may contain a request body, parameters, and headers. ::: code-group ```ts [example] const zData = z.object({ body: z .object({ foo: z.optional(z.string()), bar: z.optional(z.union([z.number(), z.null()])), }) .optional(), path: z.object({ baz: z.string(), }), query: z.optional(z.never()), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', requests: true, // [!code ++] }, ], }; ``` ::: ::: tip If you need to access individual fields, you can do so using the [`.def.shape`](https://zod.dev/api?id=shape) API. For example, we can get the request body schema with `zData.def.shape.body`. ::: You can customize the naming and casing pattern for `requests` schemas using the `.name` and `.case` options. ## Responses A single Zod schema is generated for all endpoint's responses. If the endpoint describes multiple responses, the generated schema is a union of all possible response shapes. ::: code-group ```ts [example] const zResponse = z.union([ z.object({ foo: z.optional(z.string()), }), z.object({ bar: z.optional(z.number()), }), ]); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', responses: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `responses` schemas using the `.name` and `.case` options. ## Definitions A Zod schema is generated for every reusable definition from your input. ::: code-group ```ts [example] const zFoo = z.int(); const zBar = z.object({ bar: z.optional(z.array(z.int())), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', definitions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `definitions` schemas using the `.name` and `.case` options. ## ISO Datetimes By default, values without a timezone or with a timezone offset are not allowed in the `z.iso.datetime()` method. ### Timezone offsets You can allow values with timezone offsets by setting `dates.offset` to `true`. ::: code-group ```ts [example] export const zFoo = z.iso.datetime({ offset: true }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', dates: { offset: true, // [!code ++] }, }, ], }; ``` ::: ### Local times You can allow values without a timezone by setting `dates.local` to `true`. ::: code-group ```ts [example] export const zFoo = z.iso.datetime({ local: true }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', dates: { local: true, // [!code ++] }, }, ], }; ``` ::: ## Metadata It's often useful to associate a schema with some additional [metadata](https://zod.dev/metadata) for documentation, code generation, AI structured outputs, form validation, and other purposes. You can set `metadata` to `true` to attach descriptions to schemas when available. ::: code-group ```ts [example] export const zFoo = z.string().register(z.globalRegistry, { description: 'Additional metadata', }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', metadata: true, // [!code ++] }, ], }; ``` ::: For more control over metadata, you can provide your own function. It receives the source `schema`, the target `node` object, and the `$` builder for populating metadata. ::: code-group ```ts [example] export const zFoo = z.string().register(z.globalRegistry, { hasTitle: true, createdAt: 1735732800000, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', metadata({ $, node, schema }) { // [!code ++] node.prop('hasTitle', $.literal(Boolean(schema.title))); // [!code ++] node.prop('createdAt', $.literal(Date.now())); // [!code ++] }, // [!code ++] }, ], }; ``` ::: ## Types In addition to Zod schemas, you can generate schema-specific types. These can be generated for all schemas or for specific resources. ::: code-group ```ts [example] export type ResponseZodType = z.infer; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 'mini', types: { infer: false, // by default, no `z.infer` types [!code ++] }, responses: { types: { infer: true, // `z.infer` types only for response schemas [!code ++] }, }, }, ], }; ``` ::: You can customize the naming and casing pattern for schema-specific `types` using the `.name` and `.case` options. ## Resolvers You can further customize this plugin's behavior using [resolvers](/openapi-ts/plugins/concepts/resolvers). ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/zod/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/zod/v3.md ================================================ --- title: Zod v3 Plugin description: Generate Zod v3 schemas from OpenAPI with the Zod plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Zod v3

    ### About [Zod](https://v3.zod.dev/) is a TypeScript-first schema validation library with static type inference. The Zod plugin for Hey API generates schemas from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ## Features - Zod v3 support - seamless integration with `@hey-api/openapi-ts` ecosystem - Zod schemas for requests, responses, and reusable definitions - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `zod` to your plugins and you'll be ready to generate Zod artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', // [!code ++] compatibilityVersion: 3, // [!code ++] }, ], }; ``` ### SDKs To add data validators to your SDKs, set `sdk.validator` to `true`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, }, { name: '@hey-api/sdk', // [!code ++] validator: true, // [!code ++] }, ], }; ``` Learn more about data validators in your SDKs on the [SDKs](/openapi-ts/plugins/sdk#validators) page. ## Output The Zod plugin will generate the following artifacts, depending on the input specification. ## Requests A single request schema is generated for each endpoint. It may contain a request body, parameters, and headers. ::: code-group ```ts [example] const zData = z.object({ body: z .object({ foo: z.string().optional(), bar: z.union([z.number(), z.null()]).optional(), }) .optional(), path: z.object({ baz: z.string(), }), query: z.never().optional(), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, requests: true, // [!code ++] }, ], }; ``` ::: ::: tip If you need to access individual fields, you can do so using the [`.shape`](https://v3.zod.dev/?id=shape) API. For example, we can get the request body schema with `zData.shape.body`. ::: You can customize the naming and casing pattern for `requests` schemas using the `.name` and `.case` options. ## Responses A single Zod schema is generated for all endpoint's responses. If the endpoint describes multiple responses, the generated schema is a union of all possible response shapes. ::: code-group ```ts [example] const zResponse = z.union([ z.object({ foo: z.string().optional(), }), z.object({ bar: z.number().optional(), }), ]); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, responses: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `responses` schemas using the `.name` and `.case` options. ## Definitions A Zod schema is generated for every reusable definition from your input. ::: code-group ```ts [example] const zFoo = z.number().int(); const zBar = z.object({ bar: z.array(z.number().int()).optional(), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, definitions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `definitions` schemas using the `.name` and `.case` options. ## ISO Datetimes By default, values without a timezone or with a timezone offset are not allowed in the `z.string().datetime()` method. ### Timezone offsets You can allow values with timezone offsets by setting `dates.offset` to `true`. ::: code-group ```ts [example] export const zFoo = z.string().datetime({ offset: true }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, dates: { offset: true, // [!code ++] }, }, ], }; ``` ::: ### Local times You can allow values without a timezone by setting `dates.local` to `true`. ::: code-group ```ts [example] export const zFoo = z.string().datetime({ local: true }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, dates: { local: true, // [!code ++] }, }, ], }; ``` ::: ## Metadata It's often useful to associate a schema with some additional [metadata](https://v3.zod.dev/?id=describe) for documentation, code generation, AI structured outputs, form validation, and other purposes. If this is your use case, you can set `metadata` to `true` to generate additional metadata about schemas. ::: code-group ```ts [example] export const zFoo = z.string().describe('Additional metadata'); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, metadata: true, // [!code ++] }, ], }; ``` ::: ## Types In addition to Zod schemas, you can generate schema-specific types. These can be generated for all schemas or for specific resources. ::: code-group ```ts [example] export type ResponseZodType = z.infer; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', compatibilityVersion: 3, types: { infer: false, // by default, no `z.infer` types [!code ++] }, responses: { types: { infer: true, // `z.infer` types only for response schemas [!code ++] }, }, }, ], }; ``` ::: You can customize the naming and casing pattern for schema-specific `types` using the `.name` and `.case` options. ## Resolvers You can further customize this plugin's behavior using [resolvers](/openapi-ts/plugins/concepts/resolvers). ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/zod/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/zod.md ================================================ --- title: Zod v4 Plugin description: Generate Zod v4 schemas from OpenAPI with the Zod plugin for openapi-ts. Fully compatible with validators, transformers, and all core features. ---

    Zod v4

    ### About [Zod](https://zod.dev) is a TypeScript-first schema validation library with static type inference. The Zod plugin for Hey API generates schemas from your OpenAPI spec, fully compatible with validators, transformers, and all core features. ## Features - Zod v4 support - seamless integration with `@hey-api/openapi-ts` ecosystem - Zod schemas for requests, responses, and reusable definitions - minimal learning curve thanks to extending the underlying technology ## Installation In your [configuration](/openapi-ts/get-started), add `zod` to your plugins and you'll be ready to generate Zod artifacts. :tada: ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins 'zod', // [!code ++] ], }; ``` ### SDKs To add data validators to your SDKs, set `sdk.validator` to `true`. ```js export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins 'zod', { name: '@hey-api/sdk', // [!code ++] validator: true, // [!code ++] }, ], }; ``` Learn more about data validators in your SDKs on the [SDKs](/openapi-ts/plugins/sdk#validators) page. ## Output The Zod plugin will generate the following artifacts, depending on the input specification. ## Requests A single request schema is generated for each endpoint. It may contain a request body, parameters, and headers. ::: code-group ```ts [example] const zData = z.object({ body: z .object({ foo: z.optional(z.string()), bar: z.optional(z.union([z.number(), z.null()])), }) .optional(), path: z.object({ baz: z.string(), }), query: z.optional(z.never()), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', requests: true, // [!code ++] }, ], }; ``` ::: ::: tip If you need to access individual fields, you can do so using the [`.shape`](https://zod.dev/api?id=shape) API. For example, we can get the request body schema with `zData.shape.body`. ::: You can customize the naming and casing pattern for `requests` schemas using the `.name` and `.case` options. ## Responses A single Zod schema is generated for all endpoint's responses. If the endpoint describes multiple responses, the generated schema is a union of all possible response shapes. ::: code-group ```ts [example] const zResponse = z.union([ z.object({ foo: z.optional(z.string()), }), z.object({ bar: z.optional(z.number()), }), ]); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', responses: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `responses` schemas using the `.name` and `.case` options. ## Definitions A Zod schema is generated for every reusable definition from your input. ::: code-group ```ts [example] const zFoo = z.int(); const zBar = z.object({ bar: z.optional(z.array(z.int())), }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', definitions: true, // [!code ++] }, ], }; ``` ::: You can customize the naming and casing pattern for `definitions` schemas using the `.name` and `.case` options. ## ISO Datetimes By default, values without a timezone or with a timezone offset are not allowed in the `z.iso.datetime()` method. ### Timezone offsets You can allow values with timezone offsets by setting `dates.offset` to `true`. ::: code-group ```ts [example] export const zFoo = z.iso.datetime({ offset: true }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', dates: { offset: true, // [!code ++] }, }, ], }; ``` ::: ### Local times You can allow values without a timezone by setting `dates.local` to `true`. ::: code-group ```ts [example] export const zFoo = z.iso.datetime({ local: true }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', dates: { local: true, // [!code ++] }, }, ], }; ``` ::: ## Metadata It's often useful to associate a schema with some additional [metadata](https://zod.dev/metadata) for documentation, code generation, AI structured outputs, form validation, and other purposes. You can set `metadata` to `true` to attach descriptions to schemas when available. ::: code-group ```ts [example] export const zFoo = z.string().register(z.globalRegistry, { description: 'Additional metadata', }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', metadata: true, // [!code ++] }, ], }; ``` ::: For more control over metadata, you can provide your own function. It receives the source `schema`, the target `node` object, and the `$` builder for populating metadata. ::: code-group ```ts [example] export const zFoo = z.string().register(z.globalRegistry, { hasTitle: true, createdAt: 1735732800000, }); ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', metadata({ $, node, schema }) { // [!code ++] node.prop('hasTitle', $.literal(Boolean(schema.title))); // [!code ++] node.prop('createdAt', $.literal(Date.now())); // [!code ++] }, // [!code ++] }, ], }; ``` ::: ## Types In addition to Zod schemas, you can generate schema-specific types. These can be generated for all schemas or for specific resources. ::: code-group ```ts [example] export type ResponseZodType = z.infer; ``` ```js [config] export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: 'zod', types: { infer: false, // by default, no `z.infer` types [!code ++] }, responses: { types: { infer: true, // `z.infer` types only for response schemas [!code ++] }, }, }, ], }; ``` ::: You can customize the naming and casing pattern for schema-specific `types` using the `.name` and `.case` options. ## Resolvers You can further customize this plugin's behavior using [resolvers](/openapi-ts/plugins/concepts/resolvers). ## API You can view the complete list of options in the [UserConfig](https://github.com/hey-api/openapi-ts/blob/main/packages/openapi-ts/src/plugins/zod/types.ts) interface. ================================================ FILE: docs/openapi-ts/plugins/zustand.md ================================================ --- title: Zustand description: Zustand plugin for Hey API. Compatible with all our features. --- # Zustand soon ### About [Zustand](https://zustand-demo.pmnd.rs) is a small, fast, and scalable bearbones state management solution. ================================================ FILE: docs/openapi-ts/state-management.md ================================================ --- title: State Management description: Learn about handling state with @hey-api/openapi-ts. --- # State Management Any reasonably large application will have to deal with state management at some point. State-related code is often one of the biggest boilerplates in your codebase. Well, at least until you start using our state management plugins. ## Options Hey API natively supports the following state managers. - [Pinia Colada](/openapi-ts/plugins/pinia-colada) - [TanStack Query](/openapi-ts/plugins/tanstack-query) - [SWR](/openapi-ts/plugins/swr) Soon - [Zustand](/openapi-ts/plugins/zustand) Soon Don't see your state manager? Let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ================================================ FILE: docs/openapi-ts/validators.md ================================================ --- title: Validators description: Learn about validating data with @hey-api/openapi-ts. --- # Validators There are times when you cannot blindly trust the server to return the correct data. You might be working on a critical application where any mistakes would be costly, or you're simply dealing with a legacy or undocumented system. Whatever your reason to use validators might be, you can rest assured that you're working with the correct data. ## Features - seamless integration with `@hey-api/openapi-ts` ecosystem - schemas for requests, responses, and reusable definitions ## Options Hey API natively supports the following validators. - [Valibot](/openapi-ts/plugins/valibot) - [Zod](/openapi-ts/plugins/zod) - [Ajv](/openapi-ts/plugins/ajv) Soon - [Arktype](/openapi-ts/plugins/arktype) Soon - [Joi](/openapi-ts/plugins/joi) Soon - [TypeBox](/openapi-ts/plugins/typebox) Soon - [Yup](/openapi-ts/plugins/yup) Soon Don't see your validator? Let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ================================================ FILE: docs/openapi-ts/web-frameworks.md ================================================ --- title: Web Frameworks description: Learn about generating web framework code with @hey-api/openapi-ts. --- # Web Frameworks There are two approaches to developing APIs: code-first, where you start with the code, or spec-first, where you begin with the specification. If you use the latter, you can ensure your APIs adhere to the specification with our web framework plugins. ## Options Hey API natively supports the following frameworks. - [Angular](/openapi-ts/plugins/angular) - [Fastify](/openapi-ts/plugins/fastify) - [Nest](/openapi-ts/plugins/nest) - [Adonis](/openapi-ts/plugins/adonis) Soon - [Elysia](/openapi-ts/plugins/elysia) Soon - [Express](/openapi-ts/plugins/express) Soon - [Hono](/openapi-ts/plugins/hono) Soon - [Koa](/openapi-ts/plugins/koa) Soon Don't see your framework? Let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ================================================ FILE: docs/package.json ================================================ { "name": "docs", "version": "0.10.4", "private": true, "description": "Documentation for OpenAPI TypeScript.", "type": "module", "scripts": { "build": "vitepress build", "dev": "vitepress dev", "preview": "vitepress preview" }, "dependencies": { "@stackblitz/sdk": "1.11.0", "vue3-select-component": "0.16.0" }, "devDependencies": { "sharp": "0.34.5", "vitepress": "2.0.0-alpha.16", "vitepress-plugin-llms": "1.11.0", "vue": "3.5.25" } } ================================================ FILE: docs/partials/contributors-list.md ================================================ - [Ahmed Rowaihi](https://github.com/ahmedrowaihi) - [Alessandro](https://github.com/ale18V) - [Alex Sagal](https://github.com/spikesagal) - [Alex Sarychev](https://github.com/Freddis) - [Alex Vukadinov](https://github.com/alexvuka1) - [Alex Yang](https://github.com/himself65) - [Alexander Horner](https://github.com/alexanderhorner) - [Alexander Skvortcov](https://github.com/askvortcov) - [Andrea](https://github.com/andreasciamanna) - [Andreas Adam](https://github.com/pixelmord) - [Ben Vincent](https://github.com/bvincent1) - [Björn Henriksson](https://github.com/bjornhenriksson) - [Bogdan ](https://github.com/BogdanMaier) - [Brian Tarricone](https://github.com/kelnos) - [Bryon Larrance](https://github.com/beelarr) - [Carl Kittelberger](https://github.com/icedream) - [Changwan](https://github.com/WooWan) - [Chris Wiggins](https://github.com/chriswiggins) - [Daniel Roe](https://github.com/danielroe) - [Daschi](https://github.com/Daschi1) - [David Bieregger](https://github.com/BierDav) - [David Ovčačík](https://github.com/dovca) - [Dmitriy Brolnickij](https://github.com/brolnickij) - [Erikwski](https://github.com/erikwski) - [Finn Poppinga](https://github.com/fpoppinga) - [Flo Edelmann](https://github.com/FloEdelmann) - [Florian Lutze](https://github.com/flow96) - [Francisco García](https://github.com/goltra) - [George Smith](https://github.com/georgesmith46) - [Gergan Penkov](https://github.com/gergan) - [Hector Ayala](https://github.com/bombillazo) - [Hiram Chirino](https://github.com/chirino) - [Idan Ben Ami](https://github.com/idbenami) - [Jan](https://github.com/JanST123) - [Jason Lee](https://github.com/LeeChSien) - [Jason Westover](https://github.com/j-westover) - [Jeff James](https://github.com/jsjames) - [Jianqi Pan](https://github.com/Jannchie) - [Jo](https://github.com/josh-hemphill) - [John Gozde](https://github.com/jgoz) - [Jordan Shatford](https://github.com/jordanshatford) - [Joshua](https://github.com/Joshua-hypt) - [Jostein Stuhaug](https://github.com/josstn) - [Juan Ibarra](https://github.com/j-ibarra) - [Julian Klumpers](https://github.com/julianklumpers) - [Karl Stoney](https://github.com/Stono) - [Keigo Ando](https://github.com/anchan828) - [Kenneth Apeland](https://github.com/kennidenni) - [Landon Gavin](https://github.com/seriouslag) - [Laurin](https://github.com/lausek) - [Lee Lian Hoy](https://github.com/bakakaba) - [Leo Developer](https://github.com/Le0Developer) - [Linus Fischer](https://github.com/LeiCraft) - [Louis Duchemin](https://github.com/lsdch) - [Lubos](https://github.com/mrlubos) - [Lukas Podmelle](https://github.com/lukaspodmelle) - [Luke Rohde](https://github.com/thyming) - [Maarten Knijnenberg](https://github.com/mknijnenberg) - [Mads Hougesen](https://github.com/hougesen) - [Malcolm Kee](https://github.com/malcolm-kee) - [Marcel Richter](https://github.com/mrclrchtr) - [Marek Lukáš](https://github.com/tajnymag) - [Martín Fernández](https://github.com/bilby91) - [Matsu](https://github.com/Matsuuu) - [Maurici Abad Gutierrez](https://github.com/mauriciabad) - [Max Scopp](https://github.com/max-scopp) - [Maximilian Dewald](https://github.com/maxdewald) - [Michał Grezel](https://github.com/dracomithril) - [Michiel Lankamp](https://github.com/mlankamp) - [Mika Vilpas](https://github.com/mikavilpas) - [Miklos](https://github.com/jumika) - [Nacho García](https://github.com/nachogarcia) - [Nicolas Chaulet](https://github.com/nicolas-chaulet) - [Niels Mokkenstorm](https://github.com/nmokkenstorm) - [Nikita Perepelitsa](https://github.com/quartepie) - [Nimo Beeren](https://github.com/nimobeeren) - [Novak Antonijevic](https://github.com/NovakAnton) - [Ondřej Maxa](https://github.com/maxa-ondrej) - [Pascal Ernst](https://github.com/LinuCC) - [Peter Graugaard](https://github.com/pgraug) - [Philipp Katz](https://github.com/qqilihq) - [Phuc Tran](https://github.com/Glup3) - [Rico](https://github.com/btmnk) - [Ryo Yamada](https://github.com/Liooo) - [Sebastiaan Wouters](https://github.com/SebastiaanWouters) - [Shinigami](https://github.com/Shinigami92) - [Simen Bekkhus](https://github.com/SimenB) - [Sipan Petrosyan](https://github.com/SipanP) - [Sjoerd Scheffer](https://github.com/ixnas) - [Stephen Zhou](https://github.com/hyoban) - [Stian Jensen](https://github.com/stianjensen) - [Vincent Olesen](https://github.com/volesen) - [Warren Seine](https://github.com/warrenseine) - [Will Mitchell](https://github.com/wn-mitch) - [Yuri Mikhin](https://github.com/mikhin) - [a1mer](https://github.com/a1mersnow) - [carson](https://github.com/carson2222) - [chrg1001](https://github.com/chrg1001) - [johnny kim](https://github.com/johnny-mh) - [0xfurai](https://github.com/0xfurai) - [9M6](https://github.com/9M6) - [Ben-Pfirsich](https://github.com/Ben-Pfirsich) - [Mxwllas](https://github.com/Mxwllas) - [RndUsername](https://github.com/RndUsername) - [Schroedi](https://github.com/Schroedi) - [alexedme](https://github.com/alexedme) - [ben-pietsch](https://github.com/ben-pietsch) - [fml09](https://github.com/fml09) - [henry-encord](https://github.com/henry-encord) - [hunshcn](https://github.com/hunshcn) - [jcx0](https://github.com/jcx0) - [maxdew-envelio](https://github.com/maxdew-envelio) - [nnzhadow](https://github.com/nnzhadow) - [renoschubert](https://github.com/renoschubert) ================================================ FILE: docs/partials/examples.md ================================================ ## Examples You can view live examples on [StackBlitz](https://stackblitz.com/orgs/github/hey-api/collections/openapi-ts-examples). ================================================ FILE: docs/partials/sponsors-list.md ================================================ ### Gold ### Silver ### Bronze ### Friends ================================================ FILE: docs/partials/sponsors.md ================================================ ## Sponsors Hey API is sponsor-funded. If you rely on Hey API in production, consider becoming a [sponsor](https://github.com/sponsors/hey-api) to accelerate the roadmap.
    ================================================ FILE: docs/public/robots.txt ================================================ User-agent: * Allow: / Sitemap: https://heyapi.dev/sitemap.xml ================================================ FILE: docs/tsconfig.json ================================================ { "compilerOptions": { "baseUrl": ".", "esModuleInterop": true, "module": "nodenext", "paths": { "@components/*": ["./.vitepress/theme/components/*"], "@data": ["./data/*"], "@versions/*": ["./.vitepress/theme/versions/*"] } }, "include": [".vitepress/**/*", "./**/*.ts", "./**/*.vue"] } ================================================ FILE: eslint.config.js ================================================ import eslint from '@eslint/js'; import pluginSimpleImportSort from 'eslint-plugin-simple-import-sort'; import pluginSortDestructureKeys from 'eslint-plugin-sort-destructure-keys'; import pluginSortKeysFix from 'eslint-plugin-sort-keys-fix'; import pluginTypeScriptSortKeys from 'eslint-plugin-typescript-sort-keys'; // import pluginVue from 'eslint-plugin-vue' import globals from 'globals'; import tseslint from 'typescript-eslint'; export default tseslint.config( eslint.configs.recommended, ...tseslint.configs.recommended, { languageOptions: { ecmaVersion: 'latest', globals: { ...globals.node, }, }, plugins: { 'simple-import-sort': pluginSimpleImportSort, 'sort-destructure-keys': pluginSortDestructureKeys, 'sort-keys-fix': pluginSortKeysFix, 'typescript-sort-keys': pluginTypeScriptSortKeys, }, rules: { '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/ban-ts-ignore': 'off', '@typescript-eslint/consistent-type-imports': 'warn', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-inferrable-types': 'off', '@typescript-eslint/no-non-null-assertion': 'off', '@typescript-eslint/no-var-requires': 'off', 'arrow-body-style': 'error', 'import/order': 'off', 'no-prototype-builtins': 'off', 'object-shorthand': 'error', 'simple-import-sort/exports': 'error', 'simple-import-sort/imports': 'error', 'sort-destructure-keys/sort-destructure-keys': 'warn', 'sort-imports': 'off', 'sort-keys-fix/sort-keys-fix': 'warn', 'typescript-sort-keys/interface': 'warn', 'typescript-sort-keys/string-enum': 'warn', }, }, { files: ['**/*.cjs'], rules: { '@typescript-eslint/no-require-imports': 'off', }, }, { ignores: [ '**/.tsdown/', '**/dist/', '**/node_modules/', 'temp/', 'dev/.gen/', 'examples/openapi-ts-nestjs/src/client/**/*.ts', 'examples/openapi-ts-openai/src/client/**/*.ts', '**/test/generated/', '**/__snapshots__/', '**/.next/', '**/.nuxt/', '**/.output/', '**/.svelte-kit/', '**/.vitepress/cache', '**/.vitepress/dist', '**/.angular', ], }, ); ================================================ FILE: examples/README.md ================================================ # Examples This directory contains integration examples demonstrating how to use `@hey-api/openapi-ts` with various frameworks, libraries, and client implementations. ## Available Examples - **openapi-ts-angular** - Angular integration with common HTTP client - **openapi-ts-angular-common** - Angular with @angular/common/http - **openapi-ts-axios** - Using Axios client - **openapi-ts-fastify** - Fastify server integration - **openapi-ts-fetch** - Native Fetch API client - **openapi-ts-next** - Next.js integration - **openapi-ts-nuxt** - Nuxt.js integration with plugin - **openapi-ts-ofetch** - Using ofetch client - **openapi-ts-openai** - OpenAI API integration - **openapi-ts-pinia-colada** - Vue with Pinia Colada state management - **openapi-ts-sample** - Sample/template example (excluded from CI) - **openapi-ts-tanstack-angular-query-experimental** - Angular with TanStack Query - **openapi-ts-tanstack-react-query** - React with TanStack Query - **openapi-ts-tanstack-svelte-query** - Svelte with TanStack Query - **openapi-ts-tanstack-vue-query** - Vue with TanStack Query ## Generated Code All examples (except `openapi-ts-sample`) contain generated client code that is **committed to the repository**. This ensures: 1. Examples always reflect the current state of the code generator 2. Changes to the code generator are visible in pull requests 3. CI can verify that examples are kept up-to-date ## Regenerating Examples After making changes to the core packages, regenerate all example code: ```bash pnpm examples:generate ``` This command will run `openapi-ts` for each example that has an `openapi-ts` script in its `package.json`. ## Verifying Examples To check if all examples are up-to-date with the current codebase: ```bash pnpm examples:check ``` This check is also run automatically in CI. If it fails, run `pnpm examples:generate` and commit the changes. ## Running Examples Each example can be run individually using the `example` script: ```bash # Run dev server for fetch example pnpm example fetch dev # Build fetch example pnpm example fetch build ``` Or directly using pnpm filters: ```bash pnpm --filter @example/openapi-ts-fetch dev ``` ## Creating New Examples When creating a new example: 1. Create a new directory in `examples/` 2. Add an `openapi-ts` script to `package.json` 3. Run `pnpm examples:generate` to create initial generated code 4. Commit both the source and generated code 5. The example will automatically be included in CI checks ## Excluding Examples To exclude an example from CI (like `openapi-ts-sample`): 1. Remove the `openapi-ts` script from `package.json`, or 2. Update the exclusion filters in `package.json` scripts and `.github/workflows/ci.yml` ================================================ FILE: examples/openapi-ts-angular/.editorconfig ================================================ # Editor configuration, see https://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.ts] quote_type = single ij_typescript_use_double_quotes = false [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: examples/openapi-ts-angular/.gitignore ================================================ # See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. # Compiled output /dist /tmp /out-tsc /bazel-out # Node /node_modules npm-debug.log yarn-error.log # IDEs and editors .idea/ .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # Visual Studio Code .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json .history/* # Miscellaneous /.angular/cache .sass-cache/ /connect.lock /coverage /libpeerconnection.log testem.log /typings # System files .DS_Store Thumbs.db ================================================ FILE: examples/openapi-ts-angular/.vscode/extensions.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 "recommendations": ["angular.ng-template"] } ================================================ FILE: examples/openapi-ts-angular/.vscode/launch.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "ng serve", "type": "chrome", "request": "launch", "preLaunchTask": "npm: start", "url": "http://localhost:4200/" }, { "name": "ng test", "type": "chrome", "request": "launch", "preLaunchTask": "npm: test", "url": "http://localhost:9876/debug.html" } ] } ================================================ FILE: examples/openapi-ts-angular/.vscode/tasks.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "type": "npm", "script": "start", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } }, { "type": "npm", "script": "test", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } } ] } ================================================ FILE: examples/openapi-ts-angular/README.md ================================================ # Angular This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 19.2.15. ## Development server To start a local development server, run: ```bash ng serve ``` Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files. ## Code scaffolding Angular CLI includes powerful code scaffolding tools. To generate a new component, run: ```bash ng generate component component-name ``` For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run: ```bash ng generate --help ``` ## Building To build the project run: ```bash ng build ``` This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed. ## Running unit tests To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command: ```bash ng test ``` ## Running end-to-end tests For end-to-end (e2e) testing, run: ```bash ng e2e ``` Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs. ## Additional Resources For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page. ================================================ FILE: examples/openapi-ts-angular/angular.json ================================================ { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "angular": { "projectType": "application", "schematics": {}, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/angular", "index": "src/index.html", "browser": "src/main.ts", "polyfills": ["zone.js"], "tsConfig": "tsconfig.app.json", "assets": [ { "glob": "**/*", "input": "public" } ], "styles": ["src/styles.css"], "scripts": [] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" }, { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" } ], "outputHashing": "all" }, "development": { "optimization": false, "extractLicenses": false, "sourceMap": true } }, "defaultConfiguration": "production" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "configurations": { "production": { "buildTarget": "angular:build:production" }, "development": { "buildTarget": "angular:build:development" } }, "defaultConfiguration": "development" }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n" }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "polyfills": ["zone.js", "zone.js/testing"], "tsConfig": "tsconfig.spec.json", "assets": [ { "glob": "**/*", "input": "public" } ], "styles": ["src/styles.css"], "scripts": [] } } } } }, "cli": { "analytics": false } } ================================================ FILE: examples/openapi-ts-angular/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-angular', '@hey-api/schemas', { name: '@hey-api/sdk', operations: { containerName: '{{name}}Service', strategy: 'byTags', }, }, { enums: 'javascript', name: '@hey-api/typescript', }, ], }); ================================================ FILE: examples/openapi-ts-angular/package.json ================================================ { "name": "@example/openapi-ts-angular", "version": "0.0.0", "private": true, "scripts": { "build": "ng build", "dev": "ng serve", "lint": "eslint . --report-unused-disable-directives --max-warnings 0", "ng": "ng", "openapi-ts": "openapi-ts", "serve:ssr:angular": "node dist/angular/server/server.mjs", "test:disabled": "ng test --watch=false --browsers=ChromeHeadless", "test": "echo \"Skipping tests\"", "watch": "ng build --watch --configuration development" }, "dependencies": { "@angular/common": "21.1.2", "@angular/compiler": "21.1.2", "@angular/core": "21.1.2", "@angular/forms": "21.1.2", "@angular/platform-browser": "21.1.2", "@angular/platform-browser-dynamic": "21.1.2", "@angular/platform-server": "21.1.2", "@angular/router": "21.1.2", "@angular/ssr": "21.1.2", "express": "4.21.0", "rxjs": "7.8.2", "tslib": "2.8.1", "zone.js": "0.16.0" }, "devDependencies": { "@angular-devkit/build-angular": "21.1.2", "@angular/cli": "21.1.2", "@angular/compiler-cli": "21.1.2", "@hey-api/openapi-ts": "workspace:*", "@types/express": "4.17.21", "@types/jasmine": "5.1.9", "@types/node": "24.10.10", "@typescript-eslint/eslint-plugin": "8.29.1", "@typescript-eslint/parser": "8.29.1", "eslint": "9.17.0", "jasmine-core": "5.6.0", "karma": "6.4.4", "karma-chrome-launcher": "3.2.0", "karma-coverage": "2.2.1", "karma-jasmine": "5.1.0", "karma-jasmine-html-reporter": "2.1.0", "typescript": "5.9.3" } } ================================================ FILE: examples/openapi-ts-angular/src/app/app.component.css ================================================ ================================================ FILE: examples/openapi-ts-angular/src/app/app.component.html ================================================

    {{ title }}

    @for ( item of [ { title: 'Explore the Docs', link: 'https://angular.dev' }, { title: 'Learn with Tutorials', link: 'https://angular.dev/tutorials', }, { title: 'CLI Docs', link: 'https://angular.dev/tools/cli' }, { title: 'Angular Language Service', link: 'https://angular.dev/tools/language-service', }, { title: 'Angular DevTools', link: 'https://angular.dev/tools/devtools', }, ]; track item.title ) { {{ item.title }} }
    ================================================ FILE: examples/openapi-ts-angular/src/app/app.component.spec.ts ================================================ import { provideHttpClient } from '@angular/common/http'; import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [AppComponent], providers: [provideHttpClient()], }).compileComponents(); }); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); it(`should have the 'angular' title`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app.title).toEqual('angular'); }); it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('h1')?.textContent).toContain('@hey-api/openapi-ts 🤝 Angular'); }); }); ================================================ FILE: examples/openapi-ts-angular/src/app/app.component.ts ================================================ import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { Demo } from './demo/demo'; @Component({ host: { ngSkipHydration: 'true' }, imports: [RouterOutlet, Demo], selector: 'app-root', styleUrl: './app.component.css', templateUrl: './app.component.html', }) export class AppComponent { title = '@hey-api/openapi-ts 🤝 Angular'; } ================================================ FILE: examples/openapi-ts-angular/src/app/app.config.server.ts ================================================ import type { ApplicationConfig } from '@angular/core'; import { mergeApplicationConfig } from '@angular/core'; import { provideServerRendering, withRoutes } from '@angular/ssr'; import { appConfig } from './app.config'; import { serverRoutes } from './app.routes.server'; const serverConfig: ApplicationConfig = { providers: [provideServerRendering(), provideServerRendering(withRoutes(serverRoutes))], }; export const config = mergeApplicationConfig(appConfig, serverConfig); ================================================ FILE: examples/openapi-ts-angular/src/app/app.config.ts ================================================ import { provideHttpClient, withFetch } from '@angular/common/http'; import type { ApplicationConfig } from '@angular/core'; import { provideZoneChangeDetection } from '@angular/core'; import { provideClientHydration, withEventReplay } from '@angular/platform-browser'; import { provideRouter } from '@angular/router'; import { client } from '../client/client.gen'; import { provideHeyApiClient } from '../client/client/client.gen'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideClientHydration(withEventReplay()), provideHttpClient(withFetch()), provideHeyApiClient(client), ], }; ================================================ FILE: examples/openapi-ts-angular/src/app/app.routes.server.ts ================================================ import type { ServerRoute } from '@angular/ssr'; import { RenderMode } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: '**', renderMode: RenderMode.Prerender, }, ]; ================================================ FILE: examples/openapi-ts-angular/src/app/app.routes.ts ================================================ import type { Routes } from '@angular/router'; import { Demo } from './demo/demo'; export const routes: Routes = [ { component: Demo, path: '', pathMatch: 'full', }, ]; ================================================ FILE: examples/openapi-ts-angular/src/app/demo/demo.css ================================================ /* Pet Card Styles */ .pet-card { background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%); border-radius: 16px; padding: 1.5rem; margin-top: 1.5rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); border: 1px solid rgba(0, 0, 0, 0.05); transition: transform 120ms ease, box-shadow 120ms ease; } .pet-info { display: flex; align-items: center; gap: 1rem; } .pet-avatar { width: 64px; height: 64px; border-radius: 12px; overflow: hidden; flex-shrink: 0; background: var(--red-to-pink-to-purple-horizontal-gradient); display: flex; align-items: center; justify-content: center; } .pet-image { width: 100%; height: 100%; object-fit: cover; } .pet-placeholder { color: white; font-size: 1.5rem; font-weight: 600; text-transform: uppercase; } .pet-details { flex: 1; display: flex; flex-direction: column; gap: 0.5rem; } .pet-name { font-size: 1.125rem; font-weight: 600; color: var(--gray-900); margin: 0; } .pet-category { font-size: 0.875rem; color: var(--gray-700); background: rgba(255, 65, 248, 0.1); padding: 0.25rem 0.75rem; border-radius: 20px; display: inline-block; width: fit-content; } /* Error Message Styles */ .error-message { background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%); border: 1px solid #fecaca; border-radius: 12px; padding: 1rem; margin-top: 1.5rem; box-shadow: 0 2px 4px rgba(239, 68, 68, 0.1); } .error-title { font-size: 1rem; font-weight: 600; color: #dc2626; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem; } .error-title::before { content: '⚠️'; font-size: 1.125rem; } .error-details { font-size: 0.875rem; color: #991b1b; background: rgba(239, 68, 68, 0.05); padding: 0.75rem; border-radius: 8px; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; white-space: pre-wrap; word-break: break-word; border-left: 3px solid #ef4444; } /* Button Styles Enhancement */ button { background: var(--red-to-pink-to-purple-horizontal-gradient); color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 8px; font-size: 0.875rem; font-weight: 500; cursor: pointer; transition: all 120ms ease; margin-top: 1rem; margin-right: 0.5rem; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } button:hover { transform: translateY(-1px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); } button:active { transform: translateY(0); } /* Responsive adjustments */ @media screen and (max-width: 650px) { .pet-card { padding: 1rem; margin-top: 1rem; } .pet-info { flex-direction: column; text-align: center; gap: 1rem; } .pet-avatar { width: 80px; height: 80px; align-self: center; } .error-message { padding: 0.75rem; margin-top: 1rem; } } ================================================ FILE: examples/openapi-ts-angular/src/app/demo/demo.html ================================================ @if (error()) {
    Error occurred:
    {{ error()?.error }}
    } @if (pet()) {
    @if (pet()?.photoUrls?.[0]) { } @else {
    {{ pet()?.name?.slice(0, 1) || 'N' }}
    }
    Name: {{ pet()?.name || 'N/A' }}
    Category: {{ pet()?.category?.name || 'N/A' }}
    } ================================================ FILE: examples/openapi-ts-angular/src/app/demo/demo.ts ================================================ import type { HttpErrorResponse } from '@angular/common/http'; import { HttpClient } from '@angular/common/http'; import { Component, inject, signal } from '@angular/core'; import type { AddPetErrors, Pet } from '../../client'; import { PetService } from '../../client'; import { createClient } from '../../client/client'; const localClient = createClient({ // set default base url for requests made by this client baseUrl: 'https://petstore3.swagger.io/api/v3', /** * Set default headers only for requests made by this client. This is to * demonstrate local clients and their configuration taking precedence over * internal service client. */ headers: { Authorization: 'Bearer ', }, }); @Component({ host: { ngSkipHydration: 'true' }, imports: [], selector: 'app-demo', styleUrl: './demo.css', templateUrl: './demo.html', }) export class Demo { pet = signal(undefined); error = signal< | undefined | { error: AddPetErrors[keyof AddPetErrors] | Error; response: HttpErrorResponse; } >(undefined); #petService = inject(PetService); #http = inject(HttpClient); // // you can set a global httpClient for this client like so, in your app.config, or on each request (like below) // ngOnInit(): void { // localClient.setConfig({ // httpClient: this.#http, // }); // } onGetPetByIdLocalClient = async () => { const { data, error, response } = await this.#petService.getPetById({ client: localClient, httpClient: this.#http, path: { // random id 1-10 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1), }, }); if (error) { console.log(error); this.error.set({ error, response: response as HttpErrorResponse, }); return; } this.pet.set(data); this.error.set(undefined); }; onGetPetById = async () => { const { data, error, response } = await this.#petService.getPetById({ path: { // random id 1-10 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1), }, }); if (error) { console.log(error); this.error.set({ error, response: response as HttpErrorResponse, }); return; } else { console.log(error); console.log(response); this.pet.set(data); this.error.set(undefined); } }; } ================================================ FILE: examples/openapi-ts-angular/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-angular/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-angular/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-angular/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-angular/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-angular/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-angular/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-angular/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-angular/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-angular/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-angular/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-angular/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-angular/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-angular/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, PetService, StoreService, UserService } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-angular/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-angular/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { Injectable } from '@angular/core'; import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; @Injectable({ providedIn: 'root' }) export class PetService { /** * Add a new pet to the store. * * Add a new pet to the store. */ public addPet(options: Options) { return (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); } /** * Update an existing pet. * * Update an existing pet by Id. */ public updatePet( options: Options, ) { return (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); } /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ public findPetsByStatus( options: Options, ) { return (options.client ?? client).get< FindPetsByStatusResponses, FindPetsByStatusErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); } /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ public findPetsByTags( options: Options, ) { return (options.client ?? client).get< FindPetsByTagsResponses, FindPetsByTagsErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); } /** * Deletes a pet. * * Delete a pet. */ public deletePet( options: Options, ) { return (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); } /** * Find pet by ID. * * Returns a single pet. */ public getPetById( options: Options, ) { return (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); } /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ public updatePetWithForm( options: Options, ) { return (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); } /** * Uploads an image. * * Upload image of the pet. */ public uploadFile( options: Options, ) { return (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); } } @Injectable({ providedIn: 'root' }) export class StoreService { /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ public getInventory( options?: Options, ) { return (options?.client ?? client).get( { security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }, ); } /** * Place an order for a pet. * * Place a new order in the store. */ public placeOrder( options?: Options, ) { return (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); } /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ public deleteOrder( options: Options, ) { return (options.client ?? client).delete( { url: '/store/order/{orderId}', ...options }, ); } /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ public getOrderById( options: Options, ) { return (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); } } @Injectable({ providedIn: 'root' }) export class UserService { /** * Create user. * * This can only be done by the logged in user. */ public createUser( options?: Options, ) { return (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); } /** * Creates list of users with given input array. * * Creates list of users with given input array. */ public createUsersWithListInput( options?: Options, ) { return (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); } /** * Logs user into the system. * * Log into the system. */ public loginUser( options?: Options, ) { return (options?.client ?? client).get({ url: '/user/login', ...options, }); } /** * Logs out current logged in user session. * * Log user out of the system. */ public logoutUser( options?: Options, ) { return (options?.client ?? client).get({ url: '/user/logout', ...options, }); } /** * Delete user resource. * * This can only be done by the logged in user. */ public deleteUser( options: Options, ) { return (options.client ?? client).delete({ url: '/user/{username}', ...options, }); } /** * Get user by user name. * * Get user detail based on username. */ public getUserByName( options: Options, ) { return (options.client ?? client).get< GetUserByNameResponses, GetUserByNameErrors, ThrowOnError >({ url: '/user/{username}', ...options }); } /** * Update user resource. * * This can only be done by the logged in user. */ public updateUser( options: Options, ) { return (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); } } ================================================ FILE: examples/openapi-ts-angular/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-angular/src/index.html ================================================ Hey API + Angular Demo ================================================ FILE: examples/openapi-ts-angular/src/main.server.ts ================================================ import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { config } from './app/app.config.server'; const bootstrap = () => bootstrapApplication(AppComponent, config); export default bootstrap; ================================================ FILE: examples/openapi-ts-angular/src/main.ts ================================================ import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); ================================================ FILE: examples/openapi-ts-angular/src/server.ts ================================================ import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { AngularNodeAppEngine, createNodeRequestHandler, isMainModule, writeResponseToNodeResponse, } from '@angular/ssr/node'; import express from 'express'; const serverDistFolder = dirname(fileURLToPath(import.meta.url)); const browserDistFolder = resolve(serverDistFolder, '../browser'); const app = express(); const angularApp = new AngularNodeAppEngine(); /** * Example Express Rest API endpoints can be defined here. * Uncomment and define endpoints as necessary. * * Example: * ```ts * app.get('/api/**', (req, res) => { * // Handle API request * }); * ``` */ /** * Serve static files from /browser */ app.use( express.static(browserDistFolder, { index: false, maxAge: '1y', redirect: false, }), ); /** * Handle all other requests by rendering the Angular application. */ app.use('/**', (req, res, next) => { angularApp .handle(req) .then((response) => (response ? writeResponseToNodeResponse(response, res) : next())) .catch(next); }); /** * Start the server if this module is the main entry point. * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000. */ if (isMainModule(import.meta.url)) { const port = process.env['PORT'] || 4000; app.listen(port, () => { console.log(`Node Express server listening on http://localhost:${port}`); }); } /** * Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions. */ export const reqHandler = createNodeRequestHandler(app); ================================================ FILE: examples/openapi-ts-angular/src/styles.css ================================================ /* You can add global styles to this file, and also import other style files */ ================================================ FILE: examples/openapi-ts-angular/tsconfig.app.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/app", "types": ["node"] }, "files": ["src/main.ts", "src/main.server.ts", "src/server.ts"], "include": ["src/**/*.d.ts"] } ================================================ FILE: examples/openapi-ts-angular/tsconfig.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc", "strict": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "skipLibCheck": true, "isolatedModules": true, "esModuleInterop": true, "experimentalDecorators": true, "moduleResolution": "bundler", "importHelpers": true, "target": "ES2022", "module": "ES2022" }, "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, "strictInjectionParameters": true, "strictInputAccessModifiers": true, "strictTemplates": true } } ================================================ FILE: examples/openapi-ts-angular/tsconfig.spec.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": ["jasmine"] }, "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] } ================================================ FILE: examples/openapi-ts-angular-common/.editorconfig ================================================ # Editor configuration, see https://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.ts] quote_type = single ij_typescript_use_double_quotes = false [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: examples/openapi-ts-angular-common/.gitignore ================================================ # See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. # Compiled output /dist /tmp /out-tsc /bazel-out # Node /node_modules npm-debug.log yarn-error.log # IDEs and editors .idea/ .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # Visual Studio Code .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json .history/* # Miscellaneous /.angular/cache .sass-cache/ /connect.lock /coverage /libpeerconnection.log testem.log /typings # System files .DS_Store Thumbs.db ================================================ FILE: examples/openapi-ts-angular-common/.vscode/extensions.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 "recommendations": ["angular.ng-template"] } ================================================ FILE: examples/openapi-ts-angular-common/.vscode/launch.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "ng serve", "type": "chrome", "request": "launch", "preLaunchTask": "npm: start", "url": "http://localhost:4200/" }, { "name": "ng test", "type": "chrome", "request": "launch", "preLaunchTask": "npm: test", "url": "http://localhost:9876/debug.html" } ] } ================================================ FILE: examples/openapi-ts-angular-common/.vscode/tasks.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "type": "npm", "script": "start", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } }, { "type": "npm", "script": "test", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } } ] } ================================================ FILE: examples/openapi-ts-angular-common/README.md ================================================ # Angular This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 19.2.15. ## Development server To start a local development server, run: ```bash ng serve ``` Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files. ## Code scaffolding Angular CLI includes powerful code scaffolding tools. To generate a new component, run: ```bash ng generate component component-name ``` For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run: ```bash ng generate --help ``` ## Building To build the project run: ```bash ng build ``` This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed. ## Running unit tests To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command: ```bash ng test ``` ## Running end-to-end tests For end-to-end (e2e) testing, run: ```bash ng e2e ``` Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs. ## Additional Resources For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page. ================================================ FILE: examples/openapi-ts-angular-common/angular.json ================================================ { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "angular": { "projectType": "application", "schematics": {}, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/angular", "index": "src/index.html", "browser": "src/main.ts", "polyfills": ["zone.js"], "tsConfig": "tsconfig.app.json", "assets": [ { "glob": "**/*", "input": "public" } ], "styles": ["src/styles.css"], "scripts": [] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" }, { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" } ], "outputHashing": "all" }, "development": { "optimization": false, "extractLicenses": false, "sourceMap": true } }, "defaultConfiguration": "production" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "configurations": { "production": { "buildTarget": "angular:build:production" }, "development": { "buildTarget": "angular:build:development" } }, "defaultConfiguration": "development" }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n" }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "polyfills": ["zone.js", "zone.js/testing"], "tsConfig": "tsconfig.spec.json", "assets": [ { "glob": "**/*", "input": "public" } ], "styles": ["src/styles.css"], "scripts": [] } } } } }, "cli": { "analytics": false } } ================================================ FILE: examples/openapi-ts-angular-common/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ { name: '@hey-api/client-angular', throwOnError: true, }, { httpRequests: true, httpResources: { containerName: '{{name}}ServiceResources', strategy: 'byTags', }, includeInEntry: true, name: '@angular/common', }, '@hey-api/schemas', { name: '@hey-api/sdk', responseStyle: 'data', }, { enums: 'javascript', name: '@hey-api/typescript', }, ], }); ================================================ FILE: examples/openapi-ts-angular-common/package.json ================================================ { "name": "@example/openapi-ts-angular-common", "version": "0.0.0", "private": true, "scripts": { "build": "ng build", "dev": "ng serve", "lint": "eslint . --report-unused-disable-directives --max-warnings 0", "ng": "ng", "openapi-ts": "openapi-ts", "serve:ssr:angular": "node dist/angular/server/server.mjs", "test:disabled": "ng test --watch=false --browsers=ChromeHeadless", "test": "echo \"Skipping tests\"", "watch": "ng build --watch --configuration development" }, "dependencies": { "@angular/common": "21.1.2", "@angular/compiler": "21.1.2", "@angular/core": "21.1.2", "@angular/forms": "21.1.2", "@angular/platform-browser": "21.1.2", "@angular/platform-browser-dynamic": "21.1.2", "@angular/platform-server": "21.1.2", "@angular/router": "21.1.2", "@angular/ssr": "21.1.2", "express": "4.21.0", "rxjs": "7.8.2", "tslib": "2.8.1", "zone.js": "0.16.0" }, "devDependencies": { "@angular-devkit/build-angular": "21.1.2", "@angular/cli": "21.1.2", "@angular/compiler-cli": "21.1.2", "@hey-api/openapi-ts": "workspace:*", "@types/express": "4.17.21", "@types/jasmine": "5.1.9", "@types/node": "24.10.10", "@typescript-eslint/eslint-plugin": "8.29.1", "@typescript-eslint/parser": "8.29.1", "eslint": "9.17.0", "jasmine-core": "5.6.0", "karma": "6.4.4", "karma-chrome-launcher": "3.2.0", "karma-coverage": "2.2.1", "karma-jasmine": "5.1.0", "karma-jasmine-html-reporter": "2.1.0", "typescript": "5.9.3" } } ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.component.css ================================================ ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.component.html ================================================

    {{ title }}

    @for ( item of [ { title: 'Explore the Docs', link: 'https://angular.dev' }, { title: 'Learn with Tutorials', link: 'https://angular.dev/tutorials', }, { title: 'CLI Docs', link: 'https://angular.dev/tools/cli' }, { title: 'Angular Language Service', link: 'https://angular.dev/tools/language-service', }, { title: 'Angular DevTools', link: 'https://angular.dev/tools/devtools', }, ]; track item.title ) { {{ item.title }} }
    ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.component.spec.ts ================================================ import { provideHttpClient } from '@angular/common/http'; import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [AppComponent], providers: [provideHttpClient()], }).compileComponents(); }); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); it(`should have the 'angular' title`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app.title).toEqual('angular'); }); it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('h1')?.textContent).toContain('@hey-api/openapi-ts 🤝 Angular'); }); }); ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.component.ts ================================================ import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { Demo } from './demo/demo'; @Component({ host: { ngSkipHydration: 'true' }, imports: [RouterOutlet, Demo], selector: 'app-root', styleUrl: './app.component.css', templateUrl: './app.component.html', }) export class AppComponent { title = '@hey-api/openapi-ts 🤝 Angular Resource API'; } ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.config.server.ts ================================================ import type { ApplicationConfig } from '@angular/core'; import { mergeApplicationConfig } from '@angular/core'; import { provideServerRendering, withRoutes } from '@angular/ssr'; import { appConfig } from './app.config'; import { serverRoutes } from './app.routes.server'; const serverConfig: ApplicationConfig = { providers: [provideServerRendering(withRoutes(serverRoutes))], }; export const config = mergeApplicationConfig(appConfig, serverConfig); ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.config.ts ================================================ import { provideHttpClient, withFetch } from '@angular/common/http'; import type { ApplicationConfig } from '@angular/core'; import { provideZoneChangeDetection } from '@angular/core'; import { provideClientHydration, withEventReplay } from '@angular/platform-browser'; import { provideRouter } from '@angular/router'; import { client } from '../client/client.gen'; import { provideHeyApiClient } from '../client/client/client.gen'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideClientHydration(withEventReplay()), provideHttpClient(withFetch()), provideHeyApiClient(client), ], }; ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.routes.server.ts ================================================ import type { ServerRoute } from '@angular/ssr'; import { RenderMode } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: '**', renderMode: RenderMode.Server, }, ]; ================================================ FILE: examples/openapi-ts-angular-common/src/app/app.routes.ts ================================================ import type { Routes } from '@angular/router'; import { Demo } from './demo/demo'; export const routes: Routes = [ { component: Demo, path: '', pathMatch: 'full', }, ]; ================================================ FILE: examples/openapi-ts-angular-common/src/app/demo/demo.css ================================================ /* Pet Card Styles */ .pet-card { background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%); border-radius: 16px; padding: 1.5rem; margin-top: 1.5rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); border: 1px solid rgba(0, 0, 0, 0.05); transition: transform 120ms ease, box-shadow 120ms ease; } .pet-info { display: flex; align-items: center; gap: 1rem; } .pet-avatar { width: 64px; height: 64px; border-radius: 12px; overflow: hidden; flex-shrink: 0; background: var(--red-to-pink-to-purple-horizontal-gradient); display: flex; align-items: center; justify-content: center; } .pet-image { width: 100%; height: 100%; object-fit: cover; } .pet-placeholder { color: white; font-size: 1.5rem; font-weight: 600; text-transform: uppercase; } .pet-details { flex: 1; display: flex; flex-direction: column; gap: 0.5rem; } .pet-name { font-size: 1.125rem; font-weight: 600; color: var(--gray-900); margin: 0; } .pet-category { font-size: 0.875rem; color: var(--gray-700); background: rgba(255, 65, 248, 0.1); padding: 0.25rem 0.75rem; border-radius: 20px; display: inline-block; width: fit-content; } /* Error Message Styles */ .error-message { background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%); border: 1px solid #fecaca; border-radius: 12px; padding: 1rem; margin-top: 1.5rem; box-shadow: 0 2px 4px rgba(239, 68, 68, 0.1); } .error-title { font-size: 1rem; font-weight: 600; color: #dc2626; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem; } .error-title::before { content: '⚠️'; font-size: 1.125rem; } .error-details { font-size: 0.875rem; color: #991b1b; background: rgba(239, 68, 68, 0.05); padding: 0.75rem; border-radius: 8px; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; white-space: pre-wrap; word-break: break-word; border-left: 3px solid #ef4444; } /* Button Styles Enhancement */ button { background: var(--red-to-pink-to-purple-horizontal-gradient); color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 8px; font-size: 0.875rem; font-weight: 500; cursor: pointer; transition: all 120ms ease; margin-top: 1rem; margin-right: 0.5rem; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } button:hover { transform: translateY(-1px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); } button:active { transform: translateY(0); } /* Responsive adjustments */ @media screen and (max-width: 650px) { .pet-card { padding: 1rem; margin-top: 1rem; } .pet-info { flex-direction: column; text-align: center; gap: 1rem; } .pet-avatar { width: 80px; height: 80px; align-self: center; } .error-message { padding: 0.75rem; margin-top: 1rem; } } ================================================ FILE: examples/openapi-ts-angular-common/src/app/demo/demo.html ================================================ @if (pet.error()) {
    Error occurred:
    {{ pet.error()|json }}
    } @if (pet.value()) {
    @if (pet.value()?.photoUrls?.[0]) { } @else {
    {{ pet.value()?.name?.slice(0, 1) || 'N' }}
    }
    Name: {{ pet.value()?.name || 'N/A' }}
    Category: {{ pet.value()?.category?.name || 'N/A' }}
    } ================================================ FILE: examples/openapi-ts-angular-common/src/app/demo/demo.ts ================================================ import { JsonPipe } from '@angular/common'; import { Component, inject, signal } from '@angular/core'; import { PetServiceResources } from '../../client'; @Component({ host: { ngSkipHydration: 'true' }, imports: [JsonPipe], selector: 'app-demo', styleUrl: './demo.css', templateUrl: './demo.html', }) export class Demo { #petResources = inject(PetServiceResources); petId = signal(0); // if you don't use `asClass`, you can simply remove the inject and use `getPetByIdResource(...)` here pet = this.#petResources.getPetById(() => ({ path: { petId: this.petId(), }, })); onGetPetById = async () => { this.petId.set(Math.floor(Math.random() * (10 - 1 + 1) + 1)); }; } ================================================ FILE: examples/openapi-ts-angular-common/src/client/@angular/common.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type HttpRequest, httpResource } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { client } from '../client.gen'; import type { Options } from '../sdk.gen'; import type { AddPetData, AddPetResponse, CreateUserData, CreateUserResponse, CreateUsersWithListInputData, CreateUsersWithListInputResponse, DeleteOrderData, DeletePetData, DeleteUserData, FindPetsByStatusData, FindPetsByStatusResponse, FindPetsByTagsData, FindPetsByTagsResponse, GetInventoryData, GetInventoryResponse, GetOrderByIdData, GetOrderByIdResponse, GetPetByIdData, GetPetByIdResponse, GetUserByNameData, GetUserByNameResponse, LoginUserData, LoginUserResponse, LogoutUserData, PlaceOrderData, PlaceOrderResponse, UpdatePetData, UpdatePetResponse, UpdatePetWithFormData, UpdatePetWithFormResponse, UpdateUserData, UploadFileData, UploadFileResponse, } from '../types.gen'; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPetRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'POST', responseStyle: 'data', url: '/pet', ...options, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePetRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'PUT', responseStyle: 'data', url: '/pet', ...options, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatusRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTagsRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePetRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'DELETE', responseStyle: 'data', url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetByIdRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithFormRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'POST', responseStyle: 'data', url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFileRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'POST', responseStyle: 'data', url: '/pet/{petId}/uploadImage', ...options, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventoryRequest = ( options?: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrderRequest = ( options?: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'POST', responseStyle: 'data', url: '/store/order', ...options, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrderRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'DELETE', responseStyle: 'data', url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderByIdRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUserRequest = ( options?: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'POST', responseStyle: 'data', url: '/user', ...options, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInputRequest = ( options?: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'POST', responseStyle: 'data', url: '/user/createWithList', ...options, }); /** * Logs user into the system. * * Log into the system. */ export const loginUserRequest = ( options?: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUserRequest = ( options?: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUserRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'DELETE', responseStyle: 'data', url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByNameRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'GET', responseStyle: 'data', url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUserRequest = ( options: Options, ): HttpRequest => (options?.client ?? client).requestOptions({ method: 'PUT', responseStyle: 'data', url: '/user/{username}', ...options, }); @Injectable({ providedIn: 'root' }) export class PetServiceResources { /** * Add a new pet to the store. * * Add a new pet to the store. */ public addPet( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? addPetRequest(opts) : undefined; }); } /** * Update an existing pet. * * Update an existing pet by Id. */ public updatePet( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? updatePetRequest(opts) : undefined; }); } /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ public findPetsByStatus( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? findPetsByStatusRequest(opts) : undefined; }); } /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ public findPetsByTags( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? findPetsByTagsRequest(opts) : undefined; }); } /** * Deletes a pet. * * Delete a pet. */ public deletePet( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? deletePetRequest(opts) : undefined; }); } /** * Find pet by ID. * * Returns a single pet. */ public getPetById( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? getPetByIdRequest(opts) : undefined; }); } /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ public updatePetWithForm( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? updatePetWithFormRequest(opts) : undefined; }); } /** * Uploads an image. * * Upload image of the pet. */ public uploadFile( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? uploadFileRequest(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class StoreServiceResources { /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ public getInventory( options?: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? getInventoryRequest(opts) : undefined; }); } /** * Place an order for a pet. * * Place a new order in the store. */ public placeOrder( options?: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? placeOrderRequest(opts) : undefined; }); } /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ public deleteOrder( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? deleteOrderRequest(opts) : undefined; }); } /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ public getOrderById( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? getOrderByIdRequest(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class UserServiceResources { /** * Create user. * * This can only be done by the logged in user. */ public createUser( options?: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? createUserRequest(opts) : undefined; }); } /** * Creates list of users with given input array. * * Creates list of users with given input array. */ public createUsersWithListInput( options?: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? createUsersWithListInputRequest(opts) : undefined; }); } /** * Logs user into the system. * * Log into the system. */ public loginUser( options?: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? loginUserRequest(opts) : undefined; }); } /** * Logs out current logged in user session. * * Log user out of the system. */ public logoutUser( options?: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? logoutUserRequest(opts) : undefined; }); } /** * Delete user resource. * * This can only be done by the logged in user. */ public deleteUser( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? deleteUserRequest(opts) : undefined; }); } /** * Get user by user name. * * Get user detail based on username. */ public getUserByName( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? getUserByNameRequest(opts) : undefined; }); } /** * Update user resource. * * This can only be done by the logged in user. */ public updateUser( options: () => Options | undefined, ) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? updateUserRequest(opts) : undefined; }); } } ================================================ FILE: examples/openapi-ts-angular-common/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-angular-common/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-angular-common/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-angular-common/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3', throwOnError: true, }), ); ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-angular-common/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-angular-common/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPetRequest, createUserRequest, createUsersWithListInputRequest, deleteOrderRequest, deletePetRequest, deleteUserRequest, findPetsByStatusRequest, findPetsByTagsRequest, getInventoryRequest, getOrderByIdRequest, getPetByIdRequest, getUserByNameRequest, loginUserRequest, logoutUserRequest, PetServiceResources, placeOrderRequest, StoreServiceResources, updatePetRequest, updatePetWithFormRequest, updateUserRequest, uploadFileRequest, UserServiceResources, } from './@angular/common.gen'; export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-angular-common/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-angular-common/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ responseStyle: 'data', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ responseStyle: 'data', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get< FindPetsByStatusResponses, FindPetsByStatusErrors, ThrowOnError, 'data' >({ responseStyle: 'data', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get< FindPetsByTagsResponses, FindPetsByTagsErrors, ThrowOnError, 'data' >({ responseStyle: 'data', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ responseStyle: 'data', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ responseStyle: 'data', security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError, 'data' >({ responseStyle: 'data', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, responseStyle: 'data', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ responseStyle: 'data', security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ responseStyle: 'data', url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ responseStyle: 'data', url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ responseStyle: 'data', url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ responseStyle: 'data', url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError, 'data' >({ responseStyle: 'data', url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ responseStyle: 'data', url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ responseStyle: 'data', url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ responseStyle: 'data', url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get( { responseStyle: 'data', url: '/user/{username}', ...options, }, ); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ responseStyle: 'data', url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-angular-common/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-angular-common/src/index.html ================================================ Hey API + Angular Demo ================================================ FILE: examples/openapi-ts-angular-common/src/main.server.ts ================================================ import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { config } from './app/app.config.server'; const bootstrap = () => bootstrapApplication(AppComponent, config); export default bootstrap; ================================================ FILE: examples/openapi-ts-angular-common/src/main.ts ================================================ import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); ================================================ FILE: examples/openapi-ts-angular-common/src/server.ts ================================================ import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { AngularNodeAppEngine, createNodeRequestHandler, isMainModule, writeResponseToNodeResponse, } from '@angular/ssr/node'; import express from 'express'; const serverDistFolder = dirname(fileURLToPath(import.meta.url)); const browserDistFolder = resolve(serverDistFolder, '../browser'); const app = express(); const angularApp = new AngularNodeAppEngine(); /** * Example Express Rest API endpoints can be defined here. * Uncomment and define endpoints as necessary. * * Example: * ```ts * app.get('/api/**', (req, res) => { * // Handle API request * }); * ``` */ /** * Serve static files from /browser */ app.use( express.static(browserDistFolder, { index: false, maxAge: '1y', redirect: false, }), ); /** * Handle all other requests by rendering the Angular application. */ app.use('/**', (req, res, next) => { angularApp .handle(req) .then((response) => (response ? writeResponseToNodeResponse(response, res) : next())) .catch(next); }); /** * Start the server if this module is the main entry point. * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000. */ if (isMainModule(import.meta.url)) { const port = process.env['PORT'] || 4000; app.listen(port, () => { console.log(`Node Express server listening on http://localhost:${port}`); }); } /** * Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions. */ export const reqHandler = createNodeRequestHandler(app); ================================================ FILE: examples/openapi-ts-angular-common/src/styles.css ================================================ /* You can add global styles to this file, and also import other style files */ ================================================ FILE: examples/openapi-ts-angular-common/tsconfig.app.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/app", "types": ["node"] }, "files": ["src/main.ts", "src/main.server.ts", "src/server.ts"], "include": ["src/**/*.d.ts"] } ================================================ FILE: examples/openapi-ts-angular-common/tsconfig.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc", "strict": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "skipLibCheck": true, "isolatedModules": true, "esModuleInterop": true, "experimentalDecorators": true, "moduleResolution": "bundler", "importHelpers": true, "target": "ES2022", "module": "ES2022" }, "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, "strictInjectionParameters": true, "strictInputAccessModifiers": true, "strictTemplates": true } } ================================================ FILE: examples/openapi-ts-angular-common/tsconfig.spec.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": ["jasmine"] }, "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] } ================================================ FILE: examples/openapi-ts-axios/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: examples/openapi-ts-axios/CHANGELOG.md ================================================ # @example/openapi-ts-axios ## 0.0.35 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-axios@0.9.1 ## 0.0.34 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-axios@0.9.0 ## 0.0.33 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-axios@0.8.0 ## 0.0.32 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-axios@0.7.1 ## 0.0.31 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-axios@0.7.0 ## 0.0.30 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-axios@0.6.3 ## 0.0.29 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-axios@0.6.2 ## 0.0.28 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-axios@0.6.1 ## 0.0.27 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-axios@0.6.0 ## 0.0.26 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31)]: - @hey-api/client-axios@0.5.3 ## 0.0.25 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-axios@0.5.2 ## 0.0.24 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-axios@0.5.1 ## 0.0.23 ### Patch Changes - Updated dependencies [[`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107)]: - @hey-api/client-axios@0.5.0 ## 0.0.22 ### Patch Changes - Updated dependencies []: - @hey-api/client-axios@0.4.0 ## 0.0.21 ### Patch Changes - Updated dependencies [[`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263), [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26), [`458ef50`](https://github.com/hey-api/openapi-ts/commit/458ef500a18127a618dd1e14e14e20014027e77d)]: - @hey-api/client-axios@0.3.4 ## 0.0.20 ### Patch Changes - Updated dependencies [[`ba56424`](https://github.com/hey-api/openapi-ts/commit/ba5642486cdd5461c2372c34b63019c02bc6874e)]: - @hey-api/client-axios@0.3.3 ## 0.0.19 ### Patch Changes - Updated dependencies [[`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a)]: - @hey-api/client-axios@0.3.2 ## 0.0.18 ### Patch Changes - Updated dependencies [[`cbf4e84`](https://github.com/hey-api/openapi-ts/commit/cbf4e84db7f3a47f19d8c3eaa87c71b27912c1a2)]: - @hey-api/client-axios@0.3.1 ## 0.0.17 ### Patch Changes - Updated dependencies [[`8010dbb`](https://github.com/hey-api/openapi-ts/commit/8010dbb1ab8b91d1d49d5cf16276183764a63ff3), [`8010dbb`](https://github.com/hey-api/openapi-ts/commit/8010dbb1ab8b91d1d49d5cf16276183764a63ff3), [`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0)]: - @hey-api/client-axios@0.3.0 ## 0.0.16 ### Patch Changes - Updated dependencies [[`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a)]: - @hey-api/client-axios@0.2.12 ## 0.0.15 ### Patch Changes - Updated dependencies [[`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df)]: - @hey-api/client-axios@0.2.11 ## 0.0.14 ### Patch Changes - Updated dependencies [[`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482)]: - @hey-api/client-axios@0.2.10 ## 0.0.13 ### Patch Changes - [#1151](https://github.com/hey-api/openapi-ts/pull/1151) [`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update website domain, add license documentation - Updated dependencies [[`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5)]: - @hey-api/client-axios@0.2.9 ## 0.0.12 ### Patch Changes - Updated dependencies [[`a0a5551`](https://github.com/hey-api/openapi-ts/commit/a0a55510d30a1a8dea0ade4908b5b13d51b5f9e6)]: - @hey-api/client-axios@0.2.8 ## 0.0.11 ### Patch Changes - Updated dependencies [[`7f986c2`](https://github.com/hey-api/openapi-ts/commit/7f986c2c7726ed8fbf16f8b235b7769c7d990502)]: - @hey-api/client-axios@0.2.7 ## 0.0.10 ### Patch Changes - Updated dependencies [[`fe743c2`](https://github.com/hey-api/openapi-ts/commit/fe743c2d41c23bf7e1706bceedd6319299131197)]: - @hey-api/client-axios@0.2.6 ## 0.0.9 ### Patch Changes - Updated dependencies [[`11a276a`](https://github.com/hey-api/openapi-ts/commit/11a276a1e35dde0735363e892d8142016fd87eec)]: - @hey-api/client-axios@0.2.5 ## 0.0.8 ### Patch Changes - Updated dependencies [[`7ae2b1d`](https://github.com/hey-api/openapi-ts/commit/7ae2b1db047f3b6efe917a8b43ac7c851fb86c8f), [`2079c6e`](https://github.com/hey-api/openapi-ts/commit/2079c6e83a6b71e157c8e7ea56260b4e9ff8411d)]: - @hey-api/client-axios@0.2.4 ## 0.0.7 ### Patch Changes - Updated dependencies [[`7825a2f`](https://github.com/hey-api/openapi-ts/commit/7825a2fba566a76c63775172ef0569ef375406b6)]: - @hey-api/client-axios@0.2.3 ## 0.0.6 ### Patch Changes - [#895](https://github.com/hey-api/openapi-ts/pull/895) [`44de8d8`](https://github.com/hey-api/openapi-ts/commit/44de8d89556b3abf48acc4e23c9b9c198059c757) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: define ThrowOnError generic as the last argument - Updated dependencies [[`44de8d8`](https://github.com/hey-api/openapi-ts/commit/44de8d89556b3abf48acc4e23c9b9c198059c757)]: - @hey-api/client-axios@0.2.2 ## 0.0.5 ### Patch Changes - Updated dependencies [[`ec6bfc8`](https://github.com/hey-api/openapi-ts/commit/ec6bfc8292cce7663dfc6e0fcd89b44c56f08bb4), [`a73da1c`](https://github.com/hey-api/openapi-ts/commit/a73da1c854503246b6c58f1abea5dd77727eedca)]: - @hey-api/client-axios@0.2.1 ## 0.0.4 ### Patch Changes - Updated dependencies [[`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50), [`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50)]: - @hey-api/client-axios@0.2.0 ## 0.0.3 ### Patch Changes - [#823](https://github.com/hey-api/openapi-ts/pull/823) [`23c9dcd`](https://github.com/hey-api/openapi-ts/commit/23c9dcd5de19de62d745cc539674c815b2588cd2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly process body parameter for OpenAPI 2.0 specs ## 0.0.2 ### Patch Changes - Updated dependencies [[`f8e0b7b`](https://github.com/hey-api/openapi-ts/commit/f8e0b7b7ab5cbd673ca13a21fd1180194558c7f5)]: - @hey-api/client-axios@0.1.1 ## 0.0.1 ### Patch Changes - Updated dependencies [[`b3786dc`](https://github.com/hey-api/openapi-ts/commit/b3786dc6749d8d4ae26bb63322e124663f881741)]: - @hey-api/client-axios@0.1.0 ================================================ FILE: examples/openapi-ts-axios/index.html ================================================ Hey API + Axios Demo
    ================================================ FILE: examples/openapi-ts-axios/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-axios', '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, ], }); ================================================ FILE: examples/openapi-ts-axios/package.json ================================================ { "name": "@example/openapi-ts-axios", "version": "0.0.35", "private": true, "type": "module", "scripts": { "build": "tsgo --noEmit && vite build", "dev": "vite", "lint": "eslint . --report-unused-disable-directives --max-warnings 0", "openapi-ts": "openapi-ts", "preview": "vite preview", "typecheck": "tsgo --noEmit" }, "dependencies": { "@radix-ui/react-form": "0.1.1", "@radix-ui/react-icons": "1.3.2", "@radix-ui/themes": "3.1.6", "axios": "1.8.2", "react": "19.0.0", "react-dom": "19.0.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@types/react": "19.0.1", "@types/react-dom": "19.0.1", "@typescript-eslint/eslint-plugin": "8.29.1", "@typescript-eslint/parser": "8.29.1", "@vitejs/plugin-react": "4.4.0-beta.1", "autoprefixer": "10.4.19", "eslint": "9.17.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.7", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1" } } ================================================ FILE: examples/openapi-ts-axios/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-axios/src/App.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; ================================================ FILE: examples/openapi-ts-axios/src/App.tsx ================================================ import './App.css'; import * as Form from '@radix-ui/react-form'; import { DownloadIcon, PlusIcon, ReloadIcon } from '@radix-ui/react-icons'; import { Avatar, Box, Button, Card, Container, Flex, Heading, Section, Text, TextField, } from '@radix-ui/themes'; import { useState } from 'react'; import { createClient } from './client/client'; import { PetSchema } from './client/schemas.gen'; import { addPet, getPetById, updatePet } from './client/sdk.gen'; import type { Pet } from './client/types.gen'; const localClient = createClient({ // set default base url for requests made by this client baseURL: 'https://petstore3.swagger.io/api/v3', /** * Set default headers only for requests made by this client. This is to * demonstrate local clients and their configuration taking precedence over * global configuration. */ headers: { Authorization: 'Bearer ', }, }); localClient.instance.interceptors.request.use((config) => { // Middleware is great for adding authorization tokens to requests made to // protected paths. Headers are set randomly here to allow surfacing the // default headers, too. if (config.url?.startsWith('/pet/') && config.method === 'get' && Math.random() < 0.5) { config.headers.set('Authorization', 'Bearer '); } return config; }); function App() { const [pet, setPet] = useState(); const [isRequiredNameError, setIsRequiredNameError] = useState(false); const onAddPet = async (formData: FormData) => { // simple form field validation to demonstrate using schemas if (PetSchema.required.includes('name') && !formData.get('name')) { setIsRequiredNameError(true); return; } const { data, error } = await addPet({ body: { category: { id: 0, name: formData.get('category') as string, }, id: 0, name: formData.get('name') as string, photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, }); if (error) { console.log(error); return; } setPet(data!); setIsRequiredNameError(false); }; const onGetPetById = async () => { const { data, error } = await getPetById({ client: localClient, path: { // random id 1-10 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1), }, }); if (error) { console.log(error); return; } setPet(data!); }; const onUpdatePet = async () => { const { data, error } = await updatePet({ body: { category: { id: 0, name: 'Cats', }, id: 2, name: 'Updated Kitty', photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, // setting headers per request headers: { Authorization: 'Bearer ', }, }); if (error) { console.log(error); return; } setPet(data!); }; return (
    Hey API logo @hey-api/openapi-ts 🤝 Axios
    Name: {pet?.name ?? 'N/A'} Category: {pet?.category?.name ?? 'N/A'}
    { event.preventDefault(); onAddPet(new FormData(event.currentTarget)); }} >
    Name {isRequiredNameError && ( Please enter a name )}
    Category Please enter a category
    ); } export default App; ================================================ FILE: examples/openapi-ts-axios/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-axios/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: examples/openapi-ts-axios/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-axios/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: examples/openapi-ts-axios/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseURL: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-axios/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-axios/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-axios/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-axios/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-axios/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-axios/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-axios/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-axios/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-axios/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-axios/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-axios/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ responseType: 'json', security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ responseType: 'json', security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ responseType: 'json', url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ responseType: 'json', url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ responseType: 'json', url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ responseType: 'json', url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ responseType: 'json', url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ responseType: 'json', url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-axios/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-axios/src/main.tsx ================================================ import '@radix-ui/themes/styles.css'; import { Theme } from '@radix-ui/themes'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App.tsx'; import { client } from './client/client.gen'; // configure internal service client client.setConfig({ // set default base url for requests baseURL: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); ReactDOM.createRoot(document.getElementById('root')!).render( , ); ================================================ FILE: examples/openapi-ts-axios/src/vite-env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-axios/tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{html,js,ts,jsx,tsx}'], theme: { extend: {}, }, }; ================================================ FILE: examples/openapi-ts-axios/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": false, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: examples/openapi-ts-axios/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: examples/openapi-ts-axios/vite.config.ts ================================================ import react from '@vitejs/plugin-react'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [react()], }; ================================================ FILE: examples/openapi-ts-fastify/CHANGELOG.md ================================================ # @example/openapi-ts-fastify ## 0.1.16 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-fetch@0.13.1 ## 0.1.15 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-fetch@0.13.0 ## 0.1.14 ### Patch Changes - Updated dependencies [[`4d8c030`](https://github.com/hey-api/openapi-ts/commit/4d8c03038979c9a75315cc158789b3c198c62f90)]: - @hey-api/client-fetch@0.12.0 ## 0.1.13 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-fetch@0.11.0 ## 0.1.12 ### Patch Changes - Updated dependencies [[`1f99066`](https://github.com/hey-api/openapi-ts/commit/1f99066efbb2d0e6b9e3710c701293c2cc09d65e)]: - @hey-api/client-fetch@0.10.2 ## 0.1.11 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-fetch@0.10.1 ## 0.1.10 ### Patch Changes - Updated dependencies [[`fed9699`](https://github.com/hey-api/openapi-ts/commit/fed969985275621c7c2b65ffc760c7c66fafaf72)]: - @hey-api/client-fetch@0.10.0 ## 0.1.9 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-fetch@0.9.0 ## 0.1.8 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-fetch@0.8.4 ## 0.1.7 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-fetch@0.8.3 ## 0.1.6 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-fetch@0.8.2 ## 0.1.5 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-fetch@0.8.1 ## 0.1.4 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-fetch@0.8.0 ## 0.1.3 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31)]: - @hey-api/client-fetch@0.7.3 ## 0.1.2 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-fetch@0.7.2 ## 0.1.1 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-fetch@0.7.1 ## 0.1.0 ### Minor Changes - [#1568](https://github.com/hey-api/openapi-ts/pull/1568) [`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: change the default parser ### Patch Changes - Updated dependencies [[`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107)]: - @hey-api/client-fetch@0.7.0 ## 0.0.11 ### Patch Changes - Updated dependencies [[`e2e1410`](https://github.com/hey-api/openapi-ts/commit/e2e1410b22c0c84c40d1b1803e9650d546350cb7)]: - @hey-api/client-fetch@0.6.0 ## 0.0.10 ### Patch Changes - Updated dependencies [[`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263), [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26)]: - @hey-api/client-fetch@0.5.7 ## 0.0.9 ### Patch Changes - Updated dependencies [[`ba56424`](https://github.com/hey-api/openapi-ts/commit/ba5642486cdd5461c2372c34b63019c02bc6874e)]: - @hey-api/client-fetch@0.5.6 ## 0.0.8 ### Patch Changes - Updated dependencies [[`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a)]: - @hey-api/client-fetch@0.5.5 ## 0.0.7 ### Patch Changes - Updated dependencies [[`cbf4e84`](https://github.com/hey-api/openapi-ts/commit/cbf4e84db7f3a47f19d8c3eaa87c71b27912c1a2)]: - @hey-api/client-fetch@0.5.4 ## 0.0.6 ### Patch Changes - Updated dependencies [[`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0)]: - @hey-api/client-fetch@0.5.3 ## 0.0.5 ### Patch Changes - Updated dependencies [[`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a)]: - @hey-api/client-fetch@0.5.2 ## 0.0.4 ### Patch Changes - Updated dependencies [[`fa8b0f1`](https://github.com/hey-api/openapi-ts/commit/fa8b0f11ed99c63f694a494944ccc2fbfa9706cc)]: - @hey-api/client-fetch@0.5.1 ## 0.0.3 ### Patch Changes - Updated dependencies [[`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df), [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df)]: - @hey-api/client-fetch@0.5.0 ## 0.0.2 ### Patch Changes - Updated dependencies [[`4c853d0`](https://github.com/hey-api/openapi-ts/commit/4c853d090b79245854d13831f64731db4a92978b)]: - @hey-api/client-fetch@0.4.4 ================================================ FILE: examples/openapi-ts-fastify/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://gist.githubusercontent.com/seriousme/55bd4c8ba2e598e416bb5543dcd362dc/raw/cf0b86ba37bb54bf1a6bf047c0ecf2a0ce4c62e0/petstore-v3.1.json', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: ['fastify', '@hey-api/sdk'], }); ================================================ FILE: examples/openapi-ts-fastify/openapi.json ================================================ { "openapi": "3.1.0", "info": { "title": "Petstore API", "version": "1.0.0", "description": "A sample API that uses a petstore as an example" }, "servers": [ { "url": "http://localhost:3000/v3" } ], "paths": { "/pets/{petId}": { "get": { "summary": "Find pet by ID", "operationId": "showPetById", "parameters": [ { "name": "petId", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Pet found", "content": { "application/json": { "schema": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" } } } } } } } } }, "/pets": { "get": { "summary": "List all pets", "operationId": "listPets", "responses": { "200": { "description": "A list of pets", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" } } } } } } } } }, "post": { "summary": "Create a pet", "operationId": "createPets", "responses": { "201": { "description": "Pet created" } } } } } } ================================================ FILE: examples/openapi-ts-fastify/package.json ================================================ { "name": "@example/openapi-ts-fastify", "version": "0.1.16", "private": true, "type": "module", "scripts": { "openapi-ts": "openapi-ts", "test": "vitest", "typecheck": "tsgo --noEmit" }, "dependencies": { "fastify": "5.7.4", "fastify-openapi-glue": "4.8.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "eslint": "9.17.0", "oxfmt": "0.27.0", "typescript": "5.9.3", "vite": "7.3.1", "vitest": "4.0.18" } } ================================================ FILE: examples/openapi-ts-fastify/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-fastify/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-fastify/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-fastify/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'http://petstore.swagger.io/v1' }), ); ================================================ FILE: examples/openapi-ts-fastify/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-fastify/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-fastify/src/client/fastify.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { RouteHandler } from 'fastify'; import type { CreatePetsResponses, ListPetsData, ListPetsResponses, ShowPetByIdData, ShowPetByIdResponses, } from './types.gen'; export type RouteHandlers = { createPets: RouteHandler<{ Reply: CreatePetsResponses; }>; listPets: RouteHandler<{ Querystring?: ListPetsData['query']; Reply: ListPetsResponses; }>; showPetById: RouteHandler<{ Params: ShowPetByIdData['path']; Reply: ShowPetByIdResponses; }>; }; ================================================ FILE: examples/openapi-ts-fastify/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { createPets, listPets, type Options, showPetById } from './sdk.gen'; export type { ClientOptions, CreatePetsData, CreatePetsError, CreatePetsErrors, CreatePetsResponses, Error, ListPetsData, ListPetsError, ListPetsErrors, ListPetsResponse, ListPetsResponses, Pet, Pets, ShowPetByIdData, ShowPetByIdError, ShowPetByIdErrors, ShowPetByIdResponse, ShowPetByIdResponses, } from './types.gen'; ================================================ FILE: examples/openapi-ts-fastify/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CreatePetsData, CreatePetsErrors, CreatePetsResponses, ListPetsData, ListPetsErrors, ListPetsResponses, ShowPetByIdData, ShowPetByIdErrors, ShowPetByIdResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * List all pets */ export const listPets = ( options?: Options, ) => (options?.client ?? client).get({ url: '/pets', ...options, }); /** * Create a pet */ export const createPets = ( options?: Options, ) => (options?.client ?? client).post({ url: '/pets', ...options, }); /** * Info for a specific pet */ export const showPetById = ( options: Options, ) => (options.client ?? client).get({ url: '/pets/{petId}', ...options, }); ================================================ FILE: examples/openapi-ts-fastify/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://petstore.swagger.io/v1' | (string & {}); }; export type Pet = { id: number; name: string; tag?: string; }; export type Pets = Array; export type Error = { code: number; message: string; }; export type ListPetsData = { body?: never; path?: never; query?: { /** * How many items to return at one time (max 100) */ limit?: number; }; url: '/pets'; }; export type ListPetsErrors = { /** * unexpected error */ default: Error; }; export type ListPetsError = ListPetsErrors[keyof ListPetsErrors]; export type ListPetsResponses = { /** * A paged array of pets */ 200: Pets; }; export type ListPetsResponse = ListPetsResponses[keyof ListPetsResponses]; export type CreatePetsData = { body?: never; path?: never; query?: never; url: '/pets'; }; export type CreatePetsErrors = { /** * unexpected error */ default: Error; }; export type CreatePetsError = CreatePetsErrors[keyof CreatePetsErrors]; export type CreatePetsResponses = { /** * Null response */ 201: unknown; }; export type ShowPetByIdData = { body?: never; path: { /** * The id of the pet to retrieve */ petId: string; }; query?: never; url: '/pets/{petId}'; }; export type ShowPetByIdErrors = { /** * unexpected error */ default: Error; }; export type ShowPetByIdError = ShowPetByIdErrors[keyof ShowPetByIdErrors]; export type ShowPetByIdResponses = { /** * Expected response to a valid request */ 200: Pet; }; export type ShowPetByIdResponse = ShowPetByIdResponses[keyof ShowPetByIdResponses]; ================================================ FILE: examples/openapi-ts-fastify/src/handlers.ts ================================================ import type { RouteHandlers } from './client/fastify.gen'; export const serviceHandlers: RouteHandlers = { createPets(request, reply) { reply.code(201).send(); }, listPets(request, reply) { reply.code(200).send([]); }, showPetById(request, reply) { reply.code(200).send({ id: Number(request.params.petId), name: 'Kitty', }); }, }; ================================================ FILE: examples/openapi-ts-fastify/src/index.ts ================================================ import { buildServer } from './server'; buildServer().then((fastify) => { fastify.listen({ port: 3000 }, function (err) { if (err) { fastify.log.error(err); process.exit(1); } }); }); ================================================ FILE: examples/openapi-ts-fastify/src/server.ts ================================================ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import Fastify from 'fastify'; import glue from 'fastify-openapi-glue'; import { serviceHandlers } from './handlers'; export const buildServer = async () => { const fastify = Fastify(); const specificationPath = join(__dirname, '..', 'openapi.json'); const specificationJson = JSON.parse(readFileSync(specificationPath, 'utf-8')); fastify.register(glue, { prefix: 'v3', serviceHandlers, specification: specificationJson, }); return fastify; }; ================================================ FILE: examples/openapi-ts-fastify/test/pets.test.ts ================================================ import { type FastifyInstance } from 'fastify'; import { showPetById } from 'src/client'; import { client } from 'src/client/client.gen'; import { buildServer } from 'src/server'; describe('/pet/findByTags', () => { let server: FastifyInstance; beforeAll(async () => { server = await buildServer(); await server.listen(); // @ts-ignore const baseUrl = `http://localhost:${server.server.address().port}/v3`; client.setConfig({ baseUrl }); }); afterAll(async () => { await Promise.all([server.close()]); }); test('showPetById', async () => { const result = await showPetById({ client, path: { petId: '123', }, }); expect(result.response.status).toBe(200); }); }); ================================================ FILE: examples/openapi-ts-fastify/tsconfig.json ================================================ { "include": ["src/**/*", "test/**/*"], "compilerOptions": { "esModuleInterop": true, "paths": { "*": ["./*"] }, "lib": ["es2023", "dom", "dom.iterable"], "module": "ESNext", "moduleResolution": "Bundler", "skipLibCheck": true, "strict": true, "target": "es2022", "types": ["vitest/globals"] }, "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: examples/openapi-ts-fastify/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: examples/openapi-ts-fastify/vite.config.ts ================================================ import { defineProject } from 'vitest/config'; export default defineProject({ resolve: { alias: { src: new URL('./src', import.meta.url).pathname, }, }, test: { environment: 'node', include: ['test/**/*.test.ts'], }, }); ================================================ FILE: examples/openapi-ts-fetch/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: examples/openapi-ts-fetch/CHANGELOG.md ================================================ # @example/openapi-ts-fetch ## 0.0.57 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-fetch@0.13.1 ## 0.0.56 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-fetch@0.13.0 ## 0.0.55 ### Patch Changes - Updated dependencies [[`4d8c030`](https://github.com/hey-api/openapi-ts/commit/4d8c03038979c9a75315cc158789b3c198c62f90)]: - @hey-api/client-fetch@0.12.0 ## 0.0.54 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-fetch@0.11.0 ## 0.0.53 ### Patch Changes - Updated dependencies [[`1f99066`](https://github.com/hey-api/openapi-ts/commit/1f99066efbb2d0e6b9e3710c701293c2cc09d65e)]: - @hey-api/client-fetch@0.10.2 ## 0.0.52 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-fetch@0.10.1 ## 0.0.51 ### Patch Changes - Updated dependencies [[`fed9699`](https://github.com/hey-api/openapi-ts/commit/fed969985275621c7c2b65ffc760c7c66fafaf72)]: - @hey-api/client-fetch@0.10.0 ## 0.0.50 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-fetch@0.9.0 ## 0.0.49 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-fetch@0.8.4 ## 0.0.48 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-fetch@0.8.3 ## 0.0.47 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-fetch@0.8.2 ## 0.0.46 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-fetch@0.8.1 ## 0.0.45 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-fetch@0.8.0 ## 0.0.44 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31)]: - @hey-api/client-fetch@0.7.3 ## 0.0.43 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-fetch@0.7.2 ## 0.0.42 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-fetch@0.7.1 ## 0.0.41 ### Patch Changes - Updated dependencies [[`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107)]: - @hey-api/client-fetch@0.7.0 ## 0.0.40 ### Patch Changes - Updated dependencies [[`e2e1410`](https://github.com/hey-api/openapi-ts/commit/e2e1410b22c0c84c40d1b1803e9650d546350cb7)]: - @hey-api/client-fetch@0.6.0 ## 0.0.39 ### Patch Changes - Updated dependencies [[`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263), [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26)]: - @hey-api/client-fetch@0.5.7 ## 0.0.38 ### Patch Changes - Updated dependencies [[`ba56424`](https://github.com/hey-api/openapi-ts/commit/ba5642486cdd5461c2372c34b63019c02bc6874e)]: - @hey-api/client-fetch@0.5.6 ## 0.0.37 ### Patch Changes - Updated dependencies [[`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a)]: - @hey-api/client-fetch@0.5.5 ## 0.0.36 ### Patch Changes - Updated dependencies [[`cbf4e84`](https://github.com/hey-api/openapi-ts/commit/cbf4e84db7f3a47f19d8c3eaa87c71b27912c1a2)]: - @hey-api/client-fetch@0.5.4 ## 0.0.35 ### Patch Changes - Updated dependencies [[`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0)]: - @hey-api/client-fetch@0.5.3 ## 0.0.34 ### Patch Changes - Updated dependencies [[`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a)]: - @hey-api/client-fetch@0.5.2 ## 0.0.33 ### Patch Changes - Updated dependencies [[`fa8b0f1`](https://github.com/hey-api/openapi-ts/commit/fa8b0f11ed99c63f694a494944ccc2fbfa9706cc)]: - @hey-api/client-fetch@0.5.1 ## 0.0.32 ### Patch Changes - Updated dependencies [[`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df), [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df)]: - @hey-api/client-fetch@0.5.0 ## 0.0.31 ### Patch Changes - Updated dependencies [[`4c853d0`](https://github.com/hey-api/openapi-ts/commit/4c853d090b79245854d13831f64731db4a92978b)]: - @hey-api/client-fetch@0.4.4 ## 0.0.30 ### Patch Changes - Updated dependencies [[`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482)]: - @hey-api/client-fetch@0.4.3 ## 0.0.29 ### Patch Changes - [#1151](https://github.com/hey-api/openapi-ts/pull/1151) [`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update website domain, add license documentation - Updated dependencies [[`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5)]: - @hey-api/client-fetch@0.4.2 ## 0.0.28 ### Patch Changes - Updated dependencies [[`a0a5551`](https://github.com/hey-api/openapi-ts/commit/a0a55510d30a1a8dea0ade4908b5b13d51b5f9e6)]: - @hey-api/client-fetch@0.4.1 ## 0.0.27 ### Patch Changes - Updated dependencies [[`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa), [`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa)]: - @hey-api/client-fetch@0.4.0 ## 0.0.26 ### Patch Changes - Updated dependencies [[`7f986c2`](https://github.com/hey-api/openapi-ts/commit/7f986c2c7726ed8fbf16f8b235b7769c7d990502)]: - @hey-api/client-fetch@0.3.4 ## 0.0.25 ### Patch Changes - Updated dependencies [[`fe743c2`](https://github.com/hey-api/openapi-ts/commit/fe743c2d41c23bf7e1706bceedd6319299131197)]: - @hey-api/client-fetch@0.3.3 ## 0.0.24 ### Patch Changes - Updated dependencies [[`11a276a`](https://github.com/hey-api/openapi-ts/commit/11a276a1e35dde0735363e892d8142016fd87eec)]: - @hey-api/client-fetch@0.3.2 ## 0.0.23 ### Patch Changes - Updated dependencies [[`7ae2b1d`](https://github.com/hey-api/openapi-ts/commit/7ae2b1db047f3b6efe917a8b43ac7c851fb86c8f), [`2079c6e`](https://github.com/hey-api/openapi-ts/commit/2079c6e83a6b71e157c8e7ea56260b4e9ff8411d)]: - @hey-api/client-fetch@0.3.1 ## 0.0.22 ### Patch Changes - Updated dependencies [[`7ebc1d4`](https://github.com/hey-api/openapi-ts/commit/7ebc1d44af74db2522219d71d240325f6bc5689d)]: - @hey-api/client-fetch@0.3.0 ## 0.0.21 ### Patch Changes - [#899](https://github.com/hey-api/openapi-ts/pull/899) [`a8c84c0`](https://github.com/hey-api/openapi-ts/commit/a8c84c02dbb5ef1a59f5d414dff425e135c7a446) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: preserve key name in Date transformation - Updated dependencies [[`a8c84c0`](https://github.com/hey-api/openapi-ts/commit/a8c84c02dbb5ef1a59f5d414dff425e135c7a446), [`7825a2f`](https://github.com/hey-api/openapi-ts/commit/7825a2fba566a76c63775172ef0569ef375406b6)]: - @hey-api/client-fetch@0.2.4 ## 0.0.20 ### Patch Changes - [#895](https://github.com/hey-api/openapi-ts/pull/895) [`44de8d8`](https://github.com/hey-api/openapi-ts/commit/44de8d89556b3abf48acc4e23c9b9c198059c757) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: define ThrowOnError generic as the last argument - Updated dependencies [[`44de8d8`](https://github.com/hey-api/openapi-ts/commit/44de8d89556b3abf48acc4e23c9b9c198059c757)]: - @hey-api/client-fetch@0.2.3 ## 0.0.19 ### Patch Changes - Updated dependencies [[`72e2c4f`](https://github.com/hey-api/openapi-ts/commit/72e2c4fd7d07e532a848078c034bf33b6558ad3c)]: - @hey-api/client-fetch@0.2.2 ## 0.0.18 ### Patch Changes - Updated dependencies [[`ec6bfc8`](https://github.com/hey-api/openapi-ts/commit/ec6bfc8292cce7663dfc6e0fcd89b44c56f08bb4), [`93e2d11`](https://github.com/hey-api/openapi-ts/commit/93e2d11d2a8ddd1f78dde46eceeb5543cae07e36), [`a73da1c`](https://github.com/hey-api/openapi-ts/commit/a73da1c854503246b6c58f1abea5dd77727eedca), [`da92c53`](https://github.com/hey-api/openapi-ts/commit/da92c535c14e3217d565472fe65c687243bc0dd8)]: - @hey-api/client-fetch@0.2.1 ## 0.0.17 ### Patch Changes - Updated dependencies [[`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50), [`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50)]: - @hey-api/client-fetch@0.2.0 ## 0.0.16 ### Patch Changes - Updated dependencies [[`8c9c874`](https://github.com/hey-api/openapi-ts/commit/8c9c8749594622283eed2c37bddfa0f1b8cf23a4)]: - @hey-api/client-fetch@0.1.14 ## 0.0.15 ### Patch Changes - Updated dependencies [[`8e3c634`](https://github.com/hey-api/openapi-ts/commit/8e3c6343672b9280365c3266f94e4acba533bf29)]: - @hey-api/client-fetch@0.1.13 ## 0.0.14 ### Patch Changes - [#823](https://github.com/hey-api/openapi-ts/pull/823) [`23c9dcd`](https://github.com/hey-api/openapi-ts/commit/23c9dcd5de19de62d745cc539674c815b2588cd2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly process body parameter for OpenAPI 2.0 specs ## 0.0.13 ### Patch Changes - Updated dependencies [[`0c4ee06`](https://github.com/hey-api/openapi-ts/commit/0c4ee06548f177ce83d73802471c659834c63566)]: - @hey-api/client-fetch@0.1.12 ## 0.0.12 ### Patch Changes - Updated dependencies [[`c0ee1e3`](https://github.com/hey-api/openapi-ts/commit/c0ee1e3b56d67ab922491c488233bd89c8902986)]: - @hey-api/client-fetch@0.1.11 ## 0.0.11 ### Patch Changes - Updated dependencies [[`ecd94f2`](https://github.com/hey-api/openapi-ts/commit/ecd94f2adab1dbe10e7a9c310d1fb6d1f170d332)]: - @hey-api/client-fetch@0.1.10 ## 0.0.10 ### Patch Changes - Updated dependencies [[`e7e98d2`](https://github.com/hey-api/openapi-ts/commit/e7e98d279fe0ee4c71ae72a7b57afdd517a89641)]: - @hey-api/client-fetch@0.1.9 ## 0.0.9 ### Patch Changes - Updated dependencies [[`d546a3f`](https://github.com/hey-api/openapi-ts/commit/d546a3f9fd0a6ff5181deb50ed467acd75370889)]: - @hey-api/client-fetch@0.1.8 ## 0.0.8 ### Patch Changes - Updated dependencies [[`8410046`](https://github.com/hey-api/openapi-ts/commit/8410046c45d25db48ba940a0c6c7a7cda9e86b6a)]: - @hey-api/client-fetch@0.1.7 ## 0.0.7 ### Patch Changes - Updated dependencies [[`aa661a1`](https://github.com/hey-api/openapi-ts/commit/aa661a136d1174eadf4d11538e473b0d96b91b81)]: - @hey-api/client-fetch@0.1.6 ## 0.0.6 ### Patch Changes - Updated dependencies [[`fc2b166`](https://github.com/hey-api/openapi-ts/commit/fc2b166c8f683ece948284cf7a629fcd5b096b40)]: - @hey-api/client-fetch@0.1.5 ## 0.0.5 ### Patch Changes - Updated dependencies [[`da31b74`](https://github.com/hey-api/openapi-ts/commit/da31b7424b30e00233df5a3867022832c4981312), [`34980a4`](https://github.com/hey-api/openapi-ts/commit/34980a4dc8269c9256d65984ff29270851689c43), [`34980a4`](https://github.com/hey-api/openapi-ts/commit/34980a4dc8269c9256d65984ff29270851689c43)]: - @hey-api/client-fetch@0.1.4 ## 0.0.4 ### Patch Changes - Updated dependencies [[`820002f`](https://github.com/hey-api/openapi-ts/commit/820002ffe687b01c7a9b2250e19ddbafd1aaed71)]: - @hey-api/client-fetch@0.1.3 ## 0.0.3 ### Patch Changes - Updated dependencies [[`735561c82dbe0979f2c175d274159c20ba8e622d`](https://github.com/hey-api/openapi-ts/commit/735561c82dbe0979f2c175d274159c20ba8e622d)]: - @hey-api/client-fetch@0.1.2 ## 0.0.2 ### Patch Changes - Updated dependencies [[`616a4ea0265e09f3997ac2156c341a5cc0b49029`](https://github.com/hey-api/openapi-ts/commit/616a4ea0265e09f3997ac2156c341a5cc0b49029)]: - @hey-api/client-fetch@0.1.1 ## 0.0.1 ### Patch Changes - Updated dependencies [[`c416343eb499791dd4771866de1862a2d5d69350`](https://github.com/hey-api/openapi-ts/commit/c416343eb499791dd4771866de1862a2d5d69350)]: - @hey-api/client-fetch@0.1.0 ================================================ FILE: examples/openapi-ts-fetch/index.html ================================================ Hey API + Fetch API Demo
    ================================================ FILE: examples/openapi-ts-fetch/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-fetch', '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, ], }); ================================================ FILE: examples/openapi-ts-fetch/package.json ================================================ { "name": "@example/openapi-ts-fetch", "version": "0.0.57", "private": true, "type": "module", "scripts": { "build": "tsgo --noEmit && vite build", "dev": "vite", "lint": "eslint . --report-unused-disable-directives --max-warnings 0", "openapi-ts": "openapi-ts", "preview": "vite preview", "typecheck": "tsgo --noEmit" }, "dependencies": { "@radix-ui/react-form": "0.1.1", "@radix-ui/react-icons": "1.3.2", "@radix-ui/themes": "3.1.6", "react": "19.0.0", "react-dom": "19.0.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@types/react": "19.0.1", "@types/react-dom": "19.0.1", "@typescript-eslint/eslint-plugin": "8.29.1", "@typescript-eslint/parser": "8.29.1", "@vitejs/plugin-react": "4.4.0-beta.1", "autoprefixer": "10.4.19", "eslint": "9.17.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.7", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1" } } ================================================ FILE: examples/openapi-ts-fetch/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-fetch/src/App.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; ================================================ FILE: examples/openapi-ts-fetch/src/App.tsx ================================================ import './App.css'; import * as Form from '@radix-ui/react-form'; import { DownloadIcon, PlusIcon, ReloadIcon } from '@radix-ui/react-icons'; import { Avatar, Box, Button, Card, Container, Flex, Heading, Section, Text, TextField, } from '@radix-ui/themes'; import { useState } from 'react'; import { createClient } from './client/client'; import { PetSchema } from './client/schemas.gen'; import { addPet, getPetById, updatePet } from './client/sdk.gen'; import type { Pet } from './client/types.gen'; const localClient = createClient({ // set default base url for requests made by this client baseUrl: 'https://petstore3.swagger.io/api/v3', /** * Set default headers only for requests made by this client. This is to * demonstrate local clients and their configuration taking precedence over * internal service client. */ headers: { Authorization: 'Bearer ', }, }); localClient.interceptors.request.use((request, options) => { // Middleware is great for adding authorization tokens to requests made to // protected paths. Headers are set randomly here to allow surfacing the // default headers, too. if (options.url === '/pet/{petId}' && options.method === 'GET' && Math.random() < 0.5) { request.headers.set('Authorization', 'Bearer '); } return request; }); localClient.interceptors.error.use((error) => { console.log(error); return error; }); function App() { const [pet, setPet] = useState(); const [isRequiredNameError, setIsRequiredNameError] = useState(false); const onAddPet = async (formData: FormData) => { // simple form field validation to demonstrate using schemas if (PetSchema.required.includes('name') && !formData.get('name')) { setIsRequiredNameError(true); return; } const { data, error } = await addPet({ body: { category: { id: 0, name: formData.get('category') as string, }, id: 0, name: formData.get('name') as string, photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, }); if (error) { console.log(error); return; } setPet(data!); setIsRequiredNameError(false); }; const onGetPetById = async () => { const { data, error } = await getPetById({ client: localClient, path: { // random id 1-10 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1), }, }); if (error) { console.log(error); return; } setPet(data!); }; const onUpdatePet = async () => { const { data, error } = await updatePet({ body: { category: { id: 0, name: 'Cats', }, id: 2, name: 'Updated Kitty', photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, // setting headers per request headers: { Authorization: 'Bearer ', }, }); if (error) { console.log(error); return; } setPet(data!); }; return (
    Hey API logo @hey-api/openapi-ts 🤝 Fetch API
    Name: {pet?.name ?? 'N/A'} Category: {pet?.category?.name ?? 'N/A'}
    { event.preventDefault(); onAddPet(new FormData(event.currentTarget)); }} >
    Name {isRequiredNameError && ( Please enter a name )}
    Category Please enter a category
    ); } export default App; ================================================ FILE: examples/openapi-ts-fetch/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-fetch/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-fetch/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-fetch/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-fetch/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-fetch/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-fetch/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-fetch/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-fetch/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-fetch/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-fetch/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-fetch/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-fetch/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-fetch/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-fetch/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-fetch/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-fetch/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-fetch/src/main.tsx ================================================ import '@radix-ui/themes/styles.css'; import { Theme } from '@radix-ui/themes'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App.tsx'; import { client } from './client/client.gen'; // configure internal service client client.setConfig({ // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); ReactDOM.createRoot(document.getElementById('root')!).render( , ); ================================================ FILE: examples/openapi-ts-fetch/src/vite-env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-fetch/tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{html,js,ts,jsx,tsx}'], theme: { extend: {}, }, }; ================================================ FILE: examples/openapi-ts-fetch/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": false, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: examples/openapi-ts-fetch/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: examples/openapi-ts-fetch/vite.config.ts ================================================ import react from '@vitejs/plugin-react'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [react()], }; ================================================ FILE: examples/openapi-ts-ky/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: examples/openapi-ts-ky/CHANGELOG.md ================================================ # @example/openapi-ts-ky ## 0.0.1 ### Patch Changes - Initial release of ky client example ================================================ FILE: examples/openapi-ts-ky/index.html ================================================ Hey API + Fetch API Demo
    ================================================ FILE: examples/openapi-ts-ky/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-ky', '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, ], }); ================================================ FILE: examples/openapi-ts-ky/package.json ================================================ { "name": "@example/openapi-ts-ky", "version": "0.0.1", "private": true, "type": "module", "scripts": { "build": "tsgo --noEmit && vite build", "dev": "vite", "lint": "eslint . --report-unused-disable-directives --max-warnings 0", "openapi-ts": "openapi-ts", "preview": "vite preview", "typecheck": "tsgo --noEmit" }, "dependencies": { "@radix-ui/react-form": "0.1.1", "@radix-ui/react-icons": "1.3.2", "@radix-ui/themes": "3.1.6", "ky": "1.14.0", "react": "19.0.0", "react-dom": "19.0.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@types/react": "19.0.1", "@types/react-dom": "19.0.1", "@typescript-eslint/eslint-plugin": "8.29.1", "@typescript-eslint/parser": "8.29.1", "@vitejs/plugin-react": "4.4.0-beta.1", "autoprefixer": "10.4.19", "eslint": "9.17.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.7", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1" } } ================================================ FILE: examples/openapi-ts-ky/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-ky/src/App.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; ================================================ FILE: examples/openapi-ts-ky/src/App.tsx ================================================ import './App.css'; import * as Form from '@radix-ui/react-form'; import { DownloadIcon, PlusIcon, ReloadIcon } from '@radix-ui/react-icons'; import { Avatar, Box, Button, Card, Container, Flex, Heading, Section, Text, TextField, } from '@radix-ui/themes'; import { useState } from 'react'; import { createClient } from './client/client'; import { PetSchema } from './client/schemas.gen'; import { addPet, getPetById, updatePet } from './client/sdk.gen'; import type { Pet } from './client/types.gen'; const localClient = createClient({ // set default base url for requests made by this client baseUrl: 'https://petstore3.swagger.io/api/v3', /** * Set default headers only for requests made by this client. This is to * demonstrate local clients and their configuration taking precedence over * internal service client. */ headers: { Authorization: 'Bearer ', }, }); localClient.interceptors.request.use((request, options) => { // Middleware is great for adding authorization tokens to requests made to // protected paths. Headers are set randomly here to allow surfacing the // default headers, too. if (options.url === '/pet/{petId}' && options.method === 'GET' && Math.random() < 0.5) { request.headers.set('Authorization', 'Bearer '); } return request; }); localClient.interceptors.error.use((error) => { console.log(error); return error; }); function App() { const [pet, setPet] = useState(); const [isRequiredNameError, setIsRequiredNameError] = useState(false); const onAddPet = async (formData: FormData) => { // simple form field validation to demonstrate using schemas if (PetSchema.required.includes('name') && !formData.get('name')) { setIsRequiredNameError(true); return; } const { data, error } = await addPet({ body: { category: { id: 0, name: formData.get('category') as string, }, id: 0, name: formData.get('name') as string, photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, }); if (error) { console.log(error); return; } setPet(data!); setIsRequiredNameError(false); }; const onGetPetById = async () => { const { data, error } = await getPetById({ client: localClient, path: { // random id 1-10 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1), }, }); if (error) { console.log(error); return; } setPet(data!); }; const onUpdatePet = async () => { const { data, error } = await updatePet({ body: { category: { id: 0, name: 'Cats', }, id: 2, name: 'Updated Kitty', photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, // setting headers per request headers: { Authorization: 'Bearer ', }, }); if (error) { console.log(error); return; } setPet(data!); }; return (
    Hey API logo @hey-api/openapi-ts 🤝 Fetch API
    Name: {pet?.name ?? 'N/A'} Category: {pet?.category?.name ?? 'N/A'}
    { event.preventDefault(); onAddPet(new FormData(event.currentTarget)); }} >
    Name {isRequiredNameError && ( Please enter a name )}
    Category Please enter a category
    ); } export default App; ================================================ FILE: examples/openapi-ts-ky/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions, } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-ky/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-ky/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-ky/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: examples/openapi-ts-ky/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-ky/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-ky/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-ky/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-ky/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-ky/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-ky/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-ky/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-ky/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-ky/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-ky/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-ky/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-ky/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-ky/src/main.tsx ================================================ import '@radix-ui/themes/styles.css'; import { Theme } from '@radix-ui/themes'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App.tsx'; import { client } from './client/client.gen'; // configure internal service client client.setConfig({ // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); ReactDOM.createRoot(document.getElementById('root')!).render( , ); ================================================ FILE: examples/openapi-ts-ky/src/vite-env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-ky/tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{html,js,ts,jsx,tsx}'], theme: { extend: {}, }, }; ================================================ FILE: examples/openapi-ts-ky/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": false, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: examples/openapi-ts-ky/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: examples/openapi-ts-ky/vite.config.ts ================================================ import react from '@vitejs/plugin-react'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [react()], }; ================================================ FILE: examples/openapi-ts-nestjs/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: './openapi.json', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: ['nestjs', '@hey-api/sdk'], }); ================================================ FILE: examples/openapi-ts-nestjs/openapi.json ================================================ { "openapi": "3.1.0", "info": { "title": "Petstore API", "version": "1.0.0", "description": "A sample API that uses a petstore as an example" }, "servers": [ { "url": "http://localhost:3000/v3" } ], "tags": [ { "name": "pets", "description": "Pet operations" }, { "name": "store", "description": "Store operations" } ], "paths": { "/pets": { "get": { "summary": "List all pets", "operationId": "listPets", "tags": ["pets"], "parameters": [ { "name": "limit", "in": "query", "required": false, "schema": { "type": "integer", "format": "int32", "minimum": 1, "maximum": 100 } }, { "name": "offset", "in": "query", "required": false, "schema": { "type": "integer", "format": "int32", "minimum": 0 } } ], "responses": { "200": { "description": "A list of pets", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Pet" } } } } } } }, "post": { "summary": "Create a pet", "operationId": "createPet", "tags": ["pets"], "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreatePetBody" } } } }, "responses": { "201": { "description": "Pet created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } }, "400": { "description": "Validation error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } } } } }, "/pets/{petId}": { "get": { "summary": "Find pet by ID", "operationId": "showPetById", "tags": ["pets"], "parameters": [ { "name": "petId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } } ], "responses": { "200": { "description": "Pet found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } }, "404": { "description": "Pet not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } } } }, "put": { "summary": "Update a pet", "operationId": "updatePet", "tags": ["pets"], "parameters": [ { "name": "petId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UpdatePetBody" } } } }, "responses": { "200": { "description": "Pet updated", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } }, "400": { "description": "Validation error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }, "404": { "description": "Pet not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } } } }, "delete": { "summary": "Delete a pet", "operationId": "deletePet", "tags": ["pets"], "parameters": [ { "name": "petId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } } ], "responses": { "204": { "description": "Pet deleted" }, "404": { "description": "Pet not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } } } } }, "/store/inventory": { "get": { "summary": "Returns pet inventories by status", "operationId": "getInventory", "tags": ["store"], "responses": { "200": { "description": "Successful operation", "content": { "application/json": { "schema": { "type": "object", "additionalProperties": { "type": "integer", "format": "int32" } } } } } } } } }, "components": { "schemas": { "Pet": { "type": "object", "required": ["id", "name"], "properties": { "id": { "type": "string", "format": "uuid" }, "name": { "type": "string", "minLength": 1, "maxLength": 100 }, "tag": { "type": "string" }, "status": { "type": "string", "enum": ["available", "pending", "sold"] } } }, "CreatePetBody": { "type": "object", "required": ["name"], "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 100 }, "tag": { "type": "string" } } }, "UpdatePetBody": { "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 100 }, "tag": { "type": "string" }, "status": { "type": "string", "enum": ["available", "pending", "sold"] } } }, "Error": { "type": "object", "required": ["code", "message"], "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" } } } } } } ================================================ FILE: examples/openapi-ts-nestjs/package.json ================================================ { "name": "@example/openapi-ts-nestjs", "version": "0.1.0", "private": true, "type": "module", "scripts": { "openapi-ts": "openapi-ts", "start": "node --import @swc-node/register/esm-register src/main.ts", "test": "vitest", "typecheck": "tsc --noEmit" }, "dependencies": { "@nestjs/common": "^11.0.1", "@nestjs/core": "^11.0.1", "@nestjs/platform-express": "^11.0.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@nestjs/testing": "^11.0.1", "@swc-node/register": "^1.10.10", "@swc/core": "^1.11.29", "eslint": "^9.18.0", "oxfmt": "^0.27.0", "typescript": "^5.9.3", "unplugin-swc": "^1.5.5", "vite": "^7.3.1", "vitest": "^4.0.18" } } ================================================ FILE: examples/openapi-ts-nestjs/src/app.module.ts ================================================ import { Module } from '@nestjs/common'; import { PetsModule } from './pets/pets.module'; import { StoreModule } from './store/store.module'; @Module({ imports: [PetsModule, StoreModule], }) export class AppModule {} ================================================ FILE: examples/openapi-ts-nestjs/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-nestjs/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-nestjs/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-nestjs/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'http://localhost:3000/v3' }), ); ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-nestjs/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { createPet, deletePet, getInventory, listPets, type Options, showPetById, updatePet, } from './sdk.gen'; export type { ClientOptions, CreatePetBody, CreatePetData, CreatePetError, CreatePetErrors, CreatePetResponse, CreatePetResponses, DeletePetData, DeletePetError, DeletePetErrors, DeletePetResponse, DeletePetResponses, Error, GetInventoryData, GetInventoryResponse, GetInventoryResponses, ListPetsData, ListPetsResponse, ListPetsResponses, Pet, ShowPetByIdData, ShowPetByIdError, ShowPetByIdErrors, ShowPetByIdResponse, ShowPetByIdResponses, UpdatePetBody, UpdatePetData, UpdatePetError, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, } from './types.gen'; ================================================ FILE: examples/openapi-ts-nestjs/src/client/nestjs.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { CreatePetData, CreatePetResponse, DeletePetData, DeletePetResponse, GetInventoryResponse, ListPetsData, ListPetsResponse, ShowPetByIdData, ShowPetByIdResponse, UpdatePetData, UpdatePetResponse, } from './types.gen'; export type PetsControllerMethods = { listPets: (query?: ListPetsData['query']) => Promise; createPet: (body: CreatePetData['body']) => Promise; deletePet: (path: DeletePetData['path']) => Promise; showPetById: (path: ShowPetByIdData['path']) => Promise; updatePet: ( path: UpdatePetData['path'], body: UpdatePetData['body'], ) => Promise; }; export type StoreControllerMethods = { getInventory: () => Promise; }; ================================================ FILE: examples/openapi-ts-nestjs/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CreatePetData, CreatePetErrors, CreatePetResponses, DeletePetData, DeletePetErrors, DeletePetResponses, GetInventoryData, GetInventoryResponses, ListPetsData, ListPetsResponses, ShowPetByIdData, ShowPetByIdErrors, ShowPetByIdResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * List all pets */ export const listPets = ( options?: Options, ) => (options?.client ?? client).get({ url: '/pets', ...options, }); /** * Create a pet */ export const createPet = ( options: Options, ) => (options.client ?? client).post({ url: '/pets', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Delete a pet */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ url: '/pets/{petId}', ...options, }); /** * Find pet by ID */ export const showPetById = ( options: Options, ) => (options.client ?? client).get({ url: '/pets/{petId}', ...options, }); /** * Update a pet */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ url: '/pets/{petId}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Returns pet inventories by status */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ url: '/store/inventory', ...options, }); ================================================ FILE: examples/openapi-ts-nestjs/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/v3' | (string & {}); }; export type Pet = { id: string; name: string; tag?: string; status?: 'available' | 'pending' | 'sold'; }; export type CreatePetBody = { name: string; tag?: string; }; export type UpdatePetBody = { name?: string; tag?: string; status?: 'available' | 'pending' | 'sold'; }; export type Error = { code: number; message: string; }; export type ListPetsData = { body?: never; path?: never; query?: { limit?: number; offset?: number; }; url: '/pets'; }; export type ListPetsResponses = { /** * A list of pets */ 200: Array; }; export type ListPetsResponse = ListPetsResponses[keyof ListPetsResponses]; export type CreatePetData = { body: CreatePetBody; path?: never; query?: never; url: '/pets'; }; export type CreatePetErrors = { /** * Validation error */ 400: Error; }; export type CreatePetError = CreatePetErrors[keyof CreatePetErrors]; export type CreatePetResponses = { /** * Pet created */ 201: Pet; }; export type CreatePetResponse = CreatePetResponses[keyof CreatePetResponses]; export type DeletePetData = { body?: never; path: { petId: string; }; query?: never; url: '/pets/{petId}'; }; export type DeletePetErrors = { /** * Pet not found */ 404: Error; }; export type DeletePetError = DeletePetErrors[keyof DeletePetErrors]; export type DeletePetResponses = { /** * Pet deleted */ 204: void; }; export type DeletePetResponse = DeletePetResponses[keyof DeletePetResponses]; export type ShowPetByIdData = { body?: never; path: { petId: string; }; query?: never; url: '/pets/{petId}'; }; export type ShowPetByIdErrors = { /** * Pet not found */ 404: Error; }; export type ShowPetByIdError = ShowPetByIdErrors[keyof ShowPetByIdErrors]; export type ShowPetByIdResponses = { /** * Pet found */ 200: Pet; }; export type ShowPetByIdResponse = ShowPetByIdResponses[keyof ShowPetByIdResponses]; export type UpdatePetData = { body: UpdatePetBody; path: { petId: string; }; query?: never; url: '/pets/{petId}'; }; export type UpdatePetErrors = { /** * Validation error */ 400: Error; /** * Pet not found */ 404: Error; }; export type UpdatePetError = UpdatePetErrors[keyof UpdatePetErrors]; export type UpdatePetResponses = { /** * Pet updated */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryResponses = { /** * Successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; ================================================ FILE: examples/openapi-ts-nestjs/src/main.ts ================================================ import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); ================================================ FILE: examples/openapi-ts-nestjs/src/pets/pets.controller.ts ================================================ import { Body, Controller, Get, NotFoundException, Param, Post, Query } from '@nestjs/common'; import type { PetsControllerMethods } from '../client/nestjs.gen'; import type { CreatePetData, ListPetsData, Pet, ShowPetByIdData } from '../client/types.gen'; @Controller('pets') export class PetsController implements Pick< PetsControllerMethods, 'createPet' | 'listPets' | 'showPetById' > { private readonly pets: Pet[] = [ { id: '1', name: 'Fido', status: 'available', tag: 'dog' }, { id: '2', name: 'Kitty', status: 'available', tag: 'cat' }, ]; @Get() async listPets(@Query() query?: ListPetsData['query']) { const limit = query?.limit ?? 20; return this.pets.slice(0, limit); } @Post() async createPet(@Body() body: CreatePetData['body']) { const pet: Pet = { id: crypto.randomUUID(), name: body.name, status: 'available', tag: body.tag, }; this.pets.push(pet); return pet; } @Get(':petId') async showPetById(@Param() path: ShowPetByIdData['path']) { const pet = this.pets.find((p) => p.id === path.petId); if (!pet) { throw new NotFoundException(`Pet ${path.petId} not found`); } return pet; } } ================================================ FILE: examples/openapi-ts-nestjs/src/pets/pets.module.ts ================================================ import { Module } from '@nestjs/common'; import { PetsController } from './pets.controller'; @Module({ controllers: [PetsController], }) export class PetsModule {} ================================================ FILE: examples/openapi-ts-nestjs/src/store/store.controller.ts ================================================ import { Controller, Get } from '@nestjs/common'; import type { StoreControllerMethods } from '../client/nestjs.gen'; @Controller('store') export class StoreController implements Pick { @Get('inventory') async getInventory() { return { available: 10, pending: 3, sold: 5, }; } } ================================================ FILE: examples/openapi-ts-nestjs/src/store/store.module.ts ================================================ import { Module } from '@nestjs/common'; import { StoreController } from './store.controller'; @Module({ controllers: [StoreController], }) export class StoreModule {} ================================================ FILE: examples/openapi-ts-nestjs/test/pets.test.ts ================================================ import type { INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import type { AddressInfo } from 'net'; import { AppModule } from 'src/app.module'; import { createPet, getInventory, listPets, showPetById } from 'src/client'; import { client } from 'src/client/client.gen'; let app: INestApplication; beforeAll(async () => { const moduleRef = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleRef.createNestApplication(); await app.init(); await app.listen(0); const address = app.getHttpServer().address() as AddressInfo; const baseUrl = `http://localhost:${String(address.port)}`; client.setConfig({ baseUrl }); }); afterAll(async () => { await app.close(); }); describe('PetsController', () => { test('listPets', async () => { const result = await listPets({ client }); expect(result.response.status).toBe(200); expect(Array.isArray(result.data)).toBe(true); }); test('showPetById', async () => { const result = await showPetById({ client, path: { petId: '1' }, }); expect(result.response.status).toBe(200); }); test('createPet', async () => { const result = await createPet({ body: { name: 'Buddy' }, client, }); expect(result.response.status).toBe(201); expect(result.data).toMatchObject({ name: 'Buddy' }); }); }); describe('StoreController', () => { test('getInventory', async () => { const result = await getInventory({ client }); expect(result.response.status).toBe(200); }); }); ================================================ FILE: examples/openapi-ts-nestjs/tsconfig.json ================================================ { "include": ["src/**/*", "test/**/*"], "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true, "esModuleInterop": true, "lib": ["es2023", "dom", "dom.iterable"], "module": "ESNext", "moduleResolution": "Bundler", "paths": { "src/*": ["./src/*"] }, "skipLibCheck": true, "target": "es2022", "types": ["node", "vitest/globals"], "strict": true, "noUncheckedIndexedAccess": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true }, "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: examples/openapi-ts-nestjs/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: examples/openapi-ts-nestjs/vite.config.ts ================================================ import swc from 'unplugin-swc'; import { defineProject } from 'vitest/config'; export default defineProject({ plugins: [swc.vite()], resolve: { alias: { src: new URL('./src', import.meta.url).pathname, }, }, test: { environment: 'node', globals: true, include: ['test/**/*.test.ts'], }, }); ================================================ FILE: examples/openapi-ts-next/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* .pnpm-debug.log* # env files (can opt-in for committing if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: examples/openapi-ts-next/CHANGELOG.md ================================================ # @example/openapi-ts-next ## 0.1.13 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-next@0.5.1 ## 0.1.12 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-next@0.5.0 ## 0.1.11 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-next@0.4.0 ## 0.1.10 ### Patch Changes - Updated dependencies [[`1f99066`](https://github.com/hey-api/openapi-ts/commit/1f99066efbb2d0e6b9e3710c701293c2cc09d65e)]: - @hey-api/client-next@0.3.2 ## 0.1.9 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-next@0.3.1 ## 0.1.8 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-next@0.3.0 ## 0.1.7 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-next@0.2.4 ## 0.1.6 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-next@0.2.3 ## 0.1.5 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-next@0.2.2 ## 0.1.4 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-next@0.2.1 ## 0.1.3 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-next@0.2.0 ## 0.1.2 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49)]: - @hey-api/client-next@0.1.0 ## 0.1.1 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-fetch@0.7.2 ================================================ FILE: examples/openapi-ts-next/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: examples/openapi-ts-next/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; :root { --background: #ffffff; --foreground: #171717; } @media (prefers-color-scheme: dark) { :root { --background: #0a0a0a; --foreground: #ededed; } } body { color: var(--foreground); background: var(--background); font-family: Arial, Helvetica, sans-serif; } ================================================ FILE: examples/openapi-ts-next/app/layout.tsx ================================================ import './globals.css'; import type { Metadata } from 'next'; import { Geist, Geist_Mono } from 'next/font/google'; import { client } from '@/src/client/client.gen'; client.interceptors.request.use((options) => { console.log(options); }); client.interceptors.response.use((response, options) => { console.log(response, options); return response; }); const geistSans = Geist({ subsets: ['latin'], variable: '--font-geist-sans', }); const geistMono = Geist_Mono({ subsets: ['latin'], variable: '--font-geist-mono', }); export const metadata: Metadata = { description: 'Generated by create next app', title: 'Create Next App', }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( {children} ); } ================================================ FILE: examples/openapi-ts-next/app/page.tsx ================================================ 'use client'; import Image from 'next/image'; import Link from 'next/link'; import { useEffect, useState } from 'react'; import { getPetById } from '@/src/client/sdk.gen'; import type { Pet } from '@/src/client/types.gen'; export default function Home() { const [pet, setPet] = useState(); const [petId, setPetId] = useState(8); useEffect(() => { const fetchPet = async () => { const { data } = await getPetById({ cache: 'force-cache', next: { revalidate: 10, tags: ['pet'], }, path: { petId, }, }); if (data) { setPet(data); } }; fetchPet(); }, [petId]); return (
    Next.js logo
    1. Pet name:{' '} {pet?.name}
    2. Press the button below to fetch a random pet
    Server component
    ); } ================================================ FILE: examples/openapi-ts-next/app/pet/[id]/page.tsx ================================================ import Image from 'next/image'; import Link from 'next/link'; import { notFound } from 'next/navigation'; import { getPetById } from '@/src/client/sdk.gen'; async function getPet(id: string) { const petId = Number.parseInt(id, 10); const { data: pet } = await getPetById({ cache: 'force-cache', next: { revalidate: 10, tags: ['pet'], }, path: { petId, }, throwOnError: true, }); if (!pet) { notFound(); } return pet; } export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; const pet = await getPet(id); return { name: pet.name, }; } export default async function Blog({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; const pet = await getPet(id); return (
    Next.js logo
    1. Static pet name:{' '} {pet.name}
    Client component
    ); } ================================================ FILE: examples/openapi-ts-next/next.config.ts ================================================ import type { NextConfig } from 'next'; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; ================================================ FILE: examples/openapi-ts-next/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ { name: '@hey-api/client-next', runtimeConfigPath: '../hey-api', }, '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, ], }); ================================================ FILE: examples/openapi-ts-next/package.json ================================================ { "name": "@example/openapi-ts-next", "version": "0.1.13", "private": true, "scripts": { "build": "next build", "dev": "next dev", "lint": "next lint", "openapi-ts": "openapi-ts", "start": "next start" }, "dependencies": { "next": "15.2.4", "react": "19.0.0", "react-dom": "19.0.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@types/node": "24.10.10", "@types/react": "19.0.1", "@types/react-dom": "19.0.1", "eslint": "9.17.0", "eslint-config-next": "15.1.6", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3" } } ================================================ FILE: examples/openapi-ts-next/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: examples/openapi-ts-next/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-next/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: examples/openapi-ts-next/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-next/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-next/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createClientConfig } from '../hey-api'; import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createClientConfig( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ), ); ================================================ FILE: examples/openapi-ts-next/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-next/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-next/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-next/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-next/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-next/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-next/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-next/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-next/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-next/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-next/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-next/src/hey-api.ts ================================================ import type { CreateClientConfig } from './client/client.gen'; export const createClientConfig: CreateClientConfig = (config) => ({ ...config, // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); ================================================ FILE: examples/openapi-ts-next/tailwind.config.ts ================================================ import type { Config } from 'tailwindcss'; export default { content: [ './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', './app/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: { colors: { background: 'var(--background)', foreground: 'var(--foreground)', }, }, }, } satisfies Config; ================================================ FILE: examples/openapi-ts-next/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: examples/openapi-ts-nuxt/.gitignore ================================================ # Nuxt dev/build outputs .output .data .nuxt .nitro .cache dist # Node dependencies node_modules # Logs logs *.log # Misc .DS_Store .fleet .idea # Local env files .env .env.* !.env.example ================================================ FILE: examples/openapi-ts-nuxt/.npmrc ================================================ engine-strict=true save-exact=true ================================================ FILE: examples/openapi-ts-nuxt/CHANGELOG.md ================================================ # @example/openapi-ts-nuxt ## 0.0.20 ### Patch Changes ### Updated Dependencies: - @hey-api/nuxt@0.2.1 ## 0.0.19 ### Patch Changes - Updated dependencies [[`6d56fa8`](https://github.com/hey-api/openapi-ts/commit/6d56fa8d80fd02c67746324b8edd6d008f788d67)]: - @hey-api/nuxt@0.2.0 ## 0.0.18 ### Patch Changes - Updated dependencies []: - @hey-api/nuxt@0.1.7 ## 0.0.17 ### Patch Changes - Updated dependencies []: - @hey-api/nuxt@0.1.6 ## 0.0.16 ### Patch Changes - Updated dependencies [[`09bce36`](https://github.com/hey-api/openapi-ts/commit/09bce3644680a68ea91c9a1396d506b13709ae93), [`f46e241`](https://github.com/hey-api/openapi-ts/commit/f46e2419d8eaefea4eaff232f00ec770509afcb1)]: - @hey-api/nuxt@0.1.5 ## 0.0.15 ### Patch Changes - Updated dependencies []: - @hey-api/nuxt@0.1.4 ## 0.0.14 ### Patch Changes - Updated dependencies []: - @hey-api/nuxt@0.1.3 ## 0.0.13 ### Patch Changes - Updated dependencies [[`0670a38`](https://github.com/hey-api/openapi-ts/commit/0670a38c66dffc1431a7d4b48ec06b72d4f6868f)]: - @hey-api/nuxt@0.1.2 ## 0.0.12 ### Patch Changes - Updated dependencies []: - @hey-api/nuxt@0.1.1 ## 0.0.11 ### Patch Changes - Updated dependencies [[`d80f835`](https://github.com/hey-api/openapi-ts/commit/d80f835b46775a01451f02f832ceb288c2b561d2)]: - @hey-api/nuxt@0.1.0 ## 0.0.10 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-nuxt@0.2.4 ## 0.0.9 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-nuxt@0.2.3 ## 0.0.8 ### Patch Changes - Updated dependencies [[`e86629b`](https://github.com/hey-api/openapi-ts/commit/e86629bfa9ae2a47131d3a9a240a6aa2a4f67911)]: - @hey-api/client-nuxt@0.2.2 ## 0.0.7 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-nuxt@0.2.1 ## 0.0.6 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-nuxt@0.2.0 ## 0.0.5 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb)]: - @hey-api/client-nuxt@0.1.3 ## 0.0.4 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-nuxt@0.1.2 ## 0.0.3 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-nuxt@0.1.1 ## 0.0.2 ### Patch Changes - Updated dependencies [[`14d3c4c`](https://github.com/hey-api/openapi-ts/commit/14d3c4ce0393d543e2d3aaebbfcf8f0cf32483b0)]: - @hey-api/client-nuxt@0.1.0 ================================================ FILE: examples/openapi-ts-nuxt/README.md ================================================ # Nuxt Minimal Starter Look at the [Nuxt documentation](https://nuxt.com/docs/getting-started/introduction) to learn more. ## Setup Make sure to install dependencies: ```bash # npm npm install # pnpm pnpm install # yarn yarn install # bun bun install ``` ## Development Server Start the development server on `http://localhost:3000`: ```bash # npm npm run dev # pnpm pnpm dev # yarn yarn dev # bun bun run dev ``` ## Production Build the application for production: ```bash # npm npm run build # pnpm pnpm build # yarn yarn build # bun bun run build ``` Locally preview production build: ```bash # npm npm run preview # pnpm pnpm preview # yarn yarn preview # bun bun run preview ``` Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information. ================================================ FILE: examples/openapi-ts-nuxt/app.vue ================================================ ================================================ FILE: examples/openapi-ts-nuxt/components/home.vue ================================================ ================================================ FILE: examples/openapi-ts-nuxt/nuxt.config.ts ================================================ // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ compatibilityDate: '2024-11-01', devtools: { enabled: true, }, future: { compatibilityVersion: 4, }, heyApi: { config: { input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', plugins: [ '@hey-api/schemas', { name: '@hey-api/sdk', transformer: true, validator: true, }, { enums: 'javascript', name: '@hey-api/typescript', }, '@hey-api/transformers', 'zod', ], }, }, modules: ['@hey-api/nuxt'], }); ================================================ FILE: examples/openapi-ts-nuxt/package.json ================================================ { "name": "@example/openapi-ts-nuxt", "version": "0.0.20", "private": true, "type": "module", "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": "nuxt generate", "postinstall:disabled": "nuxt prepare", "preview": "nuxt preview", "typecheck:disabled": "tsc --noEmit" }, "dependencies": { "@hey-api/nuxt": "workspace:*", "nuxt": "3.14.1592", "vue": "3.5.13", "vue-router": "4.5.0", "zod": "4.0.5" }, "devDependencies": { "vite": "7.3.1" } } ================================================ FILE: examples/openapi-ts-nuxt/public/robots.txt ================================================ ================================================ FILE: examples/openapi-ts-nuxt/server/tsconfig.json ================================================ { "extends": "../.nuxt/tsconfig.server.json" } ================================================ FILE: examples/openapi-ts-nuxt/tsconfig.json ================================================ { // https://nuxt.com/docs/guide/concepts/typescript "extends": "./.nuxt/tsconfig.json" } ================================================ FILE: examples/openapi-ts-ofetch/env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-ofetch/index.html ================================================ Hey API — ofetch example
    ================================================ FILE: examples/openapi-ts-ofetch/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-ofetch', '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, ], }); ================================================ FILE: examples/openapi-ts-ofetch/package.json ================================================ { "name": "@example/openapi-ts-ofetch", "version": "0.0.1", "private": true, "type": "module", "scripts": { "build": "vite build", "dev": "vite", "lint": "eslint . --fix", "openapi-ts": "openapi-ts", "preview": "vite preview", "typecheck": "vue-tsc --build --force" }, "dependencies": { "ofetch": "1.4.1", "vue": "3.5.13" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@rushstack/eslint-patch": "1.10.5", "@tsconfig/node24": "24.0.4", "@types/jsdom": "27.0.0", "@types/node": "24.10.10", "@vitejs/plugin-vue": "6.0.4", "@vitejs/plugin-vue-jsx": "5.1.4", "@vue/eslint-config-typescript": "14.6.0", "@vue/test-utils": "2.4.6", "@vue/tsconfig": "0.8.1", "autoprefixer": "10.4.20", "eslint": "9.17.0", "eslint-plugin-vue": "9.32.0", "jsdom": "28.0.0", "npm-run-all2": "6.2.0", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1", "vite-plugin-vue-devtools": "8.0.2", "vitest": "4.0.18", "vue-tsc": "3.2.4" } } ================================================ FILE: examples/openapi-ts-ofetch/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-ofetch/src/App.vue ================================================ ================================================ FILE: examples/openapi-ts-ofetch/src/assets/main.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; body { @apply bg-[#111113]; } ================================================ FILE: examples/openapi-ts-ofetch/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-ofetch/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-ofetch/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-ofetch/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-ofetch/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-ofetch/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-ofetch/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-ofetch/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-ofetch/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-ofetch/src/main.ts ================================================ import './assets/main.css'; import { createApp } from 'vue'; import App from './App.vue'; import { client } from './client/client.gen'; // configure internal service client client.setConfig({ // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); createApp(App).mount('#app'); ================================================ FILE: examples/openapi-ts-ofetch/tailwind.config.ts ================================================ import type { Config } from 'tailwindcss'; export default { content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], theme: { extend: {}, }, } satisfies Config; ================================================ FILE: examples/openapi-ts-ofetch/tsconfig.app.json ================================================ { "extends": "@vue/tsconfig/tsconfig.dom.json", "include": ["./env.d.ts", "./src/**/*", "./src/**/*.vue"], "exclude": ["./src/**/__tests__/*"], "compilerOptions": { "composite": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } } ================================================ FILE: examples/openapi-ts-ofetch/tsconfig.json ================================================ { "files": [], "references": [ { "path": "./tsconfig.node.json" }, { "path": "./tsconfig.app.json" } ] } ================================================ FILE: examples/openapi-ts-ofetch/tsconfig.node.json ================================================ { "extends": "@tsconfig/node24/tsconfig.json", "include": [ "vite.config.*", "vitest.config.*", "cypress.config.*", "nightwatch.conf.*", "playwright.config.*" ], "compilerOptions": { "composite": true, "noEmit": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", "module": "ESNext", "moduleResolution": "Bundler", "types": ["node"] } } ================================================ FILE: examples/openapi-ts-ofetch/vite.config.ts ================================================ import { fileURLToPath, URL } from 'node:url'; import vue from '@vitejs/plugin-vue'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [vue()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, // eslint-disable-next-line @typescript-eslint/consistent-type-imports } as import('vite').UserConfig; ================================================ FILE: examples/openapi-ts-openai/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: examples/openapi-ts-openai/index.html ================================================ Hey API + OpenAI Demo
    ================================================ FILE: examples/openapi-ts-openai/openapi-ts.config.ts ================================================ import path from 'node:path'; import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: path.resolve('..', '..', 'specs', '3.1.x', 'openai.yaml'), logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt'], }, plugins: [ '@hey-api/client-fetch', { enums: 'javascript', name: '@hey-api/typescript', }, { instance: 'OpenAI', name: '@hey-api/sdk', }, ], }); ================================================ FILE: examples/openapi-ts-openai/package.json ================================================ { "name": "@example/openapi-ts-openai", "version": "0.0.0", "private": true, "type": "module", "scripts": { "build": "tsgo --noEmit && vite build", "dev": "vite", "lint": "eslint . --report-unused-disable-directives --max-warnings 0", "openapi-ts": "openapi-ts", "preview": "vite preview", "typecheck": "tsgo --noEmit" }, "dependencies": { "@radix-ui/react-form": "0.1.1", "@radix-ui/react-icons": "1.3.2", "@radix-ui/themes": "3.1.6", "openai": "5.13.1", "react": "19.0.0", "react-dom": "19.0.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@types/react": "19.0.1", "@types/react-dom": "19.0.1", "@typescript-eslint/eslint-plugin": "8.29.1", "@typescript-eslint/parser": "8.29.1", "@vitejs/plugin-react": "4.4.0-beta.1", "autoprefixer": "10.4.19", "eslint": "9.17.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.7", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1" } } ================================================ FILE: examples/openapi-ts-openai/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-openai/src/App.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; ================================================ FILE: examples/openapi-ts-openai/src/App.tsx ================================================ import './App.css'; import * as Form from '@radix-ui/react-form'; import { PlusIcon } from '@radix-ui/react-icons'; import { Box, Button, Container, Flex, Heading, Section, TextField } from '@radix-ui/themes'; import OpenAI from 'openai'; import { useState } from 'react'; import { client as baseClient } from './client/client.gen'; import { OpenAi } from './client/sdk.gen'; const sdk = new OpenAI({ apiKey: import.meta.env.VITE_OPENAI_API_KEY, dangerouslyAllowBrowser: true, }); baseClient.setConfig({ auth() { return import.meta.env.VITE_OPENAI_API_KEY; }, }); const client = new OpenAi({ client: baseClient, }); function App() { const [isRequiredNameError] = useState(false); const onCreateResponse = async (values: FormData) => { const stream = await sdk.responses.create({ input: values.get('input') as string, model: 'gpt-5-nano', stream: true, }); for await (const event of stream) { console.log(event); } const { data, error } = await client.createResponse({ body: { input: values.get('input') as string, model: 'gpt-5-nano', stream: true, }, }); if (error) { console.log(error); return; } console.log(data?.output); }; return (
    Hey API logo @hey-api/openapi-ts 🤝 OpenAI
    { event.preventDefault(); onCreateResponse(new FormData(event.currentTarget)); }} >
    Input {isRequiredNameError && ( Please enter a name )} Please enter an input
    {/* */}
    ); } export default App; ================================================ FILE: examples/openapi-ts-openai/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-openai/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-openai/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-openai/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-openai/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://api.openai.com/v1' })); ================================================ FILE: examples/openapi-ts-openai/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-openai/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-openai/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-openai/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-openai/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-openai/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-openai/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-openai/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-openai/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { OpenAi, type Options } from './sdk.gen'; export { type ActivateOrganizationCertificatesData, type ActivateOrganizationCertificatesResponse, type ActivateOrganizationCertificatesResponses, type ActivateProjectCertificatesData, type ActivateProjectCertificatesResponse, type ActivateProjectCertificatesResponses, type AddUploadPartData, type AddUploadPartRequest, type AddUploadPartResponse, type AddUploadPartResponses, type AdminApiKey, type AdminApiKeysCreateData, type AdminApiKeysCreateResponse, type AdminApiKeysCreateResponses, type AdminApiKeysDeleteData, type AdminApiKeysDeleteResponse, type AdminApiKeysDeleteResponses, type AdminApiKeysGetData, type AdminApiKeysGetResponse, type AdminApiKeysGetResponses, type AdminApiKeysListData, type AdminApiKeysListResponse, type AdminApiKeysListResponses, type Annotation, type ApiKeyList, type ApproximateLocation, type ArchiveProjectData, type ArchiveProjectResponse, type ArchiveProjectResponses, type AssistantObject, type AssistantsApiResponseFormatOption, type AssistantsApiToolChoiceOption, type AssistantsNamedToolChoice, type AssistantStreamEvent, AssistantSupportedModels, type AssistantTool, type AssistantToolsCode, type AssistantToolsFileSearch, type AssistantToolsFileSearchTypeOnly, type AssistantToolsFunction, AudioResponseFormat, type AuditLog, type AuditLogActor, type AuditLogActorApiKey, type AuditLogActorServiceAccount, type AuditLogActorSession, type AuditLogActorUser, AuditLogEventType, type AutoChunkingStrategyRequestParam, type Batch, type BatchError, type BatchFileExpirationAfter, type BatchRequestCounts, type BatchRequestInput, type BatchRequestOutput, type CancelBatchData, type CancelBatchResponse, type CancelBatchResponses, type CancelEvalRunData, type CancelEvalRunResponse, type CancelEvalRunResponses, type CancelFineTuningJobData, type CancelFineTuningJobResponse, type CancelFineTuningJobResponses, type CancelResponseData, type CancelResponseError, type CancelResponseErrors, type CancelResponseResponse, type CancelResponseResponses, type CancelRunData, type CancelRunResponse, type CancelRunResponses, type CancelUploadData, type CancelUploadResponse, type CancelUploadResponses, type CancelVectorStoreFileBatchData, type CancelVectorStoreFileBatchResponse, type CancelVectorStoreFileBatchResponses, type Certificate, type ChatCompletionAllowedTools, type ChatCompletionAllowedToolsChoice, type ChatCompletionDeleted, type ChatCompletionFunctionCallOption, type ChatCompletionFunctions, type ChatCompletionList, type ChatCompletionMessageCustomToolCall, type ChatCompletionMessageList, type ChatCompletionMessageToolCall, type ChatCompletionMessageToolCallChunk, type ChatCompletionMessageToolCalls, type ChatCompletionModalities, type ChatCompletionNamedToolChoice, type ChatCompletionNamedToolChoiceCustom, type ChatCompletionRequestAssistantMessage, type ChatCompletionRequestAssistantMessageContentPart, type ChatCompletionRequestDeveloperMessage, type ChatCompletionRequestFunctionMessage, type ChatCompletionRequestMessage, type ChatCompletionRequestMessageContentPartAudio, type ChatCompletionRequestMessageContentPartFile, type ChatCompletionRequestMessageContentPartImage, type ChatCompletionRequestMessageContentPartRefusal, type ChatCompletionRequestMessageContentPartText, type ChatCompletionRequestSystemMessage, type ChatCompletionRequestSystemMessageContentPart, type ChatCompletionRequestToolMessage, type ChatCompletionRequestToolMessageContentPart, type ChatCompletionRequestUserMessage, type ChatCompletionRequestUserMessageContentPart, type ChatCompletionResponseMessage, ChatCompletionRole, type ChatCompletionStreamOptions, type ChatCompletionStreamResponseDelta, type ChatCompletionTokenLogprob, type ChatCompletionTool, type ChatCompletionToolChoiceOption, ChatModel, type ChunkingStrategyRequestParam, type ChunkingStrategyResponse, type Click, type ClientOptions, type CodeInterpreterFileOutput, type CodeInterpreterOutputImage, type CodeInterpreterOutputLogs, type CodeInterpreterTextOutput, type CodeInterpreterTool, type CodeInterpreterToolAuto, type CodeInterpreterToolCall, type ComparisonFilter, type CompleteUploadData, type CompleteUploadRequest, type CompleteUploadResponse, type CompleteUploadResponses, type CompletionUsage, type CompoundFilter, type ComputerAction, type ComputerCallOutputItemParam, type ComputerCallSafetyCheckParam, type ComputerScreenshotImage, type ComputerToolCall, type ComputerToolCallOutput, type ComputerToolCallOutputResource, type ComputerToolCallSafetyCheck, type ComputerUsePreviewTool, type ContainerFileCitationBody, type ContainerFileListResource, type ContainerFileResource, type ContainerListResource, type ContainerResource, type Content, type Coordinate, type CostsResult, type CreateAssistantData, type CreateAssistantRequest, type CreateAssistantResponse, type CreateAssistantResponses, type CreateBatchData, type CreateBatchResponse, type CreateBatchResponses, type CreateChatCompletionData, type CreateChatCompletionRequest, type CreateChatCompletionResponse, type CreateChatCompletionResponse2, type CreateChatCompletionResponses, type CreateChatCompletionStreamResponse, type CreateCompletionData, type CreateCompletionRequest, type CreateCompletionResponse, type CreateCompletionResponse2, type CreateCompletionResponses, type CreateContainerBody, type CreateContainerData, type CreateContainerFileBody, type CreateContainerFileData, type CreateContainerFileResponse, type CreateContainerFileResponses, type CreateContainerResponse, type CreateContainerResponses, type CreateEmbeddingData, type CreateEmbeddingRequest, type CreateEmbeddingResponse, type CreateEmbeddingResponse2, type CreateEmbeddingResponses, type CreateEvalCompletionsRunDataSource, type CreateEvalCustomDataSourceConfig, type CreateEvalData, type CreateEvalItem, type CreateEvalJsonlRunDataSource, type CreateEvalLabelModelGrader, type CreateEvalLogsDataSourceConfig, type CreateEvalRequest, type CreateEvalResponse, type CreateEvalResponses, type CreateEvalResponsesRunDataSource, type CreateEvalRunData, type CreateEvalRunError, type CreateEvalRunErrors, type CreateEvalRunRequest, type CreateEvalRunResponse, type CreateEvalRunResponses, type CreateEvalStoredCompletionsDataSourceConfig, type CreateFileData, type CreateFileRequest, type CreateFileResponse, type CreateFileResponses, type CreateFineTuningCheckpointPermissionData, type CreateFineTuningCheckpointPermissionRequest, type CreateFineTuningCheckpointPermissionResponse, type CreateFineTuningCheckpointPermissionResponses, type CreateFineTuningJobData, type CreateFineTuningJobRequest, type CreateFineTuningJobResponse, type CreateFineTuningJobResponses, type CreateImageData, type CreateImageEditData, type CreateImageEditRequest, type CreateImageEditResponse, type CreateImageEditResponses, type CreateImageRequest, type CreateImageResponse, type CreateImageResponses, type CreateImageVariationData, type CreateImageVariationRequest, type CreateImageVariationResponse, type CreateImageVariationResponses, type CreateMessageData, type CreateMessageRequest, type CreateMessageResponse, type CreateMessageResponses, type CreateModelResponseProperties, type CreateModerationData, type CreateModerationRequest, type CreateModerationResponse, type CreateModerationResponse2, type CreateModerationResponses, type CreateProjectData, type CreateProjectResponse, type CreateProjectResponses, type CreateProjectServiceAccountData, type CreateProjectServiceAccountError, type CreateProjectServiceAccountErrors, type CreateProjectServiceAccountResponse, type CreateProjectServiceAccountResponses, type CreateProjectUserData, type CreateProjectUserError, type CreateProjectUserErrors, type CreateProjectUserResponse, type CreateProjectUserResponses, type CreateRealtimeSessionData, type CreateRealtimeSessionResponse, type CreateRealtimeSessionResponses, type CreateRealtimeTranscriptionSessionData, type CreateRealtimeTranscriptionSessionResponse, type CreateRealtimeTranscriptionSessionResponses, type CreateResponse, type CreateResponseData, type CreateResponseResponse, type CreateResponseResponses, type CreateRunData, type CreateRunRequest, type CreateRunRequestWithoutStream, type CreateRunResponse, type CreateRunResponses, type CreateSpeechData, type CreateSpeechRequest, type CreateSpeechResponse, type CreateSpeechResponses, type CreateSpeechResponseStreamEvent, type CreateThreadAndRunData, type CreateThreadAndRunRequest, type CreateThreadAndRunRequestWithoutStream, type CreateThreadAndRunResponse, type CreateThreadAndRunResponses, type CreateThreadData, type CreateThreadRequest, type CreateThreadResponse, type CreateThreadResponses, type CreateTranscriptionData, type CreateTranscriptionRequest, type CreateTranscriptionResponse, type CreateTranscriptionResponseJson, type CreateTranscriptionResponses, type CreateTranscriptionResponseStreamEvent, type CreateTranscriptionResponseVerboseJson, type CreateTranslationData, type CreateTranslationRequest, type CreateTranslationResponse, type CreateTranslationResponseJson, type CreateTranslationResponses, type CreateTranslationResponseVerboseJson, type CreateUploadData, type CreateUploadRequest, type CreateUploadResponse, type CreateUploadResponses, type CreateVectorStoreData, type CreateVectorStoreFileBatchData, type CreateVectorStoreFileBatchRequest, type CreateVectorStoreFileBatchResponse, type CreateVectorStoreFileBatchResponses, type CreateVectorStoreFileData, type CreateVectorStoreFileRequest, type CreateVectorStoreFileResponse, type CreateVectorStoreFileResponses, type CreateVectorStoreRequest, type CreateVectorStoreResponse, type CreateVectorStoreResponses, type CustomTool, type CustomToolCall, type CustomToolCallOutput, type CustomToolChatCompletions, type DeactivateOrganizationCertificatesData, type DeactivateOrganizationCertificatesResponse, type DeactivateOrganizationCertificatesResponses, type DeactivateProjectCertificatesData, type DeactivateProjectCertificatesResponse, type DeactivateProjectCertificatesResponses, type DeleteAssistantData, type DeleteAssistantResponse, type DeleteAssistantResponse2, type DeleteAssistantResponses, type DeleteCertificateData, type DeleteCertificateResponse, type DeleteCertificateResponse2, type DeleteCertificateResponses, type DeleteChatCompletionData, type DeleteChatCompletionResponse, type DeleteChatCompletionResponses, type DeleteContainerData, type DeleteContainerFileData, type DeleteContainerFileResponses, type DeleteContainerResponses, type DeleteEvalData, type DeleteEvalError, type DeleteEvalErrors, type DeleteEvalResponse, type DeleteEvalResponses, type DeleteEvalRunData, type DeleteEvalRunError, type DeleteEvalRunErrors, type DeleteEvalRunResponse, type DeleteEvalRunResponses, type DeleteFileData, type DeleteFileResponse, type DeleteFileResponse2, type DeleteFileResponses, type DeleteFineTuningCheckpointPermissionData, type DeleteFineTuningCheckpointPermissionResponse, type DeleteFineTuningCheckpointPermissionResponse2, type DeleteFineTuningCheckpointPermissionResponses, type DeleteInviteData, type DeleteInviteResponse, type DeleteInviteResponses, type DeleteMessageData, type DeleteMessageResponse, type DeleteMessageResponse2, type DeleteMessageResponses, type DeleteModelData, type DeleteModelResponse, type DeleteModelResponse2, type DeleteModelResponses, type DeleteProjectApiKeyData, type DeleteProjectApiKeyError, type DeleteProjectApiKeyErrors, type DeleteProjectApiKeyResponse, type DeleteProjectApiKeyResponses, type DeleteProjectServiceAccountData, type DeleteProjectServiceAccountResponse, type DeleteProjectServiceAccountResponses, type DeleteProjectUserData, type DeleteProjectUserError, type DeleteProjectUserErrors, type DeleteProjectUserResponse, type DeleteProjectUserResponses, type DeleteResponseData, type DeleteResponseError, type DeleteResponseErrors, type DeleteResponseResponses, type DeleteThreadData, type DeleteThreadResponse, type DeleteThreadResponse2, type DeleteThreadResponses, type DeleteUserData, type DeleteUserResponse, type DeleteUserResponses, type DeleteVectorStoreData, type DeleteVectorStoreFileData, type DeleteVectorStoreFileResponse, type DeleteVectorStoreFileResponse2, type DeleteVectorStoreFileResponses, type DeleteVectorStoreResponse, type DeleteVectorStoreResponse2, type DeleteVectorStoreResponses, type DoneEvent, type DoubleClick, type DownloadFileData, type DownloadFileResponse, type DownloadFileResponses, type Drag, type EasyInputMessage, type Embedding, type Error, type ErrorEvent, type ErrorResponse, type Eval, type EvalApiError, type EvalCustomDataSourceConfig, type EvalGraderLabelModel, type EvalGraderPython, type EvalGraderScoreModel, type EvalGraderStringCheck, type EvalGraderTextSimilarity, type EvalItem, type EvalJsonlFileContentSource, type EvalJsonlFileIdSource, type EvalList, type EvalLogsDataSourceConfig, type EvalResponsesSource, type EvalRun, type EvalRunList, type EvalRunOutputItem, type EvalRunOutputItemList, type EvalStoredCompletionsDataSourceConfig, type EvalStoredCompletionsSource, type FileCitationBody, type FileExpirationAfter, type FilePath, FilePurpose, FileSearchRanker, type FileSearchRankingOptions, type FileSearchTool, type FileSearchToolCall, type Filters, type FineTuneChatCompletionRequestAssistantMessage, type FineTuneChatRequestInput, type FineTuneDpoHyperparameters, type FineTuneDpoMethod, type FineTuneMethod, type FineTunePreferenceRequestInput, type FineTuneReinforcementHyperparameters, type FineTuneReinforcementMethod, type FineTuneReinforcementRequestInput, type FineTuneSupervisedHyperparameters, type FineTuneSupervisedMethod, type FineTuningCheckpointPermission, type FineTuningIntegration, type FineTuningJob, type FineTuningJobCheckpoint, type FineTuningJobEvent, type FunctionCallOutputItemParam, type FunctionObject, type FunctionParameters, type FunctionTool, type FunctionToolCall, type FunctionToolCallOutput, type FunctionToolCallOutputResource, type FunctionToolCallResource, type GetAssistantData, type GetAssistantResponse, type GetAssistantResponses, type GetCertificateData, type GetCertificateResponse, type GetCertificateResponses, type GetChatCompletionData, type GetChatCompletionMessagesData, type GetChatCompletionMessagesResponse, type GetChatCompletionMessagesResponses, type GetChatCompletionResponse, type GetChatCompletionResponses, type GetEvalData, type GetEvalResponse, type GetEvalResponses, type GetEvalRunData, type GetEvalRunOutputItemData, type GetEvalRunOutputItemResponse, type GetEvalRunOutputItemResponses, type GetEvalRunOutputItemsData, type GetEvalRunOutputItemsResponse, type GetEvalRunOutputItemsResponses, type GetEvalRunResponse, type GetEvalRunResponses, type GetEvalRunsData, type GetEvalRunsResponse, type GetEvalRunsResponses, type GetMessageData, type GetMessageResponse, type GetMessageResponses, type GetResponseData, type GetResponseResponse, type GetResponseResponses, type GetRunData, type GetRunResponse, type GetRunResponses, type GetRunStepData, type GetRunStepResponse, type GetRunStepResponses, type GetThreadData, type GetThreadResponse, type GetThreadResponses, type GetVectorStoreData, type GetVectorStoreFileBatchData, type GetVectorStoreFileBatchResponse, type GetVectorStoreFileBatchResponses, type GetVectorStoreFileData, type GetVectorStoreFileResponse, type GetVectorStoreFileResponses, type GetVectorStoreResponse, type GetVectorStoreResponses, type GraderLabelModel, type GraderMulti, type GraderPython, type GraderScoreModel, type GraderStringCheck, type GraderTextSimilarity, type Image, type ImageEditCompletedEvent, type ImageEditPartialImageEvent, type ImageEditStreamEvent, type ImageGenCompletedEvent, type ImageGenInputUsageDetails, type ImageGenPartialImageEvent, type ImageGenStreamEvent, type ImageGenTool, type ImageGenToolCall, type ImageGenUsage, ImageInputFidelity, type ImagesResponse, type ImagesUsage, Includable, type InputAudio, type InputContent, type InputFileContent, type InputImageContent, type InputItem, type InputMessage, type InputMessageContentList, type InputMessageResource, type InputTextContent, type Invite, type InviteDeleteResponse, type InviteListResponse, type InviteRequest, type InviteUserData, type InviteUserResponse, type InviteUserResponses, type Item, type ItemReferenceParam, type ItemResource, type KeyPress, type ListAssistantsData, type ListAssistantsResponse, type ListAssistantsResponse2, type ListAssistantsResponses, type ListAuditLogsData, type ListAuditLogsResponse, type ListAuditLogsResponse2, type ListAuditLogsResponses, type ListBatchesData, type ListBatchesResponse, type ListBatchesResponse2, type ListBatchesResponses, type ListCertificatesResponse, type ListChatCompletionsData, type ListChatCompletionsResponse, type ListChatCompletionsResponses, type ListContainerFilesData, type ListContainerFilesResponse, type ListContainerFilesResponses, type ListContainersData, type ListContainersResponse, type ListContainersResponses, type ListEvalsData, type ListEvalsResponse, type ListEvalsResponses, type ListFilesData, type ListFilesInVectorStoreBatchData, type ListFilesInVectorStoreBatchResponse, type ListFilesInVectorStoreBatchResponses, type ListFilesResponse, type ListFilesResponse2, type ListFilesResponses, type ListFineTuningCheckpointPermissionResponse, type ListFineTuningCheckpointPermissionsData, type ListFineTuningCheckpointPermissionsResponse, type ListFineTuningCheckpointPermissionsResponses, type ListFineTuningEventsData, type ListFineTuningEventsResponse, type ListFineTuningEventsResponses, type ListFineTuningJobCheckpointsData, type ListFineTuningJobCheckpointsResponse, type ListFineTuningJobCheckpointsResponse2, type ListFineTuningJobCheckpointsResponses, type ListFineTuningJobEventsResponse, type ListInputItemsData, type ListInputItemsResponse, type ListInputItemsResponses, type ListInvitesData, type ListInvitesResponse, type ListInvitesResponses, type ListMessagesData, type ListMessagesResponse, type ListMessagesResponse2, type ListMessagesResponses, type ListModelsData, type ListModelsResponse, type ListModelsResponse2, type ListModelsResponses, type ListOrganizationCertificatesData, type ListOrganizationCertificatesResponse, type ListOrganizationCertificatesResponses, type ListPaginatedFineTuningJobsData, type ListPaginatedFineTuningJobsResponse, type ListPaginatedFineTuningJobsResponse2, type ListPaginatedFineTuningJobsResponses, type ListProjectApiKeysData, type ListProjectApiKeysResponse, type ListProjectApiKeysResponses, type ListProjectCertificatesData, type ListProjectCertificatesResponse, type ListProjectCertificatesResponses, type ListProjectRateLimitsData, type ListProjectRateLimitsResponse, type ListProjectRateLimitsResponses, type ListProjectsData, type ListProjectServiceAccountsData, type ListProjectServiceAccountsError, type ListProjectServiceAccountsErrors, type ListProjectServiceAccountsResponse, type ListProjectServiceAccountsResponses, type ListProjectsResponse, type ListProjectsResponses, type ListProjectUsersData, type ListProjectUsersError, type ListProjectUsersErrors, type ListProjectUsersResponse, type ListProjectUsersResponses, type ListRunsData, type ListRunsResponse, type ListRunsResponse2, type ListRunsResponses, type ListRunStepsData, type ListRunStepsResponse, type ListRunStepsResponse2, type ListRunStepsResponses, type ListUsersData, type ListUsersResponse, type ListUsersResponses, type ListVectorStoreFilesData, type ListVectorStoreFilesResponse, type ListVectorStoreFilesResponse2, type ListVectorStoreFilesResponses, type ListVectorStoresData, type ListVectorStoresResponse, type ListVectorStoresResponse2, type ListVectorStoresResponses, type LocalShellExecAction, type LocalShellTool, type LocalShellToolCall, type LocalShellToolCallOutput, type LogProb, type LogProbProperties, type McpApprovalRequest, type McpApprovalResponse, type McpApprovalResponseResource, type McpListTools, type McpListToolsTool, type McpTool, type McpToolCall, type MessageContent, type MessageContentDelta, type MessageContentImageFileObject, type MessageContentImageUrlObject, type MessageContentRefusalObject, type MessageContentTextAnnotationsFileCitationObject, type MessageContentTextAnnotationsFilePathObject, type MessageContentTextObject, type MessageDeltaContentImageFileObject, type MessageDeltaContentImageUrlObject, type MessageDeltaContentRefusalObject, type MessageDeltaContentTextAnnotationsFileCitationObject, type MessageDeltaContentTextAnnotationsFilePathObject, type MessageDeltaContentTextObject, type MessageDeltaObject, type MessageObject, type MessageRequestContentTextObject, type MessageStreamEvent, type Metadata, type Model, type ModelIds, type ModelIdsResponses, type ModelIdsShared, type ModelResponseProperties, type ModerationImageUrlInput, type ModerationTextInput, type ModifyAssistantData, type ModifyAssistantRequest, type ModifyAssistantResponse, type ModifyAssistantResponses, type ModifyCertificateData, type ModifyCertificateRequest, type ModifyCertificateResponse, type ModifyCertificateResponses, type ModifyMessageData, type ModifyMessageRequest, type ModifyMessageResponse, type ModifyMessageResponses, type ModifyProjectData, type ModifyProjectError, type ModifyProjectErrors, type ModifyProjectResponse, type ModifyProjectResponses, type ModifyProjectUserData, type ModifyProjectUserError, type ModifyProjectUserErrors, type ModifyProjectUserResponse, type ModifyProjectUserResponses, type ModifyRunData, type ModifyRunRequest, type ModifyRunResponse, type ModifyRunResponses, type ModifyThreadData, type ModifyThreadRequest, type ModifyThreadResponse, type ModifyThreadResponses, type ModifyUserData, type ModifyUserResponse, type ModifyUserResponses, type ModifyVectorStoreData, type ModifyVectorStoreResponse, type ModifyVectorStoreResponses, type Move, type OpenAiFile, type OtherChunkingStrategyResponseParam, type OutputAudio, type OutputContent, type OutputItem, type OutputMessage, type OutputTextContent, type ParallelToolCalls, type PartialImages, type PauseFineTuningJobData, type PauseFineTuningJobResponse, type PauseFineTuningJobResponses, type PostBatchCancelledWebhookPayload, type PostBatchCancelledWebhookRequest, type PostBatchCompletedWebhookPayload, type PostBatchCompletedWebhookRequest, type PostBatchExpiredWebhookPayload, type PostBatchExpiredWebhookRequest, type PostBatchFailedWebhookPayload, type PostBatchFailedWebhookRequest, type PostEvalRunCanceledWebhookPayload, type PostEvalRunCanceledWebhookRequest, type PostEvalRunFailedWebhookPayload, type PostEvalRunFailedWebhookRequest, type PostEvalRunSucceededWebhookPayload, type PostEvalRunSucceededWebhookRequest, type PostFineTuningJobCancelledWebhookPayload, type PostFineTuningJobCancelledWebhookRequest, type PostFineTuningJobFailedWebhookPayload, type PostFineTuningJobFailedWebhookRequest, type PostFineTuningJobSucceededWebhookPayload, type PostFineTuningJobSucceededWebhookRequest, type PostResponseCancelledWebhookPayload, type PostResponseCancelledWebhookRequest, type PostResponseCompletedWebhookPayload, type PostResponseCompletedWebhookRequest, type PostResponseFailedWebhookPayload, type PostResponseFailedWebhookRequest, type PostResponseIncompleteWebhookPayload, type PostResponseIncompleteWebhookRequest, type PredictionContent, type Project, type ProjectApiKey, type ProjectApiKeyDeleteResponse, type ProjectApiKeyListResponse, type ProjectCreateRequest, type ProjectListResponse, type ProjectRateLimit, type ProjectRateLimitListResponse, type ProjectRateLimitUpdateRequest, type ProjectServiceAccount, type ProjectServiceAccountApiKey, type ProjectServiceAccountCreateRequest, type ProjectServiceAccountCreateResponse, type ProjectServiceAccountDeleteResponse, type ProjectServiceAccountListResponse, type ProjectUpdateRequest, type ProjectUser, type ProjectUserCreateRequest, type ProjectUserDeleteResponse, type ProjectUserListResponse, type ProjectUserUpdateRequest, type Prompt, type RankingOptions, type RealtimeClientEvent, type RealtimeClientEventConversationItemCreate, type RealtimeClientEventConversationItemDelete, type RealtimeClientEventConversationItemRetrieve, type RealtimeClientEventConversationItemTruncate, type RealtimeClientEventInputAudioBufferAppend, type RealtimeClientEventInputAudioBufferClear, type RealtimeClientEventInputAudioBufferCommit, type RealtimeClientEventOutputAudioBufferClear, type RealtimeClientEventResponseCancel, type RealtimeClientEventResponseCreate, type RealtimeClientEventSessionUpdate, type RealtimeClientEventTranscriptionSessionUpdate, type RealtimeConnectParams, type RealtimeConversationItem, type RealtimeConversationItemContent, type RealtimeConversationItemWithReference, type RealtimeResponse, type RealtimeResponseCreateParams, type RealtimeServerEvent, type RealtimeServerEventConversationCreated, type RealtimeServerEventConversationItemCreated, type RealtimeServerEventConversationItemDeleted, type RealtimeServerEventConversationItemInputAudioTranscriptionCompleted, type RealtimeServerEventConversationItemInputAudioTranscriptionDelta, type RealtimeServerEventConversationItemInputAudioTranscriptionFailed, type RealtimeServerEventConversationItemRetrieved, type RealtimeServerEventConversationItemTruncated, type RealtimeServerEventError, type RealtimeServerEventInputAudioBufferCleared, type RealtimeServerEventInputAudioBufferCommitted, type RealtimeServerEventInputAudioBufferSpeechStarted, type RealtimeServerEventInputAudioBufferSpeechStopped, type RealtimeServerEventOutputAudioBufferCleared, type RealtimeServerEventOutputAudioBufferStarted, type RealtimeServerEventOutputAudioBufferStopped, type RealtimeServerEventRateLimitsUpdated, type RealtimeServerEventResponseAudioDelta, type RealtimeServerEventResponseAudioDone, type RealtimeServerEventResponseAudioTranscriptDelta, type RealtimeServerEventResponseAudioTranscriptDone, type RealtimeServerEventResponseContentPartAdded, type RealtimeServerEventResponseContentPartDone, type RealtimeServerEventResponseCreated, type RealtimeServerEventResponseDone, type RealtimeServerEventResponseFunctionCallArgumentsDelta, type RealtimeServerEventResponseFunctionCallArgumentsDone, type RealtimeServerEventResponseOutputItemAdded, type RealtimeServerEventResponseOutputItemDone, type RealtimeServerEventResponseTextDelta, type RealtimeServerEventResponseTextDone, type RealtimeServerEventSessionCreated, type RealtimeServerEventSessionUpdated, type RealtimeServerEventTranscriptionSessionUpdated, type RealtimeSession, type RealtimeSessionCreateRequest, type RealtimeSessionCreateResponse, type RealtimeTranscriptionSessionCreateRequest, type RealtimeTranscriptionSessionCreateResponse, type Reasoning, ReasoningEffort, type ReasoningItem, type RefusalContent, type Response, type ResponseAudioDeltaEvent, type ResponseAudioDoneEvent, type ResponseAudioTranscriptDeltaEvent, type ResponseAudioTranscriptDoneEvent, type ResponseCodeInterpreterCallCodeDeltaEvent, type ResponseCodeInterpreterCallCodeDoneEvent, type ResponseCodeInterpreterCallCompletedEvent, type ResponseCodeInterpreterCallInProgressEvent, type ResponseCodeInterpreterCallInterpretingEvent, type ResponseCompletedEvent, type ResponseContentPartAddedEvent, type ResponseContentPartDoneEvent, type ResponseCreatedEvent, type ResponseCustomToolCallInputDeltaEvent, type ResponseCustomToolCallInputDoneEvent, type ResponseError, ResponseErrorCode, type ResponseErrorEvent, type ResponseFailedEvent, type ResponseFileSearchCallCompletedEvent, type ResponseFileSearchCallInProgressEvent, type ResponseFileSearchCallSearchingEvent, type ResponseFormatJsonObject, type ResponseFormatJsonSchema, type ResponseFormatJsonSchemaSchema, type ResponseFormatText, type ResponseFormatTextGrammar, type ResponseFormatTextPython, type ResponseFunctionCallArgumentsDeltaEvent, type ResponseFunctionCallArgumentsDoneEvent, type ResponseImageGenCallCompletedEvent, type ResponseImageGenCallGeneratingEvent, type ResponseImageGenCallInProgressEvent, type ResponseImageGenCallPartialImageEvent, type ResponseIncompleteEvent, type ResponseInProgressEvent, type ResponseItemList, type ResponseLogProb, type ResponseMcpCallArgumentsDeltaEvent, type ResponseMcpCallArgumentsDoneEvent, type ResponseMcpCallCompletedEvent, type ResponseMcpCallFailedEvent, type ResponseMcpCallInProgressEvent, type ResponseMcpListToolsCompletedEvent, type ResponseMcpListToolsFailedEvent, type ResponseMcpListToolsInProgressEvent, type ResponseModalities, type ResponseOutputItemAddedEvent, type ResponseOutputItemDoneEvent, type ResponseOutputTextAnnotationAddedEvent, type ResponsePromptVariables, type ResponseProperties, type ResponseQueuedEvent, type ResponseReasoningSummaryPartAddedEvent, type ResponseReasoningSummaryPartDoneEvent, type ResponseReasoningSummaryTextDeltaEvent, type ResponseReasoningSummaryTextDoneEvent, type ResponseReasoningTextDeltaEvent, type ResponseReasoningTextDoneEvent, type ResponseRefusalDeltaEvent, type ResponseRefusalDoneEvent, type ResponseStreamEvent, type ResponseStreamOptions, type ResponseTextDeltaEvent, type ResponseTextDoneEvent, type ResponseUsage, type ResponseWebSearchCallCompletedEvent, type ResponseWebSearchCallInProgressEvent, type ResponseWebSearchCallSearchingEvent, type ResumeFineTuningJobData, type ResumeFineTuningJobResponse, type ResumeFineTuningJobResponses, type RetrieveBatchData, type RetrieveBatchResponse, type RetrieveBatchResponses, type RetrieveContainerData, type RetrieveContainerFileContentData, type RetrieveContainerFileContentResponses, type RetrieveContainerFileData, type RetrieveContainerFileResponse, type RetrieveContainerFileResponses, type RetrieveContainerResponse, type RetrieveContainerResponses, type RetrieveFileData, type RetrieveFileResponse, type RetrieveFileResponses, type RetrieveFineTuningJobData, type RetrieveFineTuningJobResponse, type RetrieveFineTuningJobResponses, type RetrieveInviteData, type RetrieveInviteResponse, type RetrieveInviteResponses, type RetrieveModelData, type RetrieveModelResponse, type RetrieveModelResponses, type RetrieveProjectApiKeyData, type RetrieveProjectApiKeyResponse, type RetrieveProjectApiKeyResponses, type RetrieveProjectData, type RetrieveProjectResponse, type RetrieveProjectResponses, type RetrieveProjectServiceAccountData, type RetrieveProjectServiceAccountResponse, type RetrieveProjectServiceAccountResponses, type RetrieveProjectUserData, type RetrieveProjectUserResponse, type RetrieveProjectUserResponses, type RetrieveUserData, type RetrieveUserResponse, type RetrieveUserResponses, type RetrieveVectorStoreFileContentData, type RetrieveVectorStoreFileContentResponse, type RetrieveVectorStoreFileContentResponses, type RunCompletionUsage, type RunGraderData, type RunGraderRequest, type RunGraderResponse, type RunGraderResponse2, type RunGraderResponses, type RunObject, RunStatus, type RunStepCompletionUsage, type RunStepDeltaObject, type RunStepDeltaObjectDelta, type RunStepDeltaStepDetailsMessageCreationObject, type RunStepDeltaStepDetailsToolCall, type RunStepDeltaStepDetailsToolCallsCodeObject, type RunStepDeltaStepDetailsToolCallsCodeOutputImageObject, type RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject, type RunStepDeltaStepDetailsToolCallsFileSearchObject, type RunStepDeltaStepDetailsToolCallsFunctionObject, type RunStepDeltaStepDetailsToolCallsObject, type RunStepDetailsMessageCreationObject, type RunStepDetailsToolCall, type RunStepDetailsToolCallsCodeObject, type RunStepDetailsToolCallsCodeOutputImageObject, type RunStepDetailsToolCallsCodeOutputLogsObject, type RunStepDetailsToolCallsFileSearchObject, type RunStepDetailsToolCallsFileSearchRankingOptionsObject, type RunStepDetailsToolCallsFileSearchResultObject, type RunStepDetailsToolCallsFunctionObject, type RunStepDetailsToolCallsObject, type RunStepObject, type RunStepStreamEvent, type RunStreamEvent, type RunToolCallObject, type Screenshot, type Scroll, type SearchVectorStoreData, type SearchVectorStoreResponse, type SearchVectorStoreResponses, ServiceTier, type SpeechAudioDeltaEvent, type SpeechAudioDoneEvent, type StaticChunkingStrategy, type StaticChunkingStrategyRequestParam, type StaticChunkingStrategyResponseParam, type StopConfiguration, type SubmitToolOuputsToRunData, type SubmitToolOuputsToRunResponse, type SubmitToolOuputsToRunResponses, type SubmitToolOutputsRunRequest, type SubmitToolOutputsRunRequestWithoutStream, type TextAnnotation, type TextAnnotationDelta, type TextResponseFormatConfiguration, type TextResponseFormatJsonSchema, type ThreadObject, type ThreadStreamEvent, type ToggleCertificatesRequest, type Tool, type ToolChoiceAllowed, type ToolChoiceCustom, type ToolChoiceFunction, type ToolChoiceMcp, ToolChoiceOptions, type ToolChoiceTypes, type TopLogProb, type TranscriptionChunkingStrategy, TranscriptionInclude, type TranscriptionSegment, type TranscriptionWord, type TranscriptTextDeltaEvent, type TranscriptTextDoneEvent, type TranscriptTextUsageDuration, type TranscriptTextUsageTokens, type TruncationObject, type Type, type UpdateChatCompletionData, type UpdateChatCompletionResponse, type UpdateChatCompletionResponses, type UpdateEvalData, type UpdateEvalResponse, type UpdateEvalResponses, type UpdateProjectRateLimitsData, type UpdateProjectRateLimitsError, type UpdateProjectRateLimitsErrors, type UpdateProjectRateLimitsResponse, type UpdateProjectRateLimitsResponses, type UpdateVectorStoreFileAttributesData, type UpdateVectorStoreFileAttributesRequest, type UpdateVectorStoreFileAttributesResponse, type UpdateVectorStoreFileAttributesResponses, type UpdateVectorStoreRequest, type Upload, type UploadCertificateData, type UploadCertificateRequest, type UploadCertificateResponse, type UploadCertificateResponses, type UploadPart, type UrlCitationBody, type UsageAudioSpeechesData, type UsageAudioSpeechesResponse, type UsageAudioSpeechesResponses, type UsageAudioSpeechesResult, type UsageAudioTranscriptionsData, type UsageAudioTranscriptionsResponse, type UsageAudioTranscriptionsResponses, type UsageAudioTranscriptionsResult, type UsageCodeInterpreterSessionsData, type UsageCodeInterpreterSessionsResponse, type UsageCodeInterpreterSessionsResponses, type UsageCodeInterpreterSessionsResult, type UsageCompletionsData, type UsageCompletionsResponse, type UsageCompletionsResponses, type UsageCompletionsResult, type UsageCostsData, type UsageCostsResponse, type UsageCostsResponses, type UsageEmbeddingsData, type UsageEmbeddingsResponse, type UsageEmbeddingsResponses, type UsageEmbeddingsResult, type UsageImagesData, type UsageImagesResponse, type UsageImagesResponses, type UsageImagesResult, type UsageModerationsData, type UsageModerationsResponse, type UsageModerationsResponses, type UsageModerationsResult, type UsageResponse, type UsageTimeBucket, type UsageVectorStoresData, type UsageVectorStoresResponse, type UsageVectorStoresResponses, type UsageVectorStoresResult, type User, type UserDeleteResponse, type UserListResponse, type UserRoleUpdateRequest, type VadConfig, type ValidateGraderData, type ValidateGraderRequest, type ValidateGraderResponse, type ValidateGraderResponse2, type ValidateGraderResponses, type VectorStoreExpirationAfter, type VectorStoreFileAttributes, type VectorStoreFileBatchObject, type VectorStoreFileContentResponse, type VectorStoreFileObject, type VectorStoreObject, type VectorStoreSearchRequest, type VectorStoreSearchResultContentObject, type VectorStoreSearchResultItem, type VectorStoreSearchResultsPage, Verbosity, type VoiceIdsShared, type Wait, type WebhookBatchCancelled, type WebhookBatchCompleted, type WebhookBatchExpired, type WebhookBatchFailed, type WebhookEvalRunCanceled, type WebhookEvalRunFailed, type WebhookEvalRunSucceeded, type WebhookFineTuningJobCancelled, type WebhookFineTuningJobFailed, type WebhookFineTuningJobSucceeded, type WebhookResponseCancelled, type WebhookResponseCompleted, type WebhookResponseFailed, type WebhookResponseIncomplete, type Webhooks, type WebSearchActionFind, type WebSearchActionOpenPage, type WebSearchActionSearch, WebSearchContextSize, type WebSearchLocation, type WebSearchPreviewTool, type WebSearchToolCall } from './types.gen'; ================================================ FILE: examples/openapi-ts-openai/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client'; import { client } from './client.gen'; import type { ActivateOrganizationCertificatesData, ActivateOrganizationCertificatesResponses, ActivateProjectCertificatesData, ActivateProjectCertificatesResponses, AddUploadPartData, AddUploadPartResponses, AdminApiKeysCreateData, AdminApiKeysCreateResponses, AdminApiKeysDeleteData, AdminApiKeysDeleteResponses, AdminApiKeysGetData, AdminApiKeysGetResponses, AdminApiKeysListData, AdminApiKeysListResponses, ArchiveProjectData, ArchiveProjectResponses, CancelBatchData, CancelBatchResponses, CancelEvalRunData, CancelEvalRunResponses, CancelFineTuningJobData, CancelFineTuningJobResponses, CancelResponseData, CancelResponseErrors, CancelResponseResponses, CancelRunData, CancelRunResponses, CancelUploadData, CancelUploadResponses, CancelVectorStoreFileBatchData, CancelVectorStoreFileBatchResponses, CompleteUploadData, CompleteUploadResponses, CreateAssistantData, CreateAssistantResponses, CreateBatchData, CreateBatchResponses, CreateChatCompletionData, CreateChatCompletionResponses, CreateCompletionData, CreateCompletionResponses, CreateContainerData, CreateContainerFileData, CreateContainerFileResponses, CreateContainerResponses, CreateEmbeddingData, CreateEmbeddingResponses, CreateEvalData, CreateEvalResponses, CreateEvalRunData, CreateEvalRunErrors, CreateEvalRunResponses, CreateFileData, CreateFileResponses, CreateFineTuningCheckpointPermissionData, CreateFineTuningCheckpointPermissionResponses, CreateFineTuningJobData, CreateFineTuningJobResponses, CreateImageData, CreateImageEditData, CreateImageEditResponses, CreateImageResponses, CreateImageVariationData, CreateImageVariationResponses, CreateMessageData, CreateMessageResponses, CreateModerationData, CreateModerationResponses, CreateProjectData, CreateProjectResponses, CreateProjectServiceAccountData, CreateProjectServiceAccountErrors, CreateProjectServiceAccountResponses, CreateProjectUserData, CreateProjectUserErrors, CreateProjectUserResponses, CreateRealtimeSessionData, CreateRealtimeSessionResponses, CreateRealtimeTranscriptionSessionData, CreateRealtimeTranscriptionSessionResponses, CreateResponseData, CreateResponseResponses, CreateRunData, CreateRunResponses, CreateSpeechData, CreateSpeechResponses, CreateThreadAndRunData, CreateThreadAndRunResponses, CreateThreadData, CreateThreadResponses, CreateTranscriptionData, CreateTranscriptionResponses, CreateTranslationData, CreateTranslationResponses, CreateUploadData, CreateUploadResponses, CreateVectorStoreData, CreateVectorStoreFileBatchData, CreateVectorStoreFileBatchResponses, CreateVectorStoreFileData, CreateVectorStoreFileResponses, CreateVectorStoreResponses, DeactivateOrganizationCertificatesData, DeactivateOrganizationCertificatesResponses, DeactivateProjectCertificatesData, DeactivateProjectCertificatesResponses, DeleteAssistantData, DeleteAssistantResponses, DeleteCertificateData, DeleteCertificateResponses, DeleteChatCompletionData, DeleteChatCompletionResponses, DeleteContainerData, DeleteContainerFileData, DeleteContainerFileResponses, DeleteContainerResponses, DeleteEvalData, DeleteEvalErrors, DeleteEvalResponses, DeleteEvalRunData, DeleteEvalRunErrors, DeleteEvalRunResponses, DeleteFileData, DeleteFileResponses, DeleteFineTuningCheckpointPermissionData, DeleteFineTuningCheckpointPermissionResponses, DeleteInviteData, DeleteInviteResponses, DeleteMessageData, DeleteMessageResponses, DeleteModelData, DeleteModelResponses, DeleteProjectApiKeyData, DeleteProjectApiKeyErrors, DeleteProjectApiKeyResponses, DeleteProjectServiceAccountData, DeleteProjectServiceAccountResponses, DeleteProjectUserData, DeleteProjectUserErrors, DeleteProjectUserResponses, DeleteResponseData, DeleteResponseErrors, DeleteResponseResponses, DeleteThreadData, DeleteThreadResponses, DeleteUserData, DeleteUserResponses, DeleteVectorStoreData, DeleteVectorStoreFileData, DeleteVectorStoreFileResponses, DeleteVectorStoreResponses, DownloadFileData, DownloadFileResponses, GetAssistantData, GetAssistantResponses, GetCertificateData, GetCertificateResponses, GetChatCompletionData, GetChatCompletionMessagesData, GetChatCompletionMessagesResponses, GetChatCompletionResponses, GetEvalData, GetEvalResponses, GetEvalRunData, GetEvalRunOutputItemData, GetEvalRunOutputItemResponses, GetEvalRunOutputItemsData, GetEvalRunOutputItemsResponses, GetEvalRunResponses, GetEvalRunsData, GetEvalRunsResponses, GetMessageData, GetMessageResponses, GetResponseData, GetResponseResponses, GetRunData, GetRunResponses, GetRunStepData, GetRunStepResponses, GetThreadData, GetThreadResponses, GetVectorStoreData, GetVectorStoreFileBatchData, GetVectorStoreFileBatchResponses, GetVectorStoreFileData, GetVectorStoreFileResponses, GetVectorStoreResponses, InviteUserData, InviteUserResponses, ListAssistantsData, ListAssistantsResponses, ListAuditLogsData, ListAuditLogsResponses, ListBatchesData, ListBatchesResponses, ListChatCompletionsData, ListChatCompletionsResponses, ListContainerFilesData, ListContainerFilesResponses, ListContainersData, ListContainersResponses, ListEvalsData, ListEvalsResponses, ListFilesData, ListFilesInVectorStoreBatchData, ListFilesInVectorStoreBatchResponses, ListFilesResponses, ListFineTuningCheckpointPermissionsData, ListFineTuningCheckpointPermissionsResponses, ListFineTuningEventsData, ListFineTuningEventsResponses, ListFineTuningJobCheckpointsData, ListFineTuningJobCheckpointsResponses, ListInputItemsData, ListInputItemsResponses, ListInvitesData, ListInvitesResponses, ListMessagesData, ListMessagesResponses, ListModelsData, ListModelsResponses, ListOrganizationCertificatesData, ListOrganizationCertificatesResponses, ListPaginatedFineTuningJobsData, ListPaginatedFineTuningJobsResponses, ListProjectApiKeysData, ListProjectApiKeysResponses, ListProjectCertificatesData, ListProjectCertificatesResponses, ListProjectRateLimitsData, ListProjectRateLimitsResponses, ListProjectsData, ListProjectServiceAccountsData, ListProjectServiceAccountsErrors, ListProjectServiceAccountsResponses, ListProjectsResponses, ListProjectUsersData, ListProjectUsersErrors, ListProjectUsersResponses, ListRunsData, ListRunsResponses, ListRunStepsData, ListRunStepsResponses, ListUsersData, ListUsersResponses, ListVectorStoreFilesData, ListVectorStoreFilesResponses, ListVectorStoresData, ListVectorStoresResponses, ModifyAssistantData, ModifyAssistantResponses, ModifyCertificateData, ModifyCertificateResponses, ModifyMessageData, ModifyMessageResponses, ModifyProjectData, ModifyProjectErrors, ModifyProjectResponses, ModifyProjectUserData, ModifyProjectUserErrors, ModifyProjectUserResponses, ModifyRunData, ModifyRunResponses, ModifyThreadData, ModifyThreadResponses, ModifyUserData, ModifyUserResponses, ModifyVectorStoreData, ModifyVectorStoreResponses, PauseFineTuningJobData, PauseFineTuningJobResponses, ResumeFineTuningJobData, ResumeFineTuningJobResponses, RetrieveBatchData, RetrieveBatchResponses, RetrieveContainerData, RetrieveContainerFileContentData, RetrieveContainerFileContentResponses, RetrieveContainerFileData, RetrieveContainerFileResponses, RetrieveContainerResponses, RetrieveFileData, RetrieveFileResponses, RetrieveFineTuningJobData, RetrieveFineTuningJobResponses, RetrieveInviteData, RetrieveInviteResponses, RetrieveModelData, RetrieveModelResponses, RetrieveProjectApiKeyData, RetrieveProjectApiKeyResponses, RetrieveProjectData, RetrieveProjectResponses, RetrieveProjectServiceAccountData, RetrieveProjectServiceAccountResponses, RetrieveProjectUserData, RetrieveProjectUserResponses, RetrieveUserData, RetrieveUserResponses, RetrieveVectorStoreFileContentData, RetrieveVectorStoreFileContentResponses, RunGraderData, RunGraderResponses, SearchVectorStoreData, SearchVectorStoreResponses, SubmitToolOuputsToRunData, SubmitToolOuputsToRunResponses, UpdateChatCompletionData, UpdateChatCompletionResponses, UpdateEvalData, UpdateEvalResponses, UpdateProjectRateLimitsData, UpdateProjectRateLimitsErrors, UpdateProjectRateLimitsResponses, UpdateVectorStoreFileAttributesData, UpdateVectorStoreFileAttributesResponses, UploadCertificateData, UploadCertificateResponses, UsageAudioSpeechesData, UsageAudioSpeechesResponses, UsageAudioTranscriptionsData, UsageAudioTranscriptionsResponses, UsageCodeInterpreterSessionsData, UsageCodeInterpreterSessionsResponses, UsageCompletionsData, UsageCompletionsResponses, UsageCostsData, UsageCostsResponses, UsageEmbeddingsData, UsageEmbeddingsResponses, UsageImagesData, UsageImagesResponses, UsageModerationsData, UsageModerationsResponses, UsageVectorStoresData, UsageVectorStoresResponses, ValidateGraderData, ValidateGraderResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new OpenAi()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class OpenAi extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); OpenAi.__registry.set(this, args?.key); } /** * List assistants * * Returns a list of assistants. */ public listAssistants(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/assistants', ...options }); } /** * Create assistant * * Create an assistant with a model and instructions. */ public createAssistant(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/assistants', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete assistant * * Delete an assistant. */ public deleteAssistant(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/assistants/{assistant_id}', ...options }); } /** * Retrieve assistant * * Retrieves an assistant. */ public getAssistant(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/assistants/{assistant_id}', ...options }); } /** * Modify assistant * * Modifies an assistant. */ public modifyAssistant(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/assistants/{assistant_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create speech * * Generates audio from the input text. */ public createSpeech(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/audio/speech', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create transcription * * Transcribes audio into the input language. */ public createTranscription(options: Options) { return (options.client ?? this.client).post({ ...formDataBodySerializer, security: [{ scheme: 'bearer', type: 'http' }], url: '/audio/transcriptions', ...options, headers: { 'Content-Type': null, ...options.headers } }); } /** * Create translation * * Translates audio into English. */ public createTranslation(options: Options) { return (options.client ?? this.client).post({ ...formDataBodySerializer, security: [{ scheme: 'bearer', type: 'http' }], url: '/audio/translations', ...options, headers: { 'Content-Type': null, ...options.headers } }); } /** * List batch * * List your organization's batches. */ public listBatches(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/batches', ...options }); } /** * Create batch * * Creates and executes a batch from an uploaded file of requests */ public createBatch(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/batches', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Retrieve batch * * Retrieves a batch. */ public retrieveBatch(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/batches/{batch_id}', ...options }); } /** * Cancel batch * * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file. */ public cancelBatch(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/batches/{batch_id}/cancel', ...options }); } /** * List Chat Completions * * List stored Chat Completions. Only Chat Completions that have been stored * with the `store` parameter set to `true` will be returned. * */ public listChatCompletions(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/chat/completions', ...options }); } /** * Create chat completion * * **Starting a new project?** We recommend trying [Responses](https://platform.openai.com/docs/api-reference/responses) * to take advantage of the latest OpenAI platform features. Compare * [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). * * --- * * Creates a model response for the given chat conversation. Learn more in the * [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), * and [audio](https://platform.openai.com/docs/guides/audio) guides. * * Parameter support can differ depending on the model used to generate the * response, particularly for newer reasoning models. Parameters that are only * supported for reasoning models are noted below. For the current state of * unsupported parameters in reasoning models, * [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). * */ public createChatCompletion(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/chat/completions', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete chat completion * * Delete a stored chat completion. Only Chat Completions that have been * created with the `store` parameter set to `true` can be deleted. * */ public deleteChatCompletion(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/chat/completions/{completion_id}', ...options }); } /** * Get chat completion * * Get a stored chat completion. Only Chat Completions that have been created * with the `store` parameter set to `true` will be returned. * */ public getChatCompletion(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/chat/completions/{completion_id}', ...options }); } /** * Update chat completion * * Modify a stored chat completion. Only Chat Completions that have been * created with the `store` parameter set to `true` can be modified. Currently, * the only supported modification is to update the `metadata` field. * */ public updateChatCompletion(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/chat/completions/{completion_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Get chat messages * * Get the messages in a stored chat completion. Only Chat Completions that * have been created with the `store` parameter set to `true` will be * returned. * */ public getChatCompletionMessages(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/chat/completions/{completion_id}/messages', ...options }); } /** * Create completion * * Creates a completion for the provided prompt and parameters. */ public createCompletion(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/completions', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List containers * * List Containers */ public listContainers(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers', ...options }); } /** * Create container * * Create Container */ public createContainer(options?: Options) { return (options?.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); } /** * Delete a container * * Delete Container */ public deleteContainer(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers/{container_id}', ...options }); } /** * Retrieve container * * Retrieve Container */ public retrieveContainer(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers/{container_id}', ...options }); } /** * List container files * * List Container files */ public listContainerFiles(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers/{container_id}/files', ...options }); } /** * Create container file * * Create a Container File * * You can send either a multipart/form-data request with the raw file content, or a JSON request with a file ID. * */ public createContainerFile(options: Options) { return (options.client ?? this.client).post({ ...formDataBodySerializer, security: [{ scheme: 'bearer', type: 'http' }], url: '/containers/{container_id}/files', ...options, headers: { 'Content-Type': null, ...options.headers } }); } /** * Delete a container file * * Delete Container File */ public deleteContainerFile(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers/{container_id}/files/{file_id}', ...options }); } /** * Retrieve container file * * Retrieve Container File */ public retrieveContainerFile(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers/{container_id}/files/{file_id}', ...options }); } /** * Retrieve container file content * * Retrieve Container File Content */ public retrieveContainerFileContent(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/containers/{container_id}/files/{file_id}/content', ...options }); } /** * Create embeddings * * Creates an embedding vector representing the input text. */ public createEmbedding(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/embeddings', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List evals * * List evaluations for a project. * */ public listEvals(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals', ...options }); } /** * Create eval * * Create the structure of an evaluation that can be used to test a model's performance. * An evaluation is a set of testing criteria and the config for a data source, which dictates the schema of the data used in the evaluation. After creating an evaluation, you can run it on different models and model parameters. We support several types of graders and datasources. * For more information, see the [Evals guide](https://platform.openai.com/docs/guides/evals). * */ public createEval(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete an eval * * Delete an evaluation. * */ public deleteEval(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}', ...options }); } /** * Get an eval * * Get an evaluation by ID. * */ public getEval(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}', ...options }); } /** * Update an eval * * Update certain properties of an evaluation. * */ public updateEval(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Get eval runs * * Get a list of runs for an evaluation. * */ public getEvalRuns(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}/runs', ...options }); } /** * Create eval run * * Kicks off a new run for a given evaluation, specifying the data source, and what model configuration to use to test. The datasource will be validated against the schema specified in the config of the evaluation. * */ public createEvalRun(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}/runs', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete eval run * * Delete an eval run. * */ public deleteEvalRun(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}/runs/{run_id}', ...options }); } /** * Get an eval run * * Get an evaluation run by ID. * */ public getEvalRun(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}/runs/{run_id}', ...options }); } /** * Cancel eval run * * Cancel an ongoing evaluation run. * */ public cancelEvalRun(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}/runs/{run_id}', ...options }); } /** * Get eval run output items * * Get a list of output items for an evaluation run. * */ public getEvalRunOutputItems(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}/runs/{run_id}/output_items', ...options }); } /** * Get an output item of an eval run * * Get an evaluation run output item by ID. * */ public getEvalRunOutputItem(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}', ...options }); } /** * List files * * Returns a list of files. */ public listFiles(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/files', ...options }); } /** * Upload file * * Upload a file that can be used across various endpoints. Individual files can be up to 512 MB, and the size of all files uploaded by one organization can be up to 1 TB. * * The Assistants API supports files up to 2 million tokens and of specific file types. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. * * The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models. * * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also has a specific required [format](https://platform.openai.com/docs/api-reference/batch/request-input). * * Please [contact us](https://help.openai.com/) if you need to increase these storage limits. * */ public createFile(options: Options) { return (options.client ?? this.client).post({ ...formDataBodySerializer, security: [{ scheme: 'bearer', type: 'http' }], url: '/files', ...options, headers: { 'Content-Type': null, ...options.headers } }); } /** * Delete file * * Delete a file. */ public deleteFile(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/files/{file_id}', ...options }); } /** * Retrieve file * * Returns information about a specific file. */ public retrieveFile(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/files/{file_id}', ...options }); } /** * Retrieve file content * * Returns the contents of the specified file. */ public downloadFile(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/files/{file_id}/content', ...options }); } /** * Run grader * * Run a grader. * */ public runGrader(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/alpha/graders/run', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Validate grader * * Validate a grader. * */ public validateGrader(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/alpha/graders/validate', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List checkpoint permissions * * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). * * Organization owners can use this endpoint to view all permissions for a fine-tuned model checkpoint. * */ public listFineTuningCheckpointPermissions(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions', ...options }); } /** * Create checkpoint permissions * * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). * * This enables organization owners to share fine-tuned models with other projects in their organization. * */ public createFineTuningCheckpointPermission(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete checkpoint permission * * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). * * Organization owners can use this endpoint to delete a permission for a fine-tuned model checkpoint. * */ public deleteFineTuningCheckpointPermission(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}', ...options }); } /** * List fine-tuning jobs * * List your organization's fine-tuning jobs * */ public listPaginatedFineTuningJobs(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs', ...options }); } /** * Create fine-tuning job * * Creates a fine-tuning job which begins the process of creating a new model from a given dataset. * * Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. * * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) * */ public createFineTuningJob(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Retrieve fine-tuning job * * Get info about a fine-tuning job. * * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) * */ public retrieveFineTuningJob(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs/{fine_tuning_job_id}', ...options }); } /** * Cancel fine-tuning * * Immediately cancel a fine-tune job. * */ public cancelFineTuningJob(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs/{fine_tuning_job_id}/cancel', ...options }); } /** * List fine-tuning checkpoints * * List checkpoints for a fine-tuning job. * */ public listFineTuningJobCheckpoints(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs/{fine_tuning_job_id}/checkpoints', ...options }); } /** * List fine-tuning events * * Get status updates for a fine-tuning job. * */ public listFineTuningEvents(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs/{fine_tuning_job_id}/events', ...options }); } /** * Pause fine-tuning * * Pause a fine-tune job. * */ public pauseFineTuningJob(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs/{fine_tuning_job_id}/pause', ...options }); } /** * Resume fine-tuning * * Resume a fine-tune job. * */ public resumeFineTuningJob(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/fine_tuning/jobs/{fine_tuning_job_id}/resume', ...options }); } /** * Create image edit * * Creates an edited or extended image given one or more source images and a prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. */ public createImageEdit(options: Options) { return (options.client ?? this.client).post({ ...formDataBodySerializer, security: [{ scheme: 'bearer', type: 'http' }], url: '/images/edits', ...options, headers: { 'Content-Type': null, ...options.headers } }); } /** * Create image * * Creates an image given a prompt. [Learn more](https://platform.openai.com/docs/guides/images). * */ public createImage(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/images/generations', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create image variation * * Creates a variation of a given image. This endpoint only supports `dall-e-2`. */ public createImageVariation(options: Options) { return (options.client ?? this.client).post({ ...formDataBodySerializer, security: [{ scheme: 'bearer', type: 'http' }], url: '/images/variations', ...options, headers: { 'Content-Type': null, ...options.headers } }); } /** * List models * * Lists the currently available models, and provides basic information about each one such as the owner and availability. */ public listModels(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/models', ...options }); } /** * Delete a fine-tuned model * * Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. */ public deleteModel(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/models/{model}', ...options }); } /** * Retrieve model * * Retrieves a model instance, providing basic information about the model such as the owner and permissioning. */ public retrieveModel(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/models/{model}', ...options }); } /** * Create moderation * * Classifies if text and/or image inputs are potentially harmful. Learn * more in the [moderation guide](https://platform.openai.com/docs/guides/moderation). * */ public createModeration(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/moderations', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List all organization and project API keys. * * List organization API keys */ public adminApiKeysList(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/admin_api_keys', ...options }); } /** * Create admin API key * * Create an organization admin API key */ public adminApiKeysCreate(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/admin_api_keys', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete admin API key * * Delete an organization admin API key */ public adminApiKeysDelete(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/admin_api_keys/{key_id}', ...options }); } /** * Retrieve admin API key * * Retrieve a single organization API key */ public adminApiKeysGet(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/admin_api_keys/{key_id}', ...options }); } /** * List audit logs * * List user actions and configuration changes within this organization. */ public listAuditLogs(options?: Options) { return (options?.client ?? this.client).get({ querySerializer: { parameters: { effective_at: { object: { style: 'form' } } } }, security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/audit_logs', ...options }); } /** * List organization certificates * * List uploaded certificates for this organization. */ public listOrganizationCertificates(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/certificates', ...options }); } /** * Upload certificate * * Upload a certificate to the organization. This does **not** automatically activate the certificate. * * Organizations can upload up to 50 certificates. * */ public uploadCertificate(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/certificates', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Activate certificates for organization * * Activate certificates at the organization level. * * You can atomically and idempotently activate up to 10 certificates at a time. * */ public activateOrganizationCertificates(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/certificates/activate', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Deactivate certificates for organization * * Deactivate certificates at the organization level. * * You can atomically and idempotently deactivate up to 10 certificates at a time. * */ public deactivateOrganizationCertificates(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/certificates/deactivate', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete certificate * * Delete a certificate from the organization. * * The certificate must be inactive for the organization and all projects. * */ public deleteCertificate(options?: Options) { return (options?.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/certificates/{certificate_id}', ...options }); } /** * Get certificate * * Get a certificate that has been uploaded to the organization. * * You can get a certificate regardless of whether it is active or not. * */ public getCertificate(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/certificates/{certificate_id}', ...options }); } /** * Modify certificate * * Modify a certificate. Note that only the name can be modified. * */ public modifyCertificate(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/certificates/{certificate_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Costs * * Get costs details for the organization. */ public usageCosts(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/costs', ...options }); } /** * List invites * * Returns a list of invites in the organization. */ public listInvites(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/invites', ...options }); } /** * Create invite * * Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization. */ public inviteUser(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/invites', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete invite * * Delete an invite. If the invite has already been accepted, it cannot be deleted. */ public deleteInvite(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/invites/{invite_id}', ...options }); } /** * Retrieve invite * * Retrieves an invite. */ public retrieveInvite(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/invites/{invite_id}', ...options }); } /** * List projects * * Returns a list of projects. */ public listProjects(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects', ...options }); } /** * Create project * * Create a new project in the organization. Projects can be created and archived, but cannot be deleted. */ public createProject(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Retrieve project * * Retrieves a project. */ public retrieveProject(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}', ...options }); } /** * Modify project * * Modifies a project in the organization. */ public modifyProject(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List project API keys * * Returns a list of API keys in the project. */ public listProjectApiKeys(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/api_keys', ...options }); } /** * Delete project API key * * Deletes an API key from the project. */ public deleteProjectApiKey(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/api_keys/{key_id}', ...options }); } /** * Retrieve project API key * * Retrieves an API key in the project. */ public retrieveProjectApiKey(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/api_keys/{key_id}', ...options }); } /** * Archive project * * Archives a project in the organization. Archived projects cannot be used or updated. */ public archiveProject(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/archive', ...options }); } /** * List project certificates * * List certificates for this project. */ public listProjectCertificates(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/certificates', ...options }); } /** * Activate certificates for project * * Activate certificates at the project level. * * You can atomically and idempotently activate up to 10 certificates at a time. * */ public activateProjectCertificates(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/certificates/activate', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Deactivate certificates for project * * Deactivate certificates at the project level. You can atomically and * idempotently deactivate up to 10 certificates at a time. * */ public deactivateProjectCertificates(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/certificates/deactivate', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List project rate limits * * Returns the rate limits per model for a project. */ public listProjectRateLimits(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/rate_limits', ...options }); } /** * Modify project rate limit * * Updates a project rate limit. */ public updateProjectRateLimits(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/rate_limits/{rate_limit_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List project service accounts * * Returns a list of service accounts in the project. */ public listProjectServiceAccounts(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/service_accounts', ...options }); } /** * Create project service account * * Creates a new service account in the project. This also returns an unredacted API key for the service account. */ public createProjectServiceAccount(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/service_accounts', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete project service account * * Deletes a service account from the project. */ public deleteProjectServiceAccount(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/service_accounts/{service_account_id}', ...options }); } /** * Retrieve project service account * * Retrieves a service account in the project. */ public retrieveProjectServiceAccount(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/service_accounts/{service_account_id}', ...options }); } /** * List project users * * Returns a list of users in the project. */ public listProjectUsers(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/users', ...options }); } /** * Create project user * * Adds a user to the project. Users must already be members of the organization to be added to a project. */ public createProjectUser(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/users', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete project user * * Deletes a user from the project. */ public deleteProjectUser(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/users/{user_id}', ...options }); } /** * Retrieve project user * * Retrieves a user in the project. */ public retrieveProjectUser(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/users/{user_id}', ...options }); } /** * Modify project user * * Modifies a user's role in the project. */ public modifyProjectUser(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/projects/{project_id}/users/{user_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Audio speeches * * Get audio speeches usage details for the organization. */ public usageAudioSpeeches(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/audio_speeches', ...options }); } /** * Audio transcriptions * * Get audio transcriptions usage details for the organization. */ public usageAudioTranscriptions(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/audio_transcriptions', ...options }); } /** * Code interpreter sessions * * Get code interpreter sessions usage details for the organization. */ public usageCodeInterpreterSessions(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/code_interpreter_sessions', ...options }); } /** * Completions * * Get completions usage details for the organization. */ public usageCompletions(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/completions', ...options }); } /** * Embeddings * * Get embeddings usage details for the organization. */ public usageEmbeddings(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/embeddings', ...options }); } /** * Images * * Get images usage details for the organization. */ public usageImages(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/images', ...options }); } /** * Moderations * * Get moderations usage details for the organization. */ public usageModerations(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/moderations', ...options }); } /** * Vector stores * * Get vector stores usage details for the organization. */ public usageVectorStores(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/usage/vector_stores', ...options }); } /** * List users * * Lists all of the users in the organization. */ public listUsers(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/users', ...options }); } /** * Delete user * * Deletes a user from the organization. */ public deleteUser(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/users/{user_id}', ...options }); } /** * Retrieve user * * Retrieves a user by their identifier. */ public retrieveUser(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/users/{user_id}', ...options }); } /** * Modify user * * Modifies a user's role in the organization. */ public modifyUser(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/organization/users/{user_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create session * * Create an ephemeral API token for use in client-side applications with the * Realtime API. Can be configured with the same session parameters as the * `session.update` client event. * * It responds with a session object, plus a `client_secret` key which contains * a usable ephemeral API token that can be used to authenticate browser clients * for the Realtime API. * */ public createRealtimeSession(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/realtime/sessions', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create transcription session * * Create an ephemeral API token for use in client-side applications with the * Realtime API specifically for realtime transcriptions. * Can be configured with the same session parameters as the `transcription_session.update` client event. * * It responds with a session object, plus a `client_secret` key which contains * a usable ephemeral API token that can be used to authenticate browser clients * for the Realtime API. * */ public createRealtimeTranscriptionSession(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/realtime/transcription_sessions', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create a model response * * Creates a model response. Provide [text](https://platform.openai.com/docs/guides/text) or * [image](https://platform.openai.com/docs/guides/images) inputs to generate [text](https://platform.openai.com/docs/guides/text) * or [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have the model call * your own [custom code](https://platform.openai.com/docs/guides/function-calling) or use built-in * [tools](https://platform.openai.com/docs/guides/tools) like [web search](https://platform.openai.com/docs/guides/tools-web-search) * or [file search](https://platform.openai.com/docs/guides/tools-file-search) to use your own data * as input for the model's response. * */ public createResponse(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/responses', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete a model response * * Deletes a model response with the given ID. * */ public deleteResponse(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/responses/{response_id}', ...options }); } /** * Get a model response * * Retrieves a model response with the given ID. * */ public getResponse(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/responses/{response_id}', ...options }); } /** * Cancel a response * * Cancels a model response with the given ID. Only responses created with * the `background` parameter set to `true` can be cancelled. * [Learn more](https://platform.openai.com/docs/guides/background). * */ public cancelResponse(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/responses/{response_id}/cancel', ...options }); } /** * List input items * * Returns a list of input items for a given response. */ public listInputItems(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/responses/{response_id}/input_items', ...options }); } /** * Create thread * * Create a thread. */ public createThread(options?: Options) { return (options?.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); } /** * Create thread and run * * Create a thread and run it in one request. */ public createThreadAndRun(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/runs', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete thread * * Delete a thread. */ public deleteThread(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}', ...options }); } /** * Retrieve thread * * Retrieves a thread. */ public getThread(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}', ...options }); } /** * Modify thread * * Modifies a thread. */ public modifyThread(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List messages * * Returns a list of messages for a given thread. */ public listMessages(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/messages', ...options }); } /** * Create message * * Create a message. */ public createMessage(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/messages', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete message * * Deletes a message. */ public deleteMessage(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/messages/{message_id}', ...options }); } /** * Retrieve message * * Retrieve a message. */ public getMessage(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/messages/{message_id}', ...options }); } /** * Modify message * * Modifies a message. */ public modifyMessage(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/messages/{message_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * List runs * * Returns a list of runs belonging to a thread. */ public listRuns(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs', ...options }); } /** * Create run * * Create a run. */ public createRun(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Retrieve run * * Retrieves a run. */ public getRun(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs/{run_id}', ...options }); } /** * Modify run * * Modifies a run. */ public modifyRun(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs/{run_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Cancel a run * * Cancels a run that is `in_progress`. */ public cancelRun(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs/{run_id}/cancel', ...options }); } /** * List run steps * * Returns a list of run steps belonging to a run. */ public listRunSteps(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs/{run_id}/steps', ...options }); } /** * Retrieve run step * * Retrieves a run step. */ public getRunStep(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs/{run_id}/steps/{step_id}', ...options }); } /** * Submit tool outputs to run * * When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request. * */ public submitToolOuputsToRun(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/threads/{thread_id}/runs/{run_id}/submit_tool_outputs', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create upload * * Creates an intermediate [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object * that you can add [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. * Currently, an Upload can accept at most 8 GB in total and expires after an * hour after you create it. * * Once you complete the Upload, we will create a * [File](https://platform.openai.com/docs/api-reference/files/object) object that contains all the parts * you uploaded. This File is usable in the rest of our platform as a regular * File object. * * For certain `purpose` values, the correct `mime_type` must be specified. * Please refer to documentation for the * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). * * For guidance on the proper filename extensions for each purpose, please * follow the documentation on [creating a * File](https://platform.openai.com/docs/api-reference/files/create). * */ public createUpload(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/uploads', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Cancel upload * * Cancels the Upload. No Parts may be added after an Upload is cancelled. * */ public cancelUpload(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/uploads/{upload_id}/cancel', ...options }); } /** * Complete upload * * Completes the [Upload](https://platform.openai.com/docs/api-reference/uploads/object). * * Within the returned Upload object, there is a nested [File](https://platform.openai.com/docs/api-reference/files/object) object that is ready to use in the rest of the platform. * * You can specify the order of the Parts by passing in an ordered list of the Part IDs. * * The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. * */ public completeUpload(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/uploads/{upload_id}/complete', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Add upload part * * Adds a [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. * * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. * * It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). * */ public addUploadPart(options: Options) { return (options.client ?? this.client).post({ ...formDataBodySerializer, security: [{ scheme: 'bearer', type: 'http' }], url: '/uploads/{upload_id}/parts', ...options, headers: { 'Content-Type': null, ...options.headers } }); } /** * List vector stores * * Returns a list of vector stores. */ public listVectorStores(options?: Options) { return (options?.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores', ...options }); } /** * Create vector store * * Create a vector store. */ public createVectorStore(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete vector store * * Delete a vector store. */ public deleteVectorStore(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}', ...options }); } /** * Retrieve vector store * * Retrieves a vector store. */ public getVectorStore(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}', ...options }); } /** * Modify vector store * * Modifies a vector store. */ public modifyVectorStore(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Create vector store file batch * * Create a vector store file batch. */ public createVectorStoreFileBatch(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/file_batches', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Retrieve vector store file batch * * Retrieves a vector store file batch. */ public getVectorStoreFileBatch(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/file_batches/{batch_id}', ...options }); } /** * Cancel vector store file batch * * Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. */ public cancelVectorStoreFileBatch(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel', ...options }); } /** * List vector store files in a batch * * Returns a list of vector store files in a batch. */ public listFilesInVectorStoreBatch(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/file_batches/{batch_id}/files', ...options }); } /** * List vector store files * * Returns a list of vector store files. */ public listVectorStoreFiles(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/files', ...options }); } /** * Create vector store file * * Create a vector store file by attaching a [File](https://platform.openai.com/docs/api-reference/files) to a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). */ public createVectorStoreFile(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/files', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Delete vector store file * * Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](https://platform.openai.com/docs/api-reference/files/delete) endpoint. */ public deleteVectorStoreFile(options: Options) { return (options.client ?? this.client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/files/{file_id}', ...options }); } /** * Retrieve vector store file * * Retrieves a vector store file. */ public getVectorStoreFile(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/files/{file_id}', ...options }); } /** * Update vector store file attributes * * Update attributes on a vector store file. */ public updateVectorStoreFileAttributes(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/files/{file_id}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } /** * Retrieve vector store file content * * Retrieve the parsed contents of a vector store file. */ public retrieveVectorStoreFileContent(options: Options) { return (options.client ?? this.client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/files/{file_id}/content', ...options }); } /** * Search vector store * * Search a vector store for relevant chunks based on a query and file attributes filter. */ public searchVectorStore(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/vector_stores/{vector_store_id}/search', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } } ================================================ FILE: examples/openapi-ts-openai/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://api.openai.com/v1' | (string & {}); }; export type Webhooks = PostBatchCancelledWebhookRequest | PostBatchCompletedWebhookRequest | PostBatchExpiredWebhookRequest | PostBatchFailedWebhookRequest | PostEvalRunCanceledWebhookRequest | PostEvalRunFailedWebhookRequest | PostEvalRunSucceededWebhookRequest | PostFineTuningJobCancelledWebhookRequest | PostFineTuningJobFailedWebhookRequest | PostFineTuningJobSucceededWebhookRequest | PostResponseCancelledWebhookRequest | PostResponseCompletedWebhookRequest | PostResponseFailedWebhookRequest | PostResponseIncompleteWebhookRequest; export type AddUploadPartRequest = { /** * The chunk of bytes for this Part. * */ data: Blob | File; }; /** * Represents an individual Admin API key in an org. */ export type AdminApiKey = { /** * The object type, which is always `organization.admin_api_key` */ object: string; /** * The identifier, which can be referenced in API endpoints */ id: string; /** * The name of the API key */ name: string; /** * The redacted value of the API key */ redacted_value: string; /** * The value of the API key. Only shown on create. */ value?: string; /** * The Unix timestamp (in seconds) of when the API key was created */ created_at: number; /** * The Unix timestamp (in seconds) of when the API key was last used */ last_used_at: number; owner: { /** * Always `user` */ type?: string; /** * The object type, which is always organization.user */ object?: string; /** * The identifier, which can be referenced in API endpoints */ id?: string; /** * The name of the user */ name?: string; /** * The Unix timestamp (in seconds) of when the user was created */ created_at?: number; /** * Always `owner` */ role?: string; }; }; export type ApiKeyList = { object?: string; data?: Array; has_more?: boolean; first_id?: string; last_id?: string; }; /** * Assistant * * Represents an `assistant` that can call the model and use tools. */ export type AssistantObject = { /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `assistant`. */ object: 'assistant'; /** * The Unix timestamp (in seconds) for when the assistant was created. */ created_at: number; /** * The name of the assistant. The maximum length is 256 characters. * */ name: string; /** * The description of the assistant. The maximum length is 512 characters. * */ description: string; /** * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. * */ model: string; /** * The system instructions that the assistant uses. The maximum length is 256,000 characters. * */ instructions: string; /** * A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. * */ tools: Array; /** * A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources?: { code_interpreter?: { /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: { /** * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. * */ vector_store_ids?: Array; }; }; metadata: Metadata; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. * */ top_p?: number; response_format?: AssistantsApiResponseFormatOption; }; /** * Represents an event emitted when streaming a Run. * * Each event in a server-sent events stream has an `event` and `data` property: * * ``` * event: thread.created * data: {"id": "thread_123", "object": "thread", ...} * ``` * * We emit events whenever a new object is created, transitions to a new state, or is being * streamed in parts (deltas). For example, we emit `thread.run.created` when a new run * is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses * to create a message during a run, we emit a `thread.message.created event`, a * `thread.message.in_progress` event, many `thread.message.delta` events, and finally a * `thread.message.completed` event. * * We may add additional events over time, so we recommend handling unknown events gracefully * in your code. See the [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) to learn how to * integrate the Assistants API with streaming. * */ export type AssistantStreamEvent = ({ event?: 'ThreadStreamEvent'; } & ThreadStreamEvent) | ({ event?: 'RunStreamEvent'; } & RunStreamEvent) | ({ event?: 'RunStepStreamEvent'; } & RunStepStreamEvent) | ({ event?: 'MessageStreamEvent'; } & MessageStreamEvent) | ({ event?: 'ErrorEvent'; } & ErrorEvent); export const AssistantSupportedModels = { GPT_5: 'gpt-5', GPT_5_MINI: 'gpt-5-mini', GPT_5_NANO: 'gpt-5-nano', GPT_5_2025_08_07: 'gpt-5-2025-08-07', GPT_5_MINI_2025_08_07: 'gpt-5-mini-2025-08-07', GPT_5_NANO_2025_08_07: 'gpt-5-nano-2025-08-07', GPT_4_1: 'gpt-4.1', GPT_4_1_MINI: 'gpt-4.1-mini', GPT_4_1_NANO: 'gpt-4.1-nano', GPT_4_1_2025_04_14: 'gpt-4.1-2025-04-14', GPT_4_1_MINI_2025_04_14: 'gpt-4.1-mini-2025-04-14', GPT_4_1_NANO_2025_04_14: 'gpt-4.1-nano-2025-04-14', O3_MINI: 'o3-mini', O3_MINI_2025_01_31: 'o3-mini-2025-01-31', O1: 'o1', O1_2024_12_17: 'o1-2024-12-17', GPT_4O: 'gpt-4o', GPT_4O_2024_11_20: 'gpt-4o-2024-11-20', GPT_4O_2024_08_06: 'gpt-4o-2024-08-06', GPT_4O_2024_05_13: 'gpt-4o-2024-05-13', GPT_4O_MINI: 'gpt-4o-mini', GPT_4O_MINI_2024_07_18: 'gpt-4o-mini-2024-07-18', GPT_4_5_PREVIEW: 'gpt-4.5-preview', GPT_4_5_PREVIEW_2025_02_27: 'gpt-4.5-preview-2025-02-27', GPT_4_TURBO: 'gpt-4-turbo', GPT_4_TURBO_2024_04_09: 'gpt-4-turbo-2024-04-09', GPT_4_0125_PREVIEW: 'gpt-4-0125-preview', GPT_4_TURBO_PREVIEW: 'gpt-4-turbo-preview', GPT_4_1106_PREVIEW: 'gpt-4-1106-preview', GPT_4_VISION_PREVIEW: 'gpt-4-vision-preview', GPT_4: 'gpt-4', GPT_4_0314: 'gpt-4-0314', GPT_4_0613: 'gpt-4-0613', GPT_4_32K: 'gpt-4-32k', GPT_4_32K_0314: 'gpt-4-32k-0314', GPT_4_32K_0613: 'gpt-4-32k-0613', GPT_3_5_TURBO: 'gpt-3.5-turbo', GPT_3_5_TURBO_16K: 'gpt-3.5-turbo-16k', GPT_3_5_TURBO_0613: 'gpt-3.5-turbo-0613', GPT_3_5_TURBO_1106: 'gpt-3.5-turbo-1106', GPT_3_5_TURBO_0125: 'gpt-3.5-turbo-0125', GPT_3_5_TURBO_16K_0613: 'gpt-3.5-turbo-16k-0613' } as const; export type AssistantSupportedModels = typeof AssistantSupportedModels[keyof typeof AssistantSupportedModels]; /** * Code interpreter tool */ export type AssistantToolsCode = { /** * The type of tool being defined: `code_interpreter` */ type: 'code_interpreter'; }; /** * FileSearch tool */ export type AssistantToolsFileSearch = { /** * The type of tool being defined: `file_search` */ type: 'file_search'; /** * Overrides for the file search tool. */ file_search?: { /** * The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive. * * Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. * */ max_num_results?: number; ranking_options?: FileSearchRankingOptions; }; }; /** * FileSearch tool */ export type AssistantToolsFileSearchTypeOnly = { /** * The type of tool being defined: `file_search` */ type: 'file_search'; }; /** * Function tool */ export type AssistantToolsFunction = { /** * The type of tool being defined: `function` */ type: 'function'; function: FunctionObject; }; /** * Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. * * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). * * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. * * **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. * */ export type AssistantsApiResponseFormatOption = 'auto' | ResponseFormatText | ResponseFormatJsonObject | ResponseFormatJsonSchema; /** * Controls which (if any) tool is called by the model. * `none` means the model will not call any tools and instead generates a message. * `auto` is the default value and means the model can pick between generating a message or calling one or more tools. * `required` means the model must call one or more tools before responding to the user. * Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. * */ export type AssistantsApiToolChoiceOption = 'none' | 'auto' | 'required' | AssistantsNamedToolChoice; /** * Specifies a tool the model should use. Use to force the model to call a specific tool. */ export type AssistantsNamedToolChoice = { /** * The type of the tool. If type is `function`, the function name must be set */ type: 'function' | 'code_interpreter' | 'file_search'; function?: { /** * The name of the function to call. */ name: string; }; }; /** * The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. * */ export const AudioResponseFormat = { JSON: 'json', TEXT: 'text', SRT: 'srt', VERBOSE_JSON: 'verbose_json', VTT: 'vtt' } as const; /** * The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. * */ export type AudioResponseFormat = typeof AudioResponseFormat[keyof typeof AudioResponseFormat]; /** * A log of a user action or configuration change within this organization. */ export type AuditLog = { /** * The ID of this log. */ id: string; type: AuditLogEventType; /** * The Unix timestamp (in seconds) of the event. */ effective_at: number; /** * The project that the action was scoped to. Absent for actions not scoped to projects. Note that any admin actions taken via Admin API keys are associated with the default project. */ project?: { /** * The project ID. */ id?: string; /** * The project title. */ name?: string; }; actor: AuditLogActor; /** * The details for events with this `type`. */ 'api_key.created'?: { /** * The tracking ID of the API key. */ id?: string; /** * The payload used to create the API key. */ data?: { /** * A list of scopes allowed for the API key, e.g. `["api.model.request"]` */ scopes?: Array; }; }; /** * The details for events with this `type`. */ 'api_key.updated'?: { /** * The tracking ID of the API key. */ id?: string; /** * The payload used to update the API key. */ changes_requested?: { /** * A list of scopes allowed for the API key, e.g. `["api.model.request"]` */ scopes?: Array; }; }; /** * The details for events with this `type`. */ 'api_key.deleted'?: { /** * The tracking ID of the API key. */ id?: string; }; /** * The project and fine-tuned model checkpoint that the checkpoint permission was created for. */ 'checkpoint_permission.created'?: { /** * The ID of the checkpoint permission. */ id?: string; /** * The payload used to create the checkpoint permission. */ data?: { /** * The ID of the project that the checkpoint permission was created for. */ project_id?: string; /** * The ID of the fine-tuned model checkpoint. */ fine_tuned_model_checkpoint?: string; }; }; /** * The details for events with this `type`. */ 'checkpoint_permission.deleted'?: { /** * The ID of the checkpoint permission. */ id?: string; }; /** * The details for events with this `type`. */ 'invite.sent'?: { /** * The ID of the invite. */ id?: string; /** * The payload used to create the invite. */ data?: { /** * The email invited to the organization. */ email?: string; /** * The role the email was invited to be. Is either `owner` or `member`. */ role?: string; }; }; /** * The details for events with this `type`. */ 'invite.accepted'?: { /** * The ID of the invite. */ id?: string; }; /** * The details for events with this `type`. */ 'invite.deleted'?: { /** * The ID of the invite. */ id?: string; }; /** * The details for events with this `type`. */ 'login.failed'?: { /** * The error code of the failure. */ error_code?: string; /** * The error message of the failure. */ error_message?: string; }; /** * The details for events with this `type`. */ 'logout.failed'?: { /** * The error code of the failure. */ error_code?: string; /** * The error message of the failure. */ error_message?: string; }; /** * The details for events with this `type`. */ 'organization.updated'?: { /** * The organization ID. */ id?: string; /** * The payload used to update the organization settings. */ changes_requested?: { /** * The organization title. */ title?: string; /** * The organization description. */ description?: string; /** * The organization name. */ name?: string; /** * Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. */ threads_ui_visibility?: string; /** * Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`. */ usage_dashboard_visibility?: string; /** * How your organization logs data from supported API calls. One of `disabled`, `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects` */ api_call_logging?: string; /** * The list of project ids if api_call_logging is set to `enabled_for_selected_projects` */ api_call_logging_project_ids?: string; }; }; /** * The details for events with this `type`. */ 'project.created'?: { /** * The project ID. */ id?: string; /** * The payload used to create the project. */ data?: { /** * The project name. */ name?: string; /** * The title of the project as seen on the dashboard. */ title?: string; }; }; /** * The details for events with this `type`. */ 'project.updated'?: { /** * The project ID. */ id?: string; /** * The payload used to update the project. */ changes_requested?: { /** * The title of the project as seen on the dashboard. */ title?: string; }; }; /** * The details for events with this `type`. */ 'project.archived'?: { /** * The project ID. */ id?: string; }; /** * The details for events with this `type`. */ 'rate_limit.updated'?: { /** * The rate limit ID */ id?: string; /** * The payload used to update the rate limits. */ changes_requested?: { /** * The maximum requests per minute. */ max_requests_per_1_minute?: number; /** * The maximum tokens per minute. */ max_tokens_per_1_minute?: number; /** * The maximum images per minute. Only relevant for certain models. */ max_images_per_1_minute?: number; /** * The maximum audio megabytes per minute. Only relevant for certain models. */ max_audio_megabytes_per_1_minute?: number; /** * The maximum requests per day. Only relevant for certain models. */ max_requests_per_1_day?: number; /** * The maximum batch input tokens per day. Only relevant for certain models. */ batch_1_day_max_input_tokens?: number; }; }; /** * The details for events with this `type`. */ 'rate_limit.deleted'?: { /** * The rate limit ID */ id?: string; }; /** * The details for events with this `type`. */ 'service_account.created'?: { /** * The service account ID. */ id?: string; /** * The payload used to create the service account. */ data?: { /** * The role of the service account. Is either `owner` or `member`. */ role?: string; }; }; /** * The details for events with this `type`. */ 'service_account.updated'?: { /** * The service account ID. */ id?: string; /** * The payload used to updated the service account. */ changes_requested?: { /** * The role of the service account. Is either `owner` or `member`. */ role?: string; }; }; /** * The details for events with this `type`. */ 'service_account.deleted'?: { /** * The service account ID. */ id?: string; }; /** * The details for events with this `type`. */ 'user.added'?: { /** * The user ID. */ id?: string; /** * The payload used to add the user to the project. */ data?: { /** * The role of the user. Is either `owner` or `member`. */ role?: string; }; }; /** * The details for events with this `type`. */ 'user.updated'?: { /** * The project ID. */ id?: string; /** * The payload used to update the user. */ changes_requested?: { /** * The role of the user. Is either `owner` or `member`. */ role?: string; }; }; /** * The details for events with this `type`. */ 'user.deleted'?: { /** * The user ID. */ id?: string; }; /** * The details for events with this `type`. */ 'certificate.created'?: { /** * The certificate ID. */ id?: string; /** * The name of the certificate. */ name?: string; }; /** * The details for events with this `type`. */ 'certificate.updated'?: { /** * The certificate ID. */ id?: string; /** * The name of the certificate. */ name?: string; }; /** * The details for events with this `type`. */ 'certificate.deleted'?: { /** * The certificate ID. */ id?: string; /** * The name of the certificate. */ name?: string; /** * The certificate content in PEM format. */ certificate?: string; }; /** * The details for events with this `type`. */ 'certificates.activated'?: { certificates?: Array<{ /** * The certificate ID. */ id?: string; /** * The name of the certificate. */ name?: string; }>; }; /** * The details for events with this `type`. */ 'certificates.deactivated'?: { certificates?: Array<{ /** * The certificate ID. */ id?: string; /** * The name of the certificate. */ name?: string; }>; }; }; /** * The actor who performed the audit logged action. */ export type AuditLogActor = { /** * The type of actor. Is either `session` or `api_key`. */ type?: 'session' | 'api_key'; session?: AuditLogActorSession; api_key?: AuditLogActorApiKey; }; /** * The API Key used to perform the audit logged action. */ export type AuditLogActorApiKey = { /** * The tracking id of the API key. */ id?: string; /** * The type of API key. Can be either `user` or `service_account`. */ type?: 'user' | 'service_account'; user?: AuditLogActorUser; service_account?: AuditLogActorServiceAccount; }; /** * The service account that performed the audit logged action. */ export type AuditLogActorServiceAccount = { /** * The service account id. */ id?: string; }; /** * The session in which the audit logged action was performed. */ export type AuditLogActorSession = { user?: AuditLogActorUser; /** * The IP address from which the action was performed. */ ip_address?: string; }; /** * The user who performed the audit logged action. */ export type AuditLogActorUser = { /** * The user id. */ id?: string; /** * The user email. */ email?: string; }; /** * The event type. */ export const AuditLogEventType = { API_KEY_CREATED: 'api_key.created', API_KEY_UPDATED: 'api_key.updated', API_KEY_DELETED: 'api_key.deleted', CHECKPOINT_PERMISSION_CREATED: 'checkpoint_permission.created', CHECKPOINT_PERMISSION_DELETED: 'checkpoint_permission.deleted', INVITE_SENT: 'invite.sent', INVITE_ACCEPTED: 'invite.accepted', INVITE_DELETED: 'invite.deleted', LOGIN_SUCCEEDED: 'login.succeeded', LOGIN_FAILED: 'login.failed', LOGOUT_SUCCEEDED: 'logout.succeeded', LOGOUT_FAILED: 'logout.failed', ORGANIZATION_UPDATED: 'organization.updated', PROJECT_CREATED: 'project.created', PROJECT_UPDATED: 'project.updated', PROJECT_ARCHIVED: 'project.archived', SERVICE_ACCOUNT_CREATED: 'service_account.created', SERVICE_ACCOUNT_UPDATED: 'service_account.updated', SERVICE_ACCOUNT_DELETED: 'service_account.deleted', RATE_LIMIT_UPDATED: 'rate_limit.updated', RATE_LIMIT_DELETED: 'rate_limit.deleted', USER_ADDED: 'user.added', USER_UPDATED: 'user.updated', USER_DELETED: 'user.deleted' } as const; /** * The event type. */ export type AuditLogEventType = typeof AuditLogEventType[keyof typeof AuditLogEventType]; /** * Auto Chunking Strategy * * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. */ export type AutoChunkingStrategyRequestParam = { /** * Always `auto`. */ type: 'auto'; }; export type Batch = { id: string; /** * The object type, which is always `batch`. */ object: 'batch'; /** * The OpenAI API endpoint used by the batch. */ endpoint: string; errors?: { /** * The object type, which is always `list`. */ object?: string; data?: Array; }; /** * The ID of the input file for the batch. */ input_file_id: string; /** * The time frame within which the batch should be processed. */ completion_window: string; /** * The current status of the batch. */ status: 'validating' | 'failed' | 'in_progress' | 'finalizing' | 'completed' | 'expired' | 'cancelling' | 'cancelled'; /** * The ID of the file containing the outputs of successfully executed requests. */ output_file_id?: string; /** * The ID of the file containing the outputs of requests with errors. */ error_file_id?: string; /** * The Unix timestamp (in seconds) for when the batch was created. */ created_at: number; /** * The Unix timestamp (in seconds) for when the batch started processing. */ in_progress_at?: number; /** * The Unix timestamp (in seconds) for when the batch will expire. */ expires_at?: number; /** * The Unix timestamp (in seconds) for when the batch started finalizing. */ finalizing_at?: number; /** * The Unix timestamp (in seconds) for when the batch was completed. */ completed_at?: number; /** * The Unix timestamp (in seconds) for when the batch failed. */ failed_at?: number; /** * The Unix timestamp (in seconds) for when the batch expired. */ expired_at?: number; /** * The Unix timestamp (in seconds) for when the batch started cancelling. */ cancelling_at?: number; /** * The Unix timestamp (in seconds) for when the batch was cancelled. */ cancelled_at?: number; request_counts?: BatchRequestCounts; metadata?: Metadata; }; /** * File expiration policy * * The expiration policy for the output and/or error file that are generated for a batch. */ export type BatchFileExpirationAfter = { /** * Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created. */ anchor: 'created_at'; /** * The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days). */ seconds: number; }; /** * The per-line object of the batch input file */ export type BatchRequestInput = { /** * A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch. */ custom_id?: string; /** * The HTTP method to be used for the request. Currently only `POST` is supported. */ method?: 'POST'; /** * The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. */ url?: string; }; /** * The per-line object of the batch output and error files */ export type BatchRequestOutput = { id?: string; /** * A developer-provided per-request id that will be used to match outputs to inputs. */ custom_id?: string; response?: { /** * The HTTP status code of the response */ status_code?: number; /** * An unique identifier for the OpenAI API request. Please include this request ID when contacting support. */ request_id?: string; /** * The JSON body of the response */ body?: { [key: string]: unknown; }; }; /** * For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure. */ error?: { /** * A machine-readable error code. */ code?: string; /** * A human-readable error message. */ message?: string; }; }; /** * Represents an individual `certificate` uploaded to the organization. */ export type Certificate = { /** * The object type. * * - If creating, updating, or getting a specific certificate, the object type is `certificate`. * - If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`. * - If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`. * */ object: 'certificate' | 'organization.certificate' | 'organization.project.certificate'; /** * The identifier, which can be referenced in API endpoints */ id: string; /** * The name of the certificate. */ name: string; /** * The Unix timestamp (in seconds) of when the certificate was uploaded. */ created_at: number; certificate_details: { /** * The Unix timestamp (in seconds) of when the certificate becomes valid. */ valid_at?: number; /** * The Unix timestamp (in seconds) of when the certificate expires. */ expires_at?: number; /** * The content of the certificate in PEM format. */ content?: string; }; /** * Whether the certificate is currently active at the specified scope. Not returned when getting details for a specific certificate. */ active?: boolean; }; /** * Allowed tools * * Constrains the tools available to the model to a pre-defined set. * */ export type ChatCompletionAllowedTools = { /** * Constrains the tools available to the model to a pre-defined set. * * `auto` allows the model to pick from among the allowed tools and generate a * message. * * `required` requires the model to call one or more of the allowed tools. * */ mode: 'auto' | 'required'; /** * A list of tool definitions that the model should be allowed to call. * * For the Chat Completions API, the list of tool definitions might look like: * ```json * [ * { "type": "function", "function": { "name": "get_weather" } }, * { "type": "function", "function": { "name": "get_time" } } * ] * ``` * */ tools: Array<{ [key: string]: unknown; }>; }; /** * Allowed tools * * Constrains the tools available to the model to a pre-defined set. * */ export type ChatCompletionAllowedToolsChoice = { /** * Allowed tool configuration type. Always `allowed_tools`. */ type: 'allowed_tools'; allowed_tools: ChatCompletionAllowedTools; }; export type ChatCompletionDeleted = { /** * The type of object being deleted. */ object: 'chat.completion.deleted'; /** * The ID of the chat completion that was deleted. */ id: string; /** * Whether the chat completion was deleted. */ deleted: boolean; }; /** * Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. * */ export type ChatCompletionFunctionCallOption = { /** * The name of the function to call. */ name: string; }; /** * @deprecated */ export type ChatCompletionFunctions = { /** * A description of what the function does, used by the model to choose when and how to call the function. */ description?: string; /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. */ name: string; parameters?: FunctionParameters; }; /** * ChatCompletionList * * An object representing a list of Chat Completions. * */ export type ChatCompletionList = { /** * The type of this object. It is always set to "list". * */ object: 'list'; /** * An array of chat completion objects. * */ data: Array; /** * The identifier of the first chat completion in the data array. */ first_id: string; /** * The identifier of the last chat completion in the data array. */ last_id: string; /** * Indicates whether there are more Chat Completions available. */ has_more: boolean; }; /** * Custom tool call * * A call to a custom tool created by the model. * */ export type ChatCompletionMessageCustomToolCall = { /** * The ID of the tool call. */ id: string; /** * The type of the tool. Always `custom`. */ type: 'custom'; /** * The custom tool that the model called. */ custom: { /** * The name of the custom tool to call. */ name: string; /** * The input for the custom tool call generated by the model. */ input: string; }; }; /** * ChatCompletionMessageList * * An object representing a list of chat completion messages. * */ export type ChatCompletionMessageList = { /** * The type of this object. It is always set to "list". * */ object: 'list'; /** * An array of chat completion message objects. * */ data: Array; }>; /** * The identifier of the first chat message in the data array. */ first_id: string; /** * The identifier of the last chat message in the data array. */ last_id: string; /** * Indicates whether there are more chat messages available. */ has_more: boolean; }; /** * Function tool call * * A call to a function tool created by the model. * */ export type ChatCompletionMessageToolCall = { /** * The ID of the tool call. */ id: string; /** * The type of the tool. Currently, only `function` is supported. */ type: 'function'; /** * The function that the model called. */ function: { /** * The name of the function to call. */ name: string; /** * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. */ arguments: string; }; }; export type ChatCompletionMessageToolCallChunk = { index: number; /** * The ID of the tool call. */ id?: string; /** * The type of the tool. Currently, only `function` is supported. */ type?: 'function'; function?: { /** * The name of the function to call. */ name?: string; /** * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. */ arguments?: string; }; }; /** * The tool calls generated by the model, such as function calls. */ export type ChatCompletionMessageToolCalls = Array<({ type?: 'ChatCompletionMessageToolCall'; } & ChatCompletionMessageToolCall) | ({ type?: 'ChatCompletionMessageCustomToolCall'; } & ChatCompletionMessageCustomToolCall)>; /** * Output types that you would like the model to generate for this request. * Most models are capable of generating text, which is the default: * * `["text"]` * * The `gpt-4o-audio-preview` model can also be used to [generate audio](https://platform.openai.com/docs/guides/audio). To * request that this model generate both text and audio responses, you can * use: * * `["text", "audio"]` * */ export type ChatCompletionModalities = Array<'text' | 'audio'>; /** * Function tool choice * * Specifies a tool the model should use. Use to force the model to call a specific function. */ export type ChatCompletionNamedToolChoice = { /** * For function calling, the type is always `function`. */ type: 'function'; function: { /** * The name of the function to call. */ name: string; }; }; /** * Custom tool choice * * Specifies a tool the model should use. Use to force the model to call a specific custom tool. */ export type ChatCompletionNamedToolChoiceCustom = { /** * For custom tool calling, the type is always `custom`. */ type: 'custom'; custom: { /** * The name of the custom tool to call. */ name: string; }; }; /** * Assistant message * * Messages sent by the model in response to user messages. * */ export type ChatCompletionRequestAssistantMessage = { /** * The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. * */ content?: string | Array; /** * The refusal message by the assistant. */ refusal?: string; /** * The role of the messages author, in this case `assistant`. */ role: 'assistant'; /** * An optional name for the participant. Provides the model information to differentiate between participants of the same role. */ name?: string; /** * Data about a previous audio response from the model. * [Learn more](https://platform.openai.com/docs/guides/audio). * */ audio?: { /** * Unique identifier for a previous audio response from the model. * */ id: string; }; tool_calls?: ChatCompletionMessageToolCalls; /** * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. * * @deprecated */ function_call?: { /** * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. */ arguments: string; /** * The name of the function to call. */ name: string; }; }; export type ChatCompletionRequestAssistantMessageContentPart = ({ type?: 'ChatCompletionRequestMessageContentPartText'; } & ChatCompletionRequestMessageContentPartText) | ({ type?: 'ChatCompletionRequestMessageContentPartRefusal'; } & ChatCompletionRequestMessageContentPartRefusal); /** * Developer message * * Developer-provided instructions that the model should follow, regardless of * messages sent by the user. With o1 models and newer, `developer` messages * replace the previous `system` messages. * */ export type ChatCompletionRequestDeveloperMessage = { /** * The contents of the developer message. */ content: string | Array; /** * The role of the messages author, in this case `developer`. */ role: 'developer'; /** * An optional name for the participant. Provides the model information to differentiate between participants of the same role. */ name?: string; }; /** * Function message * * @deprecated */ export type ChatCompletionRequestFunctionMessage = { /** * The role of the messages author, in this case `function`. */ role: 'function'; /** * The contents of the function message. */ content: string; /** * The name of the function to call. */ name: string; }; export type ChatCompletionRequestMessage = ({ role?: 'ChatCompletionRequestDeveloperMessage'; } & ChatCompletionRequestDeveloperMessage) | ({ role?: 'ChatCompletionRequestSystemMessage'; } & ChatCompletionRequestSystemMessage) | ({ role?: 'ChatCompletionRequestUserMessage'; } & ChatCompletionRequestUserMessage) | ({ role?: 'ChatCompletionRequestAssistantMessage'; } & ChatCompletionRequestAssistantMessage) | ({ role?: 'ChatCompletionRequestToolMessage'; } & ChatCompletionRequestToolMessage) | ({ role?: 'ChatCompletionRequestFunctionMessage'; } & ChatCompletionRequestFunctionMessage); /** * Audio content part * * Learn about [audio inputs](https://platform.openai.com/docs/guides/audio). * */ export type ChatCompletionRequestMessageContentPartAudio = { /** * The type of the content part. Always `input_audio`. */ type: 'input_audio'; input_audio: { /** * Base64 encoded audio data. */ data: string; /** * The format of the encoded audio data. Currently supports "wav" and "mp3". * */ format: 'wav' | 'mp3'; }; }; /** * File content part * * Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text generation. * */ export type ChatCompletionRequestMessageContentPartFile = { /** * The type of the content part. Always `file`. */ type: 'file'; file: { /** * The name of the file, used when passing the file to the model as a * string. * */ filename?: string; /** * The base64 encoded file data, used when passing the file to the model * as a string. * */ file_data?: string; /** * The ID of an uploaded file to use as input. * */ file_id?: string; }; }; /** * Image content part * * Learn about [image inputs](https://platform.openai.com/docs/guides/vision). * */ export type ChatCompletionRequestMessageContentPartImage = { /** * The type of the content part. */ type: 'image_url'; image_url: { /** * Either a URL of the image or the base64 encoded image data. */ url: string; /** * Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). */ detail?: 'auto' | 'low' | 'high'; }; }; /** * Refusal content part */ export type ChatCompletionRequestMessageContentPartRefusal = { /** * The type of the content part. */ type: 'refusal'; /** * The refusal message generated by the model. */ refusal: string; }; /** * Text content part * * Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation). * */ export type ChatCompletionRequestMessageContentPartText = { /** * The type of the content part. */ type: 'text'; /** * The text content. */ text: string; }; /** * System message * * Developer-provided instructions that the model should follow, regardless of * messages sent by the user. With o1 models and newer, use `developer` messages * for this purpose instead. * */ export type ChatCompletionRequestSystemMessage = { /** * The contents of the system message. */ content: string | Array; /** * The role of the messages author, in this case `system`. */ role: 'system'; /** * An optional name for the participant. Provides the model information to differentiate between participants of the same role. */ name?: string; }; export type ChatCompletionRequestSystemMessageContentPart = ChatCompletionRequestMessageContentPartText; /** * Tool message */ export type ChatCompletionRequestToolMessage = { /** * The role of the messages author, in this case `tool`. */ role: 'tool'; /** * The contents of the tool message. */ content: string | Array; /** * Tool call that this message is responding to. */ tool_call_id: string; }; export type ChatCompletionRequestToolMessageContentPart = ChatCompletionRequestMessageContentPartText; /** * User message * * Messages sent by an end user, containing prompts or additional context * information. * */ export type ChatCompletionRequestUserMessage = { /** * The contents of the user message. * */ content: string | Array; /** * The role of the messages author, in this case `user`. */ role: 'user'; /** * An optional name for the participant. Provides the model information to differentiate between participants of the same role. */ name?: string; }; export type ChatCompletionRequestUserMessageContentPart = ({ type?: 'ChatCompletionRequestMessageContentPartText'; } & ChatCompletionRequestMessageContentPartText) | ({ type?: 'ChatCompletionRequestMessageContentPartImage'; } & ChatCompletionRequestMessageContentPartImage) | ({ type?: 'ChatCompletionRequestMessageContentPartAudio'; } & ChatCompletionRequestMessageContentPartAudio) | ({ type?: 'ChatCompletionRequestMessageContentPartFile'; } & ChatCompletionRequestMessageContentPartFile); /** * A chat completion message generated by the model. */ export type ChatCompletionResponseMessage = { /** * The contents of the message. */ content: string; /** * The refusal message generated by the model. */ refusal: string; tool_calls?: ChatCompletionMessageToolCalls; /** * Annotations for the message, when applicable, as when using the * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). * */ annotations?: Array<{ /** * The type of the URL citation. Always `url_citation`. */ type: 'url_citation'; /** * A URL citation when using web search. */ url_citation: { /** * The index of the last character of the URL citation in the message. */ end_index: number; /** * The index of the first character of the URL citation in the message. */ start_index: number; /** * The URL of the web resource. */ url: string; /** * The title of the web resource. */ title: string; }; }>; /** * The role of the author of this message. */ role: 'assistant'; /** * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. * * @deprecated */ function_call?: { /** * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. */ arguments: string; /** * The name of the function to call. */ name: string; }; /** * If the audio output modality is requested, this object contains data * about the audio response from the model. [Learn more](https://platform.openai.com/docs/guides/audio). * */ audio?: { /** * Unique identifier for this audio response. */ id: string; /** * The Unix timestamp (in seconds) for when this audio response will * no longer be accessible on the server for use in multi-turn * conversations. * */ expires_at: number; /** * Base64 encoded audio bytes generated by the model, in the format * specified in the request. * */ data: string; /** * Transcript of the audio generated by the model. */ transcript: string; }; }; /** * The role of the author of a message */ export const ChatCompletionRole = { DEVELOPER: 'developer', SYSTEM: 'system', USER: 'user', ASSISTANT: 'assistant', TOOL: 'tool', FUNCTION: 'function' } as const; /** * The role of the author of a message */ export type ChatCompletionRole = typeof ChatCompletionRole[keyof typeof ChatCompletionRole]; /** * Options for streaming response. Only set this when you set `stream: true`. * */ export type ChatCompletionStreamOptions = { /** * If set, an additional chunk will be streamed before the `data: [DONE]` * message. The `usage` field on this chunk shows the token usage statistics * for the entire request, and the `choices` field will always be an empty * array. * * All other chunks will also include a `usage` field, but with a null * value. **NOTE:** If the stream is interrupted, you may not receive the * final usage chunk which contains the total token usage for the request. * */ include_usage?: boolean; /** * When true, stream obfuscation will be enabled. Stream obfuscation adds * random characters to an `obfuscation` field on streaming delta events to * normalize payload sizes as a mitigation to certain side-channel attacks. * These obfuscation fields are included by default, but add a small amount * of overhead to the data stream. You can set `include_obfuscation` to * false to optimize for bandwidth if you trust the network links between * your application and the OpenAI API. * */ include_obfuscation?: boolean; }; /** * A chat completion delta generated by streamed model responses. */ export type ChatCompletionStreamResponseDelta = { /** * The contents of the chunk message. */ content?: string; /** * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. * * @deprecated */ function_call?: { /** * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. */ arguments?: string; /** * The name of the function to call. */ name?: string; }; tool_calls?: Array; /** * The role of the author of this message. */ role?: 'developer' | 'system' | 'user' | 'assistant' | 'tool'; /** * The refusal message generated by the model. */ refusal?: string; }; export type ChatCompletionTokenLogprob = { /** * The token. */ token: string; /** * The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. */ logprob: number; /** * A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. */ bytes: Array; /** * List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. */ top_logprobs: Array<{ /** * The token. */ token: string; /** * The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. */ logprob: number; /** * A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. */ bytes: Array; }>; }; /** * Function tool * * A function tool that can be used to generate a response. * */ export type ChatCompletionTool = { /** * The type of the tool. Currently, only `function` is supported. */ type: 'function'; function: FunctionObject; }; /** * Controls which (if any) tool is called by the model. * `none` means the model will not call any tool and instead generates a message. * `auto` means the model can pick between generating a message or calling one or more tools. * `required` means the model must call one or more tools. * Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. * * `none` is the default when no tools are present. `auto` is the default if tools are present. * */ export type ChatCompletionToolChoiceOption = 'none' | 'auto' | 'required' | ChatCompletionAllowedToolsChoice | ChatCompletionNamedToolChoice | ChatCompletionNamedToolChoiceCustom; /** * The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. */ export type ChunkingStrategyRequestParam = ({ type?: 'AutoChunkingStrategyRequestParam'; } & AutoChunkingStrategyRequestParam) | ({ type?: 'StaticChunkingStrategyRequestParam'; } & StaticChunkingStrategyRequestParam); /** * Click * * A click action. * */ export type Click = { /** * Specifies the event type. For a click action, this property is * always set to `click`. * */ type: 'click'; /** * Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`. * */ button: 'left' | 'right' | 'wheel' | 'back' | 'forward'; /** * The x-coordinate where the click occurred. * */ x: number; /** * The y-coordinate where the click occurred. * */ y: number; }; /** * Code interpreter file output * * The output of a code interpreter tool call that is a file. * */ export type CodeInterpreterFileOutput = { /** * The type of the code interpreter file output. Always `files`. * */ type: 'files'; files: Array<{ /** * The MIME type of the file. * */ mime_type: string; /** * The ID of the file. * */ file_id: string; }>; }; /** * Code interpreter output image * * The image output from the code interpreter. * */ export type CodeInterpreterOutputImage = { /** * The type of the output. Always 'image'. */ type: 'image'; /** * The URL of the image output from the code interpreter. */ url: string; }; /** * Code interpreter output logs * * The logs output from the code interpreter. * */ export type CodeInterpreterOutputLogs = { /** * The type of the output. Always 'logs'. */ type: 'logs'; /** * The logs output from the code interpreter. */ logs: string; }; /** * Code interpreter text output * * The output of a code interpreter tool call that is text. * */ export type CodeInterpreterTextOutput = { /** * The type of the code interpreter text output. Always `logs`. * */ type: 'logs'; /** * The logs of the code interpreter tool call. * */ logs: string; }; /** * Code interpreter * * A tool that runs Python code to help generate a response to a prompt. * */ export type CodeInterpreterTool = { /** * The type of the code interpreter tool. Always `code_interpreter`. * */ type: 'code_interpreter'; /** * The code interpreter container. Can be a container ID or an object that * specifies uploaded file IDs to make available to your code. * */ container: string | CodeInterpreterToolAuto; }; /** * CodeInterpreterContainerAuto * * Configuration for a code interpreter container. Optionally specify the IDs * of the files to run the code on. * */ export type CodeInterpreterToolAuto = { /** * Always `auto`. */ type: 'auto'; /** * An optional list of uploaded files to make available to your code. * */ file_ids?: Array; }; /** * Code interpreter tool call * * A tool call to run code. * */ export type CodeInterpreterToolCall = { /** * The type of the code interpreter tool call. Always `code_interpreter_call`. * */ type: 'code_interpreter_call'; /** * The unique ID of the code interpreter tool call. * */ id: string; /** * The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`. * */ status: 'in_progress' | 'completed' | 'incomplete' | 'interpreting' | 'failed'; /** * The ID of the container used to run the code. * */ container_id: string; /** * The code to run, or null if not available. * */ code: string; /** * The outputs generated by the code interpreter, such as logs or images. * Can be null if no outputs are available. * */ outputs: Array<({ type?: 'CodeInterpreterOutputLogs'; } & CodeInterpreterOutputLogs) | ({ type?: 'CodeInterpreterOutputImage'; } & CodeInterpreterOutputImage)>; }; /** * Comparison Filter * * A filter used to compare a specified attribute key to a given value using a defined comparison operation. * */ export type ComparisonFilter = { /** * Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. * - `eq`: equals * - `ne`: not equal * - `gt`: greater than * - `gte`: greater than or equal * - `lt`: less than * - `lte`: less than or equal * */ type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; /** * The key to compare against the value. */ key: string; /** * The value to compare against the attribute key; supports string, number, or boolean types. */ value: string | number | boolean; }; export type CompleteUploadRequest = { /** * The ordered list of Part IDs. * */ part_ids: Array; /** * The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. * */ md5?: string; }; /** * Usage statistics for the completion request. */ export type CompletionUsage = { /** * Number of tokens in the generated completion. */ completion_tokens: number; /** * Number of tokens in the prompt. */ prompt_tokens: number; /** * Total number of tokens used in the request (prompt + completion). */ total_tokens: number; /** * Breakdown of tokens used in a completion. */ completion_tokens_details?: { /** * When using Predicted Outputs, the number of tokens in the * prediction that appeared in the completion. * */ accepted_prediction_tokens?: number; /** * Audio input tokens generated by the model. */ audio_tokens?: number; /** * Tokens generated by the model for reasoning. */ reasoning_tokens?: number; /** * When using Predicted Outputs, the number of tokens in the * prediction that did not appear in the completion. However, like * reasoning tokens, these tokens are still counted in the total * completion tokens for purposes of billing, output, and context window * limits. * */ rejected_prediction_tokens?: number; }; /** * Breakdown of tokens used in the prompt. */ prompt_tokens_details?: { /** * Audio input tokens present in the prompt. */ audio_tokens?: number; /** * Cached tokens present in the prompt. */ cached_tokens?: number; }; }; /** * Compound Filter * * Combine multiple filters using `and` or `or`. */ export type CompoundFilter = { /** * Type of operation: `and` or `or`. */ type: 'and' | 'or'; /** * Array of filters to combine. Items can be `ComparisonFilter` or `CompoundFilter`. */ filters: Array; }; export type ComputerAction = ({ type?: 'Click'; } & Click) | ({ type?: 'DoubleClick'; } & DoubleClick) | ({ type?: 'Drag'; } & Drag) | ({ type?: 'KeyPress'; } & KeyPress) | ({ type?: 'Move'; } & Move) | ({ type?: 'Screenshot'; } & Screenshot) | ({ type?: 'Scroll'; } & Scroll) | ({ type?: 'Type'; } & Type) | ({ type?: 'Wait'; } & Wait); /** * A computer screenshot image used with the computer use tool. * */ export type ComputerScreenshotImage = { /** * Specifies the event type. For a computer screenshot, this property is * always set to `computer_screenshot`. * */ type: 'computer_screenshot'; /** * The URL of the screenshot image. */ image_url?: string; /** * The identifier of an uploaded file that contains the screenshot. */ file_id?: string; }; /** * Computer tool call * * A tool call to a computer use tool. See the * [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information. * */ export type ComputerToolCall = { /** * The type of the computer call. Always `computer_call`. */ type: 'computer_call'; /** * The unique ID of the computer call. */ id: string; /** * An identifier used when responding to the tool call with output. * */ call_id: string; action: ComputerAction; /** * The pending safety checks for the computer call. * */ pending_safety_checks: Array; /** * The status of the item. One of `in_progress`, `completed`, or * `incomplete`. Populated when items are returned via API. * */ status: 'in_progress' | 'completed' | 'incomplete'; }; /** * Computer tool call output * * The output of a computer tool call. * */ export type ComputerToolCallOutput = { /** * The type of the computer tool call output. Always `computer_call_output`. * */ type: 'computer_call_output'; /** * The ID of the computer tool call output. * */ id?: string; /** * The ID of the computer tool call that produced the output. * */ call_id: string; /** * The safety checks reported by the API that have been acknowledged by the * developer. * */ acknowledged_safety_checks?: Array; output: ComputerScreenshotImage; /** * The status of the message input. One of `in_progress`, `completed`, or * `incomplete`. Populated when input items are returned via API. * */ status?: 'in_progress' | 'completed' | 'incomplete'; }; export type ComputerToolCallOutputResource = ComputerToolCallOutput & { /** * The unique ID of the computer call tool output. * */ id: string; }; /** * A pending safety check for the computer call. * */ export type ComputerToolCallSafetyCheck = { /** * The ID of the pending safety check. */ id: string; /** * The type of the pending safety check. */ code: string; /** * Details about the pending safety check. */ message: string; }; export type ContainerFileListResource = { /** * The type of object returned, must be 'list'. */ object: 'list'; /** * A list of container files. */ data: Array; /** * The ID of the first file in the list. */ first_id: string; /** * The ID of the last file in the list. */ last_id: string; /** * Whether there are more files available. */ has_more: boolean; }; /** * The container file object */ export type ContainerFileResource = { /** * Unique identifier for the file. */ id: string; /** * The type of this object (`container.file`). */ object: 'container.file'; /** * The container this file belongs to. */ container_id: string; /** * Unix timestamp (in seconds) when the file was created. */ created_at: number; /** * Size of the file in bytes. */ bytes: number; /** * Path of the file in the container. */ path: string; /** * Source of the file (e.g., `user`, `assistant`). */ source: string; }; export type ContainerListResource = { /** * The type of object returned, must be 'list'. */ object: 'list'; /** * A list of containers. */ data: Array; /** * The ID of the first container in the list. */ first_id: string; /** * The ID of the last container in the list. */ last_id: string; /** * Whether there are more containers available. */ has_more: boolean; }; /** * The container object */ export type ContainerResource = { /** * Unique identifier for the container. */ id: string; /** * The type of this object. */ object: string; /** * Name of the container. */ name: string; /** * Unix timestamp (in seconds) when the container was created. */ created_at: number; /** * Status of the container (e.g., active, deleted). */ status: string; /** * The container will expire after this time period. * The anchor is the reference point for the expiration. * The minutes is the number of minutes after the anchor before the container expires. * */ expires_after?: { /** * The reference point for the expiration. */ anchor?: 'last_active_at'; /** * The number of minutes after the anchor before the container expires. */ minutes?: number; }; }; /** * Multi-modal input and output contents. * */ export type Content = InputContent | OutputContent; /** * Coordinate * * An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`. * */ export type Coordinate = { /** * The x-coordinate. * */ x: number; /** * The y-coordinate. * */ y: number; }; /** * The aggregated costs details of the specific time bucket. */ export type CostsResult = { object: 'organization.costs.result'; /** * The monetary value in its associated currency. */ amount?: { /** * The numeric value of the cost. */ value?: number; /** * Lowercase ISO-4217 currency e.g. "usd" */ currency?: string; }; /** * When `group_by=line_item`, this field provides the line item of the grouped costs result. */ line_item?: string; /** * When `group_by=project_id`, this field provides the project ID of the grouped costs result. */ project_id?: string; }; export type CreateAssistantRequest = { /** * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. * */ model: string | AssistantSupportedModels; /** * The name of the assistant. The maximum length is 256 characters. * */ name?: string; /** * The description of the assistant. The maximum length is 512 characters. * */ description?: string; /** * The system instructions that the assistant uses. The maximum length is 256,000 characters. * */ instructions?: string; reasoning_effort?: ReasoningEffort; /** * A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. * */ tools?: Array; /** * A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources?: { code_interpreter?: { /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: unknown & { /** * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. * */ vector_store_ids?: Array; /** * A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant. * */ vector_stores?: Array<{ /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. * */ file_ids?: Array; /** * The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. */ chunking_strategy?: { /** * Always `auto`. */ type: 'auto'; } | { /** * Always `static`. */ type: 'static'; static: { /** * The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. */ max_chunk_size_tokens: number; /** * The number of tokens that overlap between chunks. The default value is `400`. * * Note that the overlap must not exceed half of `max_chunk_size_tokens`. * */ chunk_overlap_tokens: number; }; }; metadata?: Metadata; }>; }; }; metadata?: Metadata; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. * */ top_p?: number; response_format?: AssistantsApiResponseFormatOption; }; export type CreateChatCompletionRequest = CreateModelResponseProperties & { /** * A list of messages comprising the conversation so far. Depending on the * [model](https://platform.openai.com/docs/models) you use, different message types (modalities) are * supported, like [text](https://platform.openai.com/docs/guides/text-generation), * [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). * */ messages: Array; /** * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI * offers a wide range of models with different capabilities, performance * characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) * to browse and compare available models. * */ model: ModelIdsShared; modalities?: ResponseModalities; verbosity?: Verbosity; reasoning_effort?: ReasoningEffort; /** * An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). * */ max_completion_tokens?: number; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on * their existing frequency in the text so far, decreasing the model's * likelihood to repeat the same line verbatim. * */ frequency_penalty?: number; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on * whether they appear in the text so far, increasing the model's likelihood * to talk about new topics. * */ presence_penalty?: number; /** * Web search * * This tool searches the web for relevant results to use in a response. * Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). * */ web_search_options?: { /** * Approximate location parameters for the search. * */ user_location?: { /** * The type of location approximation. Always `approximate`. * */ type: 'approximate'; approximate: WebSearchLocation; }; search_context_size?: WebSearchContextSize; }; /** * An integer between 0 and 20 specifying the number of most likely tokens to * return at each token position, each with an associated log probability. * `logprobs` must be set to `true` if this parameter is used. * */ top_logprobs?: number; /** * An object specifying the format that the model must output. * * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables * Structured Outputs which ensures the model will match your supplied JSON * schema. Learn more in the [Structured Outputs * guide](https://platform.openai.com/docs/guides/structured-outputs). * * Setting to `{ "type": "json_object" }` enables the older JSON mode, which * ensures the message the model generates is valid JSON. Using `json_schema` * is preferred for models that support it. * */ response_format?: ResponseFormatText | ResponseFormatJsonSchema | ResponseFormatJsonObject; /** * Parameters for audio output. Required when audio output is requested with * `modalities: ["audio"]`. [Learn more](https://platform.openai.com/docs/guides/audio). * */ audio?: { /** * The voice the model uses to respond. Supported voices are * `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. * */ voice: VoiceIdsShared; /** * Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, * `opus`, or `pcm16`. * */ format: 'wav' | 'aac' | 'mp3' | 'flac' | 'opus' | 'pcm16'; }; /** * Whether or not to store the output of this chat completion request for * use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or * [evals](https://platform.openai.com/docs/guides/evals) products. * * Supports text and image inputs. Note: image inputs over 8MB will be dropped. * */ store?: boolean; /** * If set to true, the model response data will be streamed to the client * as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). * See the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) * for more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) * guide for more information on how to handle the streaming events. * */ stream?: boolean; stop?: StopConfiguration; /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in the * tokenizer) to an associated bias value from -100 to 100. Mathematically, * the bias is added to the logits generated by the model prior to sampling. * The exact effect will vary per model, but values between -1 and 1 should * decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. * */ logit_bias?: { [key: string]: number; }; /** * Whether to return log probabilities of the output tokens or not. If true, * returns the log probabilities of each output token returned in the * `content` of `message`. * */ logprobs?: boolean; /** * The maximum number of [tokens](/tokenizer) that can be generated in the * chat completion. This value can be used to control * [costs](https://openai.com/api/pricing/) for text generated via API. * * This value is now deprecated in favor of `max_completion_tokens`, and is * not compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning). * * * @deprecated */ max_tokens?: number; /** * How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. */ n?: number; /** * Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs), * which can greatly improve response times when large parts of the model * response are known ahead of time. This is most common when you are * regenerating a file with only minor changes to most of the content. * */ prediction?: { type?: 'PredictionContent'; } & PredictionContent; /** * This feature is in Beta. * If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. * Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. * * * @deprecated */ seed?: number; stream_options?: ChatCompletionStreamOptions; /** * A list of tools the model may call. You can provide either * [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or * [function tools](https://platform.openai.com/docs/guides/function-calling). * */ tools?: Array<({ type?: 'ChatCompletionTool'; } & ChatCompletionTool) | ({ type?: 'CustomToolChatCompletions'; } & CustomToolChatCompletions)>; tool_choice?: ChatCompletionToolChoiceOption; parallel_tool_calls?: ParallelToolCalls; /** * Deprecated in favor of `tool_choice`. * * Controls which (if any) function is called by the model. * * `none` means the model will not call a function and instead generates a * message. * * `auto` means the model can pick between generating a message or calling a * function. * * Specifying a particular function via `{"name": "my_function"}` forces the * model to call that function. * * `none` is the default when no functions are present. `auto` is the default * if functions are present. * * * @deprecated */ function_call?: 'none' | 'auto' | ChatCompletionFunctionCallOption; /** * Deprecated in favor of `tools`. * * A list of functions the model may generate JSON inputs for. * * * @deprecated */ functions?: Array; }; /** * Represents a chat completion response returned by model, based on the provided input. */ export type CreateChatCompletionResponse = { /** * A unique identifier for the chat completion. */ id: string; /** * A list of chat completion choices. Can be more than one if `n` is greater than 1. */ choices: Array<{ /** * The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, * `length` if the maximum number of tokens specified in the request was reached, * `content_filter` if content was omitted due to a flag from our content filters, * `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. * */ finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'; /** * The index of the choice in the list of choices. */ index: number; message: ChatCompletionResponseMessage; /** * Log probability information for the choice. */ logprobs: { /** * A list of message content tokens with log probability information. */ content: Array; /** * A list of message refusal tokens with log probability information. */ refusal: Array; }; }>; /** * The Unix timestamp (in seconds) of when the chat completion was created. */ created: number; /** * The model used for the chat completion. */ model: string; service_tier?: ServiceTier; /** * This fingerprint represents the backend configuration that the model runs with. * * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. * * * @deprecated */ system_fingerprint?: string; /** * The object type, which is always `chat.completion`. */ object: 'chat.completion'; usage?: CompletionUsage; }; /** * Represents a streamed chunk of a chat completion response returned * by the model, based on the provided input. * [Learn more](https://platform.openai.com/docs/guides/streaming-responses). * */ export type CreateChatCompletionStreamResponse = { /** * A unique identifier for the chat completion. Each chunk has the same ID. */ id: string; /** * A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the * last chunk if you set `stream_options: {"include_usage": true}`. * */ choices: Array<{ delta: ChatCompletionStreamResponseDelta; /** * Log probability information for the choice. */ logprobs?: { /** * A list of message content tokens with log probability information. */ content: Array; /** * A list of message refusal tokens with log probability information. */ refusal: Array; }; /** * The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, * `length` if the maximum number of tokens specified in the request was reached, * `content_filter` if content was omitted due to a flag from our content filters, * `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. * */ finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'; /** * The index of the choice in the list of choices. */ index: number; }>; /** * The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp. */ created: number; /** * The model to generate the completion. */ model: string; service_tier?: ServiceTier; /** * This fingerprint represents the backend configuration that the model runs with. * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. * * * @deprecated */ system_fingerprint?: string; /** * The object type, which is always `chat.completion.chunk`. */ object: 'chat.completion.chunk'; /** * An optional field that will only be present when you set * `stream_options: {"include_usage": true}` in your request. When present, it * contains a null value **except for the last chunk** which contains the * token usage statistics for the entire request. * * **NOTE:** If the stream is interrupted or cancelled, you may not * receive the final usage chunk which contains the total token usage for * the request. * */ usage?: CompletionUsage; }; export type CreateCompletionRequest = { /** * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. * */ model: string | 'gpt-3.5-turbo-instruct' | 'davinci-002' | 'babbage-002'; /** * The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. * * Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document. * */ prompt: string | Array | Array | Array>; /** * Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed. * * When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. * * **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. * */ best_of?: number; /** * Echo back the prompt in addition to the completion * */ echo?: boolean; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. * * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) * */ frequency_penalty?: number; /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. * * As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. * */ logit_bias?: { [key: string]: number; }; /** * Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. * * The maximum value for `logprobs` is 5. * */ logprobs?: number; /** * The maximum number of [tokens](/tokenizer) that can be generated in the completion. * * The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. * */ max_tokens?: number; /** * How many completions to generate for each prompt. * * **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. * */ n?: number; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. * * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) * */ presence_penalty?: number; /** * If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. * * Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. * */ seed?: number; stop?: StopConfiguration; /** * Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). * */ stream?: boolean; stream_options?: ChatCompletionStreamOptions; /** * The suffix that comes after a completion of inserted text. * * This parameter is only supported for `gpt-3.5-turbo-instruct`. * */ suffix?: string; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * * We generally recommend altering this or `top_p` but not both. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or `temperature` but not both. * */ top_p?: number; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). * */ user?: string; }; /** * Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint). * */ export type CreateCompletionResponse = { /** * A unique identifier for the completion. */ id: string; /** * The list of completion choices the model generated for the input prompt. */ choices: Array<{ /** * The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, * `length` if the maximum number of tokens specified in the request was reached, * or `content_filter` if content was omitted due to a flag from our content filters. * */ finish_reason: 'stop' | 'length' | 'content_filter'; index: number; logprobs: { text_offset?: Array; token_logprobs?: Array; tokens?: Array; top_logprobs?: Array<{ [key: string]: number; }>; }; text: string; }>; /** * The Unix timestamp (in seconds) of when the completion was created. */ created: number; /** * The model used for completion. */ model: string; /** * This fingerprint represents the backend configuration that the model runs with. * * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. * */ system_fingerprint?: string; /** * The object type, which is always "text_completion" */ object: 'text_completion'; usage?: CompletionUsage; }; export type CreateContainerBody = { /** * Name of the container to create. */ name: string; /** * IDs of files to copy to the container. */ file_ids?: Array; /** * Container expiration time in seconds relative to the 'anchor' time. */ expires_after?: { /** * Time anchor for the expiration time. Currently only 'last_active_at' is supported. */ anchor: 'last_active_at'; minutes: number; }; }; export type CreateContainerFileBody = { /** * Name of the file to create. */ file_id?: string; /** * The File object (not file name) to be uploaded. * */ file?: Blob | File; }; export type CreateEmbeddingRequest = { /** * Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request. * */ input: string | Array | Array | Array>; /** * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. * */ model: string | 'text-embedding-ada-002' | 'text-embedding-3-small' | 'text-embedding-3-large'; /** * The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/). */ encoding_format?: 'float' | 'base64'; /** * The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. * */ dimensions?: number; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). * */ user?: string; }; export type CreateEmbeddingResponse = { /** * The list of embeddings generated by the model. */ data: Array; /** * The name of the model used to generate the embedding. */ model: string; /** * The object type, which is always "list". */ object: 'list'; /** * The usage information for the request. */ usage: { /** * The number of tokens used by the prompt. */ prompt_tokens: number; /** * The total number of tokens used by the request. */ total_tokens: number; }; }; /** * CompletionsRunDataSource * * A CompletionsRunDataSource object describing a model sampling configuration. * */ export type CreateEvalCompletionsRunDataSource = { /** * The type of run data source. Always `completions`. */ type: 'completions'; /** * Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace. */ input_messages?: { /** * The type of input messages. Always `template`. */ type: 'template'; /** * A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. */ template: Array<({ type?: 'EasyInputMessage'; } & EasyInputMessage) | ({ type?: 'EvalItem'; } & EvalItem)>; } | { /** * The type of input messages. Always `item_reference`. */ type: 'item_reference'; /** * A reference to a variable in the `item` namespace. Ie, "item.input_trajectory" */ item_reference: string; }; sampling_params?: { /** * A higher temperature increases randomness in the outputs. */ temperature?: number; /** * The maximum number of tokens in the generated output. */ max_completion_tokens?: number; /** * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. */ top_p?: number; /** * A seed value to initialize the randomness, during sampling. */ seed?: number; /** * An object specifying the format that the model must output. * * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables * Structured Outputs which ensures the model will match your supplied JSON * schema. Learn more in the [Structured Outputs * guide](https://platform.openai.com/docs/guides/structured-outputs). * * Setting to `{ "type": "json_object" }` enables the older JSON mode, which * ensures the message the model generates is valid JSON. Using `json_schema` * is preferred for models that support it. * */ response_format?: ResponseFormatText | ResponseFormatJsonSchema | ResponseFormatJsonObject; /** * A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. * */ tools?: Array; }; /** * The name of the model to use for generating completions (e.g. "o3-mini"). */ model?: string; /** * Determines what populates the `item` namespace in this run's data source. */ source: ({ type?: 'EvalJsonlFileContentSource'; } & EvalJsonlFileContentSource) | ({ type?: 'EvalJsonlFileIdSource'; } & EvalJsonlFileIdSource) | ({ type?: 'EvalStoredCompletionsSource'; } & EvalStoredCompletionsSource); }; /** * CustomDataSourceConfig * * A CustomDataSourceConfig object that defines the schema for the data source used for the evaluation runs. * This schema is used to define the shape of the data that will be: * - Used to define your testing criteria and * - What data is required when creating a run * */ export type CreateEvalCustomDataSourceConfig = { /** * The type of data source. Always `custom`. */ type: 'custom'; /** * The json schema for each row in the data source. */ item_schema: { [key: string]: unknown; }; /** * Whether the eval should expect you to populate the sample namespace (ie, by generating responses off of your data source) */ include_sample_schema?: boolean; }; /** * CreateEvalItem * * A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. */ export type CreateEvalItem = { /** * The role of the message (e.g. "system", "assistant", "user"). */ role: string; /** * The content of the message. */ content: string; } | EvalItem; /** * JsonlRunDataSource * * A JsonlRunDataSource object with that specifies a JSONL file that matches the eval * */ export type CreateEvalJsonlRunDataSource = { /** * The type of data source. Always `jsonl`. */ type: 'jsonl'; /** * Determines what populates the `item` namespace in the data source. */ source: ({ type?: 'EvalJsonlFileContentSource'; } & EvalJsonlFileContentSource) | ({ type?: 'EvalJsonlFileIdSource'; } & EvalJsonlFileIdSource); }; /** * LabelModelGrader * * A LabelModelGrader object which uses a model to assign labels to each item * in the evaluation. * */ export type CreateEvalLabelModelGrader = { /** * The object type, which is always `label_model`. */ type: 'label_model'; /** * The name of the grader. */ name: string; /** * The model to use for the evaluation. Must support structured outputs. */ model: string; /** * A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. */ input: Array; /** * The labels to classify to each item in the evaluation. */ labels: Array; /** * The labels that indicate a passing result. Must be a subset of labels. */ passing_labels: Array; }; /** * LogsDataSourceConfig * * A data source config which specifies the metadata property of your logs query. * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. * */ export type CreateEvalLogsDataSourceConfig = { /** * The type of data source. Always `logs`. */ type: 'logs'; /** * Metadata filters for the logs data source. */ metadata?: { [key: string]: unknown; }; }; /** * CreateEvalRequest */ export type CreateEvalRequest = { /** * The name of the evaluation. */ name?: string; metadata?: Metadata; /** * The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation. */ data_source_config: ({ type?: 'CreateEvalCustomDataSourceConfig'; } & CreateEvalCustomDataSourceConfig) | ({ type?: 'CreateEvalLogsDataSourceConfig'; } & CreateEvalLogsDataSourceConfig) | ({ type?: 'CreateEvalStoredCompletionsDataSourceConfig'; } & CreateEvalStoredCompletionsDataSourceConfig); /** * A list of graders for all eval runs in this group. Graders can reference variables in the data source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's output, use the `sample` namespace (ie, `{{sample.output_text}}`). */ testing_criteria: Array<({ type?: 'CreateEvalLabelModelGrader'; } & CreateEvalLabelModelGrader) | ({ type?: 'EvalGraderStringCheck'; } & EvalGraderStringCheck) | ({ type?: 'EvalGraderTextSimilarity'; } & EvalGraderTextSimilarity) | ({ type?: 'EvalGraderPython'; } & EvalGraderPython) | ({ type?: 'EvalGraderScoreModel'; } & EvalGraderScoreModel)>; }; /** * ResponsesRunDataSource * * A ResponsesRunDataSource object describing a model sampling configuration. * */ export type CreateEvalResponsesRunDataSource = { /** * The type of run data source. Always `responses`. */ type: 'responses'; /** * Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace. */ input_messages?: { /** * The type of input messages. Always `template`. */ type: 'template'; /** * A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. */ template: Array<{ /** * The role of the message (e.g. "system", "assistant", "user"). */ role: string; /** * The content of the message. */ content: string; } | EvalItem>; } | { /** * The type of input messages. Always `item_reference`. */ type: 'item_reference'; /** * A reference to a variable in the `item` namespace. Ie, "item.name" */ item_reference: string; }; sampling_params?: { /** * A higher temperature increases randomness in the outputs. */ temperature?: number; /** * The maximum number of tokens in the generated output. */ max_completion_tokens?: number; /** * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. */ top_p?: number; /** * A seed value to initialize the randomness, during sampling. */ seed?: number; /** * An array of tools the model may call while generating a response. You * can specify which tool to use by setting the `tool_choice` parameter. * * The two categories of tools you can provide the model are: * * - **Built-in tools**: Tools that are provided by OpenAI that extend the * model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) * or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about * [built-in tools](https://platform.openai.com/docs/guides/tools). * - **Function calls (custom tools)**: Functions that are defined by you, * enabling the model to call your own code. Learn more about * [function calling](https://platform.openai.com/docs/guides/function-calling). * */ tools?: Array; /** * Configuration options for a text response from the model. Can be plain * text or structured JSON data. Learn more: * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) * */ text?: { format?: TextResponseFormatConfiguration; }; }; /** * The name of the model to use for generating completions (e.g. "o3-mini"). */ model?: string; /** * Determines what populates the `item` namespace in this run's data source. */ source: ({ type?: 'EvalJsonlFileContentSource'; } & EvalJsonlFileContentSource) | ({ type?: 'EvalJsonlFileIdSource'; } & EvalJsonlFileIdSource) | ({ type?: 'EvalResponsesSource'; } & EvalResponsesSource); }; /** * CreateEvalRunRequest */ export type CreateEvalRunRequest = { /** * The name of the run. */ name?: string; metadata?: Metadata; /** * Details about the run's data source. */ data_source: CreateEvalJsonlRunDataSource | CreateEvalCompletionsRunDataSource | CreateEvalResponsesRunDataSource; }; /** * StoredCompletionsDataSourceConfig * * Deprecated in favor of LogsDataSourceConfig. * * * @deprecated */ export type CreateEvalStoredCompletionsDataSourceConfig = { /** * The type of data source. Always `stored_completions`. */ type: 'stored_completions'; /** * Metadata filters for the stored completions data source. */ metadata?: { [key: string]: unknown; }; }; export type CreateFileRequest = { /** * The File object (not file name) to be uploaded. * */ file: Blob | File; purpose: FilePurpose; expires_after?: FileExpirationAfter; }; export type CreateFineTuningCheckpointPermissionRequest = { /** * The project identifiers to grant access to. */ project_ids: Array; }; export type CreateFineTuningJobRequest = { /** * The name of the model to fine-tune. You can select one of the * [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). * */ model: string | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo' | 'gpt-4o-mini'; /** * The ID of an uploaded file that contains training data. * * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. * * Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. * * The contents of the file should differ depending on if the model uses the [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) format, or if the fine-tuning method uses the [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format. * * See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details. * */ training_file: string; /** * The hyperparameters used for the fine-tuning job. * This value is now deprecated in favor of `method`, and should be passed in under the `method` parameter. * * * @deprecated */ hyperparameters?: { /** * Number of examples in each batch. A larger batch size means that model parameters * are updated less frequently, but with lower variance. * */ batch_size?: 'auto' | number; /** * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid * overfitting. * */ learning_rate_multiplier?: 'auto' | number; /** * The number of epochs to train the model for. An epoch refers to one full cycle * through the training dataset. * */ n_epochs?: 'auto' | number; }; /** * A string of up to 64 characters that will be added to your fine-tuned model name. * * For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. * */ suffix?: string; /** * The ID of an uploaded file that contains validation data. * * If you provide this file, the data is used to generate validation * metrics periodically during fine-tuning. These metrics can be viewed in * the fine-tuning results file. * The same data should not be present in both train and validation files. * * Your dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`. * * See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details. * */ validation_file?: string; /** * A list of integrations to enable for your fine-tuning job. */ integrations?: Array<{ /** * The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported. * */ type: 'wandb'; /** * The settings for your integration with Weights and Biases. This payload specifies the project that * metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags * to your run, and set a default entity (team, username, etc) to be associated with your run. * */ wandb: { /** * The name of the project that the new run will be created under. * */ project: string; /** * A display name to set for the run. If not set, we will use the Job ID as the name. * */ name?: string; /** * The entity to use for the run. This allows you to set the team or username of the WandB user that you would * like associated with the run. If not set, the default entity for the registered WandB API key is used. * */ entity?: string; /** * A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some * default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". * */ tags?: Array; }; }>; /** * The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. * If a seed is not specified, one will be generated for you. * */ seed?: number; method?: FineTuneMethod; metadata?: Metadata; }; export type CreateImageEditRequest = { /** * The image(s) to edit. Must be a supported image file or an array of images. * * For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less * than 50MB. You can provide up to 16 images. * * For `dall-e-2`, you can only provide one image, and it should be a square * `png` file less than 4MB. * */ image: Blob | File | Array; /** * A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. */ prompt: string; /** * An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. */ mask?: Blob | File; /** * Allows to set transparency for the background of the generated image(s). * This parameter is only supported for `gpt-image-1`. Must be one of * `transparent`, `opaque` or `auto` (default value). When `auto` is used, the * model will automatically determine the best background for the image. * * If `transparent`, the output format needs to support transparency, so it * should be set to either `png` (default value) or `webp`. * */ background?: 'transparent' | 'opaque' | 'auto'; /** * The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used. */ model?: string | 'dall-e-2' | 'gpt-image-1'; /** * The number of images to generate. Must be between 1 and 10. */ n?: number; /** * The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. */ size?: '256x256' | '512x512' | '1024x1024' | '1536x1024' | '1024x1536' | 'auto'; /** * The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images. */ response_format?: 'url' | 'b64_json'; /** * The format in which the generated images are returned. This parameter is * only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. * The default value is `png`. * */ output_format?: 'png' | 'jpeg' | 'webp'; /** * The compression level (0-100%) for the generated images. This parameter * is only supported for `gpt-image-1` with the `webp` or `jpeg` output * formats, and defaults to 100. * */ output_compression?: number; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). * */ user?: string; input_fidelity?: ImageInputFidelity; /** * Edit the image in streaming mode. Defaults to `false`. See the * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information. * */ stream?: boolean; partial_images?: PartialImages; /** * The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`. * */ quality?: 'standard' | 'low' | 'medium' | 'high' | 'auto'; }; export type CreateImageRequest = { /** * A text description of the desired image(s). The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`. */ prompt: string; /** * The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used. */ model?: string | 'dall-e-2' | 'dall-e-3' | 'gpt-image-1'; /** * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. */ n?: number; /** * The quality of the image that will be generated. * * - `auto` (default value) will automatically select the best quality for the given model. * - `high`, `medium` and `low` are supported for `gpt-image-1`. * - `hd` and `standard` are supported for `dall-e-3`. * - `standard` is the only option for `dall-e-2`. * */ quality?: 'standard' | 'hd' | 'low' | 'medium' | 'high' | 'auto'; /** * The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for `gpt-image-1` which will always return base64-encoded images. */ response_format?: 'url' | 'b64_json'; /** * The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. */ output_format?: 'png' | 'jpeg' | 'webp'; /** * The compression level (0-100%) for the generated images. This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100. */ output_compression?: number; /** * Generate the image in streaming mode. Defaults to `false`. See the * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information. * This parameter is only supported for `gpt-image-1`. * */ stream?: boolean; partial_images?: PartialImages; /** * The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. */ size?: 'auto' | '1024x1024' | '1536x1024' | '1024x1536' | '256x256' | '512x512' | '1792x1024' | '1024x1792'; /** * Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` for less restrictive filtering or `auto` (default value). */ moderation?: 'low' | 'auto'; /** * Allows to set transparency for the background of the generated image(s). * This parameter is only supported for `gpt-image-1`. Must be one of * `transparent`, `opaque` or `auto` (default value). When `auto` is used, the * model will automatically determine the best background for the image. * * If `transparent`, the output format needs to support transparency, so it * should be set to either `png` (default value) or `webp`. * */ background?: 'transparent' | 'opaque' | 'auto'; /** * The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. */ style?: 'vivid' | 'natural'; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). * */ user?: string; }; export type CreateImageVariationRequest = { /** * The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. */ image: Blob | File; /** * The model to use for image generation. Only `dall-e-2` is supported at this time. */ model?: string | 'dall-e-2'; /** * The number of images to generate. Must be between 1 and 10. */ n?: number; /** * The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. */ response_format?: 'url' | 'b64_json'; /** * The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. */ size?: '256x256' | '512x512' | '1024x1024'; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). * */ user?: string; }; export type CreateMessageRequest = { /** * The role of the entity that is creating the message. Allowed values include: * - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. * - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. * */ role: 'user' | 'assistant'; content: string | Array<({ type?: 'MessageContentImageFileObject'; } & MessageContentImageFileObject) | ({ type?: 'MessageContentImageUrlObject'; } & MessageContentImageUrlObject) | ({ type?: 'MessageRequestContentTextObject'; } & MessageRequestContentTextObject)>; /** * A list of files attached to the message, and the tools they should be added to. */ attachments?: Array<{ /** * The ID of the file to attach to the message. */ file_id?: string; /** * The tools to add this file to. */ tools?: Array<({ type?: 'AssistantToolsCode'; } & AssistantToolsCode) | ({ type?: 'AssistantToolsFileSearchTypeOnly'; } & AssistantToolsFileSearchTypeOnly)>; }>; metadata?: Metadata; }; export type CreateModelResponseProperties = ModelResponseProperties & { /** * An integer between 0 and 20 specifying the number of most likely tokens to * return at each token position, each with an associated log probability. * */ top_logprobs?: number; }; export type CreateModerationRequest = { /** * Input (or inputs) to classify. Can be a single string, an array of strings, or * an array of multi-modal input objects similar to other models. * */ input: string | Array | Array<({ type?: 'ModerationImageURLInput'; } & ModerationImageUrlInput) | ({ type?: 'ModerationTextInput'; } & ModerationTextInput)>; /** * The content moderation model you would like to use. Learn more in * [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about * available models [here](https://platform.openai.com/docs/models#moderation). * */ model?: string | 'omni-moderation-latest' | 'omni-moderation-2024-09-26' | 'text-moderation-latest' | 'text-moderation-stable'; }; /** * Represents if a given text input is potentially harmful. */ export type CreateModerationResponse = { /** * The unique identifier for the moderation request. */ id: string; /** * The model used to generate the moderation results. */ model: string; /** * A list of moderation objects. */ results: Array<{ /** * Whether any of the below categories are flagged. */ flagged: boolean; /** * A list of the categories, and whether they are flagged or not. */ categories: { /** * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment. */ hate: boolean; /** * Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. */ 'hate/threatening': boolean; /** * Content that expresses, incites, or promotes harassing language towards any target. */ harassment: boolean; /** * Harassment content that also includes violence or serious harm towards any target. */ 'harassment/threatening': boolean; /** * Content that includes instructions or advice that facilitate the planning or execution of wrongdoing, or that gives advice or instruction on how to commit illicit acts. For example, "how to shoplift" would fit this category. */ illicit: boolean; /** * Content that includes instructions or advice that facilitate the planning or execution of wrongdoing that also includes violence, or that gives advice or instruction on the procurement of any weapon. */ 'illicit/violent': boolean; /** * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders. */ 'self-harm': boolean; /** * Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders. */ 'self-harm/intent': boolean; /** * Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts. */ 'self-harm/instructions': boolean; /** * Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness). */ sexual: boolean; /** * Sexual content that includes an individual who is under 18 years old. */ 'sexual/minors': boolean; /** * Content that depicts death, violence, or physical injury. */ violence: boolean; /** * Content that depicts death, violence, or physical injury in graphic detail. */ 'violence/graphic': boolean; }; /** * A list of the categories along with their scores as predicted by model. */ category_scores: { /** * The score for the category 'hate'. */ hate: number; /** * The score for the category 'hate/threatening'. */ 'hate/threatening': number; /** * The score for the category 'harassment'. */ harassment: number; /** * The score for the category 'harassment/threatening'. */ 'harassment/threatening': number; /** * The score for the category 'illicit'. */ illicit: number; /** * The score for the category 'illicit/violent'. */ 'illicit/violent': number; /** * The score for the category 'self-harm'. */ 'self-harm': number; /** * The score for the category 'self-harm/intent'. */ 'self-harm/intent': number; /** * The score for the category 'self-harm/instructions'. */ 'self-harm/instructions': number; /** * The score for the category 'sexual'. */ sexual: number; /** * The score for the category 'sexual/minors'. */ 'sexual/minors': number; /** * The score for the category 'violence'. */ violence: number; /** * The score for the category 'violence/graphic'. */ 'violence/graphic': number; }; /** * A list of the categories along with the input type(s) that the score applies to. */ category_applied_input_types: { /** * The applied input type(s) for the category 'hate'. */ hate: Array<'text'>; /** * The applied input type(s) for the category 'hate/threatening'. */ 'hate/threatening': Array<'text'>; /** * The applied input type(s) for the category 'harassment'. */ harassment: Array<'text'>; /** * The applied input type(s) for the category 'harassment/threatening'. */ 'harassment/threatening': Array<'text'>; /** * The applied input type(s) for the category 'illicit'. */ illicit: Array<'text'>; /** * The applied input type(s) for the category 'illicit/violent'. */ 'illicit/violent': Array<'text'>; /** * The applied input type(s) for the category 'self-harm'. */ 'self-harm': Array<'text' | 'image'>; /** * The applied input type(s) for the category 'self-harm/intent'. */ 'self-harm/intent': Array<'text' | 'image'>; /** * The applied input type(s) for the category 'self-harm/instructions'. */ 'self-harm/instructions': Array<'text' | 'image'>; /** * The applied input type(s) for the category 'sexual'. */ sexual: Array<'text' | 'image'>; /** * The applied input type(s) for the category 'sexual/minors'. */ 'sexual/minors': Array<'text'>; /** * The applied input type(s) for the category 'violence'. */ violence: Array<'text' | 'image'>; /** * The applied input type(s) for the category 'violence/graphic'. */ 'violence/graphic': Array<'text' | 'image'>; }; }>; }; export type CreateResponse = CreateModelResponseProperties & ResponseProperties & { /** * Text, image, or file inputs to the model, used to generate a response. * * Learn more: * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) * - [Image inputs](https://platform.openai.com/docs/guides/images) * - [File inputs](https://platform.openai.com/docs/guides/pdf-files) * - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) * - [Function calling](https://platform.openai.com/docs/guides/function-calling) * */ input?: string | Array; /** * Specify additional output data to include in the model response. Currently * supported values are: * - `code_interpreter_call.outputs`: Includes the outputs of python code execution * in code interpreter tool call items. * - `computer_call_output.output.image_url`: Include image urls from the computer call output. * - `file_search_call.results`: Include the search results of * the file search tool call. * - `message.input_image.image_url`: Include image urls from the input message. * - `message.output_text.logprobs`: Include logprobs with assistant messages. * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning * tokens in reasoning item outputs. This enables reasoning items to be used in * multi-turn conversations when using the Responses API statelessly (like * when the `store` parameter is set to `false`, or when an organization is * enrolled in the zero data retention program). * */ include?: Array; /** * Whether to allow the model to run tool calls in parallel. * */ parallel_tool_calls?: boolean; /** * Whether to store the generated model response for later retrieval via * API. * */ store?: boolean; /** * A system (or developer) message inserted into the model's context. * * When using along with `previous_response_id`, the instructions from a previous * response will not be carried over to the next response. This makes it simple * to swap out system (or developer) messages in new responses. * */ instructions?: string; /** * If set to true, the model response data will be streamed to the client * as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). * See the [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) * for more information. * */ stream?: boolean; stream_options?: ResponseStreamOptions; }; export type CreateRunRequest = { /** * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. */ assistant_id: string; /** * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. */ model?: string | AssistantSupportedModels; reasoning_effort?: ReasoningEffort; /** * Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. */ instructions?: string; /** * Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. */ additional_instructions?: string; /** * Adds additional messages to the thread before creating the run. */ additional_messages?: Array; /** * Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. */ tools?: Array; metadata?: Metadata; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. * */ top_p?: number; /** * If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. * */ stream?: boolean; /** * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_prompt_tokens?: number; /** * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_completion_tokens?: number; truncation_strategy?: TruncationObject & unknown; tool_choice?: AssistantsApiToolChoiceOption & unknown; parallel_tool_calls?: ParallelToolCalls; response_format?: AssistantsApiResponseFormatOption; }; export type CreateSpeechRequest = { /** * One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. * */ model: string | 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts'; /** * The text to generate audio for. The maximum length is 4096 characters. */ input: string; /** * Control the voice of your generated audio with additional instructions. Does not work with `tts-1` or `tts-1-hd`. */ instructions?: string; /** * The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). */ voice: VoiceIdsShared; /** * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. */ response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'; /** * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default. */ speed?: number; /** * The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`. */ stream_format?: 'sse' | 'audio'; }; export type CreateSpeechResponseStreamEvent = ({ type?: 'SpeechAudioDeltaEvent'; } & SpeechAudioDeltaEvent) | ({ type?: 'SpeechAudioDoneEvent'; } & SpeechAudioDoneEvent); export type CreateThreadAndRunRequest = { /** * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. */ assistant_id: string; thread?: CreateThreadRequest; /** * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. */ model?: string | 'gpt-5' | 'gpt-5-mini' | 'gpt-5-nano' | 'gpt-5-2025-08-07' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano-2025-08-07' | 'gpt-4.1' | 'gpt-4.1-mini' | 'gpt-4.1-nano' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-11-20' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-05-13' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613'; /** * Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. */ instructions?: string; /** * Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. */ tools?: Array; /** * A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources?: { code_interpreter?: { /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: { /** * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. * */ vector_store_ids?: Array; }; }; metadata?: Metadata; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. * */ top_p?: number; /** * If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. * */ stream?: boolean; /** * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_prompt_tokens?: number; /** * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_completion_tokens?: number; truncation_strategy?: TruncationObject & unknown; tool_choice?: AssistantsApiToolChoiceOption & unknown; parallel_tool_calls?: ParallelToolCalls; response_format?: AssistantsApiResponseFormatOption; }; /** * Options to create a new thread. If no thread is provided when running a * request, an empty thread will be created. * */ export type CreateThreadRequest = { /** * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with. */ messages?: Array; /** * A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources?: { code_interpreter?: { /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: unknown & { /** * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. * */ vector_store_ids?: Array; /** * A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread. * */ vector_stores?: Array<{ /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. * */ file_ids?: Array; /** * The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. */ chunking_strategy?: { /** * Always `auto`. */ type: 'auto'; } | { /** * Always `static`. */ type: 'static'; static: { /** * The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. */ max_chunk_size_tokens: number; /** * The number of tokens that overlap between chunks. The default value is `400`. * * Note that the overlap must not exceed half of `max_chunk_size_tokens`. * */ chunk_overlap_tokens: number; }; }; metadata?: Metadata; }>; }; }; metadata?: Metadata; }; export type CreateTranscriptionRequest = { /** * The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. * */ file: Blob | File; /** * ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source Whisper V2 model). * */ model: string | 'whisper-1' | 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe'; /** * The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency. * */ language?: string; /** * An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language. * */ prompt?: string; response_format?: AudioResponseFormat; /** * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * */ temperature?: number; /** * If set to true, the model response data will be streamed to the client * as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). * See the [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) * for more information. * * Note: Streaming is not supported for the `whisper-1` model and will be ignored. * */ stream?: boolean; chunking_strategy?: TranscriptionChunkingStrategy; /** * The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. * */ timestamp_granularities?: Array<'word' | 'segment'>; /** * Additional information to include in the transcription response. * `logprobs` will return the log probabilities of the tokens in the * response to understand the model's confidence in the transcription. * `logprobs` only works with response_format set to `json` and only with * the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`. * */ include?: Array; }; /** * Represents a transcription response returned by model, based on the provided input. */ export type CreateTranscriptionResponseJson = { /** * The transcribed text. */ text: string; /** * The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array. * */ logprobs?: Array<{ /** * The token in the transcription. */ token?: string; /** * The log probability of the token. */ logprob?: number; /** * The bytes of the token. */ bytes?: Array; }>; /** * Token usage statistics for the request. */ usage?: ({ type?: 'TranscriptTextUsageTokens'; } & TranscriptTextUsageTokens) | ({ type?: 'TranscriptTextUsageDuration'; } & TranscriptTextUsageDuration); }; export type CreateTranscriptionResponseStreamEvent = ({ type?: 'TranscriptTextDeltaEvent'; } & TranscriptTextDeltaEvent) | ({ type?: 'TranscriptTextDoneEvent'; } & TranscriptTextDoneEvent); /** * Represents a verbose json transcription response returned by model, based on the provided input. */ export type CreateTranscriptionResponseVerboseJson = { /** * The language of the input audio. */ language: string; /** * The duration of the input audio. */ duration: number; /** * The transcribed text. */ text: string; /** * Extracted words and their corresponding timestamps. */ words?: Array; /** * Segments of the transcribed text and their corresponding details. */ segments?: Array; usage?: TranscriptTextUsageDuration; }; export type CreateTranslationRequest = { /** * The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. * */ file: Blob | File; /** * ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. * */ model: string | 'whisper-1'; /** * An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should be in English. * */ prompt?: string; /** * The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. * */ response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; /** * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * */ temperature?: number; }; export type CreateTranslationResponseJson = { text: string; }; export type CreateTranslationResponseVerboseJson = { /** * The language of the output translation (always `english`). */ language: string; /** * The duration of the input audio. */ duration: number; /** * The translated text. */ text: string; /** * Segments of the translated text and their corresponding details. */ segments?: Array; }; export type CreateUploadRequest = { /** * The name of the file to upload. * */ filename: string; /** * The intended purpose of the uploaded file. * * See the [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). * */ purpose: 'assistants' | 'batch' | 'fine-tune' | 'vision'; /** * The number of bytes in the file you are uploading. * */ bytes: number; /** * The MIME type of the file. * * This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. * */ mime_type: string; expires_after?: FileExpirationAfter; }; export type CreateVectorStoreFileBatchRequest = { /** * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. */ file_ids: Array; chunking_strategy?: ChunkingStrategyRequestParam; attributes?: VectorStoreFileAttributes; }; export type CreateVectorStoreFileRequest = { /** * A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. */ file_id: string; chunking_strategy?: ChunkingStrategyRequestParam; attributes?: VectorStoreFileAttributes; }; export type CreateVectorStoreRequest = { /** * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. */ file_ids?: Array; /** * The name of the vector store. */ name?: string; expires_after?: VectorStoreExpirationAfter; chunking_strategy?: ChunkingStrategyRequestParam; metadata?: Metadata; }; /** * Custom tool * * A custom tool that processes input using a specified format. Learn more about * [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools). * */ export type CustomTool = { /** * The type of the custom tool. Always `custom`. */ type: 'custom'; /** * The name of the custom tool, used to identify it in tool calls. */ name: string; /** * Optional description of the custom tool, used to provide more context. * */ description?: string; /** * The input format for the custom tool. Default is unconstrained text. * */ format?: { /** * Unconstrained text format. Always `text`. */ type: 'text'; } | { /** * Grammar format. Always `grammar`. */ type: 'grammar'; /** * The grammar definition. */ definition: string; /** * The syntax of the grammar definition. One of `lark` or `regex`. */ syntax: 'lark' | 'regex'; }; }; /** * Custom tool call * * A call to a custom tool created by the model. * */ export type CustomToolCall = { /** * The type of the custom tool call. Always `custom_tool_call`. * */ type: 'custom_tool_call'; /** * The unique ID of the custom tool call in the OpenAI platform. * */ id?: string; /** * An identifier used to map this custom tool call to a tool call output. * */ call_id: string; /** * The name of the custom tool being called. * */ name: string; /** * The input for the custom tool call generated by the model. * */ input: string; }; /** * Custom tool call output * * The output of a custom tool call from your code, being sent back to the model. * */ export type CustomToolCallOutput = { /** * The type of the custom tool call output. Always `custom_tool_call_output`. * */ type: 'custom_tool_call_output'; /** * The unique ID of the custom tool call output in the OpenAI platform. * */ id?: string; /** * The call ID, used to map this custom tool call output to a custom tool call. * */ call_id: string; /** * The output from the custom tool call generated by your code. * */ output: string; }; /** * Custom tool * * A custom tool that processes input using a specified format. * */ export type CustomToolChatCompletions = { /** * The type of the custom tool. Always `custom`. */ type: 'custom'; /** * Custom tool properties * * Properties of the custom tool. * */ custom: { /** * The name of the custom tool, used to identify it in tool calls. */ name: string; /** * Optional description of the custom tool, used to provide more context. * */ description?: string; /** * The input format for the custom tool. Default is unconstrained text. * */ format?: { /** * Unconstrained text format. Always `text`. */ type: 'text'; } | { /** * Grammar format. Always `grammar`. */ type: 'grammar'; /** * Grammar format * * Your chosen grammar. */ grammar: { /** * The grammar definition. */ definition: string; /** * The syntax of the grammar definition. One of `lark` or `regex`. */ syntax: 'lark' | 'regex'; }; }; }; }; export type DeleteAssistantResponse = { id: string; deleted: boolean; object: 'assistant.deleted'; }; export type DeleteCertificateResponse = { /** * The object type, must be `certificate.deleted`. */ object: 'certificate.deleted'; /** * The ID of the certificate that was deleted. */ id: string; }; export type DeleteFileResponse = { id: string; object: 'file'; deleted: boolean; }; export type DeleteFineTuningCheckpointPermissionResponse = { /** * The ID of the fine-tuned model checkpoint permission that was deleted. */ id: string; /** * The object type, which is always "checkpoint.permission". */ object: 'checkpoint.permission'; /** * Whether the fine-tuned model checkpoint permission was successfully deleted. */ deleted: boolean; }; export type DeleteMessageResponse = { id: string; deleted: boolean; object: 'thread.message.deleted'; }; export type DeleteModelResponse = { id: string; deleted: boolean; object: string; }; export type DeleteThreadResponse = { id: string; deleted: boolean; object: 'thread.deleted'; }; export type DeleteVectorStoreFileResponse = { id: string; deleted: boolean; object: 'vector_store.file.deleted'; }; export type DeleteVectorStoreResponse = { id: string; deleted: boolean; object: 'vector_store.deleted'; }; /** * Occurs when a stream ends. */ export type DoneEvent = { event: 'done'; data: '[DONE]'; }; /** * DoubleClick * * A double click action. * */ export type DoubleClick = { /** * Specifies the event type. For a double click action, this property is * always set to `double_click`. * */ type: 'double_click'; /** * The x-coordinate where the double click occurred. * */ x: number; /** * The y-coordinate where the double click occurred. * */ y: number; }; /** * Drag * * A drag action. * */ export type Drag = { /** * Specifies the event type. For a drag action, this property is * always set to `drag`. * */ type: 'drag'; /** * An array of coordinates representing the path of the drag action. Coordinates will appear as an array * of objects, eg * ``` * [ * { x: 100, y: 200 }, * { x: 200, y: 300 } * ] * ``` * */ path: Array; }; /** * Input message * * A message input to the model with a role indicating instruction following * hierarchy. Instructions given with the `developer` or `system` role take * precedence over instructions given with the `user` role. Messages with the * `assistant` role are presumed to have been generated by the model in previous * interactions. * */ export type EasyInputMessage = { /** * The role of the message input. One of `user`, `assistant`, `system`, or * `developer`. * */ role: 'user' | 'assistant' | 'system' | 'developer'; /** * Text, image, or audio input to the model, used to generate a response. * Can also contain previous assistant responses. * */ content: string | InputMessageContentList; /** * The type of the message input. Always `message`. * */ type?: 'message'; }; /** * Represents an embedding vector returned by embedding endpoint. * */ export type Embedding = { /** * The index of the embedding in the list of embeddings. */ index: number; /** * The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](https://platform.openai.com/docs/guides/embeddings). * */ embedding: Array; /** * The object type, which is always "embedding". */ object: 'embedding'; }; export type Error = { code: string; message: string; param: string; type: string; }; /** * Occurs when an [error](https://platform.openai.com/docs/guides/error-codes#api-errors) occurs. This can happen due to an internal server error or a timeout. */ export type ErrorEvent = { event: 'error'; data: Error; }; export type ErrorResponse = { error: Error; }; /** * Eval * * An Eval object with a data source config and testing criteria. * An Eval represents a task to be done for your LLM integration. * Like: * - Improve the quality of my chatbot * - See how well my chatbot handles customer support * - Check if o4-mini is better at my usecase than gpt-4o * */ export type Eval = { /** * The object type. */ object: 'eval'; /** * Unique identifier for the evaluation. */ id: string; /** * The name of the evaluation. */ name: string; /** * Configuration of data sources used in runs of the evaluation. */ data_source_config: ({ type?: 'EvalCustomDataSourceConfig'; } & EvalCustomDataSourceConfig) | ({ type?: 'EvalLogsDataSourceConfig'; } & EvalLogsDataSourceConfig) | ({ type?: 'EvalStoredCompletionsDataSourceConfig'; } & EvalStoredCompletionsDataSourceConfig); /** * A list of testing criteria. */ testing_criteria: Array; /** * The Unix timestamp (in seconds) for when the eval was created. */ created_at: number; metadata: Metadata; }; /** * EvalApiError * * An object representing an error response from the Eval API. * */ export type EvalApiError = { /** * The error code. */ code: string; /** * The error message. */ message: string; }; /** * CustomDataSourceConfig * * A CustomDataSourceConfig which specifies the schema of your `item` and optionally `sample` namespaces. * The response schema defines the shape of the data that will be: * - Used to define your testing criteria and * - What data is required when creating a run * */ export type EvalCustomDataSourceConfig = { /** * The type of data source. Always `custom`. */ type: 'custom'; /** * The json schema for the run data source items. * Learn how to build JSON schemas [here](https://json-schema.org/). * */ schema: { [key: string]: unknown; }; }; /** * LabelModelGrader */ export type EvalGraderLabelModel = GraderLabelModel; /** * PythonGrader */ export type EvalGraderPython = GraderPython & { /** * The threshold for the score. */ pass_threshold?: number; }; /** * ScoreModelGrader */ export type EvalGraderScoreModel = GraderScoreModel & { /** * The threshold for the score. */ pass_threshold?: number; }; /** * StringCheckGrader */ export type EvalGraderStringCheck = GraderStringCheck; /** * TextSimilarityGrader */ export type EvalGraderTextSimilarity = GraderTextSimilarity & { /** * The threshold for the score. */ pass_threshold: number; }; /** * Eval message object * * A message input to the model with a role indicating instruction following * hierarchy. Instructions given with the `developer` or `system` role take * precedence over instructions given with the `user` role. Messages with the * `assistant` role are presumed to have been generated by the model in previous * interactions. * */ export type EvalItem = { /** * The role of the message input. One of `user`, `assistant`, `system`, or * `developer`. * */ role: 'user' | 'assistant' | 'system' | 'developer'; /** * Inputs to the model - can contain template strings. * */ content: string | InputTextContent | { /** * The type of the output text. Always `output_text`. * */ type: 'output_text'; /** * The text output from the model. * */ text: string; } | { /** * The type of the image input. Always `input_image`. * */ type: 'input_image'; /** * The URL of the image input. * */ image_url: string; /** * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. * */ detail?: string; } | Array; /** * The type of the message input. Always `message`. * */ type?: 'message'; }; /** * EvalJsonlFileContentSource */ export type EvalJsonlFileContentSource = { /** * The type of jsonl source. Always `file_content`. */ type: 'file_content'; /** * The content of the jsonl file. */ content: Array<{ item: { [key: string]: unknown; }; sample?: { [key: string]: unknown; }; }>; }; /** * EvalJsonlFileIdSource */ export type EvalJsonlFileIdSource = { /** * The type of jsonl source. Always `file_id`. */ type: 'file_id'; /** * The identifier of the file. */ id: string; }; /** * EvalList * * An object representing a list of evals. * */ export type EvalList = { /** * The type of this object. It is always set to "list". * */ object: 'list'; /** * An array of eval objects. * */ data: Array; /** * The identifier of the first eval in the data array. */ first_id: string; /** * The identifier of the last eval in the data array. */ last_id: string; /** * Indicates whether there are more evals available. */ has_more: boolean; }; /** * LogsDataSourceConfig * * A LogsDataSourceConfig which specifies the metadata property of your logs query. * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. * The schema returned by this data source config is used to defined what variables are available in your evals. * `item` and `sample` are both defined when using this data source config. * */ export type EvalLogsDataSourceConfig = { /** * The type of data source. Always `logs`. */ type: 'logs'; metadata?: Metadata; /** * The json schema for the run data source items. * Learn how to build JSON schemas [here](https://json-schema.org/). * */ schema: { [key: string]: unknown; }; }; /** * EvalResponsesSource * * A EvalResponsesSource object describing a run data source configuration. * */ export type EvalResponsesSource = { /** * The type of run data source. Always `responses`. */ type: 'responses'; /** * Metadata filter for the responses. This is a query parameter used to select responses. */ metadata?: { [key: string]: unknown; }; /** * The name of the model to find responses for. This is a query parameter used to select responses. */ model?: string; /** * Optional string to search the 'instructions' field. This is a query parameter used to select responses. */ instructions_search?: string; /** * Only include items created after this timestamp (inclusive). This is a query parameter used to select responses. */ created_after?: number; /** * Only include items created before this timestamp (inclusive). This is a query parameter used to select responses. */ created_before?: number; /** * Optional reasoning effort parameter. This is a query parameter used to select responses. */ reasoning_effort?: ReasoningEffort; /** * Sampling temperature. This is a query parameter used to select responses. */ temperature?: number; /** * Nucleus sampling parameter. This is a query parameter used to select responses. */ top_p?: number; /** * List of user identifiers. This is a query parameter used to select responses. */ users?: Array; /** * List of tool names. This is a query parameter used to select responses. */ tools?: Array; }; /** * EvalRun * * A schema representing an evaluation run. * */ export type EvalRun = { /** * The type of the object. Always "eval.run". */ object: 'eval.run'; /** * Unique identifier for the evaluation run. */ id: string; /** * The identifier of the associated evaluation. */ eval_id: string; /** * The status of the evaluation run. */ status: string; /** * The model that is evaluated, if applicable. */ model: string; /** * The name of the evaluation run. */ name: string; /** * Unix timestamp (in seconds) when the evaluation run was created. */ created_at: number; /** * The URL to the rendered evaluation run report on the UI dashboard. */ report_url: string; /** * Counters summarizing the outcomes of the evaluation run. */ result_counts: { /** * Total number of executed output items. */ total: number; /** * Number of output items that resulted in an error. */ errored: number; /** * Number of output items that failed to pass the evaluation. */ failed: number; /** * Number of output items that passed the evaluation. */ passed: number; }; /** * Usage statistics for each model during the evaluation run. */ per_model_usage: Array<{ /** * The name of the model. */ model_name: string; /** * The number of invocations. */ invocation_count: number; /** * The number of prompt tokens used. */ prompt_tokens: number; /** * The number of completion tokens generated. */ completion_tokens: number; /** * The total number of tokens used. */ total_tokens: number; /** * The number of tokens retrieved from cache. */ cached_tokens: number; }>; /** * Results per testing criteria applied during the evaluation run. */ per_testing_criteria_results: Array<{ /** * A description of the testing criteria. */ testing_criteria: string; /** * Number of tests passed for this criteria. */ passed: number; /** * Number of tests failed for this criteria. */ failed: number; }>; /** * Information about the run's data source. */ data_source: ({ type?: 'CreateEvalJsonlRunDataSource'; } & CreateEvalJsonlRunDataSource) | ({ type?: 'CreateEvalCompletionsRunDataSource'; } & CreateEvalCompletionsRunDataSource) | ({ type?: 'CreateEvalResponsesRunDataSource'; } & CreateEvalResponsesRunDataSource); metadata: Metadata; error: EvalApiError; }; /** * EvalRunList * * An object representing a list of runs for an evaluation. * */ export type EvalRunList = { /** * The type of this object. It is always set to "list". * */ object: 'list'; /** * An array of eval run objects. * */ data: Array; /** * The identifier of the first eval run in the data array. */ first_id: string; /** * The identifier of the last eval run in the data array. */ last_id: string; /** * Indicates whether there are more evals available. */ has_more: boolean; }; /** * EvalRunOutputItem * * A schema representing an evaluation run output item. * */ export type EvalRunOutputItem = { /** * The type of the object. Always "eval.run.output_item". */ object: 'eval.run.output_item'; /** * Unique identifier for the evaluation run output item. */ id: string; /** * The identifier of the evaluation run associated with this output item. */ run_id: string; /** * The identifier of the evaluation group. */ eval_id: string; /** * Unix timestamp (in seconds) when the evaluation run was created. */ created_at: number; /** * The status of the evaluation run. */ status: string; /** * The identifier for the data source item. */ datasource_item_id: number; /** * Details of the input data source item. */ datasource_item: { [key: string]: unknown; }; /** * A list of results from the evaluation run. */ results: Array<{ [key: string]: unknown; }>; /** * A sample containing the input and output of the evaluation run. */ sample: { /** * An array of input messages. */ input: Array<{ /** * The role of the message sender (e.g., system, user, developer). */ role: string; /** * The content of the message. */ content: string; }>; /** * An array of output messages. */ output: Array<{ /** * The role of the message (e.g. "system", "assistant", "user"). */ role?: string; /** * The content of the message. */ content?: string; }>; /** * The reason why the sample generation was finished. */ finish_reason: string; /** * The model used for generating the sample. */ model: string; /** * Token usage details for the sample. */ usage: { /** * The total number of tokens used. */ total_tokens: number; /** * The number of completion tokens generated. */ completion_tokens: number; /** * The number of prompt tokens used. */ prompt_tokens: number; /** * The number of tokens retrieved from cache. */ cached_tokens: number; }; error: EvalApiError; /** * The sampling temperature used. */ temperature: number; /** * The maximum number of tokens allowed for completion. */ max_completion_tokens: number; /** * The top_p value used for sampling. */ top_p: number; /** * The seed used for generating the sample. */ seed: number; }; }; /** * EvalRunOutputItemList * * An object representing a list of output items for an evaluation run. * */ export type EvalRunOutputItemList = { /** * The type of this object. It is always set to "list". * */ object: 'list'; /** * An array of eval run output item objects. * */ data: Array; /** * The identifier of the first eval run output item in the data array. */ first_id: string; /** * The identifier of the last eval run output item in the data array. */ last_id: string; /** * Indicates whether there are more eval run output items available. */ has_more: boolean; }; /** * StoredCompletionsDataSourceConfig * * Deprecated in favor of LogsDataSourceConfig. * * * @deprecated */ export type EvalStoredCompletionsDataSourceConfig = { /** * The type of data source. Always `stored_completions`. */ type: 'stored_completions'; metadata?: Metadata; /** * The json schema for the run data source items. * Learn how to build JSON schemas [here](https://json-schema.org/). * */ schema: { [key: string]: unknown; }; }; /** * StoredCompletionsRunDataSource * * A StoredCompletionsRunDataSource configuration describing a set of filters * */ export type EvalStoredCompletionsSource = { /** * The type of source. Always `stored_completions`. */ type: 'stored_completions'; metadata?: Metadata; /** * An optional model to filter by (e.g., 'gpt-4o'). */ model?: string; /** * An optional Unix timestamp to filter items created after this time. */ created_after?: number; /** * An optional Unix timestamp to filter items created before this time. */ created_before?: number; /** * An optional maximum number of items to return. */ limit?: number; }; /** * File expiration policy * * The expiration policy for a file. By default, files with `purpose=batch` expire after 30 days and all other files are persisted until they are manually deleted. */ export type FileExpirationAfter = { /** * Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. */ anchor: 'created_at'; /** * The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days). */ seconds: number; }; /** * File path * * A path to a file. * */ export type FilePath = { /** * The type of the file path. Always `file_path`. * */ type: 'file_path'; /** * The ID of the file. * */ file_id: string; /** * The index of the file in the list of files. * */ index: number; }; /** * The ranker to use for the file search. If not specified will use the `auto` ranker. */ export const FileSearchRanker = { AUTO: 'auto', DEFAULT_2024_08_21: 'default_2024_08_21' } as const; /** * The ranker to use for the file search. If not specified will use the `auto` ranker. */ export type FileSearchRanker = typeof FileSearchRanker[keyof typeof FileSearchRanker]; /** * File search tool call ranking options * * The ranking options for the file search. If not specified, the file search tool will use the `auto` ranker and a score_threshold of 0. * * See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. * */ export type FileSearchRankingOptions = { ranker?: FileSearchRanker; /** * The score threshold for the file search. All values must be a floating point number between 0 and 1. */ score_threshold: number; }; /** * File search tool call * * The results of a file search tool call. See the * [file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information. * */ export type FileSearchToolCall = { /** * The unique ID of the file search tool call. * */ id: string; /** * The type of the file search tool call. Always `file_search_call`. * */ type: 'file_search_call'; /** * The status of the file search tool call. One of `in_progress`, * `searching`, `incomplete` or `failed`, * */ status: 'in_progress' | 'searching' | 'completed' | 'incomplete' | 'failed'; /** * The queries used to search for files. * */ queries: Array; /** * The results of the file search tool call. * */ results?: Array<{ /** * The unique ID of the file. * */ file_id?: string; /** * The text that was retrieved from the file. * */ text?: string; /** * The name of the file. * */ filename?: string; attributes?: VectorStoreFileAttributes; /** * The relevance score of the file - a value between 0 and 1. * */ score?: number; }>; }; export type FineTuneChatCompletionRequestAssistantMessage = { /** * Controls whether the assistant message is trained against (0 or 1) */ weight?: 0 | 1; } & ChatCompletionRequestAssistantMessage; /** * The per-line training example of a fine-tuning input file for chat models using the supervised method. * Input messages may contain text or image content only. Audio and file input messages * are not currently supported for fine-tuning. * */ export type FineTuneChatRequestInput = { messages?: Array; /** * A list of tools the model may generate JSON inputs for. */ tools?: Array; parallel_tool_calls?: ParallelToolCalls; /** * A list of functions the model may generate JSON inputs for. * * @deprecated */ functions?: Array; }; /** * The hyperparameters used for the DPO fine-tuning job. */ export type FineTuneDpoHyperparameters = { /** * The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model. * */ beta?: 'auto' | number; /** * Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. * */ batch_size?: 'auto' | number; /** * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. * */ learning_rate_multiplier?: 'auto' | number; /** * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. * */ n_epochs?: 'auto' | number; }; /** * Configuration for the DPO fine-tuning method. */ export type FineTuneDpoMethod = { hyperparameters?: FineTuneDpoHyperparameters; }; /** * The method used for fine-tuning. */ export type FineTuneMethod = { /** * The type of method. Is either `supervised`, `dpo`, or `reinforcement`. */ type: 'supervised' | 'dpo' | 'reinforcement'; supervised?: FineTuneSupervisedMethod; dpo?: FineTuneDpoMethod; reinforcement?: FineTuneReinforcementMethod; }; /** * The per-line training example of a fine-tuning input file for chat models using the dpo method. * Input messages may contain text or image content only. Audio and file input messages * are not currently supported for fine-tuning. * */ export type FineTunePreferenceRequestInput = { input?: { messages?: Array; /** * A list of tools the model may generate JSON inputs for. */ tools?: Array; parallel_tool_calls?: ParallelToolCalls; }; /** * The preferred completion message for the output. */ preferred_output?: Array; /** * The non-preferred completion message for the output. */ non_preferred_output?: Array; }; /** * The hyperparameters used for the reinforcement fine-tuning job. */ export type FineTuneReinforcementHyperparameters = { /** * Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. * */ batch_size?: 'auto' | number; /** * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. * */ learning_rate_multiplier?: 'auto' | number; /** * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. * */ n_epochs?: 'auto' | number; /** * Level of reasoning effort. * */ reasoning_effort?: 'default' | 'low' | 'medium' | 'high'; /** * Multiplier on amount of compute used for exploring search space during training. * */ compute_multiplier?: 'auto' | number; /** * The number of training steps between evaluation runs. * */ eval_interval?: 'auto' | number; /** * Number of evaluation samples to generate per training step. * */ eval_samples?: 'auto' | number; }; /** * Configuration for the reinforcement fine-tuning method. */ export type FineTuneReinforcementMethod = { /** * The grader used for the fine-tuning job. */ grader: GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderMulti; hyperparameters?: FineTuneReinforcementHyperparameters; }; /** * Per-line training example for reinforcement fine-tuning. Note that `messages` and `tools` are the only reserved keywords. * Any other arbitrary key-value data can be included on training datapoints and will be available to reference during grading under the `{{ item.XXX }}` template variable. * Input messages may contain text or image content only. Audio and file input messages * are not currently supported for fine-tuning. * */ export type FineTuneReinforcementRequestInput = { messages: Array; /** * A list of tools the model may generate JSON inputs for. */ tools?: Array; }; /** * The hyperparameters used for the fine-tuning job. */ export type FineTuneSupervisedHyperparameters = { /** * Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. * */ batch_size?: 'auto' | number; /** * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. * */ learning_rate_multiplier?: 'auto' | number; /** * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. * */ n_epochs?: 'auto' | number; }; /** * Configuration for the supervised fine-tuning method. */ export type FineTuneSupervisedMethod = { hyperparameters?: FineTuneSupervisedHyperparameters; }; /** * FineTuningCheckpointPermission * * The `checkpoint.permission` object represents a permission for a fine-tuned model checkpoint. * */ export type FineTuningCheckpointPermission = { /** * The permission identifier, which can be referenced in the API endpoints. */ id: string; /** * The Unix timestamp (in seconds) for when the permission was created. */ created_at: number; /** * The project identifier that the permission is for. */ project_id: string; /** * The object type, which is always "checkpoint.permission". */ object: 'checkpoint.permission'; }; /** * Fine-Tuning Job Integration */ export type FineTuningIntegration = { /** * The type of the integration being enabled for the fine-tuning job */ type: 'wandb'; /** * The settings for your integration with Weights and Biases. This payload specifies the project that * metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags * to your run, and set a default entity (team, username, etc) to be associated with your run. * */ wandb: { /** * The name of the project that the new run will be created under. * */ project: string; /** * A display name to set for the run. If not set, we will use the Job ID as the name. * */ name?: string; /** * The entity to use for the run. This allows you to set the team or username of the WandB user that you would * like associated with the run. If not set, the default entity for the registered WandB API key is used. * */ entity?: string; /** * A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some * default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". * */ tags?: Array; }; }; /** * FineTuningJob * * The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. * */ export type FineTuningJob = { /** * The object identifier, which can be referenced in the API endpoints. */ id: string; /** * The Unix timestamp (in seconds) for when the fine-tuning job was created. */ created_at: number; /** * For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. */ error: { /** * A machine-readable error code. */ code: string; /** * A human-readable error message. */ message: string; /** * The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. */ param: string; }; /** * The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. */ fine_tuned_model: string; /** * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. */ finished_at: number; /** * The hyperparameters used for the fine-tuning job. This value will only be returned when running `supervised` jobs. */ hyperparameters: { /** * Number of examples in each batch. A larger batch size means that model parameters * are updated less frequently, but with lower variance. * */ batch_size?: 'auto' | number; /** * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid * overfitting. * */ learning_rate_multiplier?: 'auto' | number; /** * The number of epochs to train the model for. An epoch refers to one full cycle * through the training dataset. * */ n_epochs?: 'auto' | number; }; /** * The base model that is being fine-tuned. */ model: string; /** * The object type, which is always "fine_tuning.job". */ object: 'fine_tuning.job'; /** * The organization that owns the fine-tuning job. */ organization_id: string; /** * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). */ result_files: Array; /** * The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. */ status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; /** * The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. */ trained_tokens: number; /** * The file ID used for training. You can retrieve the training data with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). */ training_file: string; /** * The file ID used for validation. You can retrieve the validation results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). */ validation_file: string; /** * A list of integrations to enable for this fine-tuning job. */ integrations?: Array<{ type?: 'FineTuningIntegration'; } & FineTuningIntegration>; /** * The seed used for the fine-tuning job. */ seed: number; /** * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running. */ estimated_finish?: number; method?: FineTuneMethod; metadata?: Metadata; }; /** * FineTuningJobCheckpoint * * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use. * */ export type FineTuningJobCheckpoint = { /** * The checkpoint identifier, which can be referenced in the API endpoints. */ id: string; /** * The Unix timestamp (in seconds) for when the checkpoint was created. */ created_at: number; /** * The name of the fine-tuned checkpoint model that is created. */ fine_tuned_model_checkpoint: string; /** * The step number that the checkpoint was created at. */ step_number: number; /** * Metrics at the step number during the fine-tuning job. */ metrics: { step?: number; train_loss?: number; train_mean_token_accuracy?: number; valid_loss?: number; valid_mean_token_accuracy?: number; full_valid_loss?: number; full_valid_mean_token_accuracy?: number; }; /** * The name of the fine-tuning job that this checkpoint was created from. */ fine_tuning_job_id: string; /** * The object type, which is always "fine_tuning.job.checkpoint". */ object: 'fine_tuning.job.checkpoint'; }; /** * Fine-tuning job event object */ export type FineTuningJobEvent = { /** * The object type, which is always "fine_tuning.job.event". */ object: 'fine_tuning.job.event'; /** * The object identifier. */ id: string; /** * The Unix timestamp (in seconds) for when the fine-tuning job was created. */ created_at: number; /** * The log level of the event. */ level: 'info' | 'warn' | 'error'; /** * The message of the event. */ message: string; /** * The type of event. */ type?: 'message' | 'metrics'; /** * The data associated with the event. */ data?: { [key: string]: unknown; }; }; export type FunctionObject = { /** * A description of what the function does, used by the model to choose when and how to call the function. */ description?: string; /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. */ name: string; parameters?: FunctionParameters; /** * Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](https://platform.openai.com/docs/guides/function-calling). */ strict?: boolean; }; /** * The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. * * Omitting `parameters` defines a function with an empty parameter list. */ export type FunctionParameters = { [key: string]: unknown; }; /** * Function tool call * * A tool call to run a function. See the * [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information. * */ export type FunctionToolCall = { /** * The unique ID of the function tool call. * */ id?: string; /** * The type of the function tool call. Always `function_call`. * */ type: 'function_call'; /** * The unique ID of the function tool call generated by the model. * */ call_id: string; /** * The name of the function to run. * */ name: string; /** * A JSON string of the arguments to pass to the function. * */ arguments: string; /** * The status of the item. One of `in_progress`, `completed`, or * `incomplete`. Populated when items are returned via API. * */ status?: 'in_progress' | 'completed' | 'incomplete'; }; /** * Function tool call output * * The output of a function tool call. * */ export type FunctionToolCallOutput = { /** * The unique ID of the function tool call output. Populated when this item * is returned via API. * */ id?: string; /** * The type of the function tool call output. Always `function_call_output`. * */ type: 'function_call_output'; /** * The unique ID of the function tool call generated by the model. * */ call_id: string; /** * A JSON string of the output of the function tool call. * */ output: string; /** * The status of the item. One of `in_progress`, `completed`, or * `incomplete`. Populated when items are returned via API. * */ status?: 'in_progress' | 'completed' | 'incomplete'; }; export type FunctionToolCallOutputResource = FunctionToolCallOutput & { /** * The unique ID of the function call tool output. * */ id: string; }; export type FunctionToolCallResource = FunctionToolCall & { /** * The unique ID of the function tool call. * */ id: string; }; /** * LabelModelGrader * * A LabelModelGrader object which uses a model to assign labels to each item * in the evaluation. * */ export type GraderLabelModel = { /** * The object type, which is always `label_model`. */ type: 'label_model'; /** * The name of the grader. */ name: string; /** * The model to use for the evaluation. Must support structured outputs. */ model: string; input: Array; /** * The labels to assign to each item in the evaluation. */ labels: Array; /** * The labels that indicate a passing result. Must be a subset of labels. */ passing_labels: Array; }; /** * MultiGrader * * A MultiGrader object combines the output of multiple graders to produce a single score. */ export type GraderMulti = { /** * The object type, which is always `multi`. */ type: 'multi'; /** * The name of the grader. */ name: string; graders: GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderLabelModel; /** * A formula to calculate the output based on grader results. */ calculate_output: string; }; /** * PythonGrader * * A PythonGrader object that runs a python script on the input. * */ export type GraderPython = { /** * The object type, which is always `python`. */ type: 'python'; /** * The name of the grader. */ name: string; /** * The source code of the python script. */ source: string; /** * The image tag to use for the python script. */ image_tag?: string; }; /** * ScoreModelGrader * * A ScoreModelGrader object that uses a model to assign a score to the input. * */ export type GraderScoreModel = { /** * The object type, which is always `score_model`. */ type: 'score_model'; /** * The name of the grader. */ name: string; /** * The model to use for the evaluation. */ model: string; /** * The sampling parameters for the model. */ sampling_params?: { [key: string]: unknown; }; /** * The input text. This may include template strings. */ input: Array; /** * The range of the score. Defaults to `[0, 1]`. */ range?: Array; }; /** * StringCheckGrader * * A StringCheckGrader object that performs a string comparison between input and reference using a specified operation. * */ export type GraderStringCheck = { /** * The object type, which is always `string_check`. */ type: 'string_check'; /** * The name of the grader. */ name: string; /** * The input text. This may include template strings. */ input: string; /** * The reference text. This may include template strings. */ reference: string; /** * The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`. */ operation: 'eq' | 'ne' | 'like' | 'ilike'; }; /** * TextSimilarityGrader * * A TextSimilarityGrader object which grades text based on similarity metrics. * */ export type GraderTextSimilarity = { /** * The type of grader. */ type: 'text_similarity'; /** * The name of the grader. */ name: string; /** * The text being graded. */ input: string; /** * The text being graded against. */ reference: string; /** * The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, * `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, * or `rouge_l`. * */ evaluation_metric: 'cosine' | 'fuzzy_match' | 'bleu' | 'gleu' | 'meteor' | 'rouge_1' | 'rouge_2' | 'rouge_3' | 'rouge_4' | 'rouge_5' | 'rouge_l'; }; /** * Represents the content or the URL of an image generated by the OpenAI API. */ export type Image = { /** * The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, and only present if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`. */ b64_json?: string; /** * When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to `url` (default value). Unsupported for `gpt-image-1`. */ url?: string; /** * For `dall-e-3` only, the revised prompt that was used to generate the image. */ revised_prompt?: string; }; /** * Emitted when image editing has completed and the final image is available. * */ export type ImageEditCompletedEvent = { /** * The type of the event. Always `image_edit.completed`. * */ type: 'image_edit.completed'; /** * Base64-encoded final edited image data, suitable for rendering as an image. * */ b64_json: string; /** * The Unix timestamp when the event was created. * */ created_at: number; /** * The size of the edited image. * */ size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; /** * The quality setting for the edited image. * */ quality: 'low' | 'medium' | 'high' | 'auto'; /** * The background setting for the edited image. * */ background: 'transparent' | 'opaque' | 'auto'; /** * The output format for the edited image. * */ output_format: 'png' | 'webp' | 'jpeg'; usage: ImagesUsage; }; /** * Emitted when a partial image is available during image editing streaming. * */ export type ImageEditPartialImageEvent = { /** * The type of the event. Always `image_edit.partial_image`. * */ type: 'image_edit.partial_image'; /** * Base64-encoded partial image data, suitable for rendering as an image. * */ b64_json: string; /** * The Unix timestamp when the event was created. * */ created_at: number; /** * The size of the requested edited image. * */ size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; /** * The quality setting for the requested edited image. * */ quality: 'low' | 'medium' | 'high' | 'auto'; /** * The background setting for the requested edited image. * */ background: 'transparent' | 'opaque' | 'auto'; /** * The output format for the requested edited image. * */ output_format: 'png' | 'webp' | 'jpeg'; /** * 0-based index for the partial image (streaming). * */ partial_image_index: number; }; export type ImageEditStreamEvent = ({ type?: 'ImageEditPartialImageEvent'; } & ImageEditPartialImageEvent) | ({ type?: 'ImageEditCompletedEvent'; } & ImageEditCompletedEvent); /** * Emitted when image generation has completed and the final image is available. * */ export type ImageGenCompletedEvent = { /** * The type of the event. Always `image_generation.completed`. * */ type: 'image_generation.completed'; /** * Base64-encoded image data, suitable for rendering as an image. * */ b64_json: string; /** * The Unix timestamp when the event was created. * */ created_at: number; /** * The size of the generated image. * */ size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; /** * The quality setting for the generated image. * */ quality: 'low' | 'medium' | 'high' | 'auto'; /** * The background setting for the generated image. * */ background: 'transparent' | 'opaque' | 'auto'; /** * The output format for the generated image. * */ output_format: 'png' | 'webp' | 'jpeg'; usage: ImagesUsage; }; /** * Emitted when a partial image is available during image generation streaming. * */ export type ImageGenPartialImageEvent = { /** * The type of the event. Always `image_generation.partial_image`. * */ type: 'image_generation.partial_image'; /** * Base64-encoded partial image data, suitable for rendering as an image. * */ b64_json: string; /** * The Unix timestamp when the event was created. * */ created_at: number; /** * The size of the requested image. * */ size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; /** * The quality setting for the requested image. * */ quality: 'low' | 'medium' | 'high' | 'auto'; /** * The background setting for the requested image. * */ background: 'transparent' | 'opaque' | 'auto'; /** * The output format for the requested image. * */ output_format: 'png' | 'webp' | 'jpeg'; /** * 0-based index for the partial image (streaming). * */ partial_image_index: number; }; export type ImageGenStreamEvent = ({ type?: 'ImageGenPartialImageEvent'; } & ImageGenPartialImageEvent) | ({ type?: 'ImageGenCompletedEvent'; } & ImageGenCompletedEvent); /** * Image generation tool * * A tool that generates images using a model like `gpt-image-1`. * */ export type ImageGenTool = { /** * The type of the image generation tool. Always `image_generation`. * */ type: 'image_generation'; /** * The image generation model to use. Default: `gpt-image-1`. * */ model?: 'gpt-image-1'; /** * The quality of the generated image. One of `low`, `medium`, `high`, * or `auto`. Default: `auto`. * */ quality?: 'low' | 'medium' | 'high' | 'auto'; /** * The size of the generated image. One of `1024x1024`, `1024x1536`, * `1536x1024`, or `auto`. Default: `auto`. * */ size?: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; /** * The output format of the generated image. One of `png`, `webp`, or * `jpeg`. Default: `png`. * */ output_format?: 'png' | 'webp' | 'jpeg'; /** * Compression level for the output image. Default: 100. * */ output_compression?: number; /** * Moderation level for the generated image. Default: `auto`. * */ moderation?: 'auto' | 'low'; /** * Background type for the generated image. One of `transparent`, * `opaque`, or `auto`. Default: `auto`. * */ background?: 'transparent' | 'opaque' | 'auto'; input_fidelity?: ImageInputFidelity; /** * Optional mask for inpainting. Contains `image_url` * (string, optional) and `file_id` (string, optional). * */ input_image_mask?: { /** * Base64-encoded mask image. * */ image_url?: string; /** * File ID for the mask image. * */ file_id?: string; }; /** * Number of partial images to generate in streaming mode, from 0 (default value) to 3. * */ partial_images?: number; }; /** * Image generation call * * An image generation request made by the model. * */ export type ImageGenToolCall = { /** * The type of the image generation call. Always `image_generation_call`. * */ type: 'image_generation_call'; /** * The unique ID of the image generation call. * */ id: string; /** * The status of the image generation call. * */ status: 'in_progress' | 'completed' | 'generating' | 'failed'; /** * The generated image encoded in base64. * */ result: string; }; /** * Control how much effort the model will exert to match the style and features, * especially facial features, of input images. This parameter is only supported * for `gpt-image-1`. Supports `high` and `low`. Defaults to `low`. * */ export const ImageInputFidelity = { HIGH: 'high', LOW: 'low' } as const; /** * Control how much effort the model will exert to match the style and features, * especially facial features, of input images. This parameter is only supported * for `gpt-image-1`. Supports `high` and `low`. Defaults to `low`. * */ export type ImageInputFidelity = typeof ImageInputFidelity[keyof typeof ImageInputFidelity]; /** * Image generation response * * The response from the image generation endpoint. */ export type ImagesResponse = { /** * The Unix timestamp (in seconds) of when the image was created. */ created: number; /** * The list of generated images. */ data?: Array; /** * The background parameter used for the image generation. Either `transparent` or `opaque`. */ background?: 'transparent' | 'opaque'; /** * The output format of the image generation. Either `png`, `webp`, or `jpeg`. */ output_format?: 'png' | 'webp' | 'jpeg'; /** * The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`. */ size?: '1024x1024' | '1024x1536' | '1536x1024'; /** * The quality of the image generated. Either `low`, `medium`, or `high`. */ quality?: 'low' | 'medium' | 'high'; usage?: ImageGenUsage; }; /** * For `gpt-image-1` only, the token usage information for the image generation. * */ export type ImagesUsage = { /** * The total number of tokens (images and text) used for the image generation. * */ total_tokens: number; /** * The number of tokens (images and text) in the input prompt. */ input_tokens: number; /** * The number of image tokens in the output image. */ output_tokens: number; /** * The input tokens detailed information for the image generation. */ input_tokens_details: { /** * The number of text tokens in the input prompt. */ text_tokens: number; /** * The number of image tokens in the input prompt. */ image_tokens: number; }; }; /** * Specify additional output data to include in the model response. Currently * supported values are: * - `code_interpreter_call.outputs`: Includes the outputs of python code execution * in code interpreter tool call items. * - `computer_call_output.output.image_url`: Include image urls from the computer call output. * - `file_search_call.results`: Include the search results of * the file search tool call. * - `message.input_image.image_url`: Include image urls from the input message. * - `message.output_text.logprobs`: Include logprobs with assistant messages. * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning * tokens in reasoning item outputs. This enables reasoning items to be used in * multi-turn conversations when using the Responses API statelessly (like * when the `store` parameter is set to `false`, or when an organization is * enrolled in the zero data retention program). * */ export const Includable = { CODE_INTERPRETER_CALL_OUTPUTS: 'code_interpreter_call.outputs', COMPUTER_CALL_OUTPUT_OUTPUT_IMAGE_URL: 'computer_call_output.output.image_url', FILE_SEARCH_CALL_RESULTS: 'file_search_call.results', MESSAGE_INPUT_IMAGE_IMAGE_URL: 'message.input_image.image_url', MESSAGE_OUTPUT_TEXT_LOGPROBS: 'message.output_text.logprobs', REASONING_ENCRYPTED_CONTENT: 'reasoning.encrypted_content' } as const; /** * Specify additional output data to include in the model response. Currently * supported values are: * - `code_interpreter_call.outputs`: Includes the outputs of python code execution * in code interpreter tool call items. * - `computer_call_output.output.image_url`: Include image urls from the computer call output. * - `file_search_call.results`: Include the search results of * the file search tool call. * - `message.input_image.image_url`: Include image urls from the input message. * - `message.output_text.logprobs`: Include logprobs with assistant messages. * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning * tokens in reasoning item outputs. This enables reasoning items to be used in * multi-turn conversations when using the Responses API statelessly (like * when the `store` parameter is set to `false`, or when an organization is * enrolled in the zero data retention program). * */ export type Includable = typeof Includable[keyof typeof Includable]; /** * Audio input * * An audio input to the model. * */ export type InputAudio = { /** * The type of the input item. Always `input_audio`. * */ type: 'input_audio'; /** * Base64-encoded audio data. * */ data: string; /** * The format of the audio data. Currently supported formats are `mp3` and * `wav`. * */ format: 'mp3' | 'wav'; }; export type InputContent = ({ type?: 'InputTextContent'; } & InputTextContent) | ({ type?: 'InputImageContent'; } & InputImageContent) | ({ type?: 'InputFileContent'; } & InputFileContent); export type InputItem = ({ type?: 'EasyInputMessage'; } & EasyInputMessage) | ({ type?: 'Item'; } & Item) | ({ type?: 'ItemReferenceParam'; } & ItemReferenceParam); /** * Input message * * A message input to the model with a role indicating instruction following * hierarchy. Instructions given with the `developer` or `system` role take * precedence over instructions given with the `user` role. * */ export type InputMessage = { /** * The type of the message input. Always set to `message`. * */ type?: 'message'; /** * The role of the message input. One of `user`, `system`, or `developer`. * */ role: 'user' | 'system' | 'developer'; /** * The status of item. One of `in_progress`, `completed`, or * `incomplete`. Populated when items are returned via API. * */ status?: 'in_progress' | 'completed' | 'incomplete'; content: InputMessageContentList; }; /** * Input item content list * * A list of one or many input items to the model, containing different content * types. * */ export type InputMessageContentList = Array; export type InputMessageResource = InputMessage & { /** * The unique ID of the message input. * */ id: string; }; /** * Represents an individual `invite` to the organization. */ export type Invite = { /** * The object type, which is always `organization.invite` */ object: 'organization.invite'; /** * The identifier, which can be referenced in API endpoints */ id: string; /** * The email address of the individual to whom the invite was sent */ email: string; /** * `owner` or `reader` */ role: 'owner' | 'reader'; /** * `accepted`,`expired`, or `pending` */ status: 'accepted' | 'expired' | 'pending'; /** * The Unix timestamp (in seconds) of when the invite was sent. */ invited_at: number; /** * The Unix timestamp (in seconds) of when the invite expires. */ expires_at: number; /** * The Unix timestamp (in seconds) of when the invite was accepted. */ accepted_at?: number; /** * The projects that were granted membership upon acceptance of the invite. */ projects?: Array<{ /** * Project's public ID */ id?: string; /** * Project membership role */ role?: 'member' | 'owner'; }>; }; export type InviteDeleteResponse = { /** * The object type, which is always `organization.invite.deleted` */ object: 'organization.invite.deleted'; id: string; deleted: boolean; }; export type InviteListResponse = { /** * The object type, which is always `list` */ object: 'list'; data: Array; /** * The first `invite_id` in the retrieved `list` */ first_id?: string; /** * The last `invite_id` in the retrieved `list` */ last_id?: string; /** * The `has_more` property is used for pagination to indicate there are additional results. */ has_more?: boolean; }; export type InviteRequest = { /** * Send an email to this address */ email: string; /** * `owner` or `reader` */ role: 'reader' | 'owner'; /** * An array of projects to which membership is granted at the same time the org invite is accepted. If omitted, the user will be invited to the default project for compatibility with legacy behavior. */ projects?: Array<{ /** * Project's public ID */ id: string; /** * Project membership role */ role: 'member' | 'owner'; }>; }; /** * Content item used to generate a response. * */ export type Item = ({ type?: 'InputMessage'; } & InputMessage) | ({ type?: 'OutputMessage'; } & OutputMessage) | ({ type?: 'FileSearchToolCall'; } & FileSearchToolCall) | ({ type?: 'ComputerToolCall'; } & ComputerToolCall) | ({ type?: 'ComputerCallOutputItemParam'; } & ComputerCallOutputItemParam) | ({ type?: 'WebSearchToolCall'; } & WebSearchToolCall) | ({ type?: 'FunctionToolCall'; } & FunctionToolCall) | ({ type?: 'FunctionCallOutputItemParam'; } & FunctionCallOutputItemParam) | ({ type?: 'ReasoningItem'; } & ReasoningItem) | ({ type?: 'ImageGenToolCall'; } & ImageGenToolCall) | ({ type?: 'CodeInterpreterToolCall'; } & CodeInterpreterToolCall) | ({ type?: 'LocalShellToolCall'; } & LocalShellToolCall) | ({ type?: 'LocalShellToolCallOutput'; } & LocalShellToolCallOutput) | ({ type?: 'MCPListTools'; } & McpListTools) | ({ type?: 'MCPApprovalRequest'; } & McpApprovalRequest) | ({ type?: 'MCPApprovalResponse'; } & McpApprovalResponse) | ({ type?: 'MCPToolCall'; } & McpToolCall) | ({ type?: 'CustomToolCallOutput'; } & CustomToolCallOutput) | ({ type?: 'CustomToolCall'; } & CustomToolCall); /** * Content item used to generate a response. * */ export type ItemResource = ({ type?: 'InputMessageResource'; } & InputMessageResource) | ({ type?: 'OutputMessage'; } & OutputMessage) | ({ type?: 'FileSearchToolCall'; } & FileSearchToolCall) | ({ type?: 'ComputerToolCall'; } & ComputerToolCall) | ({ type?: 'ComputerToolCallOutputResource'; } & ComputerToolCallOutputResource) | ({ type?: 'WebSearchToolCall'; } & WebSearchToolCall) | ({ type?: 'FunctionToolCallResource'; } & FunctionToolCallResource) | ({ type?: 'FunctionToolCallOutputResource'; } & FunctionToolCallOutputResource) | ({ type?: 'ImageGenToolCall'; } & ImageGenToolCall) | ({ type?: 'CodeInterpreterToolCall'; } & CodeInterpreterToolCall) | ({ type?: 'LocalShellToolCall'; } & LocalShellToolCall) | ({ type?: 'LocalShellToolCallOutput'; } & LocalShellToolCallOutput) | ({ type?: 'MCPListTools'; } & McpListTools) | ({ type?: 'MCPApprovalRequest'; } & McpApprovalRequest) | ({ type?: 'MCPApprovalResponseResource'; } & McpApprovalResponseResource) | ({ type?: 'MCPToolCall'; } & McpToolCall); /** * KeyPress * * A collection of keypresses the model would like to perform. * */ export type KeyPress = { /** * Specifies the event type. For a keypress action, this property is * always set to `keypress`. * */ type: 'keypress'; /** * The combination of keys the model is requesting to be pressed. This is an * array of strings, each representing a key. * */ keys: Array; }; export type ListAssistantsResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ListAuditLogsResponse = { object: 'list'; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ListBatchesResponse = { data: Array; first_id?: string; last_id?: string; has_more: boolean; object: 'list'; }; export type ListCertificatesResponse = { data: Array; first_id?: string; last_id?: string; has_more: boolean; object: 'list'; }; export type ListFilesResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ListFineTuningCheckpointPermissionResponse = { data: Array; object: 'list'; first_id?: string; last_id?: string; has_more: boolean; }; export type ListFineTuningJobCheckpointsResponse = { data: Array; object: 'list'; first_id?: string; last_id?: string; has_more: boolean; }; export type ListFineTuningJobEventsResponse = { data: Array; object: 'list'; has_more: boolean; }; export type ListMessagesResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ListModelsResponse = { object: 'list'; data: Array; }; export type ListPaginatedFineTuningJobsResponse = { data: Array; has_more: boolean; object: 'list'; }; export type ListRunStepsResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ListRunsResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ListVectorStoreFilesResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ListVectorStoresResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; /** * Local shell exec action * * Execute a shell command on the server. * */ export type LocalShellExecAction = { /** * The type of the local shell action. Always `exec`. * */ type: 'exec'; /** * The command to run. * */ command: Array; /** * Optional timeout in milliseconds for the command. * */ timeout_ms?: number; /** * Optional working directory to run the command in. * */ working_directory?: string; /** * Environment variables to set for the command. * */ env: { [key: string]: string; }; /** * Optional user to run the command as. * */ user?: string; }; /** * Local shell tool * * A tool that allows the model to execute shell commands in a local environment. * */ export type LocalShellTool = { /** * The type of the local shell tool. Always `local_shell`. */ type: 'local_shell'; }; /** * Local shell call * * A tool call to run a command on the local shell. * */ export type LocalShellToolCall = { /** * The type of the local shell call. Always `local_shell_call`. * */ type: 'local_shell_call'; /** * The unique ID of the local shell call. * */ id: string; /** * The unique ID of the local shell tool call generated by the model. * */ call_id: string; action: LocalShellExecAction; /** * The status of the local shell call. * */ status: 'in_progress' | 'completed' | 'incomplete'; }; /** * Local shell call output * * The output of a local shell tool call. * */ export type LocalShellToolCallOutput = { /** * The type of the local shell tool call output. Always `local_shell_call_output`. * */ type: 'local_shell_call_output'; /** * The unique ID of the local shell tool call generated by the model. * */ id: string; /** * A JSON string of the output of the local shell tool call. * */ output: string; /** * The status of the item. One of `in_progress`, `completed`, or `incomplete`. * */ status?: 'in_progress' | 'completed' | 'incomplete'; }; /** * A log probability object. * */ export type LogProbProperties = { /** * The token that was used to generate the log probability. * */ token: string; /** * The log probability of the token. * */ logprob: number; /** * The bytes that were used to generate the log probability. * */ bytes: Array; }; /** * MCP approval request * * A request for human approval of a tool invocation. * */ export type McpApprovalRequest = { /** * The type of the item. Always `mcp_approval_request`. * */ type: 'mcp_approval_request'; /** * The unique ID of the approval request. * */ id: string; /** * The label of the MCP server making the request. * */ server_label: string; /** * The name of the tool to run. * */ name: string; /** * A JSON string of arguments for the tool. * */ arguments: string; }; /** * MCP approval response * * A response to an MCP approval request. * */ export type McpApprovalResponse = { /** * The type of the item. Always `mcp_approval_response`. * */ type: 'mcp_approval_response'; /** * The unique ID of the approval response * */ id?: string; /** * The ID of the approval request being answered. * */ approval_request_id: string; /** * Whether the request was approved. * */ approve: boolean; /** * Optional reason for the decision. * */ reason?: string; }; /** * MCP approval response * * A response to an MCP approval request. * */ export type McpApprovalResponseResource = { /** * The type of the item. Always `mcp_approval_response`. * */ type: 'mcp_approval_response'; /** * The unique ID of the approval response * */ id: string; /** * The ID of the approval request being answered. * */ approval_request_id: string; /** * Whether the request was approved. * */ approve: boolean; /** * Optional reason for the decision. * */ reason?: string; }; /** * MCP list tools * * A list of tools available on an MCP server. * */ export type McpListTools = { /** * The type of the item. Always `mcp_list_tools`. * */ type: 'mcp_list_tools'; /** * The unique ID of the list. * */ id: string; /** * The label of the MCP server. * */ server_label: string; /** * The tools available on the server. * */ tools: Array; /** * Error message if the server could not list tools. * */ error?: string; }; /** * MCP list tools tool * * A tool available on an MCP server. * */ export type McpListToolsTool = { /** * The name of the tool. * */ name: string; /** * The description of the tool. * */ description?: string; /** * The JSON schema describing the tool's input. * */ input_schema: { [key: string]: unknown; }; /** * Additional annotations about the tool. * */ annotations?: { [key: string]: unknown; }; }; /** * MCP tool * * Give the model access to additional tools via remote Model Context Protocol * (MCP) servers. [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp). * */ export type McpTool = { /** * The type of the MCP tool. Always `mcp`. */ type: 'mcp'; /** * A label for this MCP server, used to identify it in tool calls. * */ server_label: string; /** * The URL for the MCP server. * */ server_url: string; /** * Optional description of the MCP server, used to provide more context. * */ server_description?: string; /** * Optional HTTP headers to send to the MCP server. Use for authentication * or other purposes. * */ headers?: { [key: string]: string; }; /** * List of allowed tool names or a filter object. * */ allowed_tools?: Array | { /** * MCP allowed tools * * List of allowed tool names. */ tool_names?: Array; }; /** * Specify which of the MCP server's tools require approval. */ require_approval?: { /** * A list of tools that always require approval. * */ always?: { /** * List of tools that require approval. */ tool_names?: Array; }; /** * A list of tools that never require approval. * */ never?: { /** * List of tools that do not require approval. */ tool_names?: Array; }; } | 'always' | 'never'; }; /** * MCP tool call * * An invocation of a tool on an MCP server. * */ export type McpToolCall = { /** * The type of the item. Always `mcp_call`. * */ type: 'mcp_call'; /** * The unique ID of the tool call. * */ id: string; /** * The label of the MCP server running the tool. * */ server_label: string; /** * The name of the tool that was run. * */ name: string; /** * A JSON string of the arguments passed to the tool. * */ arguments: string; /** * The output from the tool call. * */ output?: string; /** * The error from the tool call, if any. * */ error?: string; }; /** * Image file * * References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a message. */ export type MessageContentImageFileObject = { /** * Always `image_file`. */ type: 'image_file'; image_file: { /** * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. */ file_id: string; /** * Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. */ detail?: 'auto' | 'low' | 'high'; }; }; /** * Image URL * * References an image URL in the content of a message. */ export type MessageContentImageUrlObject = { /** * The type of the content part. */ type: 'image_url'; image_url: { /** * The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp. */ url: string; /** * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto` */ detail?: 'auto' | 'low' | 'high'; }; }; /** * Refusal * * The refusal content generated by the assistant. */ export type MessageContentRefusalObject = { /** * Always `refusal`. */ type: 'refusal'; refusal: string; }; /** * File citation * * A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. */ export type MessageContentTextAnnotationsFileCitationObject = { /** * Always `file_citation`. */ type: 'file_citation'; /** * The text in the message content that needs to be replaced. */ text: string; file_citation: { /** * The ID of the specific File the citation is from. */ file_id: string; }; start_index: number; end_index: number; }; /** * File path * * A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. */ export type MessageContentTextAnnotationsFilePathObject = { /** * Always `file_path`. */ type: 'file_path'; /** * The text in the message content that needs to be replaced. */ text: string; file_path: { /** * The ID of the file that was generated. */ file_id: string; }; start_index: number; end_index: number; }; /** * Text * * The text content that is part of a message. */ export type MessageContentTextObject = { /** * Always `text`. */ type: 'text'; text: { /** * The data that makes up the text. */ value: string; annotations: Array; }; }; /** * Image file * * References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a message. */ export type MessageDeltaContentImageFileObject = { /** * The index of the content part in the message. */ index: number; /** * Always `image_file`. */ type: 'image_file'; image_file?: { /** * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. */ file_id?: string; /** * Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. */ detail?: 'auto' | 'low' | 'high'; }; }; /** * Image URL * * References an image URL in the content of a message. */ export type MessageDeltaContentImageUrlObject = { /** * The index of the content part in the message. */ index: number; /** * Always `image_url`. */ type: 'image_url'; image_url?: { /** * The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp. */ url?: string; /** * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. */ detail?: 'auto' | 'low' | 'high'; }; }; /** * Refusal * * The refusal content that is part of a message. */ export type MessageDeltaContentRefusalObject = { /** * The index of the refusal part in the message. */ index: number; /** * Always `refusal`. */ type: 'refusal'; refusal?: string; }; /** * File citation * * A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. */ export type MessageDeltaContentTextAnnotationsFileCitationObject = { /** * The index of the annotation in the text content part. */ index: number; /** * Always `file_citation`. */ type: 'file_citation'; /** * The text in the message content that needs to be replaced. */ text?: string; file_citation?: { /** * The ID of the specific File the citation is from. */ file_id?: string; /** * The specific quote in the file. */ quote?: string; }; start_index?: number; end_index?: number; }; /** * File path * * A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. */ export type MessageDeltaContentTextAnnotationsFilePathObject = { /** * The index of the annotation in the text content part. */ index: number; /** * Always `file_path`. */ type: 'file_path'; /** * The text in the message content that needs to be replaced. */ text?: string; file_path?: { /** * The ID of the file that was generated. */ file_id?: string; }; start_index?: number; end_index?: number; }; /** * Text * * The text content that is part of a message. */ export type MessageDeltaContentTextObject = { /** * The index of the content part in the message. */ index: number; /** * Always `text`. */ type: 'text'; text?: { /** * The data that makes up the text. */ value?: string; annotations?: Array; }; }; /** * Message delta object * * Represents a message delta i.e. any changed fields on a message during streaming. * */ export type MessageDeltaObject = { /** * The identifier of the message, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `thread.message.delta`. */ object: 'thread.message.delta'; /** * The delta containing the fields that have changed on the Message. */ delta: { /** * The entity that produced the message. One of `user` or `assistant`. */ role?: 'user' | 'assistant'; /** * The content of the message in array of text and/or images. */ content?: Array; }; }; /** * The message object * * Represents a message within a [thread](https://platform.openai.com/docs/api-reference/threads). */ export type MessageObject = { /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `thread.message`. */ object: 'thread.message'; /** * The Unix timestamp (in seconds) for when the message was created. */ created_at: number; /** * The [thread](https://platform.openai.com/docs/api-reference/threads) ID that this message belongs to. */ thread_id: string; /** * The status of the message, which can be either `in_progress`, `incomplete`, or `completed`. */ status: 'in_progress' | 'incomplete' | 'completed'; /** * On an incomplete message, details about why the message is incomplete. */ incomplete_details: { /** * The reason the message is incomplete. */ reason: 'content_filter' | 'max_tokens' | 'run_cancelled' | 'run_expired' | 'run_failed'; }; /** * The Unix timestamp (in seconds) for when the message was completed. */ completed_at: number; /** * The Unix timestamp (in seconds) for when the message was marked as incomplete. */ incomplete_at: number; /** * The entity that produced the message. One of `user` or `assistant`. */ role: 'user' | 'assistant'; /** * The content of the message in array of text and/or images. */ content: Array; /** * If applicable, the ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) that authored this message. */ assistant_id: string; /** * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints. */ run_id: string; /** * A list of files attached to the message, and the tools they were added to. */ attachments: Array<{ /** * The ID of the file to attach to the message. */ file_id?: string; /** * The tools to add this file to. */ tools?: Array; }>; metadata: Metadata; }; /** * Text * * The text content that is part of a message. */ export type MessageRequestContentTextObject = { /** * Always `text`. */ type: 'text'; /** * Text content to be sent to the model */ text: string; }; export type MessageStreamEvent = { event: 'thread.message.created'; data: MessageObject; } | { event: 'thread.message.in_progress'; data: MessageObject; } | { event: 'thread.message.delta'; data: MessageDeltaObject; } | { event: 'thread.message.completed'; data: MessageObject; } | { event: 'thread.message.incomplete'; data: MessageObject; }; /** * Set of 16 key-value pairs that can be attached to an object. This can be * useful for storing additional information about the object in a structured * format, and querying for objects via API or the dashboard. * * Keys are strings with a maximum length of 64 characters. Values are strings * with a maximum length of 512 characters. * */ export type Metadata = { [key: string]: string; }; /** * Model * * Describes an OpenAI model offering that can be used with the API. */ export type Model = { /** * The model identifier, which can be referenced in the API endpoints. */ id: string; /** * The Unix timestamp (in seconds) when the model was created. */ created: number; /** * The object type, which is always "model". */ object: 'model'; /** * The organization that owns the model. */ owned_by: string; }; export type ModelIds = ModelIdsShared | ModelIdsResponses; export type ModelIdsResponses = ModelIdsShared | 'o1-pro' | 'o1-pro-2025-03-19' | 'o3-pro' | 'o3-pro-2025-06-10' | 'o3-deep-research' | 'o3-deep-research-2025-06-26' | 'o4-mini-deep-research' | 'o4-mini-deep-research-2025-06-26' | 'computer-use-preview' | 'computer-use-preview-2025-03-11'; export type ModelIdsShared = string | ChatModel; export type ModelResponseProperties = { metadata?: Metadata; /** * An integer between 0 and 20 specifying the number of most likely tokens to * return at each token position, each with an associated log probability. * */ top_logprobs?: number; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * We generally recommend altering this or `top_p` but not both. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, * where the model considers the results of the tokens with top_p probability * mass. So 0.1 means only the tokens comprising the top 10% probability mass * are considered. * * We generally recommend altering this or `temperature` but not both. * */ top_p?: number; /** * This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations. * A stable identifier for your end-users. * Used to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). * * * @deprecated */ user?: string; /** * A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. * The IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). * */ safety_identifier?: string; /** * Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching). * */ prompt_cache_key?: string; service_tier?: ServiceTier; }; export type ModifyAssistantRequest = { /** * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. * */ model?: string | AssistantSupportedModels; reasoning_effort?: ReasoningEffort; /** * The name of the assistant. The maximum length is 256 characters. * */ name?: string; /** * The description of the assistant. The maximum length is 512 characters. * */ description?: string; /** * The system instructions that the assistant uses. The maximum length is 256,000 characters. * */ instructions?: string; /** * A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. * */ tools?: Array; /** * A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources?: { code_interpreter?: { /** * Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: { /** * Overrides the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. * */ vector_store_ids?: Array; }; }; metadata?: Metadata; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. * */ top_p?: number; response_format?: AssistantsApiResponseFormatOption; }; export type ModifyCertificateRequest = { /** * The updated name for the certificate */ name: string; }; export type ModifyMessageRequest = { metadata?: Metadata; }; export type ModifyRunRequest = { metadata?: Metadata; }; export type ModifyThreadRequest = { /** * A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources?: { code_interpreter?: { /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: { /** * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. * */ vector_store_ids?: Array; }; }; metadata?: Metadata; }; /** * Move * * A mouse move action. * */ export type Move = { /** * Specifies the event type. For a move action, this property is * always set to `move`. * */ type: 'move'; /** * The x-coordinate to move to. * */ x: number; /** * The y-coordinate to move to. * */ y: number; }; /** * OpenAIFile * * The `File` object represents a document that has been uploaded to OpenAI. */ export type OpenAiFile = { /** * The file identifier, which can be referenced in the API endpoints. */ id: string; /** * The size of the file, in bytes. */ bytes: number; /** * The Unix timestamp (in seconds) for when the file was created. */ created_at: number; /** * The Unix timestamp (in seconds) for when the file will expire. */ expires_at?: number; /** * The name of the file. */ filename: string; /** * The object type, which is always `file`. */ object: 'file'; /** * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`. */ purpose: 'assistants' | 'assistants_output' | 'batch' | 'batch_output' | 'fine-tune' | 'fine-tune-results' | 'vision' | 'user_data'; /** * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. * * @deprecated */ status: 'uploaded' | 'processed' | 'error'; /** * Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. * * @deprecated */ status_details?: string; }; /** * Other Chunking Strategy * * This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API. */ export type OtherChunkingStrategyResponseParam = { /** * Always `other`. */ type: 'other'; }; /** * Output audio * * An audio output from the model. * */ export type OutputAudio = { /** * The type of the output audio. Always `output_audio`. * */ type: 'output_audio'; /** * Base64-encoded audio data from the model. * */ data: string; /** * The transcript of the audio data from the model. * */ transcript: string; }; export type OutputContent = ({ type?: 'OutputTextContent'; } & OutputTextContent) | ({ type?: 'RefusalContent'; } & RefusalContent); export type OutputItem = ({ type?: 'OutputMessage'; } & OutputMessage) | ({ type?: 'FileSearchToolCall'; } & FileSearchToolCall) | ({ type?: 'FunctionToolCall'; } & FunctionToolCall) | ({ type?: 'WebSearchToolCall'; } & WebSearchToolCall) | ({ type?: 'ComputerToolCall'; } & ComputerToolCall) | ({ type?: 'ReasoningItem'; } & ReasoningItem) | ({ type?: 'ImageGenToolCall'; } & ImageGenToolCall) | ({ type?: 'CodeInterpreterToolCall'; } & CodeInterpreterToolCall) | ({ type?: 'LocalShellToolCall'; } & LocalShellToolCall) | ({ type?: 'MCPToolCall'; } & McpToolCall) | ({ type?: 'MCPListTools'; } & McpListTools) | ({ type?: 'MCPApprovalRequest'; } & McpApprovalRequest) | ({ type?: 'CustomToolCall'; } & CustomToolCall); /** * Output message * * An output message from the model. * */ export type OutputMessage = { /** * The unique ID of the output message. * */ id: string; /** * The type of the output message. Always `message`. * */ type: 'message'; /** * The role of the output message. Always `assistant`. * */ role: 'assistant'; /** * The content of the output message. * */ content: Array; /** * The status of the message input. One of `in_progress`, `completed`, or * `incomplete`. Populated when input items are returned via API. * */ status: 'in_progress' | 'completed' | 'incomplete'; }; /** * Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. */ export type ParallelToolCalls = boolean; /** * The number of partial images to generate. This parameter is used for * streaming responses that return partial images. Value must be between 0 and 3. * When set to 0, the response will be a single image sent in one streaming event. * * Note that the final image may be sent before the full number of partial images * are generated if the full image is generated more quickly. * */ export type PartialImages = number; /** * Static Content * * Static predicted output content, such as the content of a text file that is * being regenerated. * */ export type PredictionContent = { /** * The type of the predicted content you want to provide. This type is * currently always `content`. * */ type: 'content'; /** * The content that should be matched when generating a model response. * If generated tokens would match this content, the entire model response * can be returned much more quickly. * */ content: string | Array; }; /** * Represents an individual project. */ export type Project = { /** * The identifier, which can be referenced in API endpoints */ id: string; /** * The object type, which is always `organization.project` */ object: 'organization.project'; /** * The name of the project. This appears in reporting. */ name: string; /** * The Unix timestamp (in seconds) of when the project was created. */ created_at: number; /** * The Unix timestamp (in seconds) of when the project was archived or `null`. */ archived_at?: number; /** * `active` or `archived` */ status: 'active' | 'archived'; }; /** * Represents an individual API key in a project. */ export type ProjectApiKey = { /** * The object type, which is always `organization.project.api_key` */ object: 'organization.project.api_key'; /** * The redacted value of the API key */ redacted_value: string; /** * The name of the API key */ name: string; /** * The Unix timestamp (in seconds) of when the API key was created */ created_at: number; /** * The Unix timestamp (in seconds) of when the API key was last used. */ last_used_at: number; /** * The identifier, which can be referenced in API endpoints */ id: string; owner: { /** * `user` or `service_account` */ type?: 'user' | 'service_account'; user?: ProjectUser; service_account?: ProjectServiceAccount; }; }; export type ProjectApiKeyDeleteResponse = { object: 'organization.project.api_key.deleted'; id: string; deleted: boolean; }; export type ProjectApiKeyListResponse = { object: 'list'; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ProjectCreateRequest = { /** * The friendly name of the project, this name appears in reports. */ name: string; }; export type ProjectListResponse = { object: 'list'; data: Array; first_id: string; last_id: string; has_more: boolean; }; /** * Represents a project rate limit config. */ export type ProjectRateLimit = { /** * The object type, which is always `project.rate_limit` */ object: 'project.rate_limit'; /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The model this rate limit applies to. */ model: string; /** * The maximum requests per minute. */ max_requests_per_1_minute: number; /** * The maximum tokens per minute. */ max_tokens_per_1_minute: number; /** * The maximum images per minute. Only present for relevant models. */ max_images_per_1_minute?: number; /** * The maximum audio megabytes per minute. Only present for relevant models. */ max_audio_megabytes_per_1_minute?: number; /** * The maximum requests per day. Only present for relevant models. */ max_requests_per_1_day?: number; /** * The maximum batch input tokens per day. Only present for relevant models. */ batch_1_day_max_input_tokens?: number; }; export type ProjectRateLimitListResponse = { object: 'list'; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ProjectRateLimitUpdateRequest = { /** * The maximum requests per minute. */ max_requests_per_1_minute?: number; /** * The maximum tokens per minute. */ max_tokens_per_1_minute?: number; /** * The maximum images per minute. Only relevant for certain models. */ max_images_per_1_minute?: number; /** * The maximum audio megabytes per minute. Only relevant for certain models. */ max_audio_megabytes_per_1_minute?: number; /** * The maximum requests per day. Only relevant for certain models. */ max_requests_per_1_day?: number; /** * The maximum batch input tokens per day. Only relevant for certain models. */ batch_1_day_max_input_tokens?: number; }; /** * Represents an individual service account in a project. */ export type ProjectServiceAccount = { /** * The object type, which is always `organization.project.service_account` */ object: 'organization.project.service_account'; /** * The identifier, which can be referenced in API endpoints */ id: string; /** * The name of the service account */ name: string; /** * `owner` or `member` */ role: 'owner' | 'member'; /** * The Unix timestamp (in seconds) of when the service account was created */ created_at: number; }; export type ProjectServiceAccountApiKey = { /** * The object type, which is always `organization.project.service_account.api_key` */ object: 'organization.project.service_account.api_key'; value: string; name: string; created_at: number; id: string; }; export type ProjectServiceAccountCreateRequest = { /** * The name of the service account being created. */ name: string; }; export type ProjectServiceAccountCreateResponse = { object: 'organization.project.service_account'; id: string; name: string; /** * Service accounts can only have one role of type `member` */ role: 'member'; created_at: number; api_key: ProjectServiceAccountApiKey; }; export type ProjectServiceAccountDeleteResponse = { object: 'organization.project.service_account.deleted'; id: string; deleted: boolean; }; export type ProjectServiceAccountListResponse = { object: 'list'; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ProjectUpdateRequest = { /** * The updated name of the project, this name appears in reports. */ name: string; }; /** * Represents an individual user in a project. */ export type ProjectUser = { /** * The object type, which is always `organization.project.user` */ object: 'organization.project.user'; /** * The identifier, which can be referenced in API endpoints */ id: string; /** * The name of the user */ name: string; /** * The email address of the user */ email: string; /** * `owner` or `member` */ role: 'owner' | 'member'; /** * The Unix timestamp (in seconds) of when the project was added. */ added_at: number; }; export type ProjectUserCreateRequest = { /** * The ID of the user. */ user_id: string; /** * `owner` or `member` */ role: 'owner' | 'member'; }; export type ProjectUserDeleteResponse = { object: 'organization.project.user.deleted'; id: string; deleted: boolean; }; export type ProjectUserListResponse = { object: string; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type ProjectUserUpdateRequest = { /** * `owner` or `member` */ role: 'owner' | 'member'; }; /** * Reference to a prompt template and its variables. * [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). * */ export type Prompt = { /** * The unique identifier of the prompt template to use. */ id: string; /** * Optional version of the prompt template. */ version?: string; variables?: ResponsePromptVariables; }; /** * A realtime client event. * */ export type RealtimeClientEvent = ({ type?: 'RealtimeClientEventConversationItemCreate'; } & RealtimeClientEventConversationItemCreate) | ({ type?: 'RealtimeClientEventConversationItemDelete'; } & RealtimeClientEventConversationItemDelete) | ({ type?: 'RealtimeClientEventConversationItemRetrieve'; } & RealtimeClientEventConversationItemRetrieve) | ({ type?: 'RealtimeClientEventConversationItemTruncate'; } & RealtimeClientEventConversationItemTruncate) | ({ type?: 'RealtimeClientEventInputAudioBufferAppend'; } & RealtimeClientEventInputAudioBufferAppend) | ({ type?: 'RealtimeClientEventInputAudioBufferClear'; } & RealtimeClientEventInputAudioBufferClear) | ({ type?: 'RealtimeClientEventOutputAudioBufferClear'; } & RealtimeClientEventOutputAudioBufferClear) | ({ type?: 'RealtimeClientEventInputAudioBufferCommit'; } & RealtimeClientEventInputAudioBufferCommit) | ({ type?: 'RealtimeClientEventResponseCancel'; } & RealtimeClientEventResponseCancel) | ({ type?: 'RealtimeClientEventResponseCreate'; } & RealtimeClientEventResponseCreate) | ({ type?: 'RealtimeClientEventSessionUpdate'; } & RealtimeClientEventSessionUpdate) | ({ type?: 'RealtimeClientEventTranscriptionSessionUpdate'; } & RealtimeClientEventTranscriptionSessionUpdate); /** * Add a new Item to the Conversation's context, including messages, function * calls, and function call responses. This event can be used both to populate a * "history" of the conversation and to add new items mid-stream, but has the * current limitation that it cannot populate assistant audio messages. * * If successful, the server will respond with a `conversation.item.created` * event, otherwise an `error` event will be sent. * */ export type RealtimeClientEventConversationItemCreate = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `conversation.item.create`. */ type: 'conversation.item.create'; /** * The ID of the preceding item after which the new item will be inserted. * If not set, the new item will be appended to the end of the conversation. * If set to `root`, the new item will be added to the beginning of the conversation. * If set to an existing ID, it allows an item to be inserted mid-conversation. If the * ID cannot be found, an error will be returned and the item will not be added. * */ previous_item_id?: string; item: RealtimeConversationItem; }; /** * Send this event when you want to remove any item from the conversation * history. The server will respond with a `conversation.item.deleted` event, * unless the item does not exist in the conversation history, in which case the * server will respond with an error. * */ export type RealtimeClientEventConversationItemDelete = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `conversation.item.delete`. */ type: 'conversation.item.delete'; /** * The ID of the item to delete. */ item_id: string; }; /** * Send this event when you want to retrieve the server's representation of a specific item in the conversation history. This is useful, for example, to inspect user audio after noise cancellation and VAD. * The server will respond with a `conversation.item.retrieved` event, * unless the item does not exist in the conversation history, in which case the * server will respond with an error. * */ export type RealtimeClientEventConversationItemRetrieve = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `conversation.item.retrieve`. */ type: 'conversation.item.retrieve'; /** * The ID of the item to retrieve. */ item_id: string; }; /** * Send this event to truncate a previous assistant message’s audio. The server * will produce audio faster than realtime, so this event is useful when the user * interrupts to truncate audio that has already been sent to the client but not * yet played. This will synchronize the server's understanding of the audio with * the client's playback. * * Truncating audio will delete the server-side text transcript to ensure there * is not text in the context that hasn't been heard by the user. * * If successful, the server will respond with a `conversation.item.truncated` * event. * */ export type RealtimeClientEventConversationItemTruncate = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `conversation.item.truncate`. */ type: 'conversation.item.truncate'; /** * The ID of the assistant message item to truncate. Only assistant message * items can be truncated. * */ item_id: string; /** * The index of the content part to truncate. Set this to 0. */ content_index: number; /** * Inclusive duration up to which audio is truncated, in milliseconds. If * the audio_end_ms is greater than the actual audio duration, the server * will respond with an error. * */ audio_end_ms: number; }; /** * Send this event to append audio bytes to the input audio buffer. The audio * buffer is temporary storage you can write to and later commit. In Server VAD * mode, the audio buffer is used to detect speech and the server will decide * when to commit. When Server VAD is disabled, you must commit the audio buffer * manually. * * The client may choose how much audio to place in each event up to a maximum * of 15 MiB, for example streaming smaller chunks from the client may allow the * VAD to be more responsive. Unlike made other client events, the server will * not send a confirmation response to this event. * */ export type RealtimeClientEventInputAudioBufferAppend = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `input_audio_buffer.append`. */ type: 'input_audio_buffer.append'; /** * Base64-encoded audio bytes. This must be in the format specified by the * `input_audio_format` field in the session configuration. * */ audio: string; }; /** * Send this event to clear the audio bytes in the buffer. The server will * respond with an `input_audio_buffer.cleared` event. * */ export type RealtimeClientEventInputAudioBufferClear = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `input_audio_buffer.clear`. */ type: 'input_audio_buffer.clear'; }; /** * Send this event to commit the user input audio buffer, which will create a * new user message item in the conversation. This event will produce an error * if the input audio buffer is empty. When in Server VAD mode, the client does * not need to send this event, the server will commit the audio buffer * automatically. * * Committing the input audio buffer will trigger input audio transcription * (if enabled in session configuration), but it will not create a response * from the model. The server will respond with an `input_audio_buffer.committed` * event. * */ export type RealtimeClientEventInputAudioBufferCommit = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `input_audio_buffer.commit`. */ type: 'input_audio_buffer.commit'; }; /** * **WebRTC Only:** Emit to cut off the current audio response. This will trigger the server to * stop generating audio and emit a `output_audio_buffer.cleared` event. This * event should be preceded by a `response.cancel` client event to stop the * generation of the current response. * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). * */ export type RealtimeClientEventOutputAudioBufferClear = { /** * The unique ID of the client event used for error handling. */ event_id?: string; /** * The event type, must be `output_audio_buffer.clear`. */ type: 'output_audio_buffer.clear'; }; /** * Send this event to cancel an in-progress response. The server will respond * with a `response.done` event with a status of `response.status=cancelled`. If * there is no response to cancel, the server will respond with an error. * */ export type RealtimeClientEventResponseCancel = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `response.cancel`. */ type: 'response.cancel'; /** * A specific response ID to cancel - if not provided, will cancel an * in-progress response in the default conversation. * */ response_id?: string; }; /** * This event instructs the server to create a Response, which means triggering * model inference. When in Server VAD mode, the server will create Responses * automatically. * * A Response will include at least one Item, and may have two, in which case * the second will be a function call. These Items will be appended to the * conversation history. * * The server will respond with a `response.created` event, events for Items * and content created, and finally a `response.done` event to indicate the * Response is complete. * * The `response.create` event includes inference configuration like * `instructions`, and `temperature`. These fields will override the Session's * configuration for this Response only. * */ export type RealtimeClientEventResponseCreate = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `response.create`. */ type: 'response.create'; response?: RealtimeResponseCreateParams; }; /** * Send this event to update the session’s default configuration. * The client may send this event at any time to update any field, * except for `voice`. However, note that once a session has been * initialized with a particular `model`, it can’t be changed to * another model using `session.update`. * * When the server receives a `session.update`, it will respond * with a `session.updated` event showing the full, effective configuration. * Only the fields that are present are updated. To clear a field like * `instructions`, pass an empty string. * */ export type RealtimeClientEventSessionUpdate = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `session.update`. */ type: 'session.update'; session: RealtimeSessionCreateRequest; }; /** * Send this event to update a transcription session. * */ export type RealtimeClientEventTranscriptionSessionUpdate = { /** * Optional client-generated ID used to identify this event. */ event_id?: string; /** * The event type, must be `transcription_session.update`. */ type: 'transcription_session.update'; session: RealtimeTranscriptionSessionCreateRequest; }; /** * The item to add to the conversation. */ export type RealtimeConversationItem = { /** * The unique ID of the item, this can be generated by the client to help * manage server-side context, but is not required because the server will * generate one if not provided. * */ id?: string; /** * The type of the item (`message`, `function_call`, `function_call_output`). * */ type?: 'message' | 'function_call' | 'function_call_output'; /** * Identifier for the API object being returned - always `realtime.item`. * */ object?: 'realtime.item'; /** * The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect * on the conversation, but are accepted for consistency with the * `conversation.item.created` event. * */ status?: 'completed' | 'incomplete' | 'in_progress'; /** * The role of the message sender (`user`, `assistant`, `system`), only * applicable for `message` items. * */ role?: 'user' | 'assistant' | 'system'; /** * The content of the message, applicable for `message` items. * - Message items of role `system` support only `input_text` content * - Message items of role `user` support `input_text` and `input_audio` * content * - Message items of role `assistant` support `text` content. * */ content?: Array; /** * The ID of the function call (for `function_call` and * `function_call_output` items). If passed on a `function_call_output` * item, the server will check that a `function_call` item with the same * ID exists in the conversation history. * */ call_id?: string; /** * The name of the function being called (for `function_call` items). * */ name?: string; /** * The arguments of the function call (for `function_call` items). * */ arguments?: string; /** * The output of the function call (for `function_call_output` items). * */ output?: string; }; /** * The item to add to the conversation. */ export type RealtimeConversationItemWithReference = { /** * For an item of type (`message` | `function_call` | `function_call_output`) * this field allows the client to assign the unique ID of the item. It is * not required because the server will generate one if not provided. * * For an item of type `item_reference`, this field is required and is a * reference to any item that has previously existed in the conversation. * */ id?: string; /** * The type of the item (`message`, `function_call`, `function_call_output`, `item_reference`). * */ type?: 'message' | 'function_call' | 'function_call_output' | 'item_reference'; /** * Identifier for the API object being returned - always `realtime.item`. * */ object?: 'realtime.item'; /** * The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect * on the conversation, but are accepted for consistency with the * `conversation.item.created` event. * */ status?: 'completed' | 'incomplete' | 'in_progress'; /** * The role of the message sender (`user`, `assistant`, `system`), only * applicable for `message` items. * */ role?: 'user' | 'assistant' | 'system'; /** * The content of the message, applicable for `message` items. * - Message items of role `system` support only `input_text` content * - Message items of role `user` support `input_text` and `input_audio` * content * - Message items of role `assistant` support `text` content. * */ content?: Array<{ /** * The content type (`input_text`, `input_audio`, `item_reference`, `text`). * */ type?: 'input_text' | 'input_audio' | 'item_reference' | 'text'; /** * The text content, used for `input_text` and `text` content types. * */ text?: string; /** * ID of a previous conversation item to reference (for `item_reference` * content types in `response.create` events). These can reference both * client and server created items. * */ id?: string; /** * Base64-encoded audio bytes, used for `input_audio` content type. * */ audio?: string; /** * The transcript of the audio, used for `input_audio` content type. * */ transcript?: string; }>; /** * The ID of the function call (for `function_call` and * `function_call_output` items). If passed on a `function_call_output` * item, the server will check that a `function_call` item with the same * ID exists in the conversation history. * */ call_id?: string; /** * The name of the function being called (for `function_call` items). * */ name?: string; /** * The arguments of the function call (for `function_call` items). * */ arguments?: string; /** * The output of the function call (for `function_call_output` items). * */ output?: string; }; /** * The response resource. */ export type RealtimeResponse = { /** * The unique ID of the response. */ id?: string; /** * The object type, must be `realtime.response`. */ object?: 'realtime.response'; /** * The final status of the response (`completed`, `cancelled`, `failed`, or * `incomplete`, `in_progress`). * */ status?: 'completed' | 'cancelled' | 'failed' | 'incomplete' | 'in_progress'; /** * Additional details about the status. */ status_details?: { /** * The type of error that caused the response to fail, corresponding * with the `status` field (`completed`, `cancelled`, `incomplete`, * `failed`). * */ type?: 'completed' | 'cancelled' | 'incomplete' | 'failed'; /** * The reason the Response did not complete. For a `cancelled` Response, * one of `turn_detected` (the server VAD detected a new start of speech) * or `client_cancelled` (the client sent a cancel event). For an * `incomplete` Response, one of `max_output_tokens` or `content_filter` * (the server-side safety filter activated and cut off the response). * */ reason?: 'turn_detected' | 'client_cancelled' | 'max_output_tokens' | 'content_filter'; /** * A description of the error that caused the response to fail, * populated when the `status` is `failed`. * */ error?: { /** * The type of error. */ type?: string; /** * Error code, if any. */ code?: string; }; }; /** * The list of output items generated by the response. */ output?: Array; metadata?: Metadata; /** * Usage statistics for the Response, this will correspond to billing. A * Realtime API session will maintain a conversation context and append new * Items to the Conversation, thus output from previous turns (text and * audio tokens) will become the input for later turns. * */ usage?: { /** * The total number of tokens in the Response including input and output * text and audio tokens. * */ total_tokens?: number; /** * The number of input tokens used in the Response, including text and * audio tokens. * */ input_tokens?: number; /** * The number of output tokens sent in the Response, including text and * audio tokens. * */ output_tokens?: number; /** * Details about the input tokens used in the Response. */ input_token_details?: { /** * The number of cached tokens used in the Response. */ cached_tokens?: number; /** * The number of text tokens used in the Response. */ text_tokens?: number; /** * The number of audio tokens used in the Response. */ audio_tokens?: number; }; /** * Details about the output tokens used in the Response. */ output_token_details?: { /** * The number of text tokens used in the Response. */ text_tokens?: number; /** * The number of audio tokens used in the Response. */ audio_tokens?: number; }; }; /** * Which conversation the response is added to, determined by the `conversation` * field in the `response.create` event. If `auto`, the response will be added to * the default conversation and the value of `conversation_id` will be an id like * `conv_1234`. If `none`, the response will not be added to any conversation and * the value of `conversation_id` will be `null`. If responses are being triggered * by server VAD, the response will be added to the default conversation, thus * the `conversation_id` will be an id like `conv_1234`. * */ conversation_id?: string; /** * The voice the model used to respond. * Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, * `shimmer`, and `verse`. * */ voice?: VoiceIdsShared; /** * The set of modalities the model used to respond. If there are multiple modalities, * the model will pick one, for example if `modalities` is `["text", "audio"]`, the model * could be responding in either text or audio. * */ modalities?: Array<'text' | 'audio'>; /** * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * */ output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; /** * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. * */ temperature?: number; /** * Maximum number of output tokens for a single assistant response, * inclusive of tool calls, that was used in this response. * */ max_output_tokens?: number | 'inf'; }; /** * Create a new Realtime response with these parameters */ export type RealtimeResponseCreateParams = { /** * The set of modalities the model can respond with. To disable audio, * set this to ["text"]. * */ modalities?: Array<'text' | 'audio'>; /** * The default system instructions (i.e. system message) prepended to model * calls. This field allows the client to guide the model on desired * responses. The model can be instructed on response content and format, * (e.g. "be extremely succinct", "act friendly", "here are examples of good * responses") and on audio behavior (e.g. "talk quickly", "inject emotion * into your voice", "laugh frequently"). The instructions are not guaranteed * to be followed by the model, but they provide guidance to the model on the * desired behavior. * * Note that the server sets default instructions which will be used if this * field is not set and are visible in the `session.created` event at the * start of the session. * */ instructions?: string; /** * The voice the model uses to respond. Voice cannot be changed during the * session once the model has responded with audio at least once. Current * voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, * `shimmer`, and `verse`. * */ voice?: VoiceIdsShared; /** * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * */ output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; /** * Tools (functions) available to the model. */ tools?: Array<{ /** * The type of the tool, i.e. `function`. */ type?: 'function'; /** * The name of the function. */ name?: string; /** * The description of the function, including guidance on when and how * to call it, and guidance about what to tell the user when calling * (if anything). * */ description?: string; /** * Parameters of the function in JSON Schema. */ parameters?: { [key: string]: unknown; }; }>; /** * How the model chooses tools. Options are `auto`, `none`, `required`, or * specify a function, like `{"type": "function", "function": {"name": "my_function"}}`. * */ tool_choice?: string; /** * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. * */ temperature?: number; /** * Maximum number of output tokens for a single assistant response, * inclusive of tool calls. Provide an integer between 1 and 4096 to * limit output tokens, or `inf` for the maximum available tokens for a * given model. Defaults to `inf`. * */ max_response_output_tokens?: number | 'inf'; /** * Controls which conversation the response is added to. Currently supports * `auto` and `none`, with `auto` as the default value. The `auto` value * means that the contents of the response will be added to the default * conversation. Set this to `none` to create an out-of-band response which * will not add items to default conversation. * */ conversation?: string | 'auto' | 'none'; metadata?: Metadata; /** * Input items to include in the prompt for the model. Using this field * creates a new context for this Response instead of using the default * conversation. An empty array `[]` will clear the context for this Response. * Note that this can include references to items from the default conversation. * */ input?: Array; }; /** * A realtime server event. * */ export type RealtimeServerEvent = ({ type?: 'RealtimeServerEventConversationCreated'; } & RealtimeServerEventConversationCreated) | ({ type?: 'RealtimeServerEventConversationItemCreated'; } & RealtimeServerEventConversationItemCreated) | ({ type?: 'RealtimeServerEventConversationItemDeleted'; } & RealtimeServerEventConversationItemDeleted) | ({ type?: 'RealtimeServerEventConversationItemInputAudioTranscriptionCompleted'; } & RealtimeServerEventConversationItemInputAudioTranscriptionCompleted) | ({ type?: 'RealtimeServerEventConversationItemInputAudioTranscriptionDelta'; } & RealtimeServerEventConversationItemInputAudioTranscriptionDelta) | ({ type?: 'RealtimeServerEventConversationItemInputAudioTranscriptionFailed'; } & RealtimeServerEventConversationItemInputAudioTranscriptionFailed) | ({ type?: 'RealtimeServerEventConversationItemRetrieved'; } & RealtimeServerEventConversationItemRetrieved) | ({ type?: 'RealtimeServerEventConversationItemTruncated'; } & RealtimeServerEventConversationItemTruncated) | ({ type?: 'RealtimeServerEventError'; } & RealtimeServerEventError) | ({ type?: 'RealtimeServerEventInputAudioBufferCleared'; } & RealtimeServerEventInputAudioBufferCleared) | ({ type?: 'RealtimeServerEventInputAudioBufferCommitted'; } & RealtimeServerEventInputAudioBufferCommitted) | ({ type?: 'RealtimeServerEventInputAudioBufferSpeechStarted'; } & RealtimeServerEventInputAudioBufferSpeechStarted) | ({ type?: 'RealtimeServerEventInputAudioBufferSpeechStopped'; } & RealtimeServerEventInputAudioBufferSpeechStopped) | ({ type?: 'RealtimeServerEventRateLimitsUpdated'; } & RealtimeServerEventRateLimitsUpdated) | ({ type?: 'RealtimeServerEventResponseAudioDelta'; } & RealtimeServerEventResponseAudioDelta) | ({ type?: 'RealtimeServerEventResponseAudioDone'; } & RealtimeServerEventResponseAudioDone) | ({ type?: 'RealtimeServerEventResponseAudioTranscriptDelta'; } & RealtimeServerEventResponseAudioTranscriptDelta) | ({ type?: 'RealtimeServerEventResponseAudioTranscriptDone'; } & RealtimeServerEventResponseAudioTranscriptDone) | ({ type?: 'RealtimeServerEventResponseContentPartAdded'; } & RealtimeServerEventResponseContentPartAdded) | ({ type?: 'RealtimeServerEventResponseContentPartDone'; } & RealtimeServerEventResponseContentPartDone) | ({ type?: 'RealtimeServerEventResponseCreated'; } & RealtimeServerEventResponseCreated) | ({ type?: 'RealtimeServerEventResponseDone'; } & RealtimeServerEventResponseDone) | ({ type?: 'RealtimeServerEventResponseFunctionCallArgumentsDelta'; } & RealtimeServerEventResponseFunctionCallArgumentsDelta) | ({ type?: 'RealtimeServerEventResponseFunctionCallArgumentsDone'; } & RealtimeServerEventResponseFunctionCallArgumentsDone) | ({ type?: 'RealtimeServerEventResponseOutputItemAdded'; } & RealtimeServerEventResponseOutputItemAdded) | ({ type?: 'RealtimeServerEventResponseOutputItemDone'; } & RealtimeServerEventResponseOutputItemDone) | ({ type?: 'RealtimeServerEventResponseTextDelta'; } & RealtimeServerEventResponseTextDelta) | ({ type?: 'RealtimeServerEventResponseTextDone'; } & RealtimeServerEventResponseTextDone) | ({ type?: 'RealtimeServerEventSessionCreated'; } & RealtimeServerEventSessionCreated) | ({ type?: 'RealtimeServerEventSessionUpdated'; } & RealtimeServerEventSessionUpdated) | ({ type?: 'RealtimeServerEventTranscriptionSessionUpdated'; } & RealtimeServerEventTranscriptionSessionUpdated) | ({ type?: 'RealtimeServerEventOutputAudioBufferStarted'; } & RealtimeServerEventOutputAudioBufferStarted) | ({ type?: 'RealtimeServerEventOutputAudioBufferStopped'; } & RealtimeServerEventOutputAudioBufferStopped) | ({ type?: 'RealtimeServerEventOutputAudioBufferCleared'; } & RealtimeServerEventOutputAudioBufferCleared); /** * Returned when a conversation is created. Emitted right after session creation. * */ export type RealtimeServerEventConversationCreated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `conversation.created`. */ type: 'conversation.created'; /** * The conversation resource. */ conversation: { /** * The unique ID of the conversation. */ id?: string; /** * The object type, must be `realtime.conversation`. */ object?: 'realtime.conversation'; }; }; /** * Returned when a conversation item is created. There are several scenarios that produce this event: * - The server is generating a Response, which if successful will produce * either one or two Items, which will be of type `message` * (role `assistant`) or type `function_call`. * - The input audio buffer has been committed, either by the client or the * server (in `server_vad` mode). The server will take the content of the * input audio buffer and add it to a new user message Item. * - The client has sent a `conversation.item.create` event to add a new Item * to the Conversation. * */ export type RealtimeServerEventConversationItemCreated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `conversation.item.created`. */ type: 'conversation.item.created'; /** * The ID of the preceding item in the Conversation context, allows the * client to understand the order of the conversation. Can be `null` if the * item has no predecessor. * */ previous_item_id?: string; item: RealtimeConversationItem; }; /** * Returned when an item in the conversation is deleted by the client with a * `conversation.item.delete` event. This event is used to synchronize the * server's understanding of the conversation history with the client's view. * */ export type RealtimeServerEventConversationItemDeleted = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `conversation.item.deleted`. */ type: 'conversation.item.deleted'; /** * The ID of the item that was deleted. */ item_id: string; }; /** * This event is the output of audio transcription for user audio written to the * user audio buffer. Transcription begins when the input audio buffer is * committed by the client or server (in `server_vad` mode). Transcription runs * asynchronously with Response creation, so this event may come before or after * the Response events. * * Realtime API models accept audio natively, and thus input transcription is a * separate process run on a separate ASR (Automatic Speech Recognition) model. * The transcript may diverge somewhat from the model's interpretation, and * should be treated as a rough guide. * */ export type RealtimeServerEventConversationItemInputAudioTranscriptionCompleted = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be * `conversation.item.input_audio_transcription.completed`. * */ type: 'conversation.item.input_audio_transcription.completed'; /** * The ID of the user message item containing the audio. */ item_id: string; /** * The index of the content part containing the audio. */ content_index: number; /** * The transcribed text. */ transcript: string; /** * The log probabilities of the transcription. */ logprobs?: Array; /** * Usage statistics for the transcription. */ usage: TranscriptTextUsageTokens | TranscriptTextUsageDuration; }; /** * Returned when the text value of an input audio transcription content part is updated. * */ export type RealtimeServerEventConversationItemInputAudioTranscriptionDelta = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `conversation.item.input_audio_transcription.delta`. */ type: 'conversation.item.input_audio_transcription.delta'; /** * The ID of the item. */ item_id: string; /** * The index of the content part in the item's content array. */ content_index?: number; /** * The text delta. */ delta?: string; /** * The log probabilities of the transcription. */ logprobs?: Array; }; /** * Returned when input audio transcription is configured, and a transcription * request for a user message failed. These events are separate from other * `error` events so that the client can identify the related Item. * */ export type RealtimeServerEventConversationItemInputAudioTranscriptionFailed = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be * `conversation.item.input_audio_transcription.failed`. * */ type: 'conversation.item.input_audio_transcription.failed'; /** * The ID of the user message item. */ item_id: string; /** * The index of the content part containing the audio. */ content_index: number; /** * Details of the transcription error. */ error: { /** * The type of error. */ type?: string; /** * Error code, if any. */ code?: string; /** * A human-readable error message. */ message?: string; /** * Parameter related to the error, if any. */ param?: string; }; }; /** * Returned when a conversation item is retrieved with `conversation.item.retrieve`. * */ export type RealtimeServerEventConversationItemRetrieved = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `conversation.item.retrieved`. */ type: 'conversation.item.retrieved'; item: RealtimeConversationItem; }; /** * Returned when an earlier assistant audio message item is truncated by the * client with a `conversation.item.truncate` event. This event is used to * synchronize the server's understanding of the audio with the client's playback. * * This action will truncate the audio and remove the server-side text transcript * to ensure there is no text in the context that hasn't been heard by the user. * */ export type RealtimeServerEventConversationItemTruncated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `conversation.item.truncated`. */ type: 'conversation.item.truncated'; /** * The ID of the assistant message item that was truncated. */ item_id: string; /** * The index of the content part that was truncated. */ content_index: number; /** * The duration up to which the audio was truncated, in milliseconds. * */ audio_end_ms: number; }; /** * Returned when an error occurs, which could be a client problem or a server * problem. Most errors are recoverable and the session will stay open, we * recommend to implementors to monitor and log error messages by default. * */ export type RealtimeServerEventError = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `error`. */ type: 'error'; /** * Details of the error. */ error: { /** * The type of error (e.g., "invalid_request_error", "server_error"). * */ type: string; /** * Error code, if any. */ code?: string; /** * A human-readable error message. */ message: string; /** * Parameter related to the error, if any. */ param?: string; /** * The event_id of the client event that caused the error, if applicable. * */ event_id?: string; }; }; /** * Returned when the input audio buffer is cleared by the client with a * `input_audio_buffer.clear` event. * */ export type RealtimeServerEventInputAudioBufferCleared = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `input_audio_buffer.cleared`. */ type: 'input_audio_buffer.cleared'; }; /** * Returned when an input audio buffer is committed, either by the client or * automatically in server VAD mode. The `item_id` property is the ID of the user * message item that will be created, thus a `conversation.item.created` event * will also be sent to the client. * */ export type RealtimeServerEventInputAudioBufferCommitted = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `input_audio_buffer.committed`. */ type: 'input_audio_buffer.committed'; /** * The ID of the preceding item after which the new item will be inserted. * Can be `null` if the item has no predecessor. * */ previous_item_id?: string; /** * The ID of the user message item that will be created. */ item_id: string; }; /** * Sent by the server when in `server_vad` mode to indicate that speech has been * detected in the audio buffer. This can happen any time audio is added to the * buffer (unless speech is already detected). The client may want to use this * event to interrupt audio playback or provide visual feedback to the user. * * The client should expect to receive a `input_audio_buffer.speech_stopped` event * when speech stops. The `item_id` property is the ID of the user message item * that will be created when speech stops and will also be included in the * `input_audio_buffer.speech_stopped` event (unless the client manually commits * the audio buffer during VAD activation). * */ export type RealtimeServerEventInputAudioBufferSpeechStarted = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `input_audio_buffer.speech_started`. */ type: 'input_audio_buffer.speech_started'; /** * Milliseconds from the start of all audio written to the buffer during the * session when speech was first detected. This will correspond to the * beginning of audio sent to the model, and thus includes the * `prefix_padding_ms` configured in the Session. * */ audio_start_ms: number; /** * The ID of the user message item that will be created when speech stops. * */ item_id: string; }; /** * Returned in `server_vad` mode when the server detects the end of speech in * the audio buffer. The server will also send an `conversation.item.created` * event with the user message item that is created from the audio buffer. * */ export type RealtimeServerEventInputAudioBufferSpeechStopped = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `input_audio_buffer.speech_stopped`. */ type: 'input_audio_buffer.speech_stopped'; /** * Milliseconds since the session started when speech stopped. This will * correspond to the end of audio sent to the model, and thus includes the * `min_silence_duration_ms` configured in the Session. * */ audio_end_ms: number; /** * The ID of the user message item that will be created. */ item_id: string; }; /** * **WebRTC Only:** Emitted when the output audio buffer is cleared. This happens either in VAD * mode when the user has interrupted (`input_audio_buffer.speech_started`), * or when the client has emitted the `output_audio_buffer.clear` event to manually * cut off the current audio response. * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). * */ export type RealtimeServerEventOutputAudioBufferCleared = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `output_audio_buffer.cleared`. */ type: 'output_audio_buffer.cleared'; /** * The unique ID of the response that produced the audio. */ response_id: string; }; /** * **WebRTC Only:** Emitted when the server begins streaming audio to the client. This event is * emitted after an audio content part has been added (`response.content_part.added`) * to the response. * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). * */ export type RealtimeServerEventOutputAudioBufferStarted = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `output_audio_buffer.started`. */ type: 'output_audio_buffer.started'; /** * The unique ID of the response that produced the audio. */ response_id: string; }; /** * **WebRTC Only:** Emitted when the output audio buffer has been completely drained on the server, * and no more audio is forthcoming. This event is emitted after the full response * data has been sent to the client (`response.done`). * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). * */ export type RealtimeServerEventOutputAudioBufferStopped = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `output_audio_buffer.stopped`. */ type: 'output_audio_buffer.stopped'; /** * The unique ID of the response that produced the audio. */ response_id: string; }; /** * Emitted at the beginning of a Response to indicate the updated rate limits. * When a Response is created some tokens will be "reserved" for the output * tokens, the rate limits shown here reflect that reservation, which is then * adjusted accordingly once the Response is completed. * */ export type RealtimeServerEventRateLimitsUpdated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `rate_limits.updated`. */ type: 'rate_limits.updated'; /** * List of rate limit information. */ rate_limits: Array<{ /** * The name of the rate limit (`requests`, `tokens`). * */ name?: 'requests' | 'tokens'; /** * The maximum allowed value for the rate limit. */ limit?: number; /** * The remaining value before the limit is reached. */ remaining?: number; /** * Seconds until the rate limit resets. */ reset_seconds?: number; }>; }; /** * Returned when the model-generated audio is updated. */ export type RealtimeServerEventResponseAudioDelta = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.audio.delta`. */ type: 'response.audio.delta'; /** * The ID of the response. */ response_id: string; /** * The ID of the item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; /** * Base64-encoded audio data delta. */ delta: string; }; /** * Returned when the model-generated audio is done. Also emitted when a Response * is interrupted, incomplete, or cancelled. * */ export type RealtimeServerEventResponseAudioDone = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.audio.done`. */ type: 'response.audio.done'; /** * The ID of the response. */ response_id: string; /** * The ID of the item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; }; /** * Returned when the model-generated transcription of audio output is updated. * */ export type RealtimeServerEventResponseAudioTranscriptDelta = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.audio_transcript.delta`. */ type: 'response.audio_transcript.delta'; /** * The ID of the response. */ response_id: string; /** * The ID of the item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; /** * The transcript delta. */ delta: string; }; /** * Returned when the model-generated transcription of audio output is done * streaming. Also emitted when a Response is interrupted, incomplete, or * cancelled. * */ export type RealtimeServerEventResponseAudioTranscriptDone = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.audio_transcript.done`. */ type: 'response.audio_transcript.done'; /** * The ID of the response. */ response_id: string; /** * The ID of the item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; /** * The final transcript of the audio. */ transcript: string; }; /** * Returned when a new content part is added to an assistant message item during * response generation. * */ export type RealtimeServerEventResponseContentPartAdded = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.content_part.added`. */ type: 'response.content_part.added'; /** * The ID of the response. */ response_id: string; /** * The ID of the item to which the content part was added. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; /** * The content part that was added. */ part: { /** * The content type ("text", "audio"). */ type?: 'text' | 'audio'; /** * The text content (if type is "text"). */ text?: string; /** * Base64-encoded audio data (if type is "audio"). */ audio?: string; /** * The transcript of the audio (if type is "audio"). */ transcript?: string; }; }; /** * Returned when a content part is done streaming in an assistant message item. * Also emitted when a Response is interrupted, incomplete, or cancelled. * */ export type RealtimeServerEventResponseContentPartDone = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.content_part.done`. */ type: 'response.content_part.done'; /** * The ID of the response. */ response_id: string; /** * The ID of the item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; /** * The content part that is done. */ part: { /** * The content type ("text", "audio"). */ type?: 'text' | 'audio'; /** * The text content (if type is "text"). */ text?: string; /** * Base64-encoded audio data (if type is "audio"). */ audio?: string; /** * The transcript of the audio (if type is "audio"). */ transcript?: string; }; }; /** * Returned when a new Response is created. The first event of response creation, * where the response is in an initial state of `in_progress`. * */ export type RealtimeServerEventResponseCreated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.created`. */ type: 'response.created'; response: RealtimeResponse; }; /** * Returned when a Response is done streaming. Always emitted, no matter the * final state. The Response object included in the `response.done` event will * include all output Items in the Response but will omit the raw audio data. * */ export type RealtimeServerEventResponseDone = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.done`. */ type: 'response.done'; response: RealtimeResponse; }; /** * Returned when the model-generated function call arguments are updated. * */ export type RealtimeServerEventResponseFunctionCallArgumentsDelta = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.function_call_arguments.delta`. * */ type: 'response.function_call_arguments.delta'; /** * The ID of the response. */ response_id: string; /** * The ID of the function call item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The ID of the function call. */ call_id: string; /** * The arguments delta as a JSON string. */ delta: string; }; /** * Returned when the model-generated function call arguments are done streaming. * Also emitted when a Response is interrupted, incomplete, or cancelled. * */ export type RealtimeServerEventResponseFunctionCallArgumentsDone = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.function_call_arguments.done`. * */ type: 'response.function_call_arguments.done'; /** * The ID of the response. */ response_id: string; /** * The ID of the function call item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The ID of the function call. */ call_id: string; /** * The final arguments as a JSON string. */ arguments: string; }; /** * Returned when a new Item is created during Response generation. */ export type RealtimeServerEventResponseOutputItemAdded = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.output_item.added`. */ type: 'response.output_item.added'; /** * The ID of the Response to which the item belongs. */ response_id: string; /** * The index of the output item in the Response. */ output_index: number; item: RealtimeConversationItem; }; /** * Returned when an Item is done streaming. Also emitted when a Response is * interrupted, incomplete, or cancelled. * */ export type RealtimeServerEventResponseOutputItemDone = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.output_item.done`. */ type: 'response.output_item.done'; /** * The ID of the Response to which the item belongs. */ response_id: string; /** * The index of the output item in the Response. */ output_index: number; item: RealtimeConversationItem; }; /** * Returned when the text value of a "text" content part is updated. */ export type RealtimeServerEventResponseTextDelta = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.text.delta`. */ type: 'response.text.delta'; /** * The ID of the response. */ response_id: string; /** * The ID of the item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; /** * The text delta. */ delta: string; }; /** * Returned when the text value of a "text" content part is done streaming. Also * emitted when a Response is interrupted, incomplete, or cancelled. * */ export type RealtimeServerEventResponseTextDone = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `response.text.done`. */ type: 'response.text.done'; /** * The ID of the response. */ response_id: string; /** * The ID of the item. */ item_id: string; /** * The index of the output item in the response. */ output_index: number; /** * The index of the content part in the item's content array. */ content_index: number; /** * The final text content. */ text: string; }; /** * Returned when a Session is created. Emitted automatically when a new * connection is established as the first server event. This event will contain * the default Session configuration. * */ export type RealtimeServerEventSessionCreated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `session.created`. */ type: 'session.created'; session: RealtimeSession; }; /** * Returned when a session is updated with a `session.update` event, unless * there is an error. * */ export type RealtimeServerEventSessionUpdated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `session.updated`. */ type: 'session.updated'; session: RealtimeSession; }; /** * Returned when a transcription session is updated with a `transcription_session.update` event, unless * there is an error. * */ export type RealtimeServerEventTranscriptionSessionUpdated = { /** * The unique ID of the server event. */ event_id: string; /** * The event type, must be `transcription_session.updated`. */ type: 'transcription_session.updated'; session: RealtimeTranscriptionSessionCreateResponse; }; /** * Realtime session object configuration. */ export type RealtimeSession = { /** * Unique identifier for the session that looks like `sess_1234567890abcdef`. * */ id?: string; /** * The set of modalities the model can respond with. To disable audio, * set this to ["text"]. * */ modalities?: unknown; /** * The Realtime model used for this session. * */ model?: 'gpt-4o-realtime-preview' | 'gpt-4o-realtime-preview-2024-10-01' | 'gpt-4o-realtime-preview-2024-12-17' | 'gpt-4o-realtime-preview-2025-06-03' | 'gpt-4o-mini-realtime-preview' | 'gpt-4o-mini-realtime-preview-2024-12-17'; /** * The default system instructions (i.e. system message) prepended to model * calls. This field allows the client to guide the model on desired * responses. The model can be instructed on response content and format, * (e.g. "be extremely succinct", "act friendly", "here are examples of good * responses") and on audio behavior (e.g. "talk quickly", "inject emotion * into your voice", "laugh frequently"). The instructions are not * guaranteed to be followed by the model, but they provide guidance to the * model on the desired behavior. * * * Note that the server sets default instructions which will be used if this * field is not set and are visible in the `session.created` event at the * start of the session. * */ instructions?: string; /** * The voice the model uses to respond. Voice cannot be changed during the * session once the model has responded with audio at least once. Current * voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, * `shimmer`, and `verse`. * */ voice?: VoiceIdsShared; /** * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, * single channel (mono), and little-endian byte order. * */ input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; /** * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * For `pcm16`, output audio is sampled at a rate of 24kHz. * */ output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; /** * Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service. * */ input_audio_transcription?: { /** * The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`. * */ model?: string; /** * The language of the input audio. Supplying the input language in * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format * will improve accuracy and latency. * */ language?: string; /** * An optional text to guide the model's style or continue a previous audio * segment. * For `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). * For `gpt-4o-transcribe` models, the prompt is a free text string, for example "expect words related to technology". * */ prompt?: string; }; /** * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response. * Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. * Semantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with "uhhm", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency. * */ turn_detection?: { /** * Type of turn detection. * */ type?: 'server_vad' | 'semantic_vad'; /** * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. * */ eagerness?: 'low' | 'medium' | 'high' | 'auto'; /** * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A * higher threshold will require louder audio to activate the model, and * thus might perform better in noisy environments. * */ threshold?: number; /** * Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in * milliseconds). Defaults to 300ms. * */ prefix_padding_ms?: number; /** * Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults * to 500ms. With shorter values the model will respond more quickly, * but may jump in on short pauses from the user. * */ silence_duration_ms?: number; /** * Whether or not to automatically generate a response when a VAD stop event occurs. * */ create_response?: boolean; /** * Whether or not to automatically interrupt any ongoing response with output to the default * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs. * */ interrupt_response?: boolean; }; /** * Configuration for input audio noise reduction. This can be set to `null` to turn off. * Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model. * Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio. * */ input_audio_noise_reduction?: { /** * Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones. * */ type?: 'near_field' | 'far_field'; }; /** * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is * the minimum speed. 1.5 is the maximum speed. This value can only be changed * in between model turns, not while a response is in progress. * */ speed?: number; /** * Tracing Configuration * * Configuration options for tracing. Set to null to disable tracing. Once * tracing is enabled for a session, the configuration cannot be modified. * * `auto` will create a trace for the session with default values for the * workflow name, group id, and metadata. * */ tracing?: 'auto' | { /** * The name of the workflow to attach to this trace. This is used to * name the trace in the traces dashboard. * */ workflow_name?: string; /** * The group id to attach to this trace to enable filtering and * grouping in the traces dashboard. * */ group_id?: string; /** * The arbitrary metadata to attach to this trace to enable * filtering in the traces dashboard. * */ metadata?: { [key: string]: unknown; }; }; /** * Tools (functions) available to the model. */ tools?: Array<{ /** * The type of the tool, i.e. `function`. */ type?: 'function'; /** * The name of the function. */ name?: string; /** * The description of the function, including guidance on when and how * to call it, and guidance about what to tell the user when calling * (if anything). * */ description?: string; /** * Parameters of the function in JSON Schema. */ parameters?: { [key: string]: unknown; }; }>; /** * How the model chooses tools. Options are `auto`, `none`, `required`, or * specify a function. * */ tool_choice?: string; /** * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a temperature of 0.8 is highly recommended for best performance. * */ temperature?: number; /** * Maximum number of output tokens for a single assistant response, * inclusive of tool calls. Provide an integer between 1 and 4096 to * limit output tokens, or `inf` for the maximum available tokens for a * given model. Defaults to `inf`. * */ max_response_output_tokens?: number | 'inf'; }; /** * Realtime session object configuration. */ export type RealtimeSessionCreateRequest = { /** * The set of modalities the model can respond with. To disable audio, * set this to ["text"]. * */ modalities?: unknown; /** * The Realtime model used for this session. * */ model?: 'gpt-4o-realtime-preview' | 'gpt-4o-realtime-preview-2024-10-01' | 'gpt-4o-realtime-preview-2024-12-17' | 'gpt-4o-realtime-preview-2025-06-03' | 'gpt-4o-mini-realtime-preview' | 'gpt-4o-mini-realtime-preview-2024-12-17'; /** * The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. "be extremely succinct", "act friendly", "here are examples of good responses") and on audio behavior (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior. * * Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session. * */ instructions?: string; /** * The voice the model uses to respond. Voice cannot be changed during the * session once the model has responded with audio at least once. Current * voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, * `shimmer`, and `verse`. * */ voice?: VoiceIdsShared; /** * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, * single channel (mono), and little-endian byte order. * */ input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; /** * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * For `pcm16`, output audio is sampled at a rate of 24kHz. * */ output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; /** * Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service. * */ input_audio_transcription?: { /** * The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`. * */ model?: string; /** * The language of the input audio. Supplying the input language in * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format * will improve accuracy and latency. * */ language?: string; /** * An optional text to guide the model's style or continue a previous audio * segment. * For `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). * For `gpt-4o-transcribe` models, the prompt is a free text string, for example "expect words related to technology". * */ prompt?: string; }; /** * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response. * Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. * Semantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with "uhhm", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency. * */ turn_detection?: { /** * Type of turn detection. * */ type?: 'server_vad' | 'semantic_vad'; /** * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. * */ eagerness?: 'low' | 'medium' | 'high' | 'auto'; /** * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A * higher threshold will require louder audio to activate the model, and * thus might perform better in noisy environments. * */ threshold?: number; /** * Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in * milliseconds). Defaults to 300ms. * */ prefix_padding_ms?: number; /** * Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults * to 500ms. With shorter values the model will respond more quickly, * but may jump in on short pauses from the user. * */ silence_duration_ms?: number; /** * Whether or not to automatically generate a response when a VAD stop event occurs. * */ create_response?: boolean; /** * Whether or not to automatically interrupt any ongoing response with output to the default * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs. * */ interrupt_response?: boolean; }; /** * Configuration for input audio noise reduction. This can be set to `null` to turn off. * Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model. * Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio. * */ input_audio_noise_reduction?: { /** * Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones. * */ type?: 'near_field' | 'far_field'; }; /** * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is * the minimum speed. 1.5 is the maximum speed. This value can only be changed * in between model turns, not while a response is in progress. * */ speed?: number; /** * Tracing Configuration * * Configuration options for tracing. Set to null to disable tracing. Once * tracing is enabled for a session, the configuration cannot be modified. * * `auto` will create a trace for the session with default values for the * workflow name, group id, and metadata. * */ tracing?: 'auto' | { /** * The name of the workflow to attach to this trace. This is used to * name the trace in the traces dashboard. * */ workflow_name?: string; /** * The group id to attach to this trace to enable filtering and * grouping in the traces dashboard. * */ group_id?: string; /** * The arbitrary metadata to attach to this trace to enable * filtering in the traces dashboard. * */ metadata?: { [key: string]: unknown; }; }; /** * Tools (functions) available to the model. */ tools?: Array<{ /** * The type of the tool, i.e. `function`. */ type?: 'function'; /** * The name of the function. */ name?: string; /** * The description of the function, including guidance on when and how * to call it, and guidance about what to tell the user when calling * (if anything). * */ description?: string; /** * Parameters of the function in JSON Schema. */ parameters?: { [key: string]: unknown; }; }>; /** * How the model chooses tools. Options are `auto`, `none`, `required`, or * specify a function. * */ tool_choice?: string; /** * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a temperature of 0.8 is highly recommended for best performance. * */ temperature?: number; /** * Maximum number of output tokens for a single assistant response, * inclusive of tool calls. Provide an integer between 1 and 4096 to * limit output tokens, or `inf` for the maximum available tokens for a * given model. Defaults to `inf`. * */ max_response_output_tokens?: number | 'inf'; /** * Configuration options for the generated client secret. * */ client_secret?: { /** * Configuration for the ephemeral token expiration. * */ expires_after?: { /** * The anchor point for the ephemeral token expiration. Only `created_at` is currently supported. * */ anchor: 'created_at'; /** * The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200`. * */ seconds?: number; }; }; }; /** * A new Realtime session configuration, with an ephemeral key. Default TTL * for keys is one minute. * */ export type RealtimeSessionCreateResponse = { /** * Ephemeral key returned by the API. */ client_secret: { /** * Ephemeral key usable in client environments to authenticate connections * to the Realtime API. Use this in client-side environments rather than * a standard API token, which should only be used server-side. * */ value: string; /** * Timestamp for when the token expires. Currently, all tokens expire * after one minute. * */ expires_at: number; }; /** * The set of modalities the model can respond with. To disable audio, * set this to ["text"]. * */ modalities?: unknown; /** * The default system instructions (i.e. system message) prepended to model * calls. This field allows the client to guide the model on desired * responses. The model can be instructed on response content and format, * (e.g. "be extremely succinct", "act friendly", "here are examples of good * responses") and on audio behavior (e.g. "talk quickly", "inject emotion * into your voice", "laugh frequently"). The instructions are not guaranteed * to be followed by the model, but they provide guidance to the model on the * desired behavior. * * Note that the server sets default instructions which will be used if this * field is not set and are visible in the `session.created` event at the * start of the session. * */ instructions?: string; /** * The voice the model uses to respond. Voice cannot be changed during the * session once the model has responded with audio at least once. Current * voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, * `shimmer`, and `verse`. * */ voice?: VoiceIdsShared; /** * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * */ input_audio_format?: string; /** * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * */ output_audio_format?: string; /** * Configuration for input audio transcription, defaults to off and can be * set to `null` to turn off once on. Input audio transcription is not native * to the model, since the model consumes audio directly. Transcription runs * asynchronously and should be treated as rough guidance * rather than the representation understood by the model. * */ input_audio_transcription?: { /** * The model to use for transcription. * */ model?: string; }; /** * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is * the minimum speed. 1.5 is the maximum speed. This value can only be changed * in between model turns, not while a response is in progress. * */ speed?: number; /** * Tracing Configuration * * Configuration options for tracing. Set to null to disable tracing. Once * tracing is enabled for a session, the configuration cannot be modified. * * `auto` will create a trace for the session with default values for the * workflow name, group id, and metadata. * */ tracing?: 'auto' | { /** * The name of the workflow to attach to this trace. This is used to * name the trace in the traces dashboard. * */ workflow_name?: string; /** * The group id to attach to this trace to enable filtering and * grouping in the traces dashboard. * */ group_id?: string; /** * The arbitrary metadata to attach to this trace to enable * filtering in the traces dashboard. * */ metadata?: { [key: string]: unknown; }; }; /** * Configuration for turn detection. Can be set to `null` to turn off. Server * VAD means that the model will detect the start and end of speech based on * audio volume and respond at the end of user speech. * */ turn_detection?: { /** * Type of turn detection, only `server_vad` is currently supported. * */ type?: string; /** * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A * higher threshold will require louder audio to activate the model, and * thus might perform better in noisy environments. * */ threshold?: number; /** * Amount of audio to include before the VAD detected speech (in * milliseconds). Defaults to 300ms. * */ prefix_padding_ms?: number; /** * Duration of silence to detect speech stop (in milliseconds). Defaults * to 500ms. With shorter values the model will respond more quickly, * but may jump in on short pauses from the user. * */ silence_duration_ms?: number; }; /** * Tools (functions) available to the model. */ tools?: Array<{ /** * The type of the tool, i.e. `function`. */ type?: 'function'; /** * The name of the function. */ name?: string; /** * The description of the function, including guidance on when and how * to call it, and guidance about what to tell the user when calling * (if anything). * */ description?: string; /** * Parameters of the function in JSON Schema. */ parameters?: { [key: string]: unknown; }; }>; /** * How the model chooses tools. Options are `auto`, `none`, `required`, or * specify a function. * */ tool_choice?: string; /** * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. * */ temperature?: number; /** * Maximum number of output tokens for a single assistant response, * inclusive of tool calls. Provide an integer between 1 and 4096 to * limit output tokens, or `inf` for the maximum available tokens for a * given model. Defaults to `inf`. * */ max_response_output_tokens?: number | 'inf'; }; /** * Realtime transcription session object configuration. */ export type RealtimeTranscriptionSessionCreateRequest = { /** * The set of modalities the model can respond with. To disable audio, * set this to ["text"]. * */ modalities?: unknown; /** * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, * single channel (mono), and little-endian byte order. * */ input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; /** * Configuration for input audio transcription. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service. * */ input_audio_transcription?: { /** * The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`. * */ model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1'; /** * The language of the input audio. Supplying the input language in * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format * will improve accuracy and latency. * */ language?: string; /** * An optional text to guide the model's style or continue a previous audio * segment. * For `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). * For `gpt-4o-transcribe` models, the prompt is a free text string, for example "expect words related to technology". * */ prompt?: string; }; /** * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response. * Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. * Semantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with "uhhm", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency. * */ turn_detection?: { /** * Type of turn detection. * */ type?: 'server_vad' | 'semantic_vad'; /** * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. * */ eagerness?: 'low' | 'medium' | 'high' | 'auto'; /** * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A * higher threshold will require louder audio to activate the model, and * thus might perform better in noisy environments. * */ threshold?: number; /** * Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in * milliseconds). Defaults to 300ms. * */ prefix_padding_ms?: number; /** * Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults * to 500ms. With shorter values the model will respond more quickly, * but may jump in on short pauses from the user. * */ silence_duration_ms?: number; /** * Whether or not to automatically generate a response when a VAD stop event occurs. Not available for transcription sessions. * */ create_response?: boolean; /** * Whether or not to automatically interrupt any ongoing response with output to the default * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs. Not available for transcription sessions. * */ interrupt_response?: boolean; }; /** * Configuration for input audio noise reduction. This can be set to `null` to turn off. * Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model. * Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio. * */ input_audio_noise_reduction?: { /** * Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones. * */ type?: 'near_field' | 'far_field'; }; /** * The set of items to include in the transcription. Current available items are: * - `item.input_audio_transcription.logprobs` * */ include?: Array; /** * Configuration options for the generated client secret. * */ client_secret?: { /** * Configuration for the ephemeral token expiration. * */ expires_at?: { /** * The anchor point for the ephemeral token expiration. Only `created_at` is currently supported. * */ anchor?: 'created_at'; /** * The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200`. * */ seconds?: number; }; }; }; /** * A new Realtime transcription session configuration. * * When a session is created on the server via REST API, the session object * also contains an ephemeral key. Default TTL for keys is 10 minutes. This * property is not present when a session is updated via the WebSocket API. * */ export type RealtimeTranscriptionSessionCreateResponse = { /** * Ephemeral key returned by the API. Only present when the session is * created on the server via REST API. * */ client_secret: { /** * Ephemeral key usable in client environments to authenticate connections * to the Realtime API. Use this in client-side environments rather than * a standard API token, which should only be used server-side. * */ value: string; /** * Timestamp for when the token expires. Currently, all tokens expire * after one minute. * */ expires_at: number; }; /** * The set of modalities the model can respond with. To disable audio, * set this to ["text"]. * */ modalities?: unknown; /** * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. * */ input_audio_format?: string; /** * Configuration of the transcription model. * */ input_audio_transcription?: { /** * The model to use for transcription. Can be `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, or `whisper-1`. * */ model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1'; /** * The language of the input audio. Supplying the input language in * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format * will improve accuracy and latency. * */ language?: string; /** * An optional text to guide the model's style or continue a previous audio * segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match * the audio language. * */ prompt?: string; }; /** * Configuration for turn detection. Can be set to `null` to turn off. Server * VAD means that the model will detect the start and end of speech based on * audio volume and respond at the end of user speech. * */ turn_detection?: { /** * Type of turn detection, only `server_vad` is currently supported. * */ type?: string; /** * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A * higher threshold will require louder audio to activate the model, and * thus might perform better in noisy environments. * */ threshold?: number; /** * Amount of audio to include before the VAD detected speech (in * milliseconds). Defaults to 300ms. * */ prefix_padding_ms?: number; /** * Duration of silence to detect speech stop (in milliseconds). Defaults * to 500ms. With shorter values the model will respond more quickly, * but may jump in on short pauses from the user. * */ silence_duration_ms?: number; }; }; /** * Reasoning * * **gpt-5 and o-series models only** * * Configuration options for * [reasoning models](https://platform.openai.com/docs/guides/reasoning). * */ export type Reasoning = { effort?: ReasoningEffort; /** * A summary of the reasoning performed by the model. This can be * useful for debugging and understanding the model's reasoning process. * One of `auto`, `concise`, or `detailed`. * */ summary?: 'auto' | 'concise' | 'detailed'; /** * **Deprecated:** use `summary` instead. * * A summary of the reasoning performed by the model. This can be * useful for debugging and understanding the model's reasoning process. * One of `auto`, `concise`, or `detailed`. * * * @deprecated */ generate_summary?: 'auto' | 'concise' | 'detailed'; }; /** * Constrains effort on reasoning for * [reasoning models](https://platform.openai.com/docs/guides/reasoning). * Currently supported values are `minimal`, `low`, `medium`, and `high`. Reducing * reasoning effort can result in faster responses and fewer tokens used * on reasoning in a response. * */ export const ReasoningEffort = { MINIMAL: 'minimal', LOW: 'low', MEDIUM: 'medium', HIGH: 'high' } as const; /** * Constrains effort on reasoning for * [reasoning models](https://platform.openai.com/docs/guides/reasoning). * Currently supported values are `minimal`, `low`, `medium`, and `high`. Reducing * reasoning effort can result in faster responses and fewer tokens used * on reasoning in a response. * */ export type ReasoningEffort = typeof ReasoningEffort[keyof typeof ReasoningEffort]; /** * Reasoning * * A description of the chain of thought used by a reasoning model while generating * a response. Be sure to include these items in your `input` to the Responses API * for subsequent turns of a conversation if you are manually * [managing context](https://platform.openai.com/docs/guides/conversation-state). * */ export type ReasoningItem = { /** * The type of the object. Always `reasoning`. * */ type: 'reasoning'; /** * The unique identifier of the reasoning content. * */ id: string; /** * The encrypted content of the reasoning item - populated when a response is * generated with `reasoning.encrypted_content` in the `include` parameter. * */ encrypted_content?: string; /** * Reasoning summary content. * */ summary: Array<{ /** * The type of the object. Always `summary_text`. * */ type: 'summary_text'; /** * A summary of the reasoning output from the model so far. * */ text: string; }>; /** * Reasoning text content. * */ content?: Array<{ /** * The type of the object. Always `reasoning_text`. * */ type: 'reasoning_text'; /** * Reasoning text output from the model. * */ text: string; }>; /** * The status of the item. One of `in_progress`, `completed`, or * `incomplete`. Populated when items are returned via API. * */ status?: 'in_progress' | 'completed' | 'incomplete'; }; /** * The response object */ export type Response = ModelResponseProperties & ResponseProperties & { /** * Unique identifier for this Response. * */ id: string; /** * The object type of this resource - always set to `response`. * */ object: 'response'; /** * The status of the response generation. One of `completed`, `failed`, * `in_progress`, `cancelled`, `queued`, or `incomplete`. * */ status?: 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete'; /** * Unix timestamp (in seconds) of when this Response was created. * */ created_at: number; error: ResponseError; /** * Details about why the response is incomplete. * */ incomplete_details: { /** * The reason why the response is incomplete. */ reason?: 'max_output_tokens' | 'content_filter'; }; /** * An array of content items generated by the model. * * - The length and order of items in the `output` array is dependent * on the model's response. * - Rather than accessing the first item in the `output` array and * assuming it's an `assistant` message with the content generated by * the model, you might consider using the `output_text` property where * supported in SDKs. * */ output: Array; /** * A system (or developer) message inserted into the model's context. * * When using along with `previous_response_id`, the instructions from a previous * response will not be carried over to the next response. This makes it simple * to swap out system (or developer) messages in new responses. * */ instructions: string | Array; /** * SDK-only convenience property that contains the aggregated text output * from all `output_text` items in the `output` array, if any are present. * Supported in the Python and JavaScript SDKs. * */ output_text?: string; usage?: ResponseUsage; /** * Whether to allow the model to run tool calls in parallel. * */ parallel_tool_calls: boolean; }; /** * Emitted when there is a partial audio response. */ export type ResponseAudioDeltaEvent = { /** * The type of the event. Always `response.audio.delta`. * */ type: 'response.audio.delta'; /** * A sequence number for this chunk of the stream response. * */ sequence_number: number; /** * A chunk of Base64 encoded response audio bytes. * */ delta: string; }; /** * Emitted when the audio response is complete. */ export type ResponseAudioDoneEvent = { /** * The type of the event. Always `response.audio.done`. * */ type: 'response.audio.done'; /** * The sequence number of the delta. * */ sequence_number: number; }; /** * Emitted when there is a partial transcript of audio. */ export type ResponseAudioTranscriptDeltaEvent = { /** * The type of the event. Always `response.audio.transcript.delta`. * */ type: 'response.audio.transcript.delta'; /** * The partial transcript of the audio response. * */ delta: string; /** * The sequence number of this event. */ sequence_number: number; }; /** * Emitted when the full audio transcript is completed. */ export type ResponseAudioTranscriptDoneEvent = { /** * The type of the event. Always `response.audio.transcript.done`. * */ type: 'response.audio.transcript.done'; /** * The sequence number of this event. */ sequence_number: number; }; /** * Emitted when a partial code snippet is streamed by the code interpreter. */ export type ResponseCodeInterpreterCallCodeDeltaEvent = { /** * The type of the event. Always `response.code_interpreter_call_code.delta`. */ type: 'response.code_interpreter_call_code.delta'; /** * The index of the output item in the response for which the code is being streamed. */ output_index: number; /** * The unique identifier of the code interpreter tool call item. */ item_id: string; /** * The partial code snippet being streamed by the code interpreter. */ delta: string; /** * The sequence number of this event, used to order streaming events. */ sequence_number: number; }; /** * Emitted when the code snippet is finalized by the code interpreter. */ export type ResponseCodeInterpreterCallCodeDoneEvent = { /** * The type of the event. Always `response.code_interpreter_call_code.done`. */ type: 'response.code_interpreter_call_code.done'; /** * The index of the output item in the response for which the code is finalized. */ output_index: number; /** * The unique identifier of the code interpreter tool call item. */ item_id: string; /** * The final code snippet output by the code interpreter. */ code: string; /** * The sequence number of this event, used to order streaming events. */ sequence_number: number; }; /** * Emitted when the code interpreter call is completed. */ export type ResponseCodeInterpreterCallCompletedEvent = { /** * The type of the event. Always `response.code_interpreter_call.completed`. */ type: 'response.code_interpreter_call.completed'; /** * The index of the output item in the response for which the code interpreter call is completed. */ output_index: number; /** * The unique identifier of the code interpreter tool call item. */ item_id: string; /** * The sequence number of this event, used to order streaming events. */ sequence_number: number; }; /** * Emitted when a code interpreter call is in progress. */ export type ResponseCodeInterpreterCallInProgressEvent = { /** * The type of the event. Always `response.code_interpreter_call.in_progress`. */ type: 'response.code_interpreter_call.in_progress'; /** * The index of the output item in the response for which the code interpreter call is in progress. */ output_index: number; /** * The unique identifier of the code interpreter tool call item. */ item_id: string; /** * The sequence number of this event, used to order streaming events. */ sequence_number: number; }; /** * Emitted when the code interpreter is actively interpreting the code snippet. */ export type ResponseCodeInterpreterCallInterpretingEvent = { /** * The type of the event. Always `response.code_interpreter_call.interpreting`. */ type: 'response.code_interpreter_call.interpreting'; /** * The index of the output item in the response for which the code interpreter is interpreting code. */ output_index: number; /** * The unique identifier of the code interpreter tool call item. */ item_id: string; /** * The sequence number of this event, used to order streaming events. */ sequence_number: number; }; /** * Emitted when the model response is complete. */ export type ResponseCompletedEvent = { /** * The type of the event. Always `response.completed`. * */ type: 'response.completed'; /** * Properties of the completed response. * */ response: Response; /** * The sequence number for this event. */ sequence_number: number; }; /** * Emitted when a new content part is added. */ export type ResponseContentPartAddedEvent = { /** * The type of the event. Always `response.content_part.added`. * */ type: 'response.content_part.added'; /** * The ID of the output item that the content part was added to. * */ item_id: string; /** * The index of the output item that the content part was added to. * */ output_index: number; /** * The index of the content part that was added. * */ content_index: number; /** * The content part that was added. * */ part: OutputContent; /** * The sequence number of this event. */ sequence_number: number; }; /** * Emitted when a content part is done. */ export type ResponseContentPartDoneEvent = { /** * The type of the event. Always `response.content_part.done`. * */ type: 'response.content_part.done'; /** * The ID of the output item that the content part was added to. * */ item_id: string; /** * The index of the output item that the content part was added to. * */ output_index: number; /** * The index of the content part that is done. * */ content_index: number; /** * The sequence number of this event. */ sequence_number: number; /** * The content part that is done. * */ part: OutputContent; }; /** * An event that is emitted when a response is created. * */ export type ResponseCreatedEvent = { /** * The type of the event. Always `response.created`. * */ type: 'response.created'; /** * The response that was created. * */ response: Response; /** * The sequence number for this event. */ sequence_number: number; }; /** * ResponseCustomToolCallInputDelta * * Event representing a delta (partial update) to the input of a custom tool call. * */ export type ResponseCustomToolCallInputDeltaEvent = { /** * The event type identifier. */ type: 'response.custom_tool_call_input.delta'; /** * The sequence number of this event. */ sequence_number: number; /** * The index of the output this delta applies to. */ output_index: number; /** * Unique identifier for the API item associated with this event. */ item_id: string; /** * The incremental input data (delta) for the custom tool call. */ delta: string; }; /** * ResponseCustomToolCallInputDone * * Event indicating that input for a custom tool call is complete. * */ export type ResponseCustomToolCallInputDoneEvent = { /** * The event type identifier. */ type: 'response.custom_tool_call_input.done'; /** * The sequence number of this event. */ sequence_number: number; /** * The index of the output this event applies to. */ output_index: number; /** * Unique identifier for the API item associated with this event. */ item_id: string; /** * The complete input data for the custom tool call. */ input: string; }; /** * An error object returned when the model fails to generate a Response. * */ export type ResponseError = { code: ResponseErrorCode; /** * A human-readable description of the error. * */ message: string; }; /** * The error code for the response. * */ export const ResponseErrorCode = { SERVER_ERROR: 'server_error', RATE_LIMIT_EXCEEDED: 'rate_limit_exceeded', INVALID_PROMPT: 'invalid_prompt', VECTOR_STORE_TIMEOUT: 'vector_store_timeout', INVALID_IMAGE: 'invalid_image', INVALID_IMAGE_FORMAT: 'invalid_image_format', INVALID_BASE64_IMAGE: 'invalid_base64_image', INVALID_IMAGE_URL: 'invalid_image_url', IMAGE_TOO_LARGE: 'image_too_large', IMAGE_TOO_SMALL: 'image_too_small', IMAGE_PARSE_ERROR: 'image_parse_error', IMAGE_CONTENT_POLICY_VIOLATION: 'image_content_policy_violation', INVALID_IMAGE_MODE: 'invalid_image_mode', IMAGE_FILE_TOO_LARGE: 'image_file_too_large', UNSUPPORTED_IMAGE_MEDIA_TYPE: 'unsupported_image_media_type', EMPTY_IMAGE_FILE: 'empty_image_file', FAILED_TO_DOWNLOAD_IMAGE: 'failed_to_download_image', IMAGE_FILE_NOT_FOUND: 'image_file_not_found' } as const; /** * The error code for the response. * */ export type ResponseErrorCode = typeof ResponseErrorCode[keyof typeof ResponseErrorCode]; /** * Emitted when an error occurs. */ export type ResponseErrorEvent = { /** * The type of the event. Always `error`. * */ type: 'error'; /** * The error code. * */ code: string; /** * The error message. * */ message: string; /** * The error parameter. * */ param: string; /** * The sequence number of this event. */ sequence_number: number; }; /** * An event that is emitted when a response fails. * */ export type ResponseFailedEvent = { /** * The type of the event. Always `response.failed`. * */ type: 'response.failed'; /** * The sequence number of this event. */ sequence_number: number; /** * The response that failed. * */ response: Response; }; /** * Emitted when a file search call is completed (results found). */ export type ResponseFileSearchCallCompletedEvent = { /** * The type of the event. Always `response.file_search_call.completed`. * */ type: 'response.file_search_call.completed'; /** * The index of the output item that the file search call is initiated. * */ output_index: number; /** * The ID of the output item that the file search call is initiated. * */ item_id: string; /** * The sequence number of this event. */ sequence_number: number; }; /** * Emitted when a file search call is initiated. */ export type ResponseFileSearchCallInProgressEvent = { /** * The type of the event. Always `response.file_search_call.in_progress`. * */ type: 'response.file_search_call.in_progress'; /** * The index of the output item that the file search call is initiated. * */ output_index: number; /** * The ID of the output item that the file search call is initiated. * */ item_id: string; /** * The sequence number of this event. */ sequence_number: number; }; /** * Emitted when a file search is currently searching. */ export type ResponseFileSearchCallSearchingEvent = { /** * The type of the event. Always `response.file_search_call.searching`. * */ type: 'response.file_search_call.searching'; /** * The index of the output item that the file search call is searching. * */ output_index: number; /** * The ID of the output item that the file search call is initiated. * */ item_id: string; /** * The sequence number of this event. */ sequence_number: number; }; /** * JSON object * * JSON object response format. An older method of generating JSON responses. * Using `json_schema` is recommended for models that support it. Note that the * model will not generate JSON without a system or user message instructing it * to do so. * */ export type ResponseFormatJsonObject = { /** * The type of response format being defined. Always `json_object`. */ type: 'json_object'; }; /** * JSON schema * * JSON Schema response format. Used to generate structured JSON responses. * Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). * */ export type ResponseFormatJsonSchema = { /** * The type of response format being defined. Always `json_schema`. */ type: 'json_schema'; /** * JSON schema * * Structured Outputs configuration options, including a JSON Schema. * */ json_schema: { /** * A description of what the response format is for, used by the model to * determine how to respond in the format. * */ description?: string; /** * The name of the response format. Must be a-z, A-Z, 0-9, or contain * underscores and dashes, with a maximum length of 64. * */ name: string; schema?: ResponseFormatJsonSchemaSchema; /** * Whether to enable strict schema adherence when generating the output. * If set to true, the model will always follow the exact schema defined * in the `schema` field. Only a subset of JSON Schema is supported when * `strict` is `true`. To learn more, read the [Structured Outputs * guide](https://platform.openai.com/docs/guides/structured-outputs). * */ strict?: boolean; }; }; /** * JSON schema * * The schema for the response format, described as a JSON Schema object. * Learn how to build JSON schemas [here](https://json-schema.org/). * */ export type ResponseFormatJsonSchemaSchema = { [key: string]: unknown; }; /** * Text * * Default response format. Used to generate text responses. * */ export type ResponseFormatText = { /** * The type of response format being defined. Always `text`. */ type: 'text'; }; /** * Text grammar * * A custom grammar for the model to follow when generating text. * Learn more in the [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars). * */ export type ResponseFormatTextGrammar = { /** * The type of response format being defined. Always `grammar`. */ type: 'grammar'; /** * The custom grammar for the model to follow. */ grammar: string; }; /** * Python grammar * * Configure the model to generate valid Python code. See the * [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars) for more details. * */ export type ResponseFormatTextPython = { /** * The type of response format being defined. Always `python`. */ type: 'python'; }; /** * Emitted when there is a partial function-call arguments delta. */ export type ResponseFunctionCallArgumentsDeltaEvent = { /** * The type of the event. Always `response.function_call_arguments.delta`. * */ type: 'response.function_call_arguments.delta'; /** * The ID of the output item that the function-call arguments delta is added to. * */ item_id: string; /** * The index of the output item that the function-call arguments delta is added to. * */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; /** * The function-call arguments delta that is added. * */ delta: string; }; /** * Emitted when function-call arguments are finalized. */ export type ResponseFunctionCallArgumentsDoneEvent = { type: 'response.function_call_arguments.done'; /** * The ID of the item. */ item_id: string; /** * The index of the output item. */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; /** * The function-call arguments. */ arguments: string; }; /** * ResponseImageGenCallCompletedEvent * * Emitted when an image generation tool call has completed and the final image is available. * */ export type ResponseImageGenCallCompletedEvent = { /** * The type of the event. Always 'response.image_generation_call.completed'. */ type: 'response.image_generation_call.completed'; /** * The index of the output item in the response's output array. */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; /** * The unique identifier of the image generation item being processed. */ item_id: string; }; /** * ResponseImageGenCallGeneratingEvent * * Emitted when an image generation tool call is actively generating an image (intermediate state). * */ export type ResponseImageGenCallGeneratingEvent = { /** * The type of the event. Always 'response.image_generation_call.generating'. */ type: 'response.image_generation_call.generating'; /** * The index of the output item in the response's output array. */ output_index: number; /** * The unique identifier of the image generation item being processed. */ item_id: string; /** * The sequence number of the image generation item being processed. */ sequence_number: number; }; /** * ResponseImageGenCallInProgressEvent * * Emitted when an image generation tool call is in progress. * */ export type ResponseImageGenCallInProgressEvent = { /** * The type of the event. Always 'response.image_generation_call.in_progress'. */ type: 'response.image_generation_call.in_progress'; /** * The index of the output item in the response's output array. */ output_index: number; /** * The unique identifier of the image generation item being processed. */ item_id: string; /** * The sequence number of the image generation item being processed. */ sequence_number: number; }; /** * ResponseImageGenCallPartialImageEvent * * Emitted when a partial image is available during image generation streaming. * */ export type ResponseImageGenCallPartialImageEvent = { /** * The type of the event. Always 'response.image_generation_call.partial_image'. */ type: 'response.image_generation_call.partial_image'; /** * The index of the output item in the response's output array. */ output_index: number; /** * The unique identifier of the image generation item being processed. */ item_id: string; /** * The sequence number of the image generation item being processed. */ sequence_number: number; /** * 0-based index for the partial image (backend is 1-based, but this is 0-based for the user). */ partial_image_index: number; /** * Base64-encoded partial image data, suitable for rendering as an image. */ partial_image_b64: string; }; /** * Emitted when the response is in progress. */ export type ResponseInProgressEvent = { /** * The type of the event. Always `response.in_progress`. * */ type: 'response.in_progress'; /** * The response that is in progress. * */ response: Response; /** * The sequence number of this event. */ sequence_number: number; }; /** * An event that is emitted when a response finishes as incomplete. * */ export type ResponseIncompleteEvent = { /** * The type of the event. Always `response.incomplete`. * */ type: 'response.incomplete'; /** * The response that was incomplete. * */ response: Response; /** * The sequence number of this event. */ sequence_number: number; }; /** * A list of Response items. */ export type ResponseItemList = { /** * The type of object returned, must be `list`. */ object: 'list'; /** * A list of items used to generate this response. */ data: Array; /** * Whether there are more items available. */ has_more: boolean; /** * The ID of the first item in the list. */ first_id: string; /** * The ID of the last item in the list. */ last_id: string; }; /** * A logprob is the logarithmic probability that the model assigns to producing * a particular token at a given position in the sequence. Less-negative (higher) * logprob values indicate greater model confidence in that token choice. * */ export type ResponseLogProb = { /** * A possible text token. */ token: string; /** * The log probability of this token. * */ logprob: number; /** * The log probability of the top 20 most likely tokens. * */ top_logprobs?: Array<{ /** * A possible text token. */ token?: string; /** * The log probability of this token. */ logprob?: number; }>; }; /** * ResponseMCPCallArgumentsDeltaEvent * * Emitted when there is a delta (partial update) to the arguments of an MCP tool call. * */ export type ResponseMcpCallArgumentsDeltaEvent = { /** * The type of the event. Always 'response.mcp_call_arguments.delta'. */ type: 'response.mcp_call_arguments.delta'; /** * The index of the output item in the response's output array. */ output_index: number; /** * The unique identifier of the MCP tool call item being processed. */ item_id: string; /** * A JSON string containing the partial update to the arguments for the MCP tool call. * */ delta: string; /** * The sequence number of this event. */ sequence_number: number; }; /** * ResponseMCPCallArgumentsDoneEvent * * Emitted when the arguments for an MCP tool call are finalized. * */ export type ResponseMcpCallArgumentsDoneEvent = { /** * The type of the event. Always 'response.mcp_call_arguments.done'. */ type: 'response.mcp_call_arguments.done'; /** * The index of the output item in the response's output array. */ output_index: number; /** * The unique identifier of the MCP tool call item being processed. */ item_id: string; /** * A JSON string containing the finalized arguments for the MCP tool call. * */ arguments: string; /** * The sequence number of this event. */ sequence_number: number; }; /** * ResponseMCPCallCompletedEvent * * Emitted when an MCP tool call has completed successfully. * */ export type ResponseMcpCallCompletedEvent = { /** * The type of the event. Always 'response.mcp_call.completed'. */ type: 'response.mcp_call.completed'; /** * The ID of the MCP tool call item that completed. */ item_id: string; /** * The index of the output item that completed. */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; }; /** * ResponseMCPCallFailedEvent * * Emitted when an MCP tool call has failed. * */ export type ResponseMcpCallFailedEvent = { /** * The type of the event. Always 'response.mcp_call.failed'. */ type: 'response.mcp_call.failed'; /** * The ID of the MCP tool call item that failed. */ item_id: string; /** * The index of the output item that failed. */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; }; /** * ResponseMCPCallInProgressEvent * * Emitted when an MCP tool call is in progress. * */ export type ResponseMcpCallInProgressEvent = { /** * The type of the event. Always 'response.mcp_call.in_progress'. */ type: 'response.mcp_call.in_progress'; /** * The sequence number of this event. */ sequence_number: number; /** * The index of the output item in the response's output array. */ output_index: number; /** * The unique identifier of the MCP tool call item being processed. */ item_id: string; }; /** * ResponseMCPListToolsCompletedEvent * * Emitted when the list of available MCP tools has been successfully retrieved. * */ export type ResponseMcpListToolsCompletedEvent = { /** * The type of the event. Always 'response.mcp_list_tools.completed'. */ type: 'response.mcp_list_tools.completed'; /** * The ID of the MCP tool call item that produced this output. */ item_id: string; /** * The index of the output item that was processed. */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; }; /** * ResponseMCPListToolsFailedEvent * * Emitted when the attempt to list available MCP tools has failed. * */ export type ResponseMcpListToolsFailedEvent = { /** * The type of the event. Always 'response.mcp_list_tools.failed'. */ type: 'response.mcp_list_tools.failed'; /** * The ID of the MCP tool call item that failed. */ item_id: string; /** * The index of the output item that failed. */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; }; /** * ResponseMCPListToolsInProgressEvent * * Emitted when the system is in the process of retrieving the list of available MCP tools. * */ export type ResponseMcpListToolsInProgressEvent = { /** * The type of the event. Always 'response.mcp_list_tools.in_progress'. */ type: 'response.mcp_list_tools.in_progress'; /** * The ID of the MCP tool call item that is being processed. */ item_id: string; /** * The index of the output item that is being processed. */ output_index: number; /** * The sequence number of this event. */ sequence_number: number; }; /** * Output types that you would like the model to generate. * Most models are capable of generating text, which is the default: * * `["text"]` * * The `gpt-4o-audio-preview` model can also be used to * [generate audio](https://platform.openai.com/docs/guides/audio). To request that this model generate * both text and audio responses, you can use: * * `["text", "audio"]` * */ export type ResponseModalities = Array<'text' | 'audio'>; /** * Emitted when a new output item is added. */ export type ResponseOutputItemAddedEvent = { /** * The type of the event. Always `response.output_item.added`. * */ type: 'response.output_item.added'; /** * The index of the output item that was added. * */ output_index: number; /** * The sequence number of this event. * */ sequence_number: number; /** * The output item that was added. * */ item: OutputItem; }; /** * Emitted when an output item is marked done. */ export type ResponseOutputItemDoneEvent = { /** * The type of the event. Always `response.output_item.done`. * */ type: 'response.output_item.done'; /** * The index of the output item that was marked done. * */ output_index: number; /** * The sequence number of this event. * */ sequence_number: number; /** * The output item that was marked done. * */ item: OutputItem; }; /** * ResponseOutputTextAnnotationAddedEvent * * Emitted when an annotation is added to output text content. * */ export type ResponseOutputTextAnnotationAddedEvent = { /** * The type of the event. Always 'response.output_text.annotation.added'. */ type: 'response.output_text.annotation.added'; /** * The unique identifier of the item to which the annotation is being added. */ item_id: string; /** * The index of the output item in the response's output array. */ output_index: number; /** * The index of the content part within the output item. */ content_index: number; /** * The index of the annotation within the content part. */ annotation_index: number; /** * The sequence number of this event. */ sequence_number: number; /** * The annotation object being added. (See annotation schema for details.) */ annotation: { [key: string]: unknown; }; }; /** * Prompt Variables * * Optional map of values to substitute in for variables in your * prompt. The substitution values can either be strings, or other * Response input types like images or files. * */ export type ResponsePromptVariables = { [key: string]: string | InputTextContent | InputImageContent | InputFileContent; }; export type ResponseProperties = { /** * The unique ID of the previous response to the model. Use this to * create multi-turn conversations. Learn more about * [conversation state](https://platform.openai.com/docs/guides/conversation-state). * */ previous_response_id?: string; /** * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI * offers a wide range of models with different capabilities, performance * characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) * to browse and compare available models. * */ model?: ModelIdsResponses; reasoning?: Reasoning; /** * Whether to run the model response in the background. * [Learn more](https://platform.openai.com/docs/guides/background). * */ background?: boolean; /** * An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). * */ max_output_tokens?: number; /** * The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored. * */ max_tool_calls?: number; /** * Configuration options for a text response from the model. Can be plain * text or structured JSON data. Learn more: * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) * */ text?: { format?: TextResponseFormatConfiguration; verbosity?: Verbosity; }; /** * An array of tools the model may call while generating a response. You * can specify which tool to use by setting the `tool_choice` parameter. * * The two categories of tools you can provide the model are: * * - **Built-in tools**: Tools that are provided by OpenAI that extend the * model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) * or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about * [built-in tools](https://platform.openai.com/docs/guides/tools). * - **Function calls (custom tools)**: Functions that are defined by you, * enabling the model to call your own code with strongly typed arguments * and outputs. Learn more about * [function calling](https://platform.openai.com/docs/guides/function-calling). You can also use * custom tools to call your own code. * */ tools?: Array; /** * How the model should select which tool (or tools) to use when generating * a response. See the `tools` parameter to see how to specify which tools * the model can call. * */ tool_choice?: ToolChoiceOptions | ToolChoiceAllowed | ToolChoiceTypes | ToolChoiceFunction | ToolChoiceMcp | ToolChoiceCustom; prompt?: Prompt; /** * The truncation strategy to use for the model response. * - `auto`: If the context of this response and previous ones exceeds * the model's context window size, the model will truncate the * response to fit the context window by dropping input items in the * middle of the conversation. * - `disabled` (default): If a model response will exceed the context window * size for a model, the request will fail with a 400 error. * */ truncation?: 'auto' | 'disabled'; }; /** * ResponseQueuedEvent * * Emitted when a response is queued and waiting to be processed. * */ export type ResponseQueuedEvent = { /** * The type of the event. Always 'response.queued'. */ type: 'response.queued'; /** * The full response object that is queued. */ response: Response; /** * The sequence number for this event. */ sequence_number: number; }; /** * Emitted when a new reasoning summary part is added. */ export type ResponseReasoningSummaryPartAddedEvent = { /** * The type of the event. Always `response.reasoning_summary_part.added`. * */ type: 'response.reasoning_summary_part.added'; /** * The ID of the item this summary part is associated with. * */ item_id: string; /** * The index of the output item this summary part is associated with. * */ output_index: number; /** * The index of the summary part within the reasoning summary. * */ summary_index: number; /** * The sequence number of this event. * */ sequence_number: number; /** * The summary part that was added. * */ part: { /** * The type of the summary part. Always `summary_text`. */ type: 'summary_text'; /** * The text of the summary part. */ text: string; }; }; /** * Emitted when a reasoning summary part is completed. */ export type ResponseReasoningSummaryPartDoneEvent = { /** * The type of the event. Always `response.reasoning_summary_part.done`. * */ type: 'response.reasoning_summary_part.done'; /** * The ID of the item this summary part is associated with. * */ item_id: string; /** * The index of the output item this summary part is associated with. * */ output_index: number; /** * The index of the summary part within the reasoning summary. * */ summary_index: number; /** * The sequence number of this event. * */ sequence_number: number; /** * The completed summary part. * */ part: { /** * The type of the summary part. Always `summary_text`. */ type: 'summary_text'; /** * The text of the summary part. */ text: string; }; }; /** * Emitted when a delta is added to a reasoning summary text. */ export type ResponseReasoningSummaryTextDeltaEvent = { /** * The type of the event. Always `response.reasoning_summary_text.delta`. * */ type: 'response.reasoning_summary_text.delta'; /** * The ID of the item this summary text delta is associated with. * */ item_id: string; /** * The index of the output item this summary text delta is associated with. * */ output_index: number; /** * The index of the summary part within the reasoning summary. * */ summary_index: number; /** * The text delta that was added to the summary. * */ delta: string; /** * The sequence number of this event. * */ sequence_number: number; }; /** * Emitted when a reasoning summary text is completed. */ export type ResponseReasoningSummaryTextDoneEvent = { /** * The type of the event. Always `response.reasoning_summary_text.done`. * */ type: 'response.reasoning_summary_text.done'; /** * The ID of the item this summary text is associated with. * */ item_id: string; /** * The index of the output item this summary text is associated with. * */ output_index: number; /** * The index of the summary part within the reasoning summary. * */ summary_index: number; /** * The full text of the completed reasoning summary. * */ text: string; /** * The sequence number of this event. * */ sequence_number: number; }; /** * Emitted when a delta is added to a reasoning text. */ export type ResponseReasoningTextDeltaEvent = { /** * The type of the event. Always `response.reasoning_text.delta`. * */ type: 'response.reasoning_text.delta'; /** * The ID of the item this reasoning text delta is associated with. * */ item_id: string; /** * The index of the output item this reasoning text delta is associated with. * */ output_index: number; /** * The index of the reasoning content part this delta is associated with. * */ content_index: number; /** * The text delta that was added to the reasoning content. * */ delta: string; /** * The sequence number of this event. * */ sequence_number: number; }; /** * Emitted when a reasoning text is completed. */ export type ResponseReasoningTextDoneEvent = { /** * The type of the event. Always `response.reasoning_text.done`. * */ type: 'response.reasoning_text.done'; /** * The ID of the item this reasoning text is associated with. * */ item_id: string; /** * The index of the output item this reasoning text is associated with. * */ output_index: number; /** * The index of the reasoning content part. * */ content_index: number; /** * The full text of the completed reasoning content. * */ text: string; /** * The sequence number of this event. * */ sequence_number: number; }; /** * Emitted when there is a partial refusal text. */ export type ResponseRefusalDeltaEvent = { /** * The type of the event. Always `response.refusal.delta`. * */ type: 'response.refusal.delta'; /** * The ID of the output item that the refusal text is added to. * */ item_id: string; /** * The index of the output item that the refusal text is added to. * */ output_index: number; /** * The index of the content part that the refusal text is added to. * */ content_index: number; /** * The refusal text that is added. * */ delta: string; /** * The sequence number of this event. * */ sequence_number: number; }; /** * Emitted when refusal text is finalized. */ export type ResponseRefusalDoneEvent = { /** * The type of the event. Always `response.refusal.done`. * */ type: 'response.refusal.done'; /** * The ID of the output item that the refusal text is finalized. * */ item_id: string; /** * The index of the output item that the refusal text is finalized. * */ output_index: number; /** * The index of the content part that the refusal text is finalized. * */ content_index: number; /** * The refusal text that is finalized. * */ refusal: string; /** * The sequence number of this event. * */ sequence_number: number; }; export type ResponseStreamEvent = ({ type?: 'ResponseAudioDeltaEvent'; } & ResponseAudioDeltaEvent) | ({ type?: 'ResponseAudioDoneEvent'; } & ResponseAudioDoneEvent) | ({ type?: 'ResponseAudioTranscriptDeltaEvent'; } & ResponseAudioTranscriptDeltaEvent) | ({ type?: 'ResponseAudioTranscriptDoneEvent'; } & ResponseAudioTranscriptDoneEvent) | ({ type?: 'ResponseCodeInterpreterCallCodeDeltaEvent'; } & ResponseCodeInterpreterCallCodeDeltaEvent) | ({ type?: 'ResponseCodeInterpreterCallCodeDoneEvent'; } & ResponseCodeInterpreterCallCodeDoneEvent) | ({ type?: 'ResponseCodeInterpreterCallCompletedEvent'; } & ResponseCodeInterpreterCallCompletedEvent) | ({ type?: 'ResponseCodeInterpreterCallInProgressEvent'; } & ResponseCodeInterpreterCallInProgressEvent) | ({ type?: 'ResponseCodeInterpreterCallInterpretingEvent'; } & ResponseCodeInterpreterCallInterpretingEvent) | ({ type?: 'ResponseCompletedEvent'; } & ResponseCompletedEvent) | ({ type?: 'ResponseContentPartAddedEvent'; } & ResponseContentPartAddedEvent) | ({ type?: 'ResponseContentPartDoneEvent'; } & ResponseContentPartDoneEvent) | ({ type?: 'ResponseCreatedEvent'; } & ResponseCreatedEvent) | ({ type?: 'ResponseErrorEvent'; } & ResponseErrorEvent) | ({ type?: 'ResponseFileSearchCallCompletedEvent'; } & ResponseFileSearchCallCompletedEvent) | ({ type?: 'ResponseFileSearchCallInProgressEvent'; } & ResponseFileSearchCallInProgressEvent) | ({ type?: 'ResponseFileSearchCallSearchingEvent'; } & ResponseFileSearchCallSearchingEvent) | ({ type?: 'ResponseFunctionCallArgumentsDeltaEvent'; } & ResponseFunctionCallArgumentsDeltaEvent) | ({ type?: 'ResponseFunctionCallArgumentsDoneEvent'; } & ResponseFunctionCallArgumentsDoneEvent) | ({ type?: 'ResponseInProgressEvent'; } & ResponseInProgressEvent) | ({ type?: 'ResponseFailedEvent'; } & ResponseFailedEvent) | ({ type?: 'ResponseIncompleteEvent'; } & ResponseIncompleteEvent) | ({ type?: 'ResponseOutputItemAddedEvent'; } & ResponseOutputItemAddedEvent) | ({ type?: 'ResponseOutputItemDoneEvent'; } & ResponseOutputItemDoneEvent) | ({ type?: 'ResponseReasoningSummaryPartAddedEvent'; } & ResponseReasoningSummaryPartAddedEvent) | ({ type?: 'ResponseReasoningSummaryPartDoneEvent'; } & ResponseReasoningSummaryPartDoneEvent) | ({ type?: 'ResponseReasoningSummaryTextDeltaEvent'; } & ResponseReasoningSummaryTextDeltaEvent) | ({ type?: 'ResponseReasoningSummaryTextDoneEvent'; } & ResponseReasoningSummaryTextDoneEvent) | ({ type?: 'ResponseReasoningTextDeltaEvent'; } & ResponseReasoningTextDeltaEvent) | ({ type?: 'ResponseReasoningTextDoneEvent'; } & ResponseReasoningTextDoneEvent) | ({ type?: 'ResponseRefusalDeltaEvent'; } & ResponseRefusalDeltaEvent) | ({ type?: 'ResponseRefusalDoneEvent'; } & ResponseRefusalDoneEvent) | ({ type?: 'ResponseTextDeltaEvent'; } & ResponseTextDeltaEvent) | ({ type?: 'ResponseTextDoneEvent'; } & ResponseTextDoneEvent) | ({ type?: 'ResponseWebSearchCallCompletedEvent'; } & ResponseWebSearchCallCompletedEvent) | ({ type?: 'ResponseWebSearchCallInProgressEvent'; } & ResponseWebSearchCallInProgressEvent) | ({ type?: 'ResponseWebSearchCallSearchingEvent'; } & ResponseWebSearchCallSearchingEvent) | ({ type?: 'ResponseImageGenCallCompletedEvent'; } & ResponseImageGenCallCompletedEvent) | ({ type?: 'ResponseImageGenCallGeneratingEvent'; } & ResponseImageGenCallGeneratingEvent) | ({ type?: 'ResponseImageGenCallInProgressEvent'; } & ResponseImageGenCallInProgressEvent) | ({ type?: 'ResponseImageGenCallPartialImageEvent'; } & ResponseImageGenCallPartialImageEvent) | ({ type?: 'ResponseMCPCallArgumentsDeltaEvent'; } & ResponseMcpCallArgumentsDeltaEvent) | ({ type?: 'ResponseMCPCallArgumentsDoneEvent'; } & ResponseMcpCallArgumentsDoneEvent) | ({ type?: 'ResponseMCPCallCompletedEvent'; } & ResponseMcpCallCompletedEvent) | ({ type?: 'ResponseMCPCallFailedEvent'; } & ResponseMcpCallFailedEvent) | ({ type?: 'ResponseMCPCallInProgressEvent'; } & ResponseMcpCallInProgressEvent) | ({ type?: 'ResponseMCPListToolsCompletedEvent'; } & ResponseMcpListToolsCompletedEvent) | ({ type?: 'ResponseMCPListToolsFailedEvent'; } & ResponseMcpListToolsFailedEvent) | ({ type?: 'ResponseMCPListToolsInProgressEvent'; } & ResponseMcpListToolsInProgressEvent) | ({ type?: 'ResponseOutputTextAnnotationAddedEvent'; } & ResponseOutputTextAnnotationAddedEvent) | ({ type?: 'ResponseQueuedEvent'; } & ResponseQueuedEvent) | ({ type?: 'ResponseCustomToolCallInputDeltaEvent'; } & ResponseCustomToolCallInputDeltaEvent) | ({ type?: 'ResponseCustomToolCallInputDoneEvent'; } & ResponseCustomToolCallInputDoneEvent); /** * Options for streaming responses. Only set this when you set `stream: true`. * */ export type ResponseStreamOptions = { /** * When true, stream obfuscation will be enabled. Stream obfuscation adds * random characters to an `obfuscation` field on streaming delta events to * normalize payload sizes as a mitigation to certain side-channel attacks. * These obfuscation fields are included by default, but add a small amount * of overhead to the data stream. You can set `include_obfuscation` to * false to optimize for bandwidth if you trust the network links between * your application and the OpenAI API. * */ include_obfuscation?: boolean; }; /** * Emitted when there is an additional text delta. */ export type ResponseTextDeltaEvent = { /** * The type of the event. Always `response.output_text.delta`. * */ type: 'response.output_text.delta'; /** * The ID of the output item that the text delta was added to. * */ item_id: string; /** * The index of the output item that the text delta was added to. * */ output_index: number; /** * The index of the content part that the text delta was added to. * */ content_index: number; /** * The text delta that was added. * */ delta: string; /** * The sequence number for this event. */ sequence_number: number; /** * The log probabilities of the tokens in the delta. * */ logprobs: Array; }; /** * Emitted when text content is finalized. */ export type ResponseTextDoneEvent = { /** * The type of the event. Always `response.output_text.done`. * */ type: 'response.output_text.done'; /** * The ID of the output item that the text content is finalized. * */ item_id: string; /** * The index of the output item that the text content is finalized. * */ output_index: number; /** * The index of the content part that the text content is finalized. * */ content_index: number; /** * The text content that is finalized. * */ text: string; /** * The sequence number for this event. */ sequence_number: number; /** * The log probabilities of the tokens in the delta. * */ logprobs: Array; }; /** * Represents token usage details including input tokens, output tokens, * a breakdown of output tokens, and the total tokens used. * */ export type ResponseUsage = { /** * The number of input tokens. */ input_tokens: number; /** * A detailed breakdown of the input tokens. */ input_tokens_details: { /** * The number of tokens that were retrieved from the cache. * [More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching). * */ cached_tokens: number; }; /** * The number of output tokens. */ output_tokens: number; /** * A detailed breakdown of the output tokens. */ output_tokens_details: { /** * The number of reasoning tokens. */ reasoning_tokens: number; }; /** * The total number of tokens used. */ total_tokens: number; }; /** * Emitted when a web search call is completed. */ export type ResponseWebSearchCallCompletedEvent = { /** * The type of the event. Always `response.web_search_call.completed`. * */ type: 'response.web_search_call.completed'; /** * The index of the output item that the web search call is associated with. * */ output_index: number; /** * Unique ID for the output item associated with the web search call. * */ item_id: string; /** * The sequence number of the web search call being processed. */ sequence_number: number; }; /** * Emitted when a web search call is initiated. */ export type ResponseWebSearchCallInProgressEvent = { /** * The type of the event. Always `response.web_search_call.in_progress`. * */ type: 'response.web_search_call.in_progress'; /** * The index of the output item that the web search call is associated with. * */ output_index: number; /** * Unique ID for the output item associated with the web search call. * */ item_id: string; /** * The sequence number of the web search call being processed. */ sequence_number: number; }; /** * Emitted when a web search call is executing. */ export type ResponseWebSearchCallSearchingEvent = { /** * The type of the event. Always `response.web_search_call.searching`. * */ type: 'response.web_search_call.searching'; /** * The index of the output item that the web search call is associated with. * */ output_index: number; /** * Unique ID for the output item associated with the web search call. * */ item_id: string; /** * The sequence number of the web search call being processed. */ sequence_number: number; }; /** * Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). */ export type RunCompletionUsage = { /** * Number of completion tokens used over the course of the run. */ completion_tokens: number; /** * Number of prompt tokens used over the course of the run. */ prompt_tokens: number; /** * Total number of tokens used (prompt + completion). */ total_tokens: number; }; /** * RunGraderRequest */ export type RunGraderRequest = { /** * The grader used for the fine-tuning job. */ grader: ({ type?: 'GraderStringCheck'; } & GraderStringCheck) | ({ type?: 'GraderTextSimilarity'; } & GraderTextSimilarity) | ({ type?: 'GraderPython'; } & GraderPython) | ({ type?: 'GraderScoreModel'; } & GraderScoreModel) | ({ type?: 'GraderMulti'; } & GraderMulti); /** * The dataset item provided to the grader. This will be used to populate * the `item` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details. * */ item?: { [key: string]: unknown; }; /** * The model sample to be evaluated. This value will be used to populate * the `sample` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details. * The `output_json` variable will be populated if the model sample is a * valid JSON string. * */ model_sample: string; }; export type RunGraderResponse = { reward: number; metadata: { name: string; type: string; errors: { formula_parse_error: boolean; sample_parse_error: boolean; truncated_observation_error: boolean; unresponsive_reward_error: boolean; invalid_variable_error: boolean; other_error: boolean; python_grader_server_error: boolean; python_grader_server_error_type: string; python_grader_runtime_error: boolean; python_grader_runtime_error_details: string; model_grader_server_error: boolean; model_grader_refusal_error: boolean; model_grader_parse_error: boolean; model_grader_server_error_details: string; }; execution_time: number; scores: { [key: string]: unknown; }; token_usage: number; sampled_model_name: string; }; sub_rewards: { [key: string]: unknown; }; model_grader_token_usage_per_model: { [key: string]: unknown; }; }; /** * A run on a thread * * Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads). */ export type RunObject = { /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `thread.run`. */ object: 'thread.run'; /** * The Unix timestamp (in seconds) for when the run was created. */ created_at: number; /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was executed on as a part of this run. */ thread_id: string; /** * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for execution of this run. */ assistant_id: string; status: RunStatus; /** * Details on the action required to continue the run. Will be `null` if no action is required. */ required_action: { /** * For now, this is always `submit_tool_outputs`. */ type: 'submit_tool_outputs'; /** * Details on the tool outputs needed for this run to continue. */ submit_tool_outputs: { /** * A list of the relevant tool calls. */ tool_calls: Array; }; }; /** * The last error associated with this run. Will be `null` if there are no errors. */ last_error: { /** * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. */ code: 'server_error' | 'rate_limit_exceeded' | 'invalid_prompt'; /** * A human-readable description of the error. */ message: string; }; /** * The Unix timestamp (in seconds) for when the run will expire. */ expires_at: number; /** * The Unix timestamp (in seconds) for when the run was started. */ started_at: number; /** * The Unix timestamp (in seconds) for when the run was cancelled. */ cancelled_at: number; /** * The Unix timestamp (in seconds) for when the run failed. */ failed_at: number; /** * The Unix timestamp (in seconds) for when the run was completed. */ completed_at: number; /** * Details on why the run is incomplete. Will be `null` if the run is not incomplete. */ incomplete_details: { /** * The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. */ reason?: 'max_completion_tokens' | 'max_prompt_tokens'; }; /** * The model that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run. */ model: string; /** * The instructions that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run. */ instructions: string; /** * The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run. */ tools: Array; metadata: Metadata; usage: RunCompletionUsage; /** * The sampling temperature used for this run. If not set, defaults to 1. */ temperature?: number; /** * The nucleus sampling value used for this run. If not set, defaults to 1. */ top_p?: number; /** * The maximum number of prompt tokens specified to have been used over the course of the run. * */ max_prompt_tokens: number; /** * The maximum number of completion tokens specified to have been used over the course of the run. * */ max_completion_tokens: number; truncation_strategy: TruncationObject & unknown; tool_choice: AssistantsApiToolChoiceOption & unknown; parallel_tool_calls: ParallelToolCalls; response_format: AssistantsApiResponseFormatOption; }; /** * Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. */ export type RunStepCompletionUsage = { /** * Number of completion tokens used over the course of the run step. */ completion_tokens: number; /** * Number of prompt tokens used over the course of the run step. */ prompt_tokens: number; /** * Total number of tokens used (prompt + completion). */ total_tokens: number; }; /** * Run step delta object * * Represents a run step delta i.e. any changed fields on a run step during streaming. * */ export type RunStepDeltaObject = { /** * The identifier of the run step, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `thread.run.step.delta`. */ object: 'thread.run.step.delta'; delta: RunStepDeltaObjectDelta; }; /** * Message creation * * Details of the message creation by the run step. */ export type RunStepDeltaStepDetailsMessageCreationObject = { /** * Always `message_creation`. */ type: 'message_creation'; message_creation?: { /** * The ID of the message that was created by this run step. */ message_id?: string; }; }; /** * Code interpreter tool call * * Details of the Code Interpreter tool call the run step was involved in. */ export type RunStepDeltaStepDetailsToolCallsCodeObject = { /** * The index of the tool call in the tool calls array. */ index: number; /** * The ID of the tool call. */ id?: string; /** * The type of tool call. This is always going to be `code_interpreter` for this type of tool call. */ type: 'code_interpreter'; /** * The Code Interpreter tool call definition. */ code_interpreter?: { /** * The input to the Code Interpreter tool call. */ input?: string; /** * The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. */ outputs?: Array<({ type?: 'RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject'; } & RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject) | ({ type?: 'RunStepDeltaStepDetailsToolCallsCodeOutputImageObject'; } & RunStepDeltaStepDetailsToolCallsCodeOutputImageObject)>; }; }; /** * Code interpreter image output */ export type RunStepDeltaStepDetailsToolCallsCodeOutputImageObject = { /** * The index of the output in the outputs array. */ index: number; /** * Always `image`. */ type: 'image'; image?: { /** * The [file](https://platform.openai.com/docs/api-reference/files) ID of the image. */ file_id?: string; }; }; /** * Code interpreter log output * * Text output from the Code Interpreter tool call as part of a run step. */ export type RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject = { /** * The index of the output in the outputs array. */ index: number; /** * Always `logs`. */ type: 'logs'; /** * The text output from the Code Interpreter tool call. */ logs?: string; }; /** * File search tool call */ export type RunStepDeltaStepDetailsToolCallsFileSearchObject = { /** * The index of the tool call in the tool calls array. */ index: number; /** * The ID of the tool call object. */ id?: string; /** * The type of tool call. This is always going to be `file_search` for this type of tool call. */ type: 'file_search'; /** * For now, this is always going to be an empty object. */ file_search: { [key: string]: unknown; }; }; /** * Function tool call */ export type RunStepDeltaStepDetailsToolCallsFunctionObject = { /** * The index of the tool call in the tool calls array. */ index: number; /** * The ID of the tool call object. */ id?: string; /** * The type of tool call. This is always going to be `function` for this type of tool call. */ type: 'function'; /** * The definition of the function that was called. */ function?: { /** * The name of the function. */ name?: string; /** * The arguments passed to the function. */ arguments?: string; /** * The output of the function. This will be `null` if the outputs have not been [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet. */ output?: string; }; }; /** * Tool calls * * Details of the tool call. */ export type RunStepDeltaStepDetailsToolCallsObject = { /** * Always `tool_calls`. */ type: 'tool_calls'; /** * An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. * */ tool_calls?: Array; }; /** * Message creation * * Details of the message creation by the run step. */ export type RunStepDetailsMessageCreationObject = { /** * Always `message_creation`. */ type: 'message_creation'; message_creation: { /** * The ID of the message that was created by this run step. */ message_id: string; }; }; /** * Code Interpreter tool call * * Details of the Code Interpreter tool call the run step was involved in. */ export type RunStepDetailsToolCallsCodeObject = { /** * The ID of the tool call. */ id: string; /** * The type of tool call. This is always going to be `code_interpreter` for this type of tool call. */ type: 'code_interpreter'; /** * The Code Interpreter tool call definition. */ code_interpreter: { /** * The input to the Code Interpreter tool call. */ input: string; /** * The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. */ outputs: Array<({ type?: 'RunStepDetailsToolCallsCodeOutputLogsObject'; } & RunStepDetailsToolCallsCodeOutputLogsObject) | ({ type?: 'RunStepDetailsToolCallsCodeOutputImageObject'; } & RunStepDetailsToolCallsCodeOutputImageObject)>; }; }; /** * Code Interpreter image output */ export type RunStepDetailsToolCallsCodeOutputImageObject = { /** * Always `image`. */ type: 'image'; image: { /** * The [file](https://platform.openai.com/docs/api-reference/files) ID of the image. */ file_id: string; }; }; /** * Code Interpreter log output * * Text output from the Code Interpreter tool call as part of a run step. */ export type RunStepDetailsToolCallsCodeOutputLogsObject = { /** * Always `logs`. */ type: 'logs'; /** * The text output from the Code Interpreter tool call. */ logs: string; }; /** * File search tool call */ export type RunStepDetailsToolCallsFileSearchObject = { /** * The ID of the tool call object. */ id: string; /** * The type of tool call. This is always going to be `file_search` for this type of tool call. */ type: 'file_search'; /** * For now, this is always going to be an empty object. */ file_search: { ranking_options?: RunStepDetailsToolCallsFileSearchRankingOptionsObject; /** * The results of the file search. */ results?: Array; }; }; /** * File search tool call ranking options * * The ranking options for the file search. */ export type RunStepDetailsToolCallsFileSearchRankingOptionsObject = { ranker: FileSearchRanker; /** * The score threshold for the file search. All values must be a floating point number between 0 and 1. */ score_threshold: number; }; /** * File search tool call result * * A result instance of the file search. */ export type RunStepDetailsToolCallsFileSearchResultObject = { /** * The ID of the file that result was found in. */ file_id: string; /** * The name of the file that result was found in. */ file_name: string; /** * The score of the result. All values must be a floating point number between 0 and 1. */ score: number; /** * The content of the result that was found. The content is only included if requested via the include query parameter. */ content?: Array<{ /** * The type of the content. */ type?: 'text'; /** * The text content of the file. */ text?: string; }>; }; /** * Function tool call */ export type RunStepDetailsToolCallsFunctionObject = { /** * The ID of the tool call object. */ id: string; /** * The type of tool call. This is always going to be `function` for this type of tool call. */ type: 'function'; /** * The definition of the function that was called. */ function: { /** * The name of the function. */ name: string; /** * The arguments passed to the function. */ arguments: string; /** * The output of the function. This will be `null` if the outputs have not been [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet. */ output: string; }; }; /** * Tool calls * * Details of the tool call. */ export type RunStepDetailsToolCallsObject = { /** * Always `tool_calls`. */ type: 'tool_calls'; /** * An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. * */ tool_calls: Array; }; /** * Run steps * * Represents a step in execution of a run. * */ export type RunStepObject = { /** * The identifier of the run step, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `thread.run.step`. */ object: 'thread.run.step'; /** * The Unix timestamp (in seconds) for when the run step was created. */ created_at: number; /** * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) associated with the run step. */ assistant_id: string; /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. */ thread_id: string; /** * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that this run step is a part of. */ run_id: string; /** * The type of run step, which can be either `message_creation` or `tool_calls`. */ type: 'message_creation' | 'tool_calls'; /** * The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`. */ status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired'; /** * The details of the run step. */ step_details: ({ type?: 'RunStepDetailsMessageCreationObject'; } & RunStepDetailsMessageCreationObject) | ({ type?: 'RunStepDetailsToolCallsObject'; } & RunStepDetailsToolCallsObject); /** * The last error associated with this run step. Will be `null` if there are no errors. */ last_error: { /** * One of `server_error` or `rate_limit_exceeded`. */ code: 'server_error' | 'rate_limit_exceeded'; /** * A human-readable description of the error. */ message: string; }; /** * The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. */ expired_at: number; /** * The Unix timestamp (in seconds) for when the run step was cancelled. */ cancelled_at: number; /** * The Unix timestamp (in seconds) for when the run step failed. */ failed_at: number; /** * The Unix timestamp (in seconds) for when the run step completed. */ completed_at: number; metadata: Metadata; usage: RunStepCompletionUsage; }; export type RunStepStreamEvent = { event: 'thread.run.step.created'; data: RunStepObject; } | { event: 'thread.run.step.in_progress'; data: RunStepObject; } | { event: 'thread.run.step.delta'; data: RunStepDeltaObject; } | { event: 'thread.run.step.completed'; data: RunStepObject; } | { event: 'thread.run.step.failed'; data: RunStepObject; } | { event: 'thread.run.step.cancelled'; data: RunStepObject; } | { event: 'thread.run.step.expired'; data: RunStepObject; }; export type RunStreamEvent = { event: 'thread.run.created'; data: RunObject; } | { event: 'thread.run.queued'; data: RunObject; } | { event: 'thread.run.in_progress'; data: RunObject; } | { event: 'thread.run.requires_action'; data: RunObject; } | { event: 'thread.run.completed'; data: RunObject; } | { event: 'thread.run.incomplete'; data: RunObject; } | { event: 'thread.run.failed'; data: RunObject; } | { event: 'thread.run.cancelling'; data: RunObject; } | { event: 'thread.run.cancelled'; data: RunObject; } | { event: 'thread.run.expired'; data: RunObject; }; /** * Tool call objects */ export type RunToolCallObject = { /** * The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoint. */ id: string; /** * The type of tool call the output is required for. For now, this is always `function`. */ type: 'function'; /** * The function definition. */ function: { /** * The name of the function. */ name: string; /** * The arguments that the model expects you to pass to the function. */ arguments: string; }; }; /** * Screenshot * * A screenshot action. * */ export type Screenshot = { /** * Specifies the event type. For a screenshot action, this property is * always set to `screenshot`. * */ type: 'screenshot'; }; /** * Scroll * * A scroll action. * */ export type Scroll = { /** * Specifies the event type. For a scroll action, this property is * always set to `scroll`. * */ type: 'scroll'; /** * The x-coordinate where the scroll occurred. * */ x: number; /** * The y-coordinate where the scroll occurred. * */ y: number; /** * The horizontal scroll distance. * */ scroll_x: number; /** * The vertical scroll distance. * */ scroll_y: number; }; /** * Specifies the processing type used for serving the request. * - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'. * - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model. * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier. * - When not set, the default behavior is 'auto'. * * When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter. * */ export const ServiceTier = { AUTO: 'auto', DEFAULT: 'default', FLEX: 'flex', SCALE: 'scale', PRIORITY: 'priority' } as const; /** * Specifies the processing type used for serving the request. * - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'. * - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model. * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier. * - When not set, the default behavior is 'auto'. * * When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter. * */ export type ServiceTier = typeof ServiceTier[keyof typeof ServiceTier]; /** * Emitted for each chunk of audio data generated during speech synthesis. */ export type SpeechAudioDeltaEvent = { /** * The type of the event. Always `speech.audio.delta`. * */ type: 'speech.audio.delta'; /** * A chunk of Base64-encoded audio data. * */ audio: string; }; /** * Emitted when the speech synthesis is complete and all audio has been streamed. */ export type SpeechAudioDoneEvent = { /** * The type of the event. Always `speech.audio.done`. * */ type: 'speech.audio.done'; /** * Token usage statistics for the request. * */ usage: { /** * Number of input tokens in the prompt. */ input_tokens: number; /** * Number of output tokens generated. */ output_tokens: number; /** * Total number of tokens used (input + output). */ total_tokens: number; }; }; export type StaticChunkingStrategy = { /** * The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. */ max_chunk_size_tokens: number; /** * The number of tokens that overlap between chunks. The default value is `400`. * * Note that the overlap must not exceed half of `max_chunk_size_tokens`. * */ chunk_overlap_tokens: number; }; /** * Static Chunking Strategy * * Customize your own chunking strategy by setting chunk size and chunk overlap. */ export type StaticChunkingStrategyRequestParam = { /** * Always `static`. */ type: 'static'; static: StaticChunkingStrategy; }; /** * Static Chunking Strategy */ export type StaticChunkingStrategyResponseParam = { /** * Always `static`. */ type: 'static'; static: StaticChunkingStrategy; }; /** * Not supported with latest reasoning models `o3` and `o4-mini`. * * Up to 4 sequences where the API will stop generating further tokens. The * returned text will not contain the stop sequence. * */ export type StopConfiguration = string | Array; export type SubmitToolOutputsRunRequest = { /** * A list of tools for which the outputs are being submitted. */ tool_outputs: Array<{ /** * The ID of the tool call in the `required_action` object within the run object the output is being submitted for. */ tool_call_id?: string; /** * The output of the tool call to be submitted to continue the run. */ output?: string; }>; /** * If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. * */ stream?: boolean; }; /** * An object specifying the format that the model must output. * * Configuring `{ "type": "json_schema" }` enables Structured Outputs, * which ensures the model will match your supplied JSON schema. Learn more in the * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). * * The default format is `{ "type": "text" }` with no additional options. * * **Not recommended for gpt-4o and newer models:** * * Setting to `{ "type": "json_object" }` enables the older JSON mode, which * ensures the message the model generates is valid JSON. Using `json_schema` * is preferred for models that support it. * */ export type TextResponseFormatConfiguration = ({ type?: 'ResponseFormatText'; } & ResponseFormatText) | ({ type?: 'TextResponseFormatJsonSchema'; } & TextResponseFormatJsonSchema) | ({ type?: 'ResponseFormatJsonObject'; } & ResponseFormatJsonObject); /** * JSON schema * * JSON Schema response format. Used to generate structured JSON responses. * Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). * */ export type TextResponseFormatJsonSchema = { /** * The type of response format being defined. Always `json_schema`. */ type: 'json_schema'; /** * A description of what the response format is for, used by the model to * determine how to respond in the format. * */ description?: string; /** * The name of the response format. Must be a-z, A-Z, 0-9, or contain * underscores and dashes, with a maximum length of 64. * */ name: string; schema: ResponseFormatJsonSchemaSchema; /** * Whether to enable strict schema adherence when generating the output. * If set to true, the model will always follow the exact schema defined * in the `schema` field. Only a subset of JSON Schema is supported when * `strict` is `true`. To learn more, read the [Structured Outputs * guide](https://platform.openai.com/docs/guides/structured-outputs). * */ strict?: boolean; }; /** * Thread * * Represents a thread that contains [messages](https://platform.openai.com/docs/api-reference/messages). */ export type ThreadObject = { /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `thread`. */ object: 'thread'; /** * The Unix timestamp (in seconds) for when the thread was created. */ created_at: number; /** * A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources: { code_interpreter?: { /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: { /** * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. * */ vector_store_ids?: Array; }; }; metadata: Metadata; }; /** * Occurs when a new [thread](https://platform.openai.com/docs/api-reference/threads/object) is created. */ export type ThreadStreamEvent = { /** * Whether to enable input audio transcription. */ enabled?: boolean; event: 'thread.created'; data: ThreadObject; }; export type ToggleCertificatesRequest = { certificate_ids: Array; }; /** * A tool that can be used to generate a response. * */ export type Tool = ({ type?: 'FunctionTool'; } & FunctionTool) | ({ type?: 'FileSearchTool'; } & FileSearchTool) | ({ type?: 'WebSearchPreviewTool'; } & WebSearchPreviewTool) | ({ type?: 'ComputerUsePreviewTool'; } & ComputerUsePreviewTool) | ({ type?: 'MCPTool'; } & McpTool) | ({ type?: 'CodeInterpreterTool'; } & CodeInterpreterTool) | ({ type?: 'ImageGenTool'; } & ImageGenTool) | ({ type?: 'LocalShellTool'; } & LocalShellTool) | ({ type?: 'CustomTool'; } & CustomTool); /** * Allowed tools * * Constrains the tools available to the model to a pre-defined set. * */ export type ToolChoiceAllowed = { /** * Allowed tool configuration type. Always `allowed_tools`. */ type: 'allowed_tools'; /** * Constrains the tools available to the model to a pre-defined set. * * `auto` allows the model to pick from among the allowed tools and generate a * message. * * `required` requires the model to call one or more of the allowed tools. * */ mode: 'auto' | 'required'; /** * A list of tool definitions that the model should be allowed to call. * * For the Responses API, the list of tool definitions might look like: * ```json * [ * { "type": "function", "name": "get_weather" }, * { "type": "mcp", "server_label": "deepwiki" }, * { "type": "image_generation" } * ] * ``` * */ tools: Array<{ [key: string]: unknown; }>; }; /** * Custom tool * * Use this option to force the model to call a specific custom tool. * */ export type ToolChoiceCustom = { /** * For custom tool calling, the type is always `custom`. */ type: 'custom'; /** * The name of the custom tool to call. */ name: string; }; /** * Function tool * * Use this option to force the model to call a specific function. * */ export type ToolChoiceFunction = { /** * For function calling, the type is always `function`. */ type: 'function'; /** * The name of the function to call. */ name: string; }; /** * MCP tool * * Use this option to force the model to call a specific tool on a remote MCP server. * */ export type ToolChoiceMcp = { /** * For MCP tools, the type is always `mcp`. */ type: 'mcp'; /** * The label of the MCP server to use. * */ server_label: string; /** * The name of the tool to call on the server. * */ name?: string; }; /** * Tool choice mode * * Controls which (if any) tool is called by the model. * * `none` means the model will not call any tool and instead generates a message. * * `auto` means the model can pick between generating a message or calling one or * more tools. * * `required` means the model must call one or more tools. * */ export const ToolChoiceOptions = { NONE: 'none', AUTO: 'auto', REQUIRED: 'required' } as const; /** * Tool choice mode * * Controls which (if any) tool is called by the model. * * `none` means the model will not call any tool and instead generates a message. * * `auto` means the model can pick between generating a message or calling one or * more tools. * * `required` means the model must call one or more tools. * */ export type ToolChoiceOptions = typeof ToolChoiceOptions[keyof typeof ToolChoiceOptions]; /** * Hosted tool * * Indicates that the model should use a built-in tool to generate a response. * [Learn more about built-in tools](https://platform.openai.com/docs/guides/tools). * */ export type ToolChoiceTypes = { /** * The type of hosted tool the model should to use. Learn more about * [built-in tools](https://platform.openai.com/docs/guides/tools). * * Allowed values are: * - `file_search` * - `web_search_preview` * - `computer_use_preview` * - `code_interpreter` * - `image_generation` * */ type: 'file_search' | 'web_search_preview' | 'computer_use_preview' | 'web_search_preview_2025_03_11' | 'image_generation' | 'code_interpreter'; }; /** * Emitted when there is an additional text delta. This is also the first event emitted when the transcription starts. Only emitted when you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`. */ export type TranscriptTextDeltaEvent = { /** * The type of the event. Always `transcript.text.delta`. * */ type: 'transcript.text.delta'; /** * The text delta that was additionally transcribed. * */ delta: string; /** * The log probabilities of the delta. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`. * */ logprobs?: Array<{ /** * The token that was used to generate the log probability. * */ token?: string; /** * The log probability of the token. * */ logprob?: number; /** * The bytes that were used to generate the log probability. * */ bytes?: Array; }>; }; /** * Emitted when the transcription is complete. Contains the complete transcription text. Only emitted when you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`. */ export type TranscriptTextDoneEvent = { /** * The type of the event. Always `transcript.text.done`. * */ type: 'transcript.text.done'; /** * The text that was transcribed. * */ text: string; /** * The log probabilities of the individual tokens in the transcription. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`. * */ logprobs?: Array<{ /** * The token that was used to generate the log probability. * */ token?: string; /** * The log probability of the token. * */ logprob?: number; /** * The bytes that were used to generate the log probability. * */ bytes?: Array; }>; usage?: TranscriptTextUsageTokens; }; /** * Duration Usage * * Usage statistics for models billed by audio input duration. */ export type TranscriptTextUsageDuration = { /** * The type of the usage object. Always `duration` for this variant. */ type: 'duration'; /** * Duration of the input audio in seconds. */ seconds: number; }; /** * Token Usage * * Usage statistics for models billed by token usage. */ export type TranscriptTextUsageTokens = { /** * The type of the usage object. Always `tokens` for this variant. */ type: 'tokens'; /** * Number of input tokens billed for this request. */ input_tokens: number; /** * Details about the input tokens billed for this request. */ input_token_details?: { /** * Number of text tokens billed for this request. */ text_tokens?: number; /** * Number of audio tokens billed for this request. */ audio_tokens?: number; }; /** * Number of output tokens generated. */ output_tokens: number; /** * Total number of tokens used (input + output). */ total_tokens: number; }; /** * Controls how the audio is cut into chunks. When set to `"auto"`, the server first normalizes loudness and then uses voice activity detection (VAD) to choose boundaries. `server_vad` object can be provided to tweak VAD detection parameters manually. If unset, the audio is transcribed as a single block. */ export type TranscriptionChunkingStrategy = 'auto' | VadConfig; export const TranscriptionInclude = { LOGPROBS: 'logprobs' } as const; export type TranscriptionInclude = typeof TranscriptionInclude[keyof typeof TranscriptionInclude]; export type TranscriptionSegment = { /** * Unique identifier of the segment. */ id: number; /** * Seek offset of the segment. */ seek: number; /** * Start time of the segment in seconds. */ start: number; /** * End time of the segment in seconds. */ end: number; /** * Text content of the segment. */ text: string; /** * Array of token IDs for the text content. */ tokens: Array; /** * Temperature parameter used for generating the segment. */ temperature: number; /** * Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. */ avg_logprob: number; /** * Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. */ compression_ratio: number; /** * Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. */ no_speech_prob: number; }; export type TranscriptionWord = { /** * The text content of the word. */ word: string; /** * Start time of the word in seconds. */ start: number; /** * End time of the word in seconds. */ end: number; }; /** * Thread Truncation Controls * * Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run. */ export type TruncationObject = { /** * The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`. */ type: 'auto' | 'last_messages'; /** * The number of most recent messages from the thread when constructing the context for the run. */ last_messages?: number; }; /** * Type * * An action to type in text. * */ export type Type = { /** * Specifies the event type. For a type action, this property is * always set to `type`. * */ type: 'type'; /** * The text to type. * */ text: string; }; export type UpdateVectorStoreFileAttributesRequest = { attributes: VectorStoreFileAttributes; }; export type UpdateVectorStoreRequest = { /** * The name of the vector store. */ name?: string; expires_after?: VectorStoreExpirationAfter & unknown; metadata?: Metadata; }; /** * Upload * * The Upload object can accept byte chunks in the form of Parts. * */ export type Upload = { /** * The Upload unique identifier, which can be referenced in API endpoints. */ id: string; /** * The Unix timestamp (in seconds) for when the Upload was created. */ created_at: number; /** * The name of the file to be uploaded. */ filename: string; /** * The intended number of bytes to be uploaded. */ bytes: number; /** * The intended purpose of the file. [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for acceptable values. */ purpose: string; /** * The status of the Upload. */ status: 'pending' | 'completed' | 'cancelled' | 'expired'; /** * The Unix timestamp (in seconds) for when the Upload will expire. */ expires_at: number; /** * The object type, which is always "upload". */ object: 'upload'; file?: OpenAiFile & unknown; }; export type UploadCertificateRequest = { /** * An optional name for the certificate */ name?: string; /** * The certificate content in PEM format */ content: string; }; /** * UploadPart * * The upload Part represents a chunk of bytes we can add to an Upload object. * */ export type UploadPart = { /** * The upload Part unique identifier, which can be referenced in API endpoints. */ id: string; /** * The Unix timestamp (in seconds) for when the Part was created. */ created_at: number; /** * The ID of the Upload object that this Part was added to. */ upload_id: string; /** * The object type, which is always `upload.part`. */ object: 'upload.part'; }; /** * The aggregated audio speeches usage details of the specific time bucket. */ export type UsageAudioSpeechesResult = { object: 'organization.usage.audio_speeches.result'; /** * The number of characters processed. */ characters: number; /** * The count of requests made to the model. */ num_model_requests: number; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; /** * When `group_by=user_id`, this field provides the user ID of the grouped usage result. */ user_id?: string; /** * When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. */ api_key_id?: string; /** * When `group_by=model`, this field provides the model name of the grouped usage result. */ model?: string; }; /** * The aggregated audio transcriptions usage details of the specific time bucket. */ export type UsageAudioTranscriptionsResult = { object: 'organization.usage.audio_transcriptions.result'; /** * The number of seconds processed. */ seconds: number; /** * The count of requests made to the model. */ num_model_requests: number; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; /** * When `group_by=user_id`, this field provides the user ID of the grouped usage result. */ user_id?: string; /** * When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. */ api_key_id?: string; /** * When `group_by=model`, this field provides the model name of the grouped usage result. */ model?: string; }; /** * The aggregated code interpreter sessions usage details of the specific time bucket. */ export type UsageCodeInterpreterSessionsResult = { object: 'organization.usage.code_interpreter_sessions.result'; /** * The number of code interpreter sessions. */ num_sessions?: number; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; }; /** * The aggregated completions usage details of the specific time bucket. */ export type UsageCompletionsResult = { object: 'organization.usage.completions.result'; /** * The aggregated number of text input tokens used, including cached tokens. For customers subscribe to scale tier, this includes scale tier tokens. */ input_tokens: number; /** * The aggregated number of text input tokens that has been cached from previous requests. For customers subscribe to scale tier, this includes scale tier tokens. */ input_cached_tokens?: number; /** * The aggregated number of text output tokens used. For customers subscribe to scale tier, this includes scale tier tokens. */ output_tokens: number; /** * The aggregated number of audio input tokens used, including cached tokens. */ input_audio_tokens?: number; /** * The aggregated number of audio output tokens used. */ output_audio_tokens?: number; /** * The count of requests made to the model. */ num_model_requests: number; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; /** * When `group_by=user_id`, this field provides the user ID of the grouped usage result. */ user_id?: string; /** * When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. */ api_key_id?: string; /** * When `group_by=model`, this field provides the model name of the grouped usage result. */ model?: string; /** * When `group_by=batch`, this field tells whether the grouped usage result is batch or not. */ batch?: boolean; }; /** * The aggregated embeddings usage details of the specific time bucket. */ export type UsageEmbeddingsResult = { object: 'organization.usage.embeddings.result'; /** * The aggregated number of input tokens used. */ input_tokens: number; /** * The count of requests made to the model. */ num_model_requests: number; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; /** * When `group_by=user_id`, this field provides the user ID of the grouped usage result. */ user_id?: string; /** * When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. */ api_key_id?: string; /** * When `group_by=model`, this field provides the model name of the grouped usage result. */ model?: string; }; /** * The aggregated images usage details of the specific time bucket. */ export type UsageImagesResult = { object: 'organization.usage.images.result'; /** * The number of images processed. */ images: number; /** * The count of requests made to the model. */ num_model_requests: number; /** * When `group_by=source`, this field provides the source of the grouped usage result, possible values are `image.generation`, `image.edit`, `image.variation`. */ source?: string; /** * When `group_by=size`, this field provides the image size of the grouped usage result. */ size?: string; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; /** * When `group_by=user_id`, this field provides the user ID of the grouped usage result. */ user_id?: string; /** * When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. */ api_key_id?: string; /** * When `group_by=model`, this field provides the model name of the grouped usage result. */ model?: string; }; /** * The aggregated moderations usage details of the specific time bucket. */ export type UsageModerationsResult = { object: 'organization.usage.moderations.result'; /** * The aggregated number of input tokens used. */ input_tokens: number; /** * The count of requests made to the model. */ num_model_requests: number; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; /** * When `group_by=user_id`, this field provides the user ID of the grouped usage result. */ user_id?: string; /** * When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. */ api_key_id?: string; /** * When `group_by=model`, this field provides the model name of the grouped usage result. */ model?: string; }; export type UsageResponse = { object: 'page'; data: Array; has_more: boolean; next_page: string; }; export type UsageTimeBucket = { object: 'bucket'; start_time: number; end_time: number; result: Array<({ object?: 'UsageCompletionsResult'; } & UsageCompletionsResult) | ({ object?: 'UsageEmbeddingsResult'; } & UsageEmbeddingsResult) | ({ object?: 'UsageModerationsResult'; } & UsageModerationsResult) | ({ object?: 'UsageImagesResult'; } & UsageImagesResult) | ({ object?: 'UsageAudioSpeechesResult'; } & UsageAudioSpeechesResult) | ({ object?: 'UsageAudioTranscriptionsResult'; } & UsageAudioTranscriptionsResult) | ({ object?: 'UsageVectorStoresResult'; } & UsageVectorStoresResult) | ({ object?: 'UsageCodeInterpreterSessionsResult'; } & UsageCodeInterpreterSessionsResult) | ({ object?: 'CostsResult'; } & CostsResult)>; }; /** * The aggregated vector stores usage details of the specific time bucket. */ export type UsageVectorStoresResult = { object: 'organization.usage.vector_stores.result'; /** * The vector stores usage in bytes. */ usage_bytes: number; /** * When `group_by=project_id`, this field provides the project ID of the grouped usage result. */ project_id?: string; }; /** * Represents an individual `user` within an organization. */ export type User = { /** * The object type, which is always `organization.user` */ object: 'organization.user'; /** * The identifier, which can be referenced in API endpoints */ id: string; /** * The name of the user */ name: string; /** * The email address of the user */ email: string; /** * `owner` or `reader` */ role: 'owner' | 'reader'; /** * The Unix timestamp (in seconds) of when the user was added. */ added_at: number; }; export type UserDeleteResponse = { object: 'organization.user.deleted'; id: string; deleted: boolean; }; export type UserListResponse = { object: 'list'; data: Array; first_id: string; last_id: string; has_more: boolean; }; export type UserRoleUpdateRequest = { /** * `owner` or `reader` */ role: 'owner' | 'reader'; }; export type VadConfig = { /** * Must be set to `server_vad` to enable manual chunking using server side VAD. */ type: 'server_vad'; /** * Amount of audio to include before the VAD detected speech (in * milliseconds). * */ prefix_padding_ms?: number; /** * Duration of silence to detect speech stop (in milliseconds). * With shorter values the model will respond more quickly, * but may jump in on short pauses from the user. * */ silence_duration_ms?: number; /** * Sensitivity threshold (0.0 to 1.0) for voice activity detection. A * higher threshold will require louder audio to activate the model, and * thus might perform better in noisy environments. * */ threshold?: number; }; /** * ValidateGraderRequest */ export type ValidateGraderRequest = { /** * The grader used for the fine-tuning job. */ grader: GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderMulti; }; /** * ValidateGraderResponse */ export type ValidateGraderResponse = { /** * The grader used for the fine-tuning job. */ grader?: GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderMulti; }; /** * Vector store expiration policy * * The expiration policy for a vector store. */ export type VectorStoreExpirationAfter = { /** * Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. */ anchor: 'last_active_at'; /** * The number of days after the anchor time that the vector store will expire. */ days: number; }; /** * Set of 16 key-value pairs that can be attached to an object. This can be * useful for storing additional information about the object in a structured * format, and querying for objects via API or the dashboard. Keys are strings * with a maximum length of 64 characters. Values are strings with a maximum * length of 512 characters, booleans, or numbers. * */ export type VectorStoreFileAttributes = { [key: string]: string | number | boolean; }; /** * Vector store file batch * * A batch of files attached to a vector store. */ export type VectorStoreFileBatchObject = { /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `vector_store.file_batch`. */ object: 'vector_store.files_batch'; /** * The Unix timestamp (in seconds) for when the vector store files batch was created. */ created_at: number; /** * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to. */ vector_store_id: string; /** * The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. */ status: 'in_progress' | 'completed' | 'cancelled' | 'failed'; file_counts: { /** * The number of files that are currently being processed. */ in_progress: number; /** * The number of files that have been processed. */ completed: number; /** * The number of files that have failed to process. */ failed: number; /** * The number of files that where cancelled. */ cancelled: number; /** * The total number of files. */ total: number; }; }; /** * Represents the parsed content of a vector store file. */ export type VectorStoreFileContentResponse = { /** * The object type, which is always `vector_store.file_content.page` */ object: 'vector_store.file_content.page'; /** * Parsed content of the file. */ data: Array<{ /** * The content type (currently only `"text"`) */ type?: string; /** * The text content */ text?: string; }>; /** * Indicates if there are more content pages to fetch. */ has_more: boolean; /** * The token for the next page, if any. */ next_page: string; }; /** * Vector store files * * A list of files attached to a vector store. */ export type VectorStoreFileObject = { /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `vector_store.file`. */ object: 'vector_store.file'; /** * The total vector store usage in bytes. Note that this may be different from the original file size. */ usage_bytes: number; /** * The Unix timestamp (in seconds) for when the vector store file was created. */ created_at: number; /** * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to. */ vector_store_id: string; /** * The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. */ status: 'in_progress' | 'completed' | 'cancelled' | 'failed'; /** * The last error associated with this vector store file. Will be `null` if there are no errors. */ last_error: { /** * One of `server_error` or `rate_limit_exceeded`. */ code: 'server_error' | 'unsupported_file' | 'invalid_file'; /** * A human-readable description of the error. */ message: string; }; chunking_strategy?: ChunkingStrategyResponse; attributes?: VectorStoreFileAttributes; }; /** * Vector store * * A vector store is a collection of processed files can be used by the `file_search` tool. */ export type VectorStoreObject = { /** * The identifier, which can be referenced in API endpoints. */ id: string; /** * The object type, which is always `vector_store`. */ object: 'vector_store'; /** * The Unix timestamp (in seconds) for when the vector store was created. */ created_at: number; /** * The name of the vector store. */ name: string; /** * The total number of bytes used by the files in the vector store. */ usage_bytes: number; file_counts: { /** * The number of files that are currently being processed. */ in_progress: number; /** * The number of files that have been successfully processed. */ completed: number; /** * The number of files that have failed to process. */ failed: number; /** * The number of files that were cancelled. */ cancelled: number; /** * The total number of files. */ total: number; }; /** * The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. */ status: 'expired' | 'in_progress' | 'completed'; expires_after?: VectorStoreExpirationAfter; /** * The Unix timestamp (in seconds) for when the vector store will expire. */ expires_at?: number; /** * The Unix timestamp (in seconds) for when the vector store was last active. */ last_active_at: number; metadata: Metadata; }; export type VectorStoreSearchRequest = { /** * A query string for a search */ query: string | Array; /** * Whether to rewrite the natural language query for vector search. */ rewrite_query?: boolean; /** * The maximum number of results to return. This number should be between 1 and 50 inclusive. */ max_num_results?: number; /** * A filter to apply based on file attributes. */ filters?: ComparisonFilter | CompoundFilter; /** * Ranking options for search. */ ranking_options?: { /** * Enable re-ranking; set to `none` to disable, which can help reduce latency. */ ranker?: 'none' | 'auto' | 'default-2024-11-15'; score_threshold?: number; }; }; export type VectorStoreSearchResultContentObject = { /** * The type of content. */ type: 'text'; /** * The text content returned from search. */ text: string; }; export type VectorStoreSearchResultItem = { /** * The ID of the vector store file. */ file_id: string; /** * The name of the vector store file. */ filename: string; /** * The similarity score for the result. */ score: number; attributes: VectorStoreFileAttributes; /** * Content chunks from the file. */ content: Array; }; export type VectorStoreSearchResultsPage = { /** * The object type, which is always `vector_store.search_results.page` */ object: 'vector_store.search_results.page'; search_query: Array; /** * The list of search result items. */ data: Array; /** * Indicates if there are more results to fetch. */ has_more: boolean; /** * The token for the next page, if any. */ next_page: string; }; /** * Constrains the verbosity of the model's response. Lower values will result in * more concise responses, while higher values will result in more verbose responses. * Currently supported values are `low`, `medium`, and `high`. * */ export const Verbosity = { LOW: 'low', MEDIUM: 'medium', HIGH: 'high' } as const; /** * Constrains the verbosity of the model's response. Lower values will result in * more concise responses, while higher values will result in more verbose responses. * Currently supported values are `low`, `medium`, and `high`. * */ export type Verbosity = typeof Verbosity[keyof typeof Verbosity]; export type VoiceIdsShared = string | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; /** * Wait * * A wait action. * */ export type Wait = { /** * Specifies the event type. For a wait action, this property is * always set to `wait`. * */ type: 'wait'; }; /** * Find action * * Action type "find": Searches for a pattern within a loaded page. * */ export type WebSearchActionFind = { /** * The action type. * */ type: 'find'; /** * The URL of the page searched for the pattern. * */ url: string; /** * The pattern or text to search for within the page. * */ pattern: string; }; /** * Open page action * * Action type "open_page" - Opens a specific URL from search results. * */ export type WebSearchActionOpenPage = { /** * The action type. * */ type: 'open_page'; /** * The URL opened by the model. * */ url: string; }; /** * Search action * * Action type "search" - Performs a web search query. * */ export type WebSearchActionSearch = { /** * The action type. * */ type: 'search'; /** * The search query. * */ query: string; }; /** * High level guidance for the amount of context window space to use for the * search. One of `low`, `medium`, or `high`. `medium` is the default. * */ export const WebSearchContextSize = { LOW: 'low', MEDIUM: 'medium', HIGH: 'high' } as const; /** * High level guidance for the amount of context window space to use for the * search. One of `low`, `medium`, or `high`. `medium` is the default. * */ export type WebSearchContextSize = typeof WebSearchContextSize[keyof typeof WebSearchContextSize]; /** * Web search location * * Approximate location parameters for the search. */ export type WebSearchLocation = { /** * The two-letter * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, * e.g. `US`. * */ country?: string; /** * Free text input for the region of the user, e.g. `California`. * */ region?: string; /** * Free text input for the city of the user, e.g. `San Francisco`. * */ city?: string; /** * The [IANA timezone](https://timeapi.io/documentation/iana-timezones) * of the user, e.g. `America/Los_Angeles`. * */ timezone?: string; }; /** * Web search tool call * * The results of a web search tool call. See the * [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information. * */ export type WebSearchToolCall = { /** * The unique ID of the web search tool call. * */ id: string; /** * The type of the web search tool call. Always `web_search_call`. * */ type: 'web_search_call'; /** * The status of the web search tool call. * */ status: 'in_progress' | 'searching' | 'completed' | 'failed'; /** * An object describing the specific action taken in this web search call. * Includes details on how the model used the web (search, open_page, find). * */ action: ({ type?: 'WebSearchActionSearch'; } & WebSearchActionSearch) | ({ type?: 'WebSearchActionOpenPage'; } & WebSearchActionOpenPage) | ({ type?: 'WebSearchActionFind'; } & WebSearchActionFind); }; /** * batch.cancelled * * Sent when a batch API request has been cancelled. * */ export type WebhookBatchCancelled = { /** * The Unix timestamp (in seconds) of when the batch API request was cancelled. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the batch API request. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `batch.cancelled`. * */ type: 'batch.cancelled'; }; /** * batch.completed * * Sent when a batch API request has been completed. * */ export type WebhookBatchCompleted = { /** * The Unix timestamp (in seconds) of when the batch API request was completed. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the batch API request. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `batch.completed`. * */ type: 'batch.completed'; }; /** * batch.expired * * Sent when a batch API request has expired. * */ export type WebhookBatchExpired = { /** * The Unix timestamp (in seconds) of when the batch API request expired. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the batch API request. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `batch.expired`. * */ type: 'batch.expired'; }; /** * batch.failed * * Sent when a batch API request has failed. * */ export type WebhookBatchFailed = { /** * The Unix timestamp (in seconds) of when the batch API request failed. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the batch API request. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `batch.failed`. * */ type: 'batch.failed'; }; /** * eval.run.canceled * * Sent when an eval run has been canceled. * */ export type WebhookEvalRunCanceled = { /** * The Unix timestamp (in seconds) of when the eval run was canceled. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the eval run. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `eval.run.canceled`. * */ type: 'eval.run.canceled'; }; /** * eval.run.failed * * Sent when an eval run has failed. * */ export type WebhookEvalRunFailed = { /** * The Unix timestamp (in seconds) of when the eval run failed. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the eval run. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `eval.run.failed`. * */ type: 'eval.run.failed'; }; /** * eval.run.succeeded * * Sent when an eval run has succeeded. * */ export type WebhookEvalRunSucceeded = { /** * The Unix timestamp (in seconds) of when the eval run succeeded. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the eval run. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `eval.run.succeeded`. * */ type: 'eval.run.succeeded'; }; /** * fine_tuning.job.cancelled * * Sent when a fine-tuning job has been cancelled. * */ export type WebhookFineTuningJobCancelled = { /** * The Unix timestamp (in seconds) of when the fine-tuning job was cancelled. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the fine-tuning job. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `fine_tuning.job.cancelled`. * */ type: 'fine_tuning.job.cancelled'; }; /** * fine_tuning.job.failed * * Sent when a fine-tuning job has failed. * */ export type WebhookFineTuningJobFailed = { /** * The Unix timestamp (in seconds) of when the fine-tuning job failed. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the fine-tuning job. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `fine_tuning.job.failed`. * */ type: 'fine_tuning.job.failed'; }; /** * fine_tuning.job.succeeded * * Sent when a fine-tuning job has succeeded. * */ export type WebhookFineTuningJobSucceeded = { /** * The Unix timestamp (in seconds) of when the fine-tuning job succeeded. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the fine-tuning job. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `fine_tuning.job.succeeded`. * */ type: 'fine_tuning.job.succeeded'; }; /** * response.cancelled * * Sent when a background response has been cancelled. * */ export type WebhookResponseCancelled = { /** * The Unix timestamp (in seconds) of when the model response was cancelled. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the model response. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `response.cancelled`. * */ type: 'response.cancelled'; }; /** * response.completed * * Sent when a background response has been completed. * */ export type WebhookResponseCompleted = { /** * The Unix timestamp (in seconds) of when the model response was completed. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the model response. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `response.completed`. * */ type: 'response.completed'; }; /** * response.failed * * Sent when a background response has failed. * */ export type WebhookResponseFailed = { /** * The Unix timestamp (in seconds) of when the model response failed. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the model response. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `response.failed`. * */ type: 'response.failed'; }; /** * response.incomplete * * Sent when a background response has been interrupted. * */ export type WebhookResponseIncomplete = { /** * The Unix timestamp (in seconds) of when the model response was interrupted. * */ created_at: number; /** * The unique ID of the event. * */ id: string; /** * Event data payload. * */ data: { /** * The unique ID of the model response. * */ id: string; }; /** * The object of the event. Always `event`. * */ object?: 'event'; /** * The type of the event. Always `response.incomplete`. * */ type: 'response.incomplete'; }; /** * Input text * * A text input to the model. */ export type InputTextContent = { /** * The type of the input item. Always `input_text`. */ type: 'input_text'; /** * The text input to the model. */ text: string; }; /** * Input image * * An image input to the model. Learn about [image inputs](https://platform.openai.com/docs/guides/vision). */ export type InputImageContent = { /** * The type of the input item. Always `input_image`. */ type: 'input_image'; image_url?: string | null; file_id?: string | null; /** * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. */ detail: 'low' | 'high' | 'auto'; }; /** * Input file * * A file input to the model. */ export type InputFileContent = { /** * The type of the input item. Always `input_file`. */ type: 'input_file'; file_id?: string | null; /** * The name of the file to be sent to the model. */ filename?: string; /** * The URL of the file to be sent to the model. */ file_url?: string; /** * The content of the file to be sent to the model. * */ file_data?: string; }; /** * Function * * Defines a function in your own code the model can choose to call. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). */ export type FunctionTool = { /** * The type of the function tool. Always `function`. */ type: 'function'; /** * The name of the function to call. */ name: string; description?: string | null; parameters: { [key: string]: unknown; } | null; strict: boolean | null; }; export type RankingOptions = { /** * The ranker to use for the file search. */ ranker?: 'auto' | 'default-2024-11-15'; /** * The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results. */ score_threshold?: number; }; export type Filters = ComparisonFilter | CompoundFilter; /** * File search * * A tool that searches for relevant content from uploaded files. Learn more about the [file search tool](https://platform.openai.com/docs/guides/tools-file-search). */ export type FileSearchTool = { /** * The type of the file search tool. Always `file_search`. */ type: 'file_search'; /** * The IDs of the vector stores to search. */ vector_store_ids: Array; /** * The maximum number of results to return. This number should be between 1 and 50 inclusive. */ max_num_results?: number; /** * Ranking options for search. */ ranking_options?: RankingOptions; filters?: Filters | null; }; export type ApproximateLocation = { /** * The type of location approximation. Always `approximate`. */ type: 'approximate'; country?: string | null; region?: string | null; city?: string | null; timezone?: string | null; }; /** * Web search preview * * This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search). */ export type WebSearchPreviewTool = { /** * The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. */ type: 'web_search_preview' | 'web_search_preview_2025_03_11'; user_location?: ApproximateLocation | null; /** * High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default. */ search_context_size?: 'low' | 'medium' | 'high'; }; /** * Computer use preview * * A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use). */ export type ComputerUsePreviewTool = { /** * The type of the computer use tool. Always `computer_use_preview`. */ type: 'computer_use_preview'; /** * The type of computer environment to control. */ environment: 'windows' | 'mac' | 'linux' | 'ubuntu' | 'browser'; /** * The width of the computer display. */ display_width: number; /** * The height of the computer display. */ display_height: number; }; /** * Input usage details * * The input tokens detailed information for the image generation. */ export type ImageGenInputUsageDetails = { /** * The number of text tokens in the input prompt. */ text_tokens: number; /** * The number of image tokens in the input prompt. */ image_tokens: number; }; /** * Image generation usage * * For `gpt-image-1` only, the token usage information for the image generation. */ export type ImageGenUsage = { /** * The number of tokens (images and text) in the input prompt. */ input_tokens: number; /** * The total number of tokens (images and text) used for the image generation. */ total_tokens: number; /** * The number of output tokens generated by the model. */ output_tokens: number; input_tokens_details: ImageGenInputUsageDetails; }; /** * File citation * * A citation to a file. */ export type FileCitationBody = { /** * The type of the file citation. Always `file_citation`. */ type: 'file_citation'; /** * The ID of the file. */ file_id: string; /** * The index of the file in the list of files. */ index: number; /** * The filename of the file cited. */ filename: string; }; /** * URL citation * * A citation for a web resource used to generate a model response. */ export type UrlCitationBody = { /** * The type of the URL citation. Always `url_citation`. */ type: 'url_citation'; /** * The URL of the web resource. */ url: string; /** * The index of the first character of the URL citation in the message. */ start_index: number; /** * The index of the last character of the URL citation in the message. */ end_index: number; /** * The title of the web resource. */ title: string; }; /** * Container file citation * * A citation for a container file used to generate a model response. */ export type ContainerFileCitationBody = { /** * The type of the container file citation. Always `container_file_citation`. */ type: 'container_file_citation'; /** * The ID of the container file. */ container_id: string; /** * The ID of the file. */ file_id: string; /** * The index of the first character of the container file citation in the message. */ start_index: number; /** * The index of the last character of the container file citation in the message. */ end_index: number; /** * The filename of the container file cited. */ filename: string; }; export type Annotation = ({ type?: 'FileCitationBody'; } & FileCitationBody) | ({ type?: 'UrlCitationBody'; } & UrlCitationBody) | ({ type?: 'ContainerFileCitationBody'; } & ContainerFileCitationBody) | ({ type?: 'FilePath'; } & FilePath); /** * Top log probability * * The top log probability of a token. */ export type TopLogProb = { token: string; logprob: number; bytes: Array; }; /** * Log probability * * The log probability of a token. */ export type LogProb = { token: string; logprob: number; bytes: Array; top_logprobs: Array; }; /** * Output text * * A text output from the model. */ export type OutputTextContent = { /** * The type of the output text. Always `output_text`. */ type: 'output_text'; /** * The text output from the model. */ text: string; /** * The annotations of the text output. */ annotations: Array; logprobs?: Array; }; /** * Refusal * * A refusal from the model. */ export type RefusalContent = { /** * The type of the refusal. Always `refusal`. */ type: 'refusal'; /** * The refusal explanation from the model. */ refusal: string; }; /** * A pending safety check for the computer call. */ export type ComputerCallSafetyCheckParam = { /** * The ID of the pending safety check. */ id: string; code?: string | null; message?: string | null; }; /** * Computer tool call output * * The output of a computer tool call. */ export type ComputerCallOutputItemParam = { id?: string | null; /** * The ID of the computer tool call that produced the output. */ call_id: string; /** * The type of the computer tool call output. Always `computer_call_output`. */ type: 'computer_call_output'; output: ComputerScreenshotImage; acknowledged_safety_checks?: Array | null; status?: 'in_progress' | 'completed' | 'incomplete' | null; }; /** * Function tool call output * * The output of a function tool call. */ export type FunctionCallOutputItemParam = { id?: string | null; /** * The unique ID of the function tool call generated by the model. */ call_id: string; /** * The type of the function tool call output. Always `function_call_output`. */ type: 'function_call_output'; /** * A JSON string of the output of the function tool call. */ output: string; status?: 'in_progress' | 'completed' | 'incomplete' | null; }; /** * Item reference * * An internal identifier for an item to reference. */ export type ItemReferenceParam = { type?: 'item_reference' | null; /** * The ID of the item to reference. */ id: string; }; export type RealtimeConversationItemContent = { /** * The content type (`input_text`, `input_audio`, `item_reference`, `text`, `audio`). * */ type?: 'input_text' | 'input_audio' | 'item_reference' | 'text' | 'audio'; /** * The text content, used for `input_text` and `text` content types. * */ text?: string; /** * ID of a previous conversation item to reference (for `item_reference` * content types in `response.create` events). These can reference both * client and server created items. * */ id?: string; /** * Base64-encoded audio bytes, used for `input_audio` content type. * */ audio?: string; /** * The transcript of the audio, used for `input_audio` and `audio` * content types. * */ transcript?: string; }; export type RealtimeConnectParams = { model: string; }; /** * An object describing an image to classify. */ export type ModerationImageUrlInput = { /** * Always `image_url`. */ type: 'image_url'; /** * Contains either an image URL or a data URL for a base64 encoded image. */ image_url: { /** * Either a URL of the image or the base64 encoded image data. */ url: string; }; }; /** * An object describing text to classify. */ export type ModerationTextInput = { /** * Always `text`. */ type: 'text'; /** * A string of text to classify. */ text: string; }; /** * The strategy used to chunk the file. */ export type ChunkingStrategyResponse = ({ type?: 'StaticChunkingStrategyResponseParam'; } & StaticChunkingStrategyResponseParam) | ({ type?: 'OtherChunkingStrategyResponseParam'; } & OtherChunkingStrategyResponseParam); /** * The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets * */ export const FilePurpose = { ASSISTANTS: 'assistants', BATCH: 'batch', FINE_TUNE: 'fine-tune', VISION: 'vision', USER_DATA: 'user_data', EVALS: 'evals' } as const; /** * The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets * */ export type FilePurpose = typeof FilePurpose[keyof typeof FilePurpose]; export type BatchError = { /** * An error code identifying the error type. */ code?: string; /** * A human-readable message providing more details about the error. */ message?: string; /** * The name of the parameter that caused the error, if applicable. */ param?: string; /** * The line number of the input file where the error occurred, if applicable. */ line?: number; }; /** * The request counts for different statuses within the batch. */ export type BatchRequestCounts = { /** * Total number of requests in the batch. */ total: number; /** * Number of requests that have been completed successfully. */ completed: number; /** * Number of requests that have failed. */ failed: number; }; export type AssistantTool = ({ type?: 'AssistantToolsCode'; } & AssistantToolsCode) | ({ type?: 'AssistantToolsFileSearch'; } & AssistantToolsFileSearch) | ({ type?: 'AssistantToolsFunction'; } & AssistantToolsFunction); export type TextAnnotationDelta = ({ type?: 'MessageDeltaContentTextAnnotationsFileCitationObject'; } & MessageDeltaContentTextAnnotationsFileCitationObject) | ({ type?: 'MessageDeltaContentTextAnnotationsFilePathObject'; } & MessageDeltaContentTextAnnotationsFilePathObject); export type TextAnnotation = ({ type?: 'MessageContentTextAnnotationsFileCitationObject'; } & MessageContentTextAnnotationsFileCitationObject) | ({ type?: 'MessageContentTextAnnotationsFilePathObject'; } & MessageContentTextAnnotationsFilePathObject); export type RunStepDetailsToolCall = ({ type?: 'RunStepDetailsToolCallsCodeObject'; } & RunStepDetailsToolCallsCodeObject) | ({ type?: 'RunStepDetailsToolCallsFileSearchObject'; } & RunStepDetailsToolCallsFileSearchObject) | ({ type?: 'RunStepDetailsToolCallsFunctionObject'; } & RunStepDetailsToolCallsFunctionObject); export type RunStepDeltaStepDetailsToolCall = ({ type?: 'RunStepDeltaStepDetailsToolCallsCodeObject'; } & RunStepDeltaStepDetailsToolCallsCodeObject) | ({ type?: 'RunStepDeltaStepDetailsToolCallsFileSearchObject'; } & RunStepDeltaStepDetailsToolCallsFileSearchObject) | ({ type?: 'RunStepDeltaStepDetailsToolCallsFunctionObject'; } & RunStepDeltaStepDetailsToolCallsFunctionObject); export type MessageContent = ({ type?: 'MessageContentImageFileObject'; } & MessageContentImageFileObject) | ({ type?: 'MessageContentImageUrlObject'; } & MessageContentImageUrlObject) | ({ type?: 'MessageContentTextObject'; } & MessageContentTextObject) | ({ type?: 'MessageContentRefusalObject'; } & MessageContentRefusalObject); export type MessageContentDelta = ({ type?: 'MessageDeltaContentImageFileObject'; } & MessageDeltaContentImageFileObject) | ({ type?: 'MessageDeltaContentTextObject'; } & MessageDeltaContentTextObject) | ({ type?: 'MessageDeltaContentRefusalObject'; } & MessageDeltaContentRefusalObject) | ({ type?: 'MessageDeltaContentImageUrlObject'; } & MessageDeltaContentImageUrlObject); export const ChatModel = { GPT_5: 'gpt-5', GPT_5_MINI: 'gpt-5-mini', GPT_5_NANO: 'gpt-5-nano', GPT_5_2025_08_07: 'gpt-5-2025-08-07', GPT_5_MINI_2025_08_07: 'gpt-5-mini-2025-08-07', GPT_5_NANO_2025_08_07: 'gpt-5-nano-2025-08-07', GPT_5_CHAT_LATEST: 'gpt-5-chat-latest', GPT_4_1: 'gpt-4.1', GPT_4_1_MINI: 'gpt-4.1-mini', GPT_4_1_NANO: 'gpt-4.1-nano', GPT_4_1_2025_04_14: 'gpt-4.1-2025-04-14', GPT_4_1_MINI_2025_04_14: 'gpt-4.1-mini-2025-04-14', GPT_4_1_NANO_2025_04_14: 'gpt-4.1-nano-2025-04-14', O4_MINI: 'o4-mini', O4_MINI_2025_04_16: 'o4-mini-2025-04-16', O3: 'o3', O3_2025_04_16: 'o3-2025-04-16', O3_MINI: 'o3-mini', O3_MINI_2025_01_31: 'o3-mini-2025-01-31', O1: 'o1', O1_2024_12_17: 'o1-2024-12-17', O1_PREVIEW: 'o1-preview', O1_PREVIEW_2024_09_12: 'o1-preview-2024-09-12', O1_MINI: 'o1-mini', O1_MINI_2024_09_12: 'o1-mini-2024-09-12', GPT_4O: 'gpt-4o', GPT_4O_2024_11_20: 'gpt-4o-2024-11-20', GPT_4O_2024_08_06: 'gpt-4o-2024-08-06', GPT_4O_2024_05_13: 'gpt-4o-2024-05-13', GPT_4O_AUDIO_PREVIEW: 'gpt-4o-audio-preview', GPT_4O_AUDIO_PREVIEW_2024_10_01: 'gpt-4o-audio-preview-2024-10-01', GPT_4O_AUDIO_PREVIEW_2024_12_17: 'gpt-4o-audio-preview-2024-12-17', GPT_4O_AUDIO_PREVIEW_2025_06_03: 'gpt-4o-audio-preview-2025-06-03', GPT_4O_MINI_AUDIO_PREVIEW: 'gpt-4o-mini-audio-preview', GPT_4O_MINI_AUDIO_PREVIEW_2024_12_17: 'gpt-4o-mini-audio-preview-2024-12-17', GPT_4O_SEARCH_PREVIEW: 'gpt-4o-search-preview', GPT_4O_MINI_SEARCH_PREVIEW: 'gpt-4o-mini-search-preview', GPT_4O_SEARCH_PREVIEW_2025_03_11: 'gpt-4o-search-preview-2025-03-11', GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11: 'gpt-4o-mini-search-preview-2025-03-11', CHATGPT_4O_LATEST: 'chatgpt-4o-latest', CODEX_MINI_LATEST: 'codex-mini-latest', GPT_4O_MINI: 'gpt-4o-mini', GPT_4O_MINI_2024_07_18: 'gpt-4o-mini-2024-07-18', GPT_4_TURBO: 'gpt-4-turbo', GPT_4_TURBO_2024_04_09: 'gpt-4-turbo-2024-04-09', GPT_4_0125_PREVIEW: 'gpt-4-0125-preview', GPT_4_TURBO_PREVIEW: 'gpt-4-turbo-preview', GPT_4_1106_PREVIEW: 'gpt-4-1106-preview', GPT_4_VISION_PREVIEW: 'gpt-4-vision-preview', GPT_4: 'gpt-4', GPT_4_0314: 'gpt-4-0314', GPT_4_0613: 'gpt-4-0613', GPT_4_32K: 'gpt-4-32k', GPT_4_32K_0314: 'gpt-4-32k-0314', GPT_4_32K_0613: 'gpt-4-32k-0613', GPT_3_5_TURBO: 'gpt-3.5-turbo', GPT_3_5_TURBO_16K: 'gpt-3.5-turbo-16k', GPT_3_5_TURBO_0301: 'gpt-3.5-turbo-0301', GPT_3_5_TURBO_0613: 'gpt-3.5-turbo-0613', GPT_3_5_TURBO_1106: 'gpt-3.5-turbo-1106', GPT_3_5_TURBO_0125: 'gpt-3.5-turbo-0125', GPT_3_5_TURBO_16K_0613: 'gpt-3.5-turbo-16k-0613' } as const; export type ChatModel = typeof ChatModel[keyof typeof ChatModel]; export type CreateThreadAndRunRequestWithoutStream = { /** * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. */ assistant_id: string; thread?: CreateThreadRequest; /** * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. */ model?: string | 'gpt-5' | 'gpt-5-mini' | 'gpt-5-nano' | 'gpt-5-2025-08-07' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano-2025-08-07' | 'gpt-4.1' | 'gpt-4.1-mini' | 'gpt-4.1-nano' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-11-20' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-05-13' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613'; /** * Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. */ instructions?: string; /** * Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. */ tools?: Array; /** * A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. * */ tool_resources?: { code_interpreter?: { /** * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. * */ file_ids?: Array; }; file_search?: { /** * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. * */ vector_store_ids?: Array; }; }; metadata?: Metadata; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. * */ top_p?: number; /** * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_prompt_tokens?: number; /** * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_completion_tokens?: number; truncation_strategy?: TruncationObject & unknown; tool_choice?: AssistantsApiToolChoiceOption & unknown; parallel_tool_calls?: ParallelToolCalls; response_format?: AssistantsApiResponseFormatOption; }; export type CreateRunRequestWithoutStream = { /** * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. */ assistant_id: string; /** * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. */ model?: string | AssistantSupportedModels; reasoning_effort?: ReasoningEffort; /** * Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. */ instructions?: string; /** * Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. */ additional_instructions?: string; /** * Adds additional messages to the thread before creating the run. */ additional_messages?: Array; /** * Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. */ tools?: Array; metadata?: Metadata; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. * */ top_p?: number; /** * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_prompt_tokens?: number; /** * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. * */ max_completion_tokens?: number; truncation_strategy?: TruncationObject & unknown; tool_choice?: AssistantsApiToolChoiceOption & unknown; parallel_tool_calls?: ParallelToolCalls; response_format?: AssistantsApiResponseFormatOption; }; export type SubmitToolOutputsRunRequestWithoutStream = { /** * A list of tools for which the outputs are being submitted. */ tool_outputs: Array<{ /** * The ID of the tool call in the `required_action` object within the run object the output is being submitted for. */ tool_call_id?: string; /** * The output of the tool call to be submitted to continue the run. */ output?: string; }>; }; /** * The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`. */ export const RunStatus = { QUEUED: 'queued', IN_PROGRESS: 'in_progress', REQUIRES_ACTION: 'requires_action', CANCELLING: 'cancelling', CANCELLED: 'cancelled', FAILED: 'failed', COMPLETED: 'completed', INCOMPLETE: 'incomplete', EXPIRED: 'expired' } as const; /** * The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`. */ export type RunStatus = typeof RunStatus[keyof typeof RunStatus]; /** * The delta containing the fields that have changed on the run step. */ export type RunStepDeltaObjectDelta = { /** * The details of the run step. */ step_details?: ({ type?: 'RunStepDeltaStepDetailsMessageCreationObject'; } & RunStepDeltaStepDetailsMessageCreationObject) | ({ type?: 'RunStepDeltaStepDetailsToolCallsObject'; } & RunStepDeltaStepDetailsToolCallsObject); }; export type ListAssistantsData = { body?: never; path?: never; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; }; url: '/assistants'; }; export type ListAssistantsResponses = { /** * OK */ 200: ListAssistantsResponse; }; export type ListAssistantsResponse2 = ListAssistantsResponses[keyof ListAssistantsResponses]; export type CreateAssistantData = { body: CreateAssistantRequest; path?: never; query?: never; url: '/assistants'; }; export type CreateAssistantResponses = { /** * OK */ 200: AssistantObject; }; export type CreateAssistantResponse = CreateAssistantResponses[keyof CreateAssistantResponses]; export type DeleteAssistantData = { body?: never; path: { /** * The ID of the assistant to delete. */ assistant_id: string; }; query?: never; url: '/assistants/{assistant_id}'; }; export type DeleteAssistantResponses = { /** * OK */ 200: DeleteAssistantResponse; }; export type DeleteAssistantResponse2 = DeleteAssistantResponses[keyof DeleteAssistantResponses]; export type GetAssistantData = { body?: never; path: { /** * The ID of the assistant to retrieve. */ assistant_id: string; }; query?: never; url: '/assistants/{assistant_id}'; }; export type GetAssistantResponses = { /** * OK */ 200: AssistantObject; }; export type GetAssistantResponse = GetAssistantResponses[keyof GetAssistantResponses]; export type ModifyAssistantData = { body: ModifyAssistantRequest; path: { /** * The ID of the assistant to modify. */ assistant_id: string; }; query?: never; url: '/assistants/{assistant_id}'; }; export type ModifyAssistantResponses = { /** * OK */ 200: AssistantObject; }; export type ModifyAssistantResponse = ModifyAssistantResponses[keyof ModifyAssistantResponses]; export type CreateSpeechData = { body: CreateSpeechRequest; path?: never; query?: never; url: '/audio/speech'; }; export type CreateSpeechResponses = { /** * OK */ 200: Blob | File; }; export type CreateSpeechResponse = CreateSpeechResponses[keyof CreateSpeechResponses]; export type CreateTranscriptionData = { body: CreateTranscriptionRequest; path?: never; query?: never; url: '/audio/transcriptions'; }; export type CreateTranscriptionResponses = { /** * OK */ 200: CreateTranscriptionResponseJson | CreateTranscriptionResponseVerboseJson; }; export type CreateTranscriptionResponse = CreateTranscriptionResponses[keyof CreateTranscriptionResponses]; export type CreateTranslationData = { body: CreateTranslationRequest; path?: never; query?: never; url: '/audio/translations'; }; export type CreateTranslationResponses = { /** * OK */ 200: CreateTranslationResponseJson | CreateTranslationResponseVerboseJson; }; export type CreateTranslationResponse = CreateTranslationResponses[keyof CreateTranslationResponses]; export type ListBatchesData = { body?: never; path?: never; query?: { /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; }; url: '/batches'; }; export type ListBatchesResponses = { /** * Batch listed successfully. */ 200: ListBatchesResponse; }; export type ListBatchesResponse2 = ListBatchesResponses[keyof ListBatchesResponses]; export type CreateBatchData = { body: { /** * The ID of an uploaded file that contains requests for the new batch. * * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. * * Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size. * */ input_file_id: string; /** * The endpoint to be used for all requests in the batch. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch. */ endpoint: '/v1/responses' | '/v1/chat/completions' | '/v1/embeddings' | '/v1/completions'; /** * The time frame within which the batch should be processed. Currently only `24h` is supported. */ completion_window: '24h'; metadata?: Metadata; output_expires_after?: BatchFileExpirationAfter; }; path?: never; query?: never; url: '/batches'; }; export type CreateBatchResponses = { /** * Batch created successfully. */ 200: Batch; }; export type CreateBatchResponse = CreateBatchResponses[keyof CreateBatchResponses]; export type RetrieveBatchData = { body?: never; path: { /** * The ID of the batch to retrieve. */ batch_id: string; }; query?: never; url: '/batches/{batch_id}'; }; export type RetrieveBatchResponses = { /** * Batch retrieved successfully. */ 200: Batch; }; export type RetrieveBatchResponse = RetrieveBatchResponses[keyof RetrieveBatchResponses]; export type CancelBatchData = { body?: never; path: { /** * The ID of the batch to cancel. */ batch_id: string; }; query?: never; url: '/batches/{batch_id}/cancel'; }; export type CancelBatchResponses = { /** * Batch is cancelling. Returns the cancelling batch's details. */ 200: Batch; }; export type CancelBatchResponse = CancelBatchResponses[keyof CancelBatchResponses]; export type ListChatCompletionsData = { body?: never; path?: never; query?: { /** * The model used to generate the Chat Completions. */ model?: string; /** * A list of metadata keys to filter the Chat Completions by. Example: * * `metadata[key1]=value1&metadata[key2]=value2` * */ metadata?: Metadata; /** * Identifier for the last chat completion from the previous pagination request. */ after?: string; /** * Number of Chat Completions to retrieve. */ limit?: number; /** * Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. */ order?: 'asc' | 'desc'; }; url: '/chat/completions'; }; export type ListChatCompletionsResponses = { /** * A list of Chat Completions */ 200: ChatCompletionList; }; export type ListChatCompletionsResponse = ListChatCompletionsResponses[keyof ListChatCompletionsResponses]; export type CreateChatCompletionData = { body: CreateChatCompletionRequest; path?: never; query?: never; url: '/chat/completions'; }; export type CreateChatCompletionResponses = { /** * OK */ 200: CreateChatCompletionResponse; }; export type CreateChatCompletionResponse2 = CreateChatCompletionResponses[keyof CreateChatCompletionResponses]; export type DeleteChatCompletionData = { body?: never; path: { /** * The ID of the chat completion to delete. */ completion_id: string; }; query?: never; url: '/chat/completions/{completion_id}'; }; export type DeleteChatCompletionResponses = { /** * The chat completion was deleted successfully. */ 200: ChatCompletionDeleted; }; export type DeleteChatCompletionResponse = DeleteChatCompletionResponses[keyof DeleteChatCompletionResponses]; export type GetChatCompletionData = { body?: never; path: { /** * The ID of the chat completion to retrieve. */ completion_id: string; }; query?: never; url: '/chat/completions/{completion_id}'; }; export type GetChatCompletionResponses = { /** * A chat completion */ 200: CreateChatCompletionResponse; }; export type GetChatCompletionResponse = GetChatCompletionResponses[keyof GetChatCompletionResponses]; export type UpdateChatCompletionData = { body: { metadata: Metadata; }; path: { /** * The ID of the chat completion to update. */ completion_id: string; }; query?: never; url: '/chat/completions/{completion_id}'; }; export type UpdateChatCompletionResponses = { /** * A chat completion */ 200: CreateChatCompletionResponse; }; export type UpdateChatCompletionResponse = UpdateChatCompletionResponses[keyof UpdateChatCompletionResponses]; export type GetChatCompletionMessagesData = { body?: never; path: { /** * The ID of the chat completion to retrieve messages from. */ completion_id: string; }; query?: { /** * Identifier for the last message from the previous pagination request. */ after?: string; /** * Number of messages to retrieve. */ limit?: number; /** * Sort order for messages by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. */ order?: 'asc' | 'desc'; }; url: '/chat/completions/{completion_id}/messages'; }; export type GetChatCompletionMessagesResponses = { /** * A list of messages */ 200: ChatCompletionMessageList; }; export type GetChatCompletionMessagesResponse = GetChatCompletionMessagesResponses[keyof GetChatCompletionMessagesResponses]; export type CreateCompletionData = { body: CreateCompletionRequest; path?: never; query?: never; url: '/completions'; }; export type CreateCompletionResponses = { /** * OK */ 200: CreateCompletionResponse; }; export type CreateCompletionResponse2 = CreateCompletionResponses[keyof CreateCompletionResponses]; export type ListContainersData = { body?: never; path?: never; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; }; url: '/containers'; }; export type ListContainersResponses = { /** * Success */ 200: ContainerListResource; }; export type ListContainersResponse = ListContainersResponses[keyof ListContainersResponses]; export type CreateContainerData = { body?: CreateContainerBody; path?: never; query?: never; url: '/containers'; }; export type CreateContainerResponses = { /** * Success */ 200: ContainerResource; }; export type CreateContainerResponse = CreateContainerResponses[keyof CreateContainerResponses]; export type DeleteContainerData = { body?: never; path: { /** * The ID of the container to delete. */ container_id: string; }; query?: never; url: '/containers/{container_id}'; }; export type DeleteContainerResponses = { /** * OK */ 200: unknown; }; export type RetrieveContainerData = { body?: never; path: { container_id: string; }; query?: never; url: '/containers/{container_id}'; }; export type RetrieveContainerResponses = { /** * Success */ 200: ContainerResource; }; export type RetrieveContainerResponse = RetrieveContainerResponses[keyof RetrieveContainerResponses]; export type ListContainerFilesData = { body?: never; path: { container_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; }; url: '/containers/{container_id}/files'; }; export type ListContainerFilesResponses = { /** * Success */ 200: ContainerFileListResource; }; export type ListContainerFilesResponse = ListContainerFilesResponses[keyof ListContainerFilesResponses]; export type CreateContainerFileData = { body: CreateContainerFileBody; path: { container_id: string; }; query?: never; url: '/containers/{container_id}/files'; }; export type CreateContainerFileResponses = { /** * Success */ 200: ContainerFileResource; }; export type CreateContainerFileResponse = CreateContainerFileResponses[keyof CreateContainerFileResponses]; export type DeleteContainerFileData = { body?: never; path: { container_id: string; file_id: string; }; query?: never; url: '/containers/{container_id}/files/{file_id}'; }; export type DeleteContainerFileResponses = { /** * OK */ 200: unknown; }; export type RetrieveContainerFileData = { body?: never; path: { container_id: string; file_id: string; }; query?: never; url: '/containers/{container_id}/files/{file_id}'; }; export type RetrieveContainerFileResponses = { /** * Success */ 200: ContainerFileResource; }; export type RetrieveContainerFileResponse = RetrieveContainerFileResponses[keyof RetrieveContainerFileResponses]; export type RetrieveContainerFileContentData = { body?: never; path: { container_id: string; file_id: string; }; query?: never; url: '/containers/{container_id}/files/{file_id}/content'; }; export type RetrieveContainerFileContentResponses = { /** * Success */ 200: unknown; }; export type CreateEmbeddingData = { body: CreateEmbeddingRequest; path?: never; query?: never; url: '/embeddings'; }; export type CreateEmbeddingResponses = { /** * OK */ 200: CreateEmbeddingResponse; }; export type CreateEmbeddingResponse2 = CreateEmbeddingResponses[keyof CreateEmbeddingResponses]; export type ListEvalsData = { body?: never; path?: never; query?: { /** * Identifier for the last eval from the previous pagination request. */ after?: string; /** * Number of evals to retrieve. */ limit?: number; /** * Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for descending order. */ order?: 'asc' | 'desc'; /** * Evals can be ordered by creation time or last updated time. Use * `created_at` for creation time or `updated_at` for last updated time. * */ order_by?: 'created_at' | 'updated_at'; }; url: '/evals'; }; export type ListEvalsResponses = { /** * A list of evals */ 200: EvalList; }; export type ListEvalsResponse = ListEvalsResponses[keyof ListEvalsResponses]; export type CreateEvalData = { body: CreateEvalRequest; path?: never; query?: never; url: '/evals'; }; export type CreateEvalResponses = { /** * OK */ 201: Eval; }; export type CreateEvalResponse = CreateEvalResponses[keyof CreateEvalResponses]; export type DeleteEvalData = { body?: never; path: { /** * The ID of the evaluation to delete. */ eval_id: string; }; query?: never; url: '/evals/{eval_id}'; }; export type DeleteEvalErrors = { /** * Evaluation not found. */ 404: Error; }; export type DeleteEvalError = DeleteEvalErrors[keyof DeleteEvalErrors]; export type DeleteEvalResponses = { /** * Successfully deleted the evaluation. */ 200: { object: string; deleted: boolean; eval_id: string; }; }; export type DeleteEvalResponse = DeleteEvalResponses[keyof DeleteEvalResponses]; export type GetEvalData = { body?: never; path: { /** * The ID of the evaluation to retrieve. */ eval_id: string; }; query?: never; url: '/evals/{eval_id}'; }; export type GetEvalResponses = { /** * The evaluation */ 200: Eval; }; export type GetEvalResponse = GetEvalResponses[keyof GetEvalResponses]; export type UpdateEvalData = { /** * Request to update an evaluation */ body: { /** * Rename the evaluation. */ name?: string; metadata?: Metadata; }; path: { /** * The ID of the evaluation to update. */ eval_id: string; }; query?: never; url: '/evals/{eval_id}'; }; export type UpdateEvalResponses = { /** * The updated evaluation */ 200: Eval; }; export type UpdateEvalResponse = UpdateEvalResponses[keyof UpdateEvalResponses]; export type GetEvalRunsData = { body?: never; path: { /** * The ID of the evaluation to retrieve runs for. */ eval_id: string; }; query?: { /** * Identifier for the last run from the previous pagination request. */ after?: string; /** * Number of runs to retrieve. */ limit?: number; /** * Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. */ order?: 'asc' | 'desc'; /** * Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` | `canceled`. */ status?: 'queued' | 'in_progress' | 'completed' | 'canceled' | 'failed'; }; url: '/evals/{eval_id}/runs'; }; export type GetEvalRunsResponses = { /** * A list of runs for the evaluation */ 200: EvalRunList; }; export type GetEvalRunsResponse = GetEvalRunsResponses[keyof GetEvalRunsResponses]; export type CreateEvalRunData = { body: CreateEvalRunRequest; path: { /** * The ID of the evaluation to create a run for. */ eval_id: string; }; query?: never; url: '/evals/{eval_id}/runs'; }; export type CreateEvalRunErrors = { /** * Bad request (for example, missing eval object) */ 400: Error; }; export type CreateEvalRunError = CreateEvalRunErrors[keyof CreateEvalRunErrors]; export type CreateEvalRunResponses = { /** * Successfully created a run for the evaluation */ 201: EvalRun; }; export type CreateEvalRunResponse = CreateEvalRunResponses[keyof CreateEvalRunResponses]; export type DeleteEvalRunData = { body?: never; path: { /** * The ID of the evaluation to delete the run from. */ eval_id: string; /** * The ID of the run to delete. */ run_id: string; }; query?: never; url: '/evals/{eval_id}/runs/{run_id}'; }; export type DeleteEvalRunErrors = { /** * Run not found */ 404: Error; }; export type DeleteEvalRunError = DeleteEvalRunErrors[keyof DeleteEvalRunErrors]; export type DeleteEvalRunResponses = { /** * Successfully deleted the eval run */ 200: { object?: string; deleted?: boolean; run_id?: string; }; }; export type DeleteEvalRunResponse = DeleteEvalRunResponses[keyof DeleteEvalRunResponses]; export type GetEvalRunData = { body?: never; path: { /** * The ID of the evaluation to retrieve runs for. */ eval_id: string; /** * The ID of the run to retrieve. */ run_id: string; }; query?: never; url: '/evals/{eval_id}/runs/{run_id}'; }; export type GetEvalRunResponses = { /** * The evaluation run */ 200: EvalRun; }; export type GetEvalRunResponse = GetEvalRunResponses[keyof GetEvalRunResponses]; export type CancelEvalRunData = { body?: never; path: { /** * The ID of the evaluation whose run you want to cancel. */ eval_id: string; /** * The ID of the run to cancel. */ run_id: string; }; query?: never; url: '/evals/{eval_id}/runs/{run_id}'; }; export type CancelEvalRunResponses = { /** * The canceled eval run object */ 200: EvalRun; }; export type CancelEvalRunResponse = CancelEvalRunResponses[keyof CancelEvalRunResponses]; export type GetEvalRunOutputItemsData = { body?: never; path: { /** * The ID of the evaluation to retrieve runs for. */ eval_id: string; /** * The ID of the run to retrieve output items for. */ run_id: string; }; query?: { /** * Identifier for the last output item from the previous pagination request. */ after?: string; /** * Number of output items to retrieve. */ limit?: number; /** * Filter output items by status. Use `failed` to filter by failed output * items or `pass` to filter by passed output items. * */ status?: 'fail' | 'pass'; /** * Sort order for output items by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. */ order?: 'asc' | 'desc'; }; url: '/evals/{eval_id}/runs/{run_id}/output_items'; }; export type GetEvalRunOutputItemsResponses = { /** * A list of output items for the evaluation run */ 200: EvalRunOutputItemList; }; export type GetEvalRunOutputItemsResponse = GetEvalRunOutputItemsResponses[keyof GetEvalRunOutputItemsResponses]; export type GetEvalRunOutputItemData = { body?: never; path: { /** * The ID of the evaluation to retrieve runs for. */ eval_id: string; /** * The ID of the run to retrieve. */ run_id: string; /** * The ID of the output item to retrieve. */ output_item_id: string; }; query?: never; url: '/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}'; }; export type GetEvalRunOutputItemResponses = { /** * The evaluation run output item */ 200: EvalRunOutputItem; }; export type GetEvalRunOutputItemResponse = GetEvalRunOutputItemResponses[keyof GetEvalRunOutputItemResponses]; export type ListFilesData = { body?: never; path?: never; query?: { /** * Only return files with the given purpose. */ purpose?: string; /** * A limit on the number of objects to be returned. Limit can range between 1 and 10,000, and the default is 10,000. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; }; url: '/files'; }; export type ListFilesResponses = { /** * OK */ 200: ListFilesResponse; }; export type ListFilesResponse2 = ListFilesResponses[keyof ListFilesResponses]; export type CreateFileData = { body: CreateFileRequest; path?: never; query?: never; url: '/files'; }; export type CreateFileResponses = { /** * OK */ 200: OpenAiFile; }; export type CreateFileResponse = CreateFileResponses[keyof CreateFileResponses]; export type DeleteFileData = { body?: never; path: { /** * The ID of the file to use for this request. */ file_id: string; }; query?: never; url: '/files/{file_id}'; }; export type DeleteFileResponses = { /** * OK */ 200: DeleteFileResponse; }; export type DeleteFileResponse2 = DeleteFileResponses[keyof DeleteFileResponses]; export type RetrieveFileData = { body?: never; path: { /** * The ID of the file to use for this request. */ file_id: string; }; query?: never; url: '/files/{file_id}'; }; export type RetrieveFileResponses = { /** * OK */ 200: OpenAiFile; }; export type RetrieveFileResponse = RetrieveFileResponses[keyof RetrieveFileResponses]; export type DownloadFileData = { body?: never; path: { /** * The ID of the file to use for this request. */ file_id: string; }; query?: never; url: '/files/{file_id}/content'; }; export type DownloadFileResponses = { /** * OK */ 200: string; }; export type DownloadFileResponse = DownloadFileResponses[keyof DownloadFileResponses]; export type RunGraderData = { body: RunGraderRequest; path?: never; query?: never; url: '/fine_tuning/alpha/graders/run'; }; export type RunGraderResponses = { /** * OK */ 200: RunGraderResponse; }; export type RunGraderResponse2 = RunGraderResponses[keyof RunGraderResponses]; export type ValidateGraderData = { body: ValidateGraderRequest; path?: never; query?: never; url: '/fine_tuning/alpha/graders/validate'; }; export type ValidateGraderResponses = { /** * OK */ 200: ValidateGraderResponse; }; export type ValidateGraderResponse2 = ValidateGraderResponses[keyof ValidateGraderResponses]; export type ListFineTuningCheckpointPermissionsData = { body?: never; path: { /** * The ID of the fine-tuned model checkpoint to get permissions for. * */ fine_tuned_model_checkpoint: string; }; query?: { /** * The ID of the project to get permissions for. */ project_id?: string; /** * Identifier for the last permission ID from the previous pagination request. */ after?: string; /** * Number of permissions to retrieve. */ limit?: number; /** * The order in which to retrieve permissions. */ order?: 'ascending' | 'descending'; }; url: '/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions'; }; export type ListFineTuningCheckpointPermissionsResponses = { /** * OK */ 200: ListFineTuningCheckpointPermissionResponse; }; export type ListFineTuningCheckpointPermissionsResponse = ListFineTuningCheckpointPermissionsResponses[keyof ListFineTuningCheckpointPermissionsResponses]; export type CreateFineTuningCheckpointPermissionData = { body: CreateFineTuningCheckpointPermissionRequest; path: { /** * The ID of the fine-tuned model checkpoint to create a permission for. * */ fine_tuned_model_checkpoint: string; }; query?: never; url: '/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions'; }; export type CreateFineTuningCheckpointPermissionResponses = { /** * OK */ 200: ListFineTuningCheckpointPermissionResponse; }; export type CreateFineTuningCheckpointPermissionResponse = CreateFineTuningCheckpointPermissionResponses[keyof CreateFineTuningCheckpointPermissionResponses]; export type DeleteFineTuningCheckpointPermissionData = { body?: never; path: { /** * The ID of the fine-tuned model checkpoint to delete a permission for. * */ fine_tuned_model_checkpoint: string; /** * The ID of the fine-tuned model checkpoint permission to delete. * */ permission_id: string; }; query?: never; url: '/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}'; }; export type DeleteFineTuningCheckpointPermissionResponses = { /** * OK */ 200: DeleteFineTuningCheckpointPermissionResponse; }; export type DeleteFineTuningCheckpointPermissionResponse2 = DeleteFineTuningCheckpointPermissionResponses[keyof DeleteFineTuningCheckpointPermissionResponses]; export type ListPaginatedFineTuningJobsData = { body?: never; path?: never; query?: { /** * Identifier for the last job from the previous pagination request. */ after?: string; /** * Number of fine-tuning jobs to retrieve. */ limit?: number; /** * Optional metadata filter. To filter, use the syntax `metadata[k]=v`. Alternatively, set `metadata=null` to indicate no metadata. * */ metadata?: { [key: string]: string; }; }; url: '/fine_tuning/jobs'; }; export type ListPaginatedFineTuningJobsResponses = { /** * OK */ 200: ListPaginatedFineTuningJobsResponse; }; export type ListPaginatedFineTuningJobsResponse2 = ListPaginatedFineTuningJobsResponses[keyof ListPaginatedFineTuningJobsResponses]; export type CreateFineTuningJobData = { body: CreateFineTuningJobRequest; path?: never; query?: never; url: '/fine_tuning/jobs'; }; export type CreateFineTuningJobResponses = { /** * OK */ 200: FineTuningJob; }; export type CreateFineTuningJobResponse = CreateFineTuningJobResponses[keyof CreateFineTuningJobResponses]; export type RetrieveFineTuningJobData = { body?: never; path: { /** * The ID of the fine-tuning job. * */ fine_tuning_job_id: string; }; query?: never; url: '/fine_tuning/jobs/{fine_tuning_job_id}'; }; export type RetrieveFineTuningJobResponses = { /** * OK */ 200: FineTuningJob; }; export type RetrieveFineTuningJobResponse = RetrieveFineTuningJobResponses[keyof RetrieveFineTuningJobResponses]; export type CancelFineTuningJobData = { body?: never; path: { /** * The ID of the fine-tuning job to cancel. * */ fine_tuning_job_id: string; }; query?: never; url: '/fine_tuning/jobs/{fine_tuning_job_id}/cancel'; }; export type CancelFineTuningJobResponses = { /** * OK */ 200: FineTuningJob; }; export type CancelFineTuningJobResponse = CancelFineTuningJobResponses[keyof CancelFineTuningJobResponses]; export type ListFineTuningJobCheckpointsData = { body?: never; path: { /** * The ID of the fine-tuning job to get checkpoints for. * */ fine_tuning_job_id: string; }; query?: { /** * Identifier for the last checkpoint ID from the previous pagination request. */ after?: string; /** * Number of checkpoints to retrieve. */ limit?: number; }; url: '/fine_tuning/jobs/{fine_tuning_job_id}/checkpoints'; }; export type ListFineTuningJobCheckpointsResponses = { /** * OK */ 200: ListFineTuningJobCheckpointsResponse; }; export type ListFineTuningJobCheckpointsResponse2 = ListFineTuningJobCheckpointsResponses[keyof ListFineTuningJobCheckpointsResponses]; export type ListFineTuningEventsData = { body?: never; path: { /** * The ID of the fine-tuning job to get events for. * */ fine_tuning_job_id: string; }; query?: { /** * Identifier for the last event from the previous pagination request. */ after?: string; /** * Number of events to retrieve. */ limit?: number; }; url: '/fine_tuning/jobs/{fine_tuning_job_id}/events'; }; export type ListFineTuningEventsResponses = { /** * OK */ 200: ListFineTuningJobEventsResponse; }; export type ListFineTuningEventsResponse = ListFineTuningEventsResponses[keyof ListFineTuningEventsResponses]; export type PauseFineTuningJobData = { body?: never; path: { /** * The ID of the fine-tuning job to pause. * */ fine_tuning_job_id: string; }; query?: never; url: '/fine_tuning/jobs/{fine_tuning_job_id}/pause'; }; export type PauseFineTuningJobResponses = { /** * OK */ 200: FineTuningJob; }; export type PauseFineTuningJobResponse = PauseFineTuningJobResponses[keyof PauseFineTuningJobResponses]; export type ResumeFineTuningJobData = { body?: never; path: { /** * The ID of the fine-tuning job to resume. * */ fine_tuning_job_id: string; }; query?: never; url: '/fine_tuning/jobs/{fine_tuning_job_id}/resume'; }; export type ResumeFineTuningJobResponses = { /** * OK */ 200: FineTuningJob; }; export type ResumeFineTuningJobResponse = ResumeFineTuningJobResponses[keyof ResumeFineTuningJobResponses]; export type CreateImageEditData = { body: CreateImageEditRequest; path?: never; query?: never; url: '/images/edits'; }; export type CreateImageEditResponses = { /** * OK */ 200: ImagesResponse; }; export type CreateImageEditResponse = CreateImageEditResponses[keyof CreateImageEditResponses]; export type CreateImageData = { body: CreateImageRequest; path?: never; query?: never; url: '/images/generations'; }; export type CreateImageResponses = { /** * OK */ 200: ImagesResponse; }; export type CreateImageResponse = CreateImageResponses[keyof CreateImageResponses]; export type CreateImageVariationData = { body: CreateImageVariationRequest; path?: never; query?: never; url: '/images/variations'; }; export type CreateImageVariationResponses = { /** * OK */ 200: ImagesResponse; }; export type CreateImageVariationResponse = CreateImageVariationResponses[keyof CreateImageVariationResponses]; export type ListModelsData = { body?: never; path?: never; query?: never; url: '/models'; }; export type ListModelsResponses = { /** * OK */ 200: ListModelsResponse; }; export type ListModelsResponse2 = ListModelsResponses[keyof ListModelsResponses]; export type DeleteModelData = { body?: never; path: { /** * The model to delete */ model: string; }; query?: never; url: '/models/{model}'; }; export type DeleteModelResponses = { /** * OK */ 200: DeleteModelResponse; }; export type DeleteModelResponse2 = DeleteModelResponses[keyof DeleteModelResponses]; export type RetrieveModelData = { body?: never; path: { /** * The ID of the model to use for this request */ model: string; }; query?: never; url: '/models/{model}'; }; export type RetrieveModelResponses = { /** * OK */ 200: Model; }; export type RetrieveModelResponse = RetrieveModelResponses[keyof RetrieveModelResponses]; export type CreateModerationData = { body: CreateModerationRequest; path?: never; query?: never; url: '/moderations'; }; export type CreateModerationResponses = { /** * OK */ 200: CreateModerationResponse; }; export type CreateModerationResponse2 = CreateModerationResponses[keyof CreateModerationResponses]; export type AdminApiKeysListData = { body?: never; path?: never; query?: { /** * Return keys with IDs that come after this ID in the pagination order. */ after?: string; /** * Order results by creation time, ascending or descending. */ order?: 'asc' | 'desc'; /** * Maximum number of keys to return. */ limit?: number; }; url: '/organization/admin_api_keys'; }; export type AdminApiKeysListResponses = { /** * A list of organization API keys. */ 200: ApiKeyList; }; export type AdminApiKeysListResponse = AdminApiKeysListResponses[keyof AdminApiKeysListResponses]; export type AdminApiKeysCreateData = { body: { name: string; }; path?: never; query?: never; url: '/organization/admin_api_keys'; }; export type AdminApiKeysCreateResponses = { /** * The newly created admin API key. */ 200: AdminApiKey; }; export type AdminApiKeysCreateResponse = AdminApiKeysCreateResponses[keyof AdminApiKeysCreateResponses]; export type AdminApiKeysDeleteData = { body?: never; path: { /** * The ID of the API key to be deleted. */ key_id: string; }; query?: never; url: '/organization/admin_api_keys/{key_id}'; }; export type AdminApiKeysDeleteResponses = { /** * Confirmation that the API key was deleted. */ 200: { id?: string; object?: string; deleted?: boolean; }; }; export type AdminApiKeysDeleteResponse = AdminApiKeysDeleteResponses[keyof AdminApiKeysDeleteResponses]; export type AdminApiKeysGetData = { body?: never; path: { /** * The ID of the API key. */ key_id: string; }; query?: never; url: '/organization/admin_api_keys/{key_id}'; }; export type AdminApiKeysGetResponses = { /** * Details of the requested API key. */ 200: AdminApiKey; }; export type AdminApiKeysGetResponse = AdminApiKeysGetResponses[keyof AdminApiKeysGetResponses]; export type ListAuditLogsData = { body?: never; path?: never; query?: { /** * Return only events whose `effective_at` (Unix seconds) is in this range. */ effective_at?: { /** * Return only events whose `effective_at` (Unix seconds) is greater than this value. */ gt?: number; /** * Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value. */ gte?: number; /** * Return only events whose `effective_at` (Unix seconds) is less than this value. */ lt?: number; /** * Return only events whose `effective_at` (Unix seconds) is less than or equal to this value. */ lte?: number; }; /** * Return only events for these projects. */ 'project_ids[]'?: Array; /** * Return only events with a `type` in one of these values. For example, `project.created`. For all options, see the documentation for the [audit log object](https://platform.openai.com/docs/api-reference/audit-logs/object). */ 'event_types[]'?: Array; /** * Return only events performed by these actors. Can be a user ID, a service account ID, or an api key tracking ID. */ 'actor_ids[]'?: Array; /** * Return only events performed by users with these emails. */ 'actor_emails[]'?: Array; /** * Return only events performed on these targets. For example, a project ID updated. */ 'resource_ids[]'?: Array; /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; }; url: '/organization/audit_logs'; }; export type ListAuditLogsResponses = { /** * Audit logs listed successfully. */ 200: ListAuditLogsResponse; }; export type ListAuditLogsResponse2 = ListAuditLogsResponses[keyof ListAuditLogsResponses]; export type ListOrganizationCertificatesData = { body?: never; path?: never; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; }; url: '/organization/certificates'; }; export type ListOrganizationCertificatesResponses = { /** * Certificates listed successfully. */ 200: ListCertificatesResponse; }; export type ListOrganizationCertificatesResponse = ListOrganizationCertificatesResponses[keyof ListOrganizationCertificatesResponses]; export type UploadCertificateData = { /** * The certificate upload payload. */ body: UploadCertificateRequest; path?: never; query?: never; url: '/organization/certificates'; }; export type UploadCertificateResponses = { /** * Certificate uploaded successfully. */ 200: Certificate; }; export type UploadCertificateResponse = UploadCertificateResponses[keyof UploadCertificateResponses]; export type ActivateOrganizationCertificatesData = { /** * The certificate activation payload. */ body: ToggleCertificatesRequest; path?: never; query?: never; url: '/organization/certificates/activate'; }; export type ActivateOrganizationCertificatesResponses = { /** * Certificates activated successfully. */ 200: ListCertificatesResponse; }; export type ActivateOrganizationCertificatesResponse = ActivateOrganizationCertificatesResponses[keyof ActivateOrganizationCertificatesResponses]; export type DeactivateOrganizationCertificatesData = { /** * The certificate deactivation payload. */ body: ToggleCertificatesRequest; path?: never; query?: never; url: '/organization/certificates/deactivate'; }; export type DeactivateOrganizationCertificatesResponses = { /** * Certificates deactivated successfully. */ 200: ListCertificatesResponse; }; export type DeactivateOrganizationCertificatesResponse = DeactivateOrganizationCertificatesResponses[keyof DeactivateOrganizationCertificatesResponses]; export type DeleteCertificateData = { body?: never; path?: never; query?: never; url: '/organization/certificates/{certificate_id}'; }; export type DeleteCertificateResponses = { /** * Certificate deleted successfully. */ 200: DeleteCertificateResponse; }; export type DeleteCertificateResponse2 = DeleteCertificateResponses[keyof DeleteCertificateResponses]; export type GetCertificateData = { body?: never; path: { /** * Unique ID of the certificate to retrieve. */ certificate_id: string; }; query?: { /** * A list of additional fields to include in the response. Currently the only supported value is `content` to fetch the PEM content of the certificate. */ include?: Array<'content'>; }; url: '/organization/certificates/{certificate_id}'; }; export type GetCertificateResponses = { /** * Certificate retrieved successfully. */ 200: Certificate; }; export type GetCertificateResponse = GetCertificateResponses[keyof GetCertificateResponses]; export type ModifyCertificateData = { /** * The certificate modification payload. */ body: ModifyCertificateRequest; path?: never; query?: never; url: '/organization/certificates/{certificate_id}'; }; export type ModifyCertificateResponses = { /** * Certificate modified successfully. */ 200: Certificate; }; export type ModifyCertificateResponse = ModifyCertificateResponses[keyof ModifyCertificateResponses]; export type UsageCostsData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently only `1d` is supported, default to `1d`. */ bucket_width?: '1d'; /** * Return only costs for these projects. */ project_ids?: Array; /** * Group the costs by the specified fields. Support fields include `project_id`, `line_item` and any combination of them. */ group_by?: Array<'project_id' | 'line_item'>; /** * A limit on the number of buckets to be returned. Limit can range between 1 and 180, and the default is 7. * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/costs'; }; export type UsageCostsResponses = { /** * Costs data retrieved successfully. */ 200: UsageResponse; }; export type UsageCostsResponse = UsageCostsResponses[keyof UsageCostsResponses]; export type ListInvitesData = { body?: never; path?: never; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; }; url: '/organization/invites'; }; export type ListInvitesResponses = { /** * Invites listed successfully. */ 200: InviteListResponse; }; export type ListInvitesResponse = ListInvitesResponses[keyof ListInvitesResponses]; export type InviteUserData = { /** * The invite request payload. */ body: InviteRequest; path?: never; query?: never; url: '/organization/invites'; }; export type InviteUserResponses = { /** * User invited successfully. */ 200: Invite; }; export type InviteUserResponse = InviteUserResponses[keyof InviteUserResponses]; export type DeleteInviteData = { body?: never; path: { /** * The ID of the invite to delete. */ invite_id: string; }; query?: never; url: '/organization/invites/{invite_id}'; }; export type DeleteInviteResponses = { /** * Invite deleted successfully. */ 200: InviteDeleteResponse; }; export type DeleteInviteResponse = DeleteInviteResponses[keyof DeleteInviteResponses]; export type RetrieveInviteData = { body?: never; path: { /** * The ID of the invite to retrieve. */ invite_id: string; }; query?: never; url: '/organization/invites/{invite_id}'; }; export type RetrieveInviteResponses = { /** * Invite retrieved successfully. */ 200: Invite; }; export type RetrieveInviteResponse = RetrieveInviteResponses[keyof RetrieveInviteResponses]; export type ListProjectsData = { body?: never; path?: never; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * If `true` returns all projects including those that have been `archived`. Archived projects are not included by default. */ include_archived?: boolean; }; url: '/organization/projects'; }; export type ListProjectsResponses = { /** * Projects listed successfully. */ 200: ProjectListResponse; }; export type ListProjectsResponse = ListProjectsResponses[keyof ListProjectsResponses]; export type CreateProjectData = { /** * The project create request payload. */ body: ProjectCreateRequest; path?: never; query?: never; url: '/organization/projects'; }; export type CreateProjectResponses = { /** * Project created successfully. */ 200: Project; }; export type CreateProjectResponse = CreateProjectResponses[keyof CreateProjectResponses]; export type RetrieveProjectData = { body?: never; path: { /** * The ID of the project. */ project_id: string; }; query?: never; url: '/organization/projects/{project_id}'; }; export type RetrieveProjectResponses = { /** * Project retrieved successfully. */ 200: Project; }; export type RetrieveProjectResponse = RetrieveProjectResponses[keyof RetrieveProjectResponses]; export type ModifyProjectData = { /** * The project update request payload. */ body: ProjectUpdateRequest; path: { /** * The ID of the project. */ project_id: string; }; query?: never; url: '/organization/projects/{project_id}'; }; export type ModifyProjectErrors = { /** * Error response when updating the default project. */ 400: ErrorResponse; }; export type ModifyProjectError = ModifyProjectErrors[keyof ModifyProjectErrors]; export type ModifyProjectResponses = { /** * Project updated successfully. */ 200: Project; }; export type ModifyProjectResponse = ModifyProjectResponses[keyof ModifyProjectResponses]; export type ListProjectApiKeysData = { body?: never; path: { /** * The ID of the project. */ project_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; }; url: '/organization/projects/{project_id}/api_keys'; }; export type ListProjectApiKeysResponses = { /** * Project API keys listed successfully. */ 200: ProjectApiKeyListResponse; }; export type ListProjectApiKeysResponse = ListProjectApiKeysResponses[keyof ListProjectApiKeysResponses]; export type DeleteProjectApiKeyData = { body?: never; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the API key. */ key_id: string; }; query?: never; url: '/organization/projects/{project_id}/api_keys/{key_id}'; }; export type DeleteProjectApiKeyErrors = { /** * Error response for various conditions. */ 400: ErrorResponse; }; export type DeleteProjectApiKeyError = DeleteProjectApiKeyErrors[keyof DeleteProjectApiKeyErrors]; export type DeleteProjectApiKeyResponses = { /** * Project API key deleted successfully. */ 200: ProjectApiKeyDeleteResponse; }; export type DeleteProjectApiKeyResponse = DeleteProjectApiKeyResponses[keyof DeleteProjectApiKeyResponses]; export type RetrieveProjectApiKeyData = { body?: never; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the API key. */ key_id: string; }; query?: never; url: '/organization/projects/{project_id}/api_keys/{key_id}'; }; export type RetrieveProjectApiKeyResponses = { /** * Project API key retrieved successfully. */ 200: ProjectApiKey; }; export type RetrieveProjectApiKeyResponse = RetrieveProjectApiKeyResponses[keyof RetrieveProjectApiKeyResponses]; export type ArchiveProjectData = { body?: never; path: { /** * The ID of the project. */ project_id: string; }; query?: never; url: '/organization/projects/{project_id}/archive'; }; export type ArchiveProjectResponses = { /** * Project archived successfully. */ 200: Project; }; export type ArchiveProjectResponse = ArchiveProjectResponses[keyof ArchiveProjectResponses]; export type ListProjectCertificatesData = { body?: never; path: { /** * The ID of the project. */ project_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; }; url: '/organization/projects/{project_id}/certificates'; }; export type ListProjectCertificatesResponses = { /** * Certificates listed successfully. */ 200: ListCertificatesResponse; }; export type ListProjectCertificatesResponse = ListProjectCertificatesResponses[keyof ListProjectCertificatesResponses]; export type ActivateProjectCertificatesData = { /** * The certificate activation payload. */ body: ToggleCertificatesRequest; path: { /** * The ID of the project. */ project_id: string; }; query?: never; url: '/organization/projects/{project_id}/certificates/activate'; }; export type ActivateProjectCertificatesResponses = { /** * Certificates activated successfully. */ 200: ListCertificatesResponse; }; export type ActivateProjectCertificatesResponse = ActivateProjectCertificatesResponses[keyof ActivateProjectCertificatesResponses]; export type DeactivateProjectCertificatesData = { /** * The certificate deactivation payload. */ body: ToggleCertificatesRequest; path: { /** * The ID of the project. */ project_id: string; }; query?: never; url: '/organization/projects/{project_id}/certificates/deactivate'; }; export type DeactivateProjectCertificatesResponses = { /** * Certificates deactivated successfully. */ 200: ListCertificatesResponse; }; export type DeactivateProjectCertificatesResponse = DeactivateProjectCertificatesResponses[keyof DeactivateProjectCertificatesResponses]; export type ListProjectRateLimitsData = { body?: never; path: { /** * The ID of the project. */ project_id: string; }; query?: { /** * A limit on the number of objects to be returned. The default is 100. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, beginning with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; }; url: '/organization/projects/{project_id}/rate_limits'; }; export type ListProjectRateLimitsResponses = { /** * Project rate limits listed successfully. */ 200: ProjectRateLimitListResponse; }; export type ListProjectRateLimitsResponse = ListProjectRateLimitsResponses[keyof ListProjectRateLimitsResponses]; export type UpdateProjectRateLimitsData = { /** * The project rate limit update request payload. */ body: ProjectRateLimitUpdateRequest; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the rate limit. */ rate_limit_id: string; }; query?: never; url: '/organization/projects/{project_id}/rate_limits/{rate_limit_id}'; }; export type UpdateProjectRateLimitsErrors = { /** * Error response for various conditions. */ 400: ErrorResponse; }; export type UpdateProjectRateLimitsError = UpdateProjectRateLimitsErrors[keyof UpdateProjectRateLimitsErrors]; export type UpdateProjectRateLimitsResponses = { /** * Project rate limit updated successfully. */ 200: ProjectRateLimit; }; export type UpdateProjectRateLimitsResponse = UpdateProjectRateLimitsResponses[keyof UpdateProjectRateLimitsResponses]; export type ListProjectServiceAccountsData = { body?: never; path: { /** * The ID of the project. */ project_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; }; url: '/organization/projects/{project_id}/service_accounts'; }; export type ListProjectServiceAccountsErrors = { /** * Error response when project is archived. */ 400: ErrorResponse; }; export type ListProjectServiceAccountsError = ListProjectServiceAccountsErrors[keyof ListProjectServiceAccountsErrors]; export type ListProjectServiceAccountsResponses = { /** * Project service accounts listed successfully. */ 200: ProjectServiceAccountListResponse; }; export type ListProjectServiceAccountsResponse = ListProjectServiceAccountsResponses[keyof ListProjectServiceAccountsResponses]; export type CreateProjectServiceAccountData = { /** * The project service account create request payload. */ body: ProjectServiceAccountCreateRequest; path: { /** * The ID of the project. */ project_id: string; }; query?: never; url: '/organization/projects/{project_id}/service_accounts'; }; export type CreateProjectServiceAccountErrors = { /** * Error response when project is archived. */ 400: ErrorResponse; }; export type CreateProjectServiceAccountError = CreateProjectServiceAccountErrors[keyof CreateProjectServiceAccountErrors]; export type CreateProjectServiceAccountResponses = { /** * Project service account created successfully. */ 200: ProjectServiceAccountCreateResponse; }; export type CreateProjectServiceAccountResponse = CreateProjectServiceAccountResponses[keyof CreateProjectServiceAccountResponses]; export type DeleteProjectServiceAccountData = { body?: never; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the service account. */ service_account_id: string; }; query?: never; url: '/organization/projects/{project_id}/service_accounts/{service_account_id}'; }; export type DeleteProjectServiceAccountResponses = { /** * Project service account deleted successfully. */ 200: ProjectServiceAccountDeleteResponse; }; export type DeleteProjectServiceAccountResponse = DeleteProjectServiceAccountResponses[keyof DeleteProjectServiceAccountResponses]; export type RetrieveProjectServiceAccountData = { body?: never; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the service account. */ service_account_id: string; }; query?: never; url: '/organization/projects/{project_id}/service_accounts/{service_account_id}'; }; export type RetrieveProjectServiceAccountResponses = { /** * Project service account retrieved successfully. */ 200: ProjectServiceAccount; }; export type RetrieveProjectServiceAccountResponse = RetrieveProjectServiceAccountResponses[keyof RetrieveProjectServiceAccountResponses]; export type ListProjectUsersData = { body?: never; path: { /** * The ID of the project. */ project_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; }; url: '/organization/projects/{project_id}/users'; }; export type ListProjectUsersErrors = { /** * Error response when project is archived. */ 400: ErrorResponse; }; export type ListProjectUsersError = ListProjectUsersErrors[keyof ListProjectUsersErrors]; export type ListProjectUsersResponses = { /** * Project users listed successfully. */ 200: ProjectUserListResponse; }; export type ListProjectUsersResponse = ListProjectUsersResponses[keyof ListProjectUsersResponses]; export type CreateProjectUserData = { /** * The project user create request payload. */ body: ProjectUserCreateRequest; path: { /** * The ID of the project. */ project_id: string; }; query?: never; url: '/organization/projects/{project_id}/users'; }; export type CreateProjectUserErrors = { /** * Error response for various conditions. */ 400: ErrorResponse; }; export type CreateProjectUserError = CreateProjectUserErrors[keyof CreateProjectUserErrors]; export type CreateProjectUserResponses = { /** * User added to project successfully. */ 200: ProjectUser; }; export type CreateProjectUserResponse = CreateProjectUserResponses[keyof CreateProjectUserResponses]; export type DeleteProjectUserData = { body?: never; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the user. */ user_id: string; }; query?: never; url: '/organization/projects/{project_id}/users/{user_id}'; }; export type DeleteProjectUserErrors = { /** * Error response for various conditions. */ 400: ErrorResponse; }; export type DeleteProjectUserError = DeleteProjectUserErrors[keyof DeleteProjectUserErrors]; export type DeleteProjectUserResponses = { /** * Project user deleted successfully. */ 200: ProjectUserDeleteResponse; }; export type DeleteProjectUserResponse = DeleteProjectUserResponses[keyof DeleteProjectUserResponses]; export type RetrieveProjectUserData = { body?: never; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the user. */ user_id: string; }; query?: never; url: '/organization/projects/{project_id}/users/{user_id}'; }; export type RetrieveProjectUserResponses = { /** * Project user retrieved successfully. */ 200: ProjectUser; }; export type RetrieveProjectUserResponse = RetrieveProjectUserResponses[keyof RetrieveProjectUserResponses]; export type ModifyProjectUserData = { /** * The project user update request payload. */ body: ProjectUserUpdateRequest; path: { /** * The ID of the project. */ project_id: string; /** * The ID of the user. */ user_id: string; }; query?: never; url: '/organization/projects/{project_id}/users/{user_id}'; }; export type ModifyProjectUserErrors = { /** * Error response for various conditions. */ 400: ErrorResponse; }; export type ModifyProjectUserError = ModifyProjectUserErrors[keyof ModifyProjectUserErrors]; export type ModifyProjectUserResponses = { /** * Project user's role updated successfully. */ 200: ProjectUser; }; export type ModifyProjectUserResponse = ModifyProjectUserResponses[keyof ModifyProjectUserResponses]; export type UsageAudioSpeechesData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usage for these projects. */ project_ids?: Array; /** * Return only usage for these users. */ user_ids?: Array; /** * Return only usage for these API keys. */ api_key_ids?: Array; /** * Return only usage for these models. */ models?: Array; /** * Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. */ group_by?: Array<'project_id' | 'user_id' | 'api_key_id' | 'model'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/audio_speeches'; }; export type UsageAudioSpeechesResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageAudioSpeechesResponse = UsageAudioSpeechesResponses[keyof UsageAudioSpeechesResponses]; export type UsageAudioTranscriptionsData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usage for these projects. */ project_ids?: Array; /** * Return only usage for these users. */ user_ids?: Array; /** * Return only usage for these API keys. */ api_key_ids?: Array; /** * Return only usage for these models. */ models?: Array; /** * Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. */ group_by?: Array<'project_id' | 'user_id' | 'api_key_id' | 'model'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/audio_transcriptions'; }; export type UsageAudioTranscriptionsResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageAudioTranscriptionsResponse = UsageAudioTranscriptionsResponses[keyof UsageAudioTranscriptionsResponses]; export type UsageCodeInterpreterSessionsData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usage for these projects. */ project_ids?: Array; /** * Group the usage data by the specified fields. Support fields include `project_id`. */ group_by?: Array<'project_id'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/code_interpreter_sessions'; }; export type UsageCodeInterpreterSessionsResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageCodeInterpreterSessionsResponse = UsageCodeInterpreterSessionsResponses[keyof UsageCodeInterpreterSessionsResponses]; export type UsageCompletionsData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usage for these projects. */ project_ids?: Array; /** * Return only usage for these users. */ user_ids?: Array; /** * Return only usage for these API keys. */ api_key_ids?: Array; /** * Return only usage for these models. */ models?: Array; /** * If `true`, return batch jobs only. If `false`, return non-batch jobs only. By default, return both. * */ batch?: boolean; /** * Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch` or any combination of them. */ group_by?: Array<'project_id' | 'user_id' | 'api_key_id' | 'model' | 'batch'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/completions'; }; export type UsageCompletionsResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageCompletionsResponse = UsageCompletionsResponses[keyof UsageCompletionsResponses]; export type UsageEmbeddingsData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usage for these projects. */ project_ids?: Array; /** * Return only usage for these users. */ user_ids?: Array; /** * Return only usage for these API keys. */ api_key_ids?: Array; /** * Return only usage for these models. */ models?: Array; /** * Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. */ group_by?: Array<'project_id' | 'user_id' | 'api_key_id' | 'model'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/embeddings'; }; export type UsageEmbeddingsResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageEmbeddingsResponse = UsageEmbeddingsResponses[keyof UsageEmbeddingsResponses]; export type UsageImagesData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usages for these sources. Possible values are `image.generation`, `image.edit`, `image.variation` or any combination of them. */ sources?: Array<'image.generation' | 'image.edit' | 'image.variation'>; /** * Return only usages for these image sizes. Possible values are `256x256`, `512x512`, `1024x1024`, `1792x1792`, `1024x1792` or any combination of them. */ sizes?: Array<'256x256' | '512x512' | '1024x1024' | '1792x1792' | '1024x1792'>; /** * Return only usage for these projects. */ project_ids?: Array; /** * Return only usage for these users. */ user_ids?: Array; /** * Return only usage for these API keys. */ api_key_ids?: Array; /** * Return only usage for these models. */ models?: Array; /** * Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `size`, `source` or any combination of them. */ group_by?: Array<'project_id' | 'user_id' | 'api_key_id' | 'model' | 'size' | 'source'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/images'; }; export type UsageImagesResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageImagesResponse = UsageImagesResponses[keyof UsageImagesResponses]; export type UsageModerationsData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usage for these projects. */ project_ids?: Array; /** * Return only usage for these users. */ user_ids?: Array; /** * Return only usage for these API keys. */ api_key_ids?: Array; /** * Return only usage for these models. */ models?: Array; /** * Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. */ group_by?: Array<'project_id' | 'user_id' | 'api_key_id' | 'model'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/moderations'; }; export type UsageModerationsResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageModerationsResponse = UsageModerationsResponses[keyof UsageModerationsResponses]; export type UsageVectorStoresData = { body?: never; path?: never; query: { /** * Start time (Unix seconds) of the query time range, inclusive. */ start_time: number; /** * End time (Unix seconds) of the query time range, exclusive. */ end_time?: number; /** * Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. */ bucket_width?: '1m' | '1h' | '1d'; /** * Return only usage for these projects. */ project_ids?: Array; /** * Group the usage data by the specified fields. Support fields include `project_id`. */ group_by?: Array<'project_id'>; /** * Specifies the number of buckets to return. * - `bucket_width=1d`: default: 7, max: 31 * - `bucket_width=1h`: default: 24, max: 168 * - `bucket_width=1m`: default: 60, max: 1440 * */ limit?: number; /** * A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. */ page?: string; }; url: '/organization/usage/vector_stores'; }; export type UsageVectorStoresResponses = { /** * Usage data retrieved successfully. */ 200: UsageResponse; }; export type UsageVectorStoresResponse = UsageVectorStoresResponses[keyof UsageVectorStoresResponses]; export type ListUsersData = { body?: never; path?: never; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * Filter by the email address of users. */ emails?: Array; }; url: '/organization/users'; }; export type ListUsersResponses = { /** * Users listed successfully. */ 200: UserListResponse; }; export type ListUsersResponse = ListUsersResponses[keyof ListUsersResponses]; export type DeleteUserData = { body?: never; path: { /** * The ID of the user. */ user_id: string; }; query?: never; url: '/organization/users/{user_id}'; }; export type DeleteUserResponses = { /** * User deleted successfully. */ 200: UserDeleteResponse; }; export type DeleteUserResponse = DeleteUserResponses[keyof DeleteUserResponses]; export type RetrieveUserData = { body?: never; path: { /** * The ID of the user. */ user_id: string; }; query?: never; url: '/organization/users/{user_id}'; }; export type RetrieveUserResponses = { /** * User retrieved successfully. */ 200: User; }; export type RetrieveUserResponse = RetrieveUserResponses[keyof RetrieveUserResponses]; export type ModifyUserData = { /** * The new user role to modify. This must be one of `owner` or `member`. */ body: UserRoleUpdateRequest; path: { /** * The ID of the user. */ user_id: string; }; query?: never; url: '/organization/users/{user_id}'; }; export type ModifyUserResponses = { /** * User role updated successfully. */ 200: User; }; export type ModifyUserResponse = ModifyUserResponses[keyof ModifyUserResponses]; export type CreateRealtimeSessionData = { /** * Create an ephemeral API key with the given session configuration. */ body: RealtimeSessionCreateRequest; path?: never; query?: never; url: '/realtime/sessions'; }; export type CreateRealtimeSessionResponses = { /** * Session created successfully. */ 200: RealtimeSessionCreateResponse; }; export type CreateRealtimeSessionResponse = CreateRealtimeSessionResponses[keyof CreateRealtimeSessionResponses]; export type CreateRealtimeTranscriptionSessionData = { /** * Create an ephemeral API key with the given session configuration. */ body: RealtimeTranscriptionSessionCreateRequest; path?: never; query?: never; url: '/realtime/transcription_sessions'; }; export type CreateRealtimeTranscriptionSessionResponses = { /** * Session created successfully. */ 200: RealtimeTranscriptionSessionCreateResponse; }; export type CreateRealtimeTranscriptionSessionResponse = CreateRealtimeTranscriptionSessionResponses[keyof CreateRealtimeTranscriptionSessionResponses]; export type CreateResponseData = { body: CreateResponse; path?: never; query?: never; url: '/responses'; }; export type CreateResponseResponses = { /** * OK */ 200: Response; }; export type CreateResponseResponse = CreateResponseResponses[keyof CreateResponseResponses]; export type DeleteResponseData = { body?: never; path: { /** * The ID of the response to delete. */ response_id: string; }; query?: never; url: '/responses/{response_id}'; }; export type DeleteResponseErrors = { /** * Not Found */ 404: Error; }; export type DeleteResponseError = DeleteResponseErrors[keyof DeleteResponseErrors]; export type DeleteResponseResponses = { /** * OK */ 200: unknown; }; export type GetResponseData = { body?: never; path: { /** * The ID of the response to retrieve. */ response_id: string; }; query?: { /** * Additional fields to include in the response. See the `include` * parameter for Response creation above for more information. * */ include?: Array; /** * If set to true, the model response data will be streamed to the client * as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). * See the [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) * for more information. * */ stream?: boolean; /** * The sequence number of the event after which to start streaming. * */ starting_after?: number; /** * When true, stream obfuscation will be enabled. Stream obfuscation adds * random characters to an `obfuscation` field on streaming delta events * to normalize payload sizes as a mitigation to certain side-channel * attacks. These obfuscation fields are included by default, but add a * small amount of overhead to the data stream. You can set * `include_obfuscation` to false to optimize for bandwidth if you trust * the network links between your application and the OpenAI API. * */ include_obfuscation?: boolean; }; url: '/responses/{response_id}'; }; export type GetResponseResponses = { /** * OK */ 200: Response; }; export type GetResponseResponse = GetResponseResponses[keyof GetResponseResponses]; export type CancelResponseData = { body?: never; path: { /** * The ID of the response to cancel. */ response_id: string; }; query?: never; url: '/responses/{response_id}/cancel'; }; export type CancelResponseErrors = { /** * Not Found */ 404: Error; }; export type CancelResponseError = CancelResponseErrors[keyof CancelResponseErrors]; export type CancelResponseResponses = { /** * OK */ 200: Response; }; export type CancelResponseResponse = CancelResponseResponses[keyof CancelResponseResponses]; export type ListInputItemsData = { body?: never; path: { /** * The ID of the response to retrieve input items for. */ response_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between * 1 and 100, and the default is 20. * */ limit?: number; /** * The order to return the input items in. Default is `desc`. * - `asc`: Return the input items in ascending order. * - `desc`: Return the input items in descending order. * */ order?: 'asc' | 'desc'; /** * An item ID to list items after, used in pagination. * */ after?: string; /** * An item ID to list items before, used in pagination. * */ before?: string; /** * Additional fields to include in the response. See the `include` * parameter for Response creation above for more information. * */ include?: Array; }; url: '/responses/{response_id}/input_items'; }; export type ListInputItemsResponses = { /** * OK */ 200: ResponseItemList; }; export type ListInputItemsResponse = ListInputItemsResponses[keyof ListInputItemsResponses]; export type CreateThreadData = { body?: CreateThreadRequest; path?: never; query?: never; url: '/threads'; }; export type CreateThreadResponses = { /** * OK */ 200: ThreadObject; }; export type CreateThreadResponse = CreateThreadResponses[keyof CreateThreadResponses]; export type CreateThreadAndRunData = { body: CreateThreadAndRunRequest; path?: never; query?: never; url: '/threads/runs'; }; export type CreateThreadAndRunResponses = { /** * OK */ 200: RunObject; }; export type CreateThreadAndRunResponse = CreateThreadAndRunResponses[keyof CreateThreadAndRunResponses]; export type DeleteThreadData = { body?: never; path: { /** * The ID of the thread to delete. */ thread_id: string; }; query?: never; url: '/threads/{thread_id}'; }; export type DeleteThreadResponses = { /** * OK */ 200: DeleteThreadResponse; }; export type DeleteThreadResponse2 = DeleteThreadResponses[keyof DeleteThreadResponses]; export type GetThreadData = { body?: never; path: { /** * The ID of the thread to retrieve. */ thread_id: string; }; query?: never; url: '/threads/{thread_id}'; }; export type GetThreadResponses = { /** * OK */ 200: ThreadObject; }; export type GetThreadResponse = GetThreadResponses[keyof GetThreadResponses]; export type ModifyThreadData = { body: ModifyThreadRequest; path: { /** * The ID of the thread to modify. Only the `metadata` can be modified. */ thread_id: string; }; query?: never; url: '/threads/{thread_id}'; }; export type ModifyThreadResponses = { /** * OK */ 200: ThreadObject; }; export type ModifyThreadResponse = ModifyThreadResponses[keyof ModifyThreadResponses]; export type ListMessagesData = { body?: never; path: { /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) the messages belong to. */ thread_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; /** * Filter messages by the run ID that generated them. * */ run_id?: string; }; url: '/threads/{thread_id}/messages'; }; export type ListMessagesResponses = { /** * OK */ 200: ListMessagesResponse; }; export type ListMessagesResponse2 = ListMessagesResponses[keyof ListMessagesResponses]; export type CreateMessageData = { body: CreateMessageRequest; path: { /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to create a message for. */ thread_id: string; }; query?: never; url: '/threads/{thread_id}/messages'; }; export type CreateMessageResponses = { /** * OK */ 200: MessageObject; }; export type CreateMessageResponse = CreateMessageResponses[keyof CreateMessageResponses]; export type DeleteMessageData = { body?: never; path: { /** * The ID of the thread to which this message belongs. */ thread_id: string; /** * The ID of the message to delete. */ message_id: string; }; query?: never; url: '/threads/{thread_id}/messages/{message_id}'; }; export type DeleteMessageResponses = { /** * OK */ 200: DeleteMessageResponse; }; export type DeleteMessageResponse2 = DeleteMessageResponses[keyof DeleteMessageResponses]; export type GetMessageData = { body?: never; path: { /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this message belongs. */ thread_id: string; /** * The ID of the message to retrieve. */ message_id: string; }; query?: never; url: '/threads/{thread_id}/messages/{message_id}'; }; export type GetMessageResponses = { /** * OK */ 200: MessageObject; }; export type GetMessageResponse = GetMessageResponses[keyof GetMessageResponses]; export type ModifyMessageData = { body: ModifyMessageRequest; path: { /** * The ID of the thread to which this message belongs. */ thread_id: string; /** * The ID of the message to modify. */ message_id: string; }; query?: never; url: '/threads/{thread_id}/messages/{message_id}'; }; export type ModifyMessageResponses = { /** * OK */ 200: MessageObject; }; export type ModifyMessageResponse = ModifyMessageResponses[keyof ModifyMessageResponses]; export type ListRunsData = { body?: never; path: { /** * The ID of the thread the run belongs to. */ thread_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; }; url: '/threads/{thread_id}/runs'; }; export type ListRunsResponses = { /** * OK */ 200: ListRunsResponse; }; export type ListRunsResponse2 = ListRunsResponses[keyof ListRunsResponses]; export type CreateRunData = { body: CreateRunRequest; path: { /** * The ID of the thread to run. */ thread_id: string; }; query?: { /** * A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. * * See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. * */ 'include[]'?: Array<'step_details.tool_calls[*].file_search.results[*].content'>; }; url: '/threads/{thread_id}/runs'; }; export type CreateRunResponses = { /** * OK */ 200: RunObject; }; export type CreateRunResponse = CreateRunResponses[keyof CreateRunResponses]; export type GetRunData = { body?: never; path: { /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. */ thread_id: string; /** * The ID of the run to retrieve. */ run_id: string; }; query?: never; url: '/threads/{thread_id}/runs/{run_id}'; }; export type GetRunResponses = { /** * OK */ 200: RunObject; }; export type GetRunResponse = GetRunResponses[keyof GetRunResponses]; export type ModifyRunData = { body: ModifyRunRequest; path: { /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. */ thread_id: string; /** * The ID of the run to modify. */ run_id: string; }; query?: never; url: '/threads/{thread_id}/runs/{run_id}'; }; export type ModifyRunResponses = { /** * OK */ 200: RunObject; }; export type ModifyRunResponse = ModifyRunResponses[keyof ModifyRunResponses]; export type CancelRunData = { body?: never; path: { /** * The ID of the thread to which this run belongs. */ thread_id: string; /** * The ID of the run to cancel. */ run_id: string; }; query?: never; url: '/threads/{thread_id}/runs/{run_id}/cancel'; }; export type CancelRunResponses = { /** * OK */ 200: RunObject; }; export type CancelRunResponse = CancelRunResponses[keyof CancelRunResponses]; export type ListRunStepsData = { body?: never; path: { /** * The ID of the thread the run and run steps belong to. */ thread_id: string; /** * The ID of the run the run steps belong to. */ run_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; /** * A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. * * See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. * */ 'include[]'?: Array<'step_details.tool_calls[*].file_search.results[*].content'>; }; url: '/threads/{thread_id}/runs/{run_id}/steps'; }; export type ListRunStepsResponses = { /** * OK */ 200: ListRunStepsResponse; }; export type ListRunStepsResponse2 = ListRunStepsResponses[keyof ListRunStepsResponses]; export type GetRunStepData = { body?: never; path: { /** * The ID of the thread to which the run and run step belongs. */ thread_id: string; /** * The ID of the run to which the run step belongs. */ run_id: string; /** * The ID of the run step to retrieve. */ step_id: string; }; query?: { /** * A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. * * See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. * */ 'include[]'?: Array<'step_details.tool_calls[*].file_search.results[*].content'>; }; url: '/threads/{thread_id}/runs/{run_id}/steps/{step_id}'; }; export type GetRunStepResponses = { /** * OK */ 200: RunStepObject; }; export type GetRunStepResponse = GetRunStepResponses[keyof GetRunStepResponses]; export type SubmitToolOuputsToRunData = { body: SubmitToolOutputsRunRequest; path: { /** * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this run belongs. */ thread_id: string; /** * The ID of the run that requires the tool output submission. */ run_id: string; }; query?: never; url: '/threads/{thread_id}/runs/{run_id}/submit_tool_outputs'; }; export type SubmitToolOuputsToRunResponses = { /** * OK */ 200: RunObject; }; export type SubmitToolOuputsToRunResponse = SubmitToolOuputsToRunResponses[keyof SubmitToolOuputsToRunResponses]; export type CreateUploadData = { body: CreateUploadRequest; path?: never; query?: never; url: '/uploads'; }; export type CreateUploadResponses = { /** * OK */ 200: Upload; }; export type CreateUploadResponse = CreateUploadResponses[keyof CreateUploadResponses]; export type CancelUploadData = { body?: never; path: { /** * The ID of the Upload. * */ upload_id: string; }; query?: never; url: '/uploads/{upload_id}/cancel'; }; export type CancelUploadResponses = { /** * OK */ 200: Upload; }; export type CancelUploadResponse = CancelUploadResponses[keyof CancelUploadResponses]; export type CompleteUploadData = { body: CompleteUploadRequest; path: { /** * The ID of the Upload. * */ upload_id: string; }; query?: never; url: '/uploads/{upload_id}/complete'; }; export type CompleteUploadResponses = { /** * OK */ 200: Upload; }; export type CompleteUploadResponse = CompleteUploadResponses[keyof CompleteUploadResponses]; export type AddUploadPartData = { body: AddUploadPartRequest; path: { /** * The ID of the Upload. * */ upload_id: string; }; query?: never; url: '/uploads/{upload_id}/parts'; }; export type AddUploadPartResponses = { /** * OK */ 200: UploadPart; }; export type AddUploadPartResponse = AddUploadPartResponses[keyof AddUploadPartResponses]; export type ListVectorStoresData = { body?: never; path?: never; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; }; url: '/vector_stores'; }; export type ListVectorStoresResponses = { /** * OK */ 200: ListVectorStoresResponse; }; export type ListVectorStoresResponse2 = ListVectorStoresResponses[keyof ListVectorStoresResponses]; export type CreateVectorStoreData = { body: CreateVectorStoreRequest; path?: never; query?: never; url: '/vector_stores'; }; export type CreateVectorStoreResponses = { /** * OK */ 200: VectorStoreObject; }; export type CreateVectorStoreResponse = CreateVectorStoreResponses[keyof CreateVectorStoreResponses]; export type DeleteVectorStoreData = { body?: never; path: { /** * The ID of the vector store to delete. */ vector_store_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}'; }; export type DeleteVectorStoreResponses = { /** * OK */ 200: DeleteVectorStoreResponse; }; export type DeleteVectorStoreResponse2 = DeleteVectorStoreResponses[keyof DeleteVectorStoreResponses]; export type GetVectorStoreData = { body?: never; path: { /** * The ID of the vector store to retrieve. */ vector_store_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}'; }; export type GetVectorStoreResponses = { /** * OK */ 200: VectorStoreObject; }; export type GetVectorStoreResponse = GetVectorStoreResponses[keyof GetVectorStoreResponses]; export type ModifyVectorStoreData = { body: UpdateVectorStoreRequest; path: { /** * The ID of the vector store to modify. */ vector_store_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}'; }; export type ModifyVectorStoreResponses = { /** * OK */ 200: VectorStoreObject; }; export type ModifyVectorStoreResponse = ModifyVectorStoreResponses[keyof ModifyVectorStoreResponses]; export type CreateVectorStoreFileBatchData = { body: CreateVectorStoreFileBatchRequest; path: { /** * The ID of the vector store for which to create a File Batch. * */ vector_store_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/file_batches'; }; export type CreateVectorStoreFileBatchResponses = { /** * OK */ 200: VectorStoreFileBatchObject; }; export type CreateVectorStoreFileBatchResponse = CreateVectorStoreFileBatchResponses[keyof CreateVectorStoreFileBatchResponses]; export type GetVectorStoreFileBatchData = { body?: never; path: { /** * The ID of the vector store that the file batch belongs to. */ vector_store_id: string; /** * The ID of the file batch being retrieved. */ batch_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/file_batches/{batch_id}'; }; export type GetVectorStoreFileBatchResponses = { /** * OK */ 200: VectorStoreFileBatchObject; }; export type GetVectorStoreFileBatchResponse = GetVectorStoreFileBatchResponses[keyof GetVectorStoreFileBatchResponses]; export type CancelVectorStoreFileBatchData = { body?: never; path: { /** * The ID of the vector store that the file batch belongs to. */ vector_store_id: string; /** * The ID of the file batch to cancel. */ batch_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel'; }; export type CancelVectorStoreFileBatchResponses = { /** * OK */ 200: VectorStoreFileBatchObject; }; export type CancelVectorStoreFileBatchResponse = CancelVectorStoreFileBatchResponses[keyof CancelVectorStoreFileBatchResponses]; export type ListFilesInVectorStoreBatchData = { body?: never; path: { /** * The ID of the vector store that the files belong to. */ vector_store_id: string; /** * The ID of the file batch that the files belong to. */ batch_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; /** * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. */ filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; }; url: '/vector_stores/{vector_store_id}/file_batches/{batch_id}/files'; }; export type ListFilesInVectorStoreBatchResponses = { /** * OK */ 200: ListVectorStoreFilesResponse; }; export type ListFilesInVectorStoreBatchResponse = ListFilesInVectorStoreBatchResponses[keyof ListFilesInVectorStoreBatchResponses]; export type ListVectorStoreFilesData = { body?: never; path: { /** * The ID of the vector store that the files belong to. */ vector_store_id: string; }; query?: { /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. * */ limit?: number; /** * Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. * */ order?: 'asc' | 'desc'; /** * A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * */ after?: string; /** * A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. * */ before?: string; /** * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. */ filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; }; url: '/vector_stores/{vector_store_id}/files'; }; export type ListVectorStoreFilesResponses = { /** * OK */ 200: ListVectorStoreFilesResponse; }; export type ListVectorStoreFilesResponse2 = ListVectorStoreFilesResponses[keyof ListVectorStoreFilesResponses]; export type CreateVectorStoreFileData = { body: CreateVectorStoreFileRequest; path: { /** * The ID of the vector store for which to create a File. * */ vector_store_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/files'; }; export type CreateVectorStoreFileResponses = { /** * OK */ 200: VectorStoreFileObject; }; export type CreateVectorStoreFileResponse = CreateVectorStoreFileResponses[keyof CreateVectorStoreFileResponses]; export type DeleteVectorStoreFileData = { body?: never; path: { /** * The ID of the vector store that the file belongs to. */ vector_store_id: string; /** * The ID of the file to delete. */ file_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/files/{file_id}'; }; export type DeleteVectorStoreFileResponses = { /** * OK */ 200: DeleteVectorStoreFileResponse; }; export type DeleteVectorStoreFileResponse2 = DeleteVectorStoreFileResponses[keyof DeleteVectorStoreFileResponses]; export type GetVectorStoreFileData = { body?: never; path: { /** * The ID of the vector store that the file belongs to. */ vector_store_id: string; /** * The ID of the file being retrieved. */ file_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/files/{file_id}'; }; export type GetVectorStoreFileResponses = { /** * OK */ 200: VectorStoreFileObject; }; export type GetVectorStoreFileResponse = GetVectorStoreFileResponses[keyof GetVectorStoreFileResponses]; export type UpdateVectorStoreFileAttributesData = { body: UpdateVectorStoreFileAttributesRequest; path: { /** * The ID of the vector store the file belongs to. */ vector_store_id: string; /** * The ID of the file to update attributes. */ file_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/files/{file_id}'; }; export type UpdateVectorStoreFileAttributesResponses = { /** * OK */ 200: VectorStoreFileObject; }; export type UpdateVectorStoreFileAttributesResponse = UpdateVectorStoreFileAttributesResponses[keyof UpdateVectorStoreFileAttributesResponses]; export type RetrieveVectorStoreFileContentData = { body?: never; path: { /** * The ID of the vector store. */ vector_store_id: string; /** * The ID of the file within the vector store. */ file_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/files/{file_id}/content'; }; export type RetrieveVectorStoreFileContentResponses = { /** * OK */ 200: VectorStoreFileContentResponse; }; export type RetrieveVectorStoreFileContentResponse = RetrieveVectorStoreFileContentResponses[keyof RetrieveVectorStoreFileContentResponses]; export type SearchVectorStoreData = { body: VectorStoreSearchRequest; path: { /** * The ID of the vector store to search. */ vector_store_id: string; }; query?: never; url: '/vector_stores/{vector_store_id}/search'; }; export type SearchVectorStoreResponses = { /** * OK */ 200: VectorStoreSearchResultsPage; }; export type SearchVectorStoreResponse = SearchVectorStoreResponses[keyof SearchVectorStoreResponses]; /** * The event payload sent by the API. */ export type PostBatchCancelledWebhookPayload = WebhookBatchCancelled; export type PostBatchCancelledWebhookRequest = { body: PostBatchCancelledWebhookPayload; key: 'batch_cancelled'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostBatchCompletedWebhookPayload = WebhookBatchCompleted; export type PostBatchCompletedWebhookRequest = { body: PostBatchCompletedWebhookPayload; key: 'batch_completed'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostBatchExpiredWebhookPayload = WebhookBatchExpired; export type PostBatchExpiredWebhookRequest = { body: PostBatchExpiredWebhookPayload; key: 'batch_expired'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostBatchFailedWebhookPayload = WebhookBatchFailed; export type PostBatchFailedWebhookRequest = { body: PostBatchFailedWebhookPayload; key: 'batch_failed'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostEvalRunCanceledWebhookPayload = WebhookEvalRunCanceled; export type PostEvalRunCanceledWebhookRequest = { body: PostEvalRunCanceledWebhookPayload; key: 'eval_run_canceled'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostEvalRunFailedWebhookPayload = WebhookEvalRunFailed; export type PostEvalRunFailedWebhookRequest = { body: PostEvalRunFailedWebhookPayload; key: 'eval_run_failed'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostEvalRunSucceededWebhookPayload = WebhookEvalRunSucceeded; export type PostEvalRunSucceededWebhookRequest = { body: PostEvalRunSucceededWebhookPayload; key: 'eval_run_succeeded'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostFineTuningJobCancelledWebhookPayload = WebhookFineTuningJobCancelled; export type PostFineTuningJobCancelledWebhookRequest = { body: PostFineTuningJobCancelledWebhookPayload; key: 'fine_tuning_job_cancelled'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostFineTuningJobFailedWebhookPayload = WebhookFineTuningJobFailed; export type PostFineTuningJobFailedWebhookRequest = { body: PostFineTuningJobFailedWebhookPayload; key: 'fine_tuning_job_failed'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostFineTuningJobSucceededWebhookPayload = WebhookFineTuningJobSucceeded; export type PostFineTuningJobSucceededWebhookRequest = { body: PostFineTuningJobSucceededWebhookPayload; key: 'fine_tuning_job_succeeded'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostResponseCancelledWebhookPayload = WebhookResponseCancelled; export type PostResponseCancelledWebhookRequest = { body: PostResponseCancelledWebhookPayload; key: 'response_cancelled'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostResponseCompletedWebhookPayload = WebhookResponseCompleted; export type PostResponseCompletedWebhookRequest = { body: PostResponseCompletedWebhookPayload; key: 'response_completed'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostResponseFailedWebhookPayload = WebhookResponseFailed; export type PostResponseFailedWebhookRequest = { body: PostResponseFailedWebhookPayload; key: 'response_failed'; path?: never; query?: never; }; /** * The event payload sent by the API. */ export type PostResponseIncompleteWebhookPayload = WebhookResponseIncomplete; export type PostResponseIncompleteWebhookRequest = { body: PostResponseIncompleteWebhookPayload; key: 'response_incomplete'; path?: never; query?: never; }; ================================================ FILE: examples/openapi-ts-openai/src/main.tsx ================================================ import '@radix-ui/themes/styles.css'; import { Theme } from '@radix-ui/themes'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App.tsx'; ReactDOM.createRoot(document.getElementById('root')!).render( , ); ================================================ FILE: examples/openapi-ts-openai/src/vite-env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-openai/tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{html,js,ts,jsx,tsx}'], theme: { extend: {}, }, }; ================================================ FILE: examples/openapi-ts-openai/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": false, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: examples/openapi-ts-openai/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: examples/openapi-ts-openai/vite.config.ts ================================================ import react from '@vitejs/plugin-react'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [react()], }; ================================================ FILE: examples/openapi-ts-pinia-colada/.eslintrc.cjs ================================================ /* eslint-env node */ require('@rushstack/eslint-patch/modern-module-resolution'); module.exports = { extends: ['plugin:vue/vue3-essential', 'eslint:recommended', '@vue/eslint-config-typescript'], files: ['**/*.{vue,js,jsx,cjs,mjs,ts,tsx,cts,mts}'], parserOptions: { ecmaVersion: 'latest', }, }; ================================================ FILE: examples/openapi-ts-pinia-colada/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules .DS_Store dist dist-ssr coverage *.local /cypress/videos/ /cypress/screenshots/ # Editor directories and files .vscode/* !.vscode/extensions.json .idea *.suo *.ntvs* *.njsproj *.sln *.sw? *.tsbuildinfo ================================================ FILE: examples/openapi-ts-pinia-colada/.vscode/extensions.json ================================================ { "recommendations": ["Vue.volar", "dbaeumer.vscode-eslint", "oxc.oxc-vscode"] } ================================================ FILE: examples/openapi-ts-pinia-colada/README.md ================================================ # @hey-api/openapi-ts with Pinia Colada Example This example demonstrates how to use @hey-api/openapi-ts with Pinia Colada for Vue 3 applications. ## Recommended IDE Setup [VSCode](https://code.visualstudio.com) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur). ## Type Support for `.vue` Imports in TS TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types. ## Customize configuration See [Vite Configuration Reference](https://vitejs.dev/config). ## Project Setup ```sh pnpm install ``` ### Compile and Hot-Reload for Development ```sh pnpm dev ``` ### Type-Check, Compile and Minify for Production ```sh pnpm build ``` ### Run Unit Tests with [Vitest](https://vitest.dev) ```sh pnpm test:unit ``` ### Lint with [ESLint](https://eslint.org) ```sh pnpm lint ``` ================================================ FILE: examples/openapi-ts-pinia-colada/env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-pinia-colada/index.html ================================================ Hey API + Pinia Colada Demo
    ================================================ FILE: examples/openapi-ts-pinia-colada/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-fetch', '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, { includeInEntry: true, name: '@pinia/colada', queryKeys: false, }, ], }); ================================================ FILE: examples/openapi-ts-pinia-colada/package.json ================================================ { "name": "@example/openapi-ts-pinia-colada", "version": "0.0.0", "private": true, "type": "module", "scripts": { "build-only": "vite build", "build": "run-p typecheck \"build-only {@}\" --", "dev": "vite", "format": "oxfmt src/", "lint": "eslint . --fix", "openapi-ts": "openapi-ts", "preview": "vite preview", "test:unit": "vitest", "typecheck": "vue-tsc --build --force" }, "dependencies": { "@pinia/colada": "0.17.5", "pinia": "3.0.3", "vue": "3.5.13", "vue-router": "4.5.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@pinia/colada-devtools": "0.1.6", "@rushstack/eslint-patch": "1.10.5", "@tsconfig/node24": "24.0.4", "@types/jsdom": "27.0.0", "@types/node": "24.10.10", "@vitejs/plugin-vue": "6.0.4", "@vitejs/plugin-vue-jsx": "5.1.4", "@vue/eslint-config-typescript": "14.6.0", "@vue/test-utils": "2.4.6", "@vue/tsconfig": "0.8.1", "autoprefixer": "10.4.20", "eslint": "9.17.0", "eslint-plugin-vue": "9.32.0", "jsdom": "28.0.0", "npm-run-all2": "6.2.0", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1", "vite-plugin-vue-devtools": "8.0.2", "vitest": "4.0.18", "vue-tsc": "3.2.4" } } ================================================ FILE: examples/openapi-ts-pinia-colada/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/App.vue ================================================ ================================================ FILE: examples/openapi-ts-pinia-colada/src/assets/main.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; body { @apply bg-[#111113]; } ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/@pinia/colada.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'; import { serializeQueryKeyValue } from '../client'; import { client } from '../client.gen'; import { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from '../sdk.gen'; import type { AddPetData, AddPetResponse, CreateUserData, CreateUserResponse, CreateUsersWithListInputData, CreateUsersWithListInputResponse, DeleteOrderData, DeletePetData, DeleteUserData, FindPetsByStatusData, FindPetsByStatusResponse, FindPetsByTagsData, FindPetsByTagsResponse, GetInventoryData, GetInventoryResponse, GetOrderByIdData, GetOrderByIdResponse, GetPetByIdData, GetPetByIdResponse, GetUserByNameData, GetUserByNameResponse, LoginUserData, LoginUserResponse, LogoutUserData, PlaceOrderData, PlaceOrderResponse, UpdatePetData, UpdatePetResponse, UpdatePetWithFormData, UpdatePetWithFormResponse, UpdateUserData, UploadFileData, UploadFileResponse, } from '../types.gen'; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPetMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await addPet({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePetMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await updatePet({ ...options, ...vars, throwOnError: true, }); return data; }, }); export type QueryKey = [ Pick & { _id: string; baseUrl?: _JSONValue; body?: _JSONValue; query?: _JSONValue; tags?: _JSONValue; }, ]; const createQueryKey = ( id: string, options?: TOptions, tags?: ReadonlyArray, ): [QueryKey[0]] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl, } as QueryKey[0]; if (tags) { params.tags = tags as unknown as _JSONValue; } if (options?.body !== undefined) { const normalizedBody = serializeQueryKeyValue(options.body); if (normalizedBody !== undefined) { params.body = normalizedBody; } } if (options?.path) { params.path = options.path; } if (options?.query !== undefined) { const normalizedQuery = serializeQueryKeyValue(options.query); if (normalizedQuery !== undefined) { params.query = normalizedQuery; } } return [params]; }; /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatusQuery = defineQueryOptions< Options, FindPetsByStatusResponse, Error >((options: Options) => ({ key: createQueryKey('findPetsByStatus', options), query: async (context) => { const { data } = await findPetsByStatus({ ...options, ...context, throwOnError: true, }); return data; }, })); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTagsQuery = defineQueryOptions< Options, FindPetsByTagsResponse, Error >((options: Options) => ({ key: createQueryKey('findPetsByTags', options), query: async (context) => { const { data } = await findPetsByTags({ ...options, ...context, throwOnError: true, }); return data; }, })); /** * Deletes a pet. * * Delete a pet. */ export const deletePetMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deletePet({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetByIdQuery = defineQueryOptions< Options, GetPetByIdResponse, Error >((options: Options) => ({ key: createQueryKey('getPetById', options), query: async (context) => { const { data } = await getPetById({ ...options, ...context, throwOnError: true, }); return data; }, })); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithFormMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await updatePetWithForm({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFileMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await uploadFile({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventoryQuery = defineQueryOptions< Options, GetInventoryResponse, Error >((options?: Options) => ({ key: createQueryKey('getInventory', options), query: async (context) => { const { data } = await getInventory({ ...options, ...context, throwOnError: true, }); return data; }, })); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrderMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await placeOrder({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrderMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deleteOrder({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderByIdQuery = defineQueryOptions< Options, GetOrderByIdResponse, Error >((options: Options) => ({ key: createQueryKey('getOrderById', options), query: async (context) => { const { data } = await getOrderById({ ...options, ...context, throwOnError: true, }); return data; }, })); /** * Create user. * * This can only be done by the logged in user. */ export const createUserMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await createUser({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInputMutation = ( options?: Partial>, ): UseMutationOptions< CreateUsersWithListInputResponse, Options, Error > => ({ mutation: async (vars) => { const { data } = await createUsersWithListInput({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUserQuery = defineQueryOptions, LoginUserResponse, Error>( (options?: Options) => ({ key: createQueryKey('loginUser', options), query: async (context) => { const { data } = await loginUser({ ...options, ...context, throwOnError: true, }); return data; }, }), ); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUserQuery = defineQueryOptions, unknown, Error>( (options?: Options) => ({ key: createQueryKey('logoutUser', options), query: async (context) => { const { data } = await logoutUser({ ...options, ...context, throwOnError: true, }); return data; }, }), ); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUserMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deleteUser({ ...options, ...vars, throwOnError: true, }); return data; }, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByNameQuery = defineQueryOptions< Options, GetUserByNameResponse, Error >((options: Options) => ({ key: createQueryKey('getUserByName', options), query: async (context) => { const { data } = await getUserByName({ ...options, ...context, throwOnError: true, }); return data; }, })); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUserMutation = ( options?: Partial>, ): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await updateUser({ ...options, ...vars, throwOnError: true, }); return data; }, }); ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPetMutation, createUserMutation, createUsersWithListInputMutation, deleteOrderMutation, deletePetMutation, deleteUserMutation, findPetsByStatusQuery, findPetsByTagsQuery, getInventoryQuery, getOrderByIdQuery, getPetByIdQuery, getUserByNameQuery, loginUserQuery, logoutUserQuery, placeOrderMutation, type QueryKey, updatePetMutation, updatePetWithFormMutation, updateUserMutation, uploadFileMutation, } from './@pinia/colada.gen'; export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-pinia-colada/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-pinia-colada/src/main.ts ================================================ import './assets/main.css'; import { PiniaColada } from '@pinia/colada'; import { createPinia } from 'pinia'; import { createApp } from 'vue'; import App from './App.vue'; import { client } from './client/client.gen'; import router from './router'; // configure internal service client client.setConfig({ // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); const app = createApp(App); const pinia = createPinia(); app.use(pinia); app.use(PiniaColada); app.use(router); app.mount('#app'); ================================================ FILE: examples/openapi-ts-pinia-colada/src/router/index.ts ================================================ import { createRouter, createWebHistory } from 'vue-router'; import PiniaColadaExample from '@/views/PiniaColadaExample.vue'; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { component: PiniaColadaExample, name: 'home', path: '/', }, ], }); export default router; ================================================ FILE: examples/openapi-ts-pinia-colada/src/views/PiniaColadaExample.vue ================================================ ================================================ FILE: examples/openapi-ts-pinia-colada/tailwind.config.ts ================================================ import type { Config } from 'tailwindcss'; export default { content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], theme: { extend: {}, }, } satisfies Config; ================================================ FILE: examples/openapi-ts-pinia-colada/tsconfig.app.json ================================================ { "extends": "@vue/tsconfig/tsconfig.dom.json", "include": ["./env.d.ts", "./src/**/*", "./src/**/*.vue"], "exclude": ["./src/**/__tests__/*"], "compilerOptions": { "composite": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } } ================================================ FILE: examples/openapi-ts-pinia-colada/tsconfig.json ================================================ { "files": [], "references": [ { "path": "./tsconfig.node.json" }, { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.vitest.json" } ] } ================================================ FILE: examples/openapi-ts-pinia-colada/tsconfig.node.json ================================================ { "extends": "@tsconfig/node24/tsconfig.json", "include": [ "vite.config.*", "vitest.config.*", "cypress.config.*", "nightwatch.conf.*", "playwright.config.*" ], "compilerOptions": { "composite": true, "noEmit": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", "module": "ESNext", "moduleResolution": "Bundler", "types": ["node"] } } ================================================ FILE: examples/openapi-ts-pinia-colada/tsconfig.vitest.json ================================================ { "extends": "./tsconfig.app.json", "exclude": [], "compilerOptions": { "composite": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo", "lib": [], "types": ["node", "jsdom"] } } ================================================ FILE: examples/openapi-ts-pinia-colada/vite.config.ts ================================================ import { fileURLToPath, URL } from 'node:url'; import vue from '@vitejs/plugin-vue'; import vueJsx from '@vitejs/plugin-vue-jsx'; import vueDevTools from 'vite-plugin-vue-devtools'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [vue(), vueJsx(), vueDevTools()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, }; ================================================ FILE: examples/openapi-ts-pinia-colada/vitest.config.ts ================================================ import { fileURLToPath } from 'node:url'; import { configDefaults, defineProject, mergeConfig } from 'vitest/config'; import viteConfig from './vite.config'; export default mergeConfig( viteConfig, defineProject({ test: { environment: 'jsdom', exclude: [...configDefaults.exclude, 'e2e/**'], root: fileURLToPath(new URL('./', import.meta.url)), }, }), ); ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/.editorconfig ================================================ # Editor configuration, see https://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.ts] quote_type = single ij_typescript_use_double_quotes = false [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/.eslintignore ================================================ .angular ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/.gitignore ================================================ # See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. # Compiled output /dist /tmp /out-tsc /bazel-out # Node /node_modules npm-debug.log yarn-error.log # IDEs and editors .idea/ .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # Visual Studio Code .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json .history/* # Miscellaneous /.angular/cache .sass-cache/ /connect.lock /coverage /libpeerconnection.log testem.log /typings # System files .DS_Store Thumbs.db ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/.vscode/extensions.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 "recommendations": ["angular.ng-template"] } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/.vscode/launch.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "ng serve", "type": "chrome", "request": "launch", "preLaunchTask": "npm: start", "url": "http://localhost:4200/" }, { "name": "ng test", "type": "chrome", "request": "launch", "preLaunchTask": "npm: test", "url": "http://localhost:9876/debug.html" } ] } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/.vscode/tasks.json ================================================ { // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "type": "npm", "script": "start", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } }, { "type": "npm", "script": "test", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } } ] } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/CHANGELOG.md ================================================ # @example/openapi-ts-tanstack-angular-query-experimental ## 0.0.28 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-fetch@0.13.1 ## 0.0.27 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-fetch@0.13.0 ## 0.0.26 ### Patch Changes - Updated dependencies [[`4d8c030`](https://github.com/hey-api/openapi-ts/commit/4d8c03038979c9a75315cc158789b3c198c62f90)]: - @hey-api/client-fetch@0.12.0 ## 0.0.25 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-fetch@0.11.0 ## 0.0.24 ### Patch Changes - Updated dependencies [[`1f99066`](https://github.com/hey-api/openapi-ts/commit/1f99066efbb2d0e6b9e3710c701293c2cc09d65e)]: - @hey-api/client-fetch@0.10.2 ## 0.0.23 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-fetch@0.10.1 ## 0.0.22 ### Patch Changes - Updated dependencies [[`fed9699`](https://github.com/hey-api/openapi-ts/commit/fed969985275621c7c2b65ffc760c7c66fafaf72)]: - @hey-api/client-fetch@0.10.0 ## 0.0.21 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-fetch@0.9.0 ## 0.0.20 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-fetch@0.8.4 ## 0.0.19 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-fetch@0.8.3 ## 0.0.18 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-fetch@0.8.2 ## 0.0.17 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-fetch@0.8.1 ## 0.0.16 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-fetch@0.8.0 ## 0.0.15 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31)]: - @hey-api/client-fetch@0.7.3 ## 0.0.14 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-fetch@0.7.2 ## 0.0.13 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-fetch@0.7.1 ## 0.0.12 ### Patch Changes - Updated dependencies [[`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107)]: - @hey-api/client-fetch@0.7.0 ## 0.0.11 ### Patch Changes - Updated dependencies [[`e2e1410`](https://github.com/hey-api/openapi-ts/commit/e2e1410b22c0c84c40d1b1803e9650d546350cb7)]: - @hey-api/client-fetch@0.6.0 ## 0.0.10 ### Patch Changes - Updated dependencies [[`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263), [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26)]: - @hey-api/client-fetch@0.5.7 ## 0.0.9 ### Patch Changes - Updated dependencies [[`ba56424`](https://github.com/hey-api/openapi-ts/commit/ba5642486cdd5461c2372c34b63019c02bc6874e)]: - @hey-api/client-fetch@0.5.6 ## 0.0.8 ### Patch Changes - Updated dependencies [[`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a)]: - @hey-api/client-fetch@0.5.5 ## 0.0.7 ### Patch Changes - Updated dependencies [[`cbf4e84`](https://github.com/hey-api/openapi-ts/commit/cbf4e84db7f3a47f19d8c3eaa87c71b27912c1a2)]: - @hey-api/client-fetch@0.5.4 ## 0.0.6 ### Patch Changes - Updated dependencies [[`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0)]: - @hey-api/client-fetch@0.5.3 ## 0.0.5 ### Patch Changes - Updated dependencies [[`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a)]: - @hey-api/client-fetch@0.5.2 ## 0.0.4 ### Patch Changes - Updated dependencies [[`fa8b0f1`](https://github.com/hey-api/openapi-ts/commit/fa8b0f11ed99c63f694a494944ccc2fbfa9706cc)]: - @hey-api/client-fetch@0.5.1 ## 0.0.3 ### Patch Changes - Updated dependencies [[`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df), [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df)]: - @hey-api/client-fetch@0.5.0 ## 0.0.2 ### Patch Changes - Updated dependencies [[`4c853d0`](https://github.com/hey-api/openapi-ts/commit/4c853d090b79245854d13831f64731db4a92978b)]: - @hey-api/client-fetch@0.4.4 ## 0.0.1 ### Patch Changes - Updated dependencies [[`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482)]: - @hey-api/client-fetch@0.4.3 ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/README.md ================================================ # OpenapiTsTanstackAngularQueryExperimental This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 18.2.7. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities. ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page. ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/angular.json ================================================ { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "openapi-ts-tanstack-angular-query-experimental": { "projectType": "application", "schematics": {}, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/openapi-ts-tanstack-angular-query-experimental", "index": "src/index.html", "browser": "src/main.ts", "polyfills": ["zone.js"], "tsConfig": "tsconfig.app.json", "assets": [ { "glob": "**/*", "input": "public" } ], "styles": ["@angular/material/prebuilt-themes/azure-blue.css", "src/styles.css"], "scripts": [] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" }, { "type": "anyComponentStyle", "maximumWarning": "2kB", "maximumError": "4kB" } ], "outputHashing": "all" }, "development": { "optimization": false, "extractLicenses": false, "sourceMap": true } }, "defaultConfiguration": "production" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "configurations": { "production": { "buildTarget": "openapi-ts-tanstack-angular-query-experimental:build:production" }, "development": { "buildTarget": "openapi-ts-tanstack-angular-query-experimental:build:development" } }, "defaultConfiguration": "development" }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n" } } } }, "cli": { "analytics": false } } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ { name: '@hey-api/client-angular', // throwOnError: true, }, '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, '@tanstack/angular-query-experimental', ], }); ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/package.json ================================================ { "name": "@example/openapi-ts-tanstack-angular-query-experimental", "version": "0.0.28", "private": true, "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "watch": "ng build --watch --configuration development", "openapi-ts": "openapi-ts", "typecheck": "tsc --project tsconfig.app.json --noEmit" }, "dependencies": { "@angular/animations": "21.1.2", "@angular/cdk": "21.1.2", "@angular/common": "21.1.2", "@angular/compiler": "21.1.2", "@angular/core": "21.1.2", "@angular/forms": "21.1.2", "@angular/material": "21.1.2", "@angular/platform-browser": "21.1.2", "@angular/platform-browser-dynamic": "21.1.2", "@angular/router": "21.1.2", "@tanstack/angular-query-experimental": "5.73.3", "rxjs": "7.8.2", "tslib": "2.8.1", "zone.js": "0.16.0" }, "devDependencies": { "@angular-devkit/build-angular": "21.1.2", "@angular/cli": "21.1.2", "@angular/compiler-cli": "21.1.2", "@hey-api/openapi-ts": "workspace:*", "@types/jasmine": "5.1.9", "jasmine-core": "5.6.0", "karma": "6.4.4", "karma-chrome-launcher": "3.2.0", "karma-coverage": "2.2.1", "karma-jasmine": "5.1.0", "karma-jasmine-html-reporter": "2.1.0", "typescript": "5.9.3" } } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/app.component.css ================================================ :host { display: contents; } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/app.component.html ================================================ ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/app.component.ts ================================================ import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ imports: [RouterOutlet], selector: 'app-root', standalone: true, styleUrl: './app.component.css', templateUrl: './app.component.html', }) export class AppComponent { title = 'openapi-ts-tanstack-angular-query-experimental'; } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/app.config.ts ================================================ import { provideHttpClient, withFetch } from '@angular/common/http'; import type { ApplicationConfig } from '@angular/core'; import { provideZoneChangeDetection } from '@angular/core'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; import { provideRouter } from '@angular/router'; import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'; import { client } from '../client/client.gen'; import { provideHeyApiClient } from '../client/client/client.gen'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient(withFetch()), provideHeyApiClient(client), provideTanStackQuery( new QueryClient({ defaultOptions: { queries: { retry: 0, }, }, }), ), provideAnimationsAsync(), ], }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/app.routes.ts ================================================ import type { Routes } from '@angular/router'; import { PetStoreComponent } from './pet-store/pet-store.component'; export const routes: Routes = [ { component: PetStoreComponent, path: '', }, ]; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/pet-store/pet-store.component.css ================================================ :host { display: grid; gap: 20px; max-width: 400px; margin: auto; } .pet-store-header { display: flex; gap: 1rem; align-items: flex-start; flex-wrap: wrap; } mat-card { margin-bottom: 20px; } .pet-card { width: 100%; margin-top: 1rem; } .pet-card-title { font-size: 1.4rem; font-weight: 600; } .pet-card-subtitle { font-size: 1rem; color: #666; } .pet-card-image { object-fit: cover; min-height: 180px; background: #fafafa; } .pet-status { margin-top: 0.5rem; color: #888; } .pet-form-card { margin-top: 2rem; max-width: 400px; } .pet-form-title { font-size: 1.2rem; font-weight: 500; } .pet-form-content { display: flex; flex-direction: column; gap: 1rem; } .actions { display: flex; gap: 0.5rem; } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/pet-store/pet-store.component.html ================================================ @let pet = petState.data();
    @if (petState.isLoading()) { } @if (pet) { {{ pet.name }} {{ pet.category?.name }}

    Status: {{ pet.status }}

    }
    @if (addPet.data()) {
        {{addPet.data()|json}}
      
    } @if (updatePet.data()) {
        {{updatePet.data()|json}}
      
    }
    Pet Form Name
    ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/app/pet-store/pet-store.component.ts ================================================ import { JsonPipe } from '@angular/common'; import { Component, effect, inject, signal, viewChild } from '@angular/core'; import { FormsModule, NgForm } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { MatSnackBar } from '@angular/material/snack-bar'; import { injectMutation, injectQuery } from '@tanstack/angular-query-experimental'; import type { Pet } from '../../client'; import { addPetMutation, getPetByIdOptions, updatePetMutation, } from '../../client/@tanstack/angular-query-experimental.gen'; @Component({ imports: [ JsonPipe, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatProgressSpinner, ], selector: 'app-pet-store', standalone: true, styleUrls: ['./pet-store.component.css'], templateUrl: './pet-store.component.html', }) export class PetStoreComponent { #snackbar = inject(MatSnackBar); form = viewChild.required(NgForm); petId = signal(undefined); petState = injectQuery(() => ({ enabled: (this.petId() ?? 0) > 0, ...getPetByIdOptions({ path: { petId: this.petId()! }, }), })); addPet = injectMutation(() => ({ ...addPetMutation(), onError: (err) => { this.#snackbar.open(err.message); }, onSuccess: () => { this.#snackbar.open('Pet added successfully!'); }, })); updatePet = injectMutation(() => ({ ...updatePetMutation(), onError: (err) => { this.#snackbar.open(err.message); }, onSuccess: () => { this.#snackbar.open('Pet updated successfully!'); }, })); nextPetState: Partial = {}; constructor() { effect(() => { const err = this.petState.error(); if (err) { this.#snackbar.open(String(err)); } }); effect(() => { this.nextPetState = { ...this.petState.data() }; }); } getRandomPet() { // random id 1-10 this.petId.set(Math.floor(Math.random() * (10 - 1 + 1) + 1)); } handleUpdatePet = async (event: Event) => { event.preventDefault(); await this.updatePet.mutateAsync({ body: this.nextPetState as Pet, }); }; onSubmit = async (form: NgForm) => { if (!form.valid) { return; } await this.addPet.mutateAsync({ body: this.nextPetState as Pet, }); }; } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions, } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from '../sdk.gen'; import type { AddPetData, AddPetResponse, CreateUserData, CreateUserResponse, CreateUsersWithListInputData, CreateUsersWithListInputResponse, DeleteOrderData, DeletePetData, DeleteUserData, FindPetsByStatusData, FindPetsByStatusResponse, FindPetsByTagsData, FindPetsByTagsResponse, GetInventoryData, GetInventoryResponse, GetOrderByIdData, GetOrderByIdResponse, GetPetByIdData, GetPetByIdResponse, GetUserByNameData, GetUserByNameResponse, LoginUserData, LoginUserResponse, LogoutUserData, PlaceOrderData, PlaceOrderResponse, UpdatePetData, UpdatePetResponse, UpdatePetWithFormData, UpdatePetWithFormResponse, UpdateUserData, UploadFileData, UploadFileResponse, } from '../types.gen'; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPetMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await addPet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePetMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< UpdatePetResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await updatePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; }, ]; const createQueryKey = ( id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray, ): [QueryKey[0]] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl, } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const findPetsByStatusQueryKey = (options: Options) => createQueryKey('findPetsByStatus', options); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatusOptions = (options: Options) => queryOptions< FindPetsByStatusResponse, DefaultError, FindPetsByStatusResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await findPetsByStatus({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByStatusQueryKey(options), }); export const findPetsByTagsQueryKey = (options: Options) => createQueryKey('findPetsByTags', options); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTagsOptions = (options: Options) => queryOptions< FindPetsByTagsResponse, DefaultError, FindPetsByTagsResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await findPetsByTags({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByTagsQueryKey(options), }); /** * Deletes a pet. * * Delete a pet. */ export const deletePetMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deletePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getPetByIdQueryKey = (options: Options) => createQueryKey('getPetById', options); /** * Find pet by ID. * * Returns a single pet. */ export const getPetByIdOptions = (options: Options) => queryOptions< GetPetByIdResponse, DefaultError, GetPetByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getPetById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getPetByIdQueryKey(options), }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithFormMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< UpdatePetWithFormResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await updatePetWithForm({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Uploads an image. * * Upload image of the pet. */ export const uploadFileMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< UploadFileResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getInventoryQueryKey = (options?: Options) => createQueryKey('getInventory', options); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventoryOptions = (options?: Options) => queryOptions< GetInventoryResponse, DefaultError, GetInventoryResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getInventory({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getInventoryQueryKey(options), }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrderMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< PlaceOrderResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await placeOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrderMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getOrderByIdQueryKey = (options: Options) => createQueryKey('getOrderById', options); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderByIdOptions = (options: Options) => queryOptions< GetOrderByIdResponse, DefaultError, GetOrderByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getOrderById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getOrderByIdQueryKey(options), }); /** * Create user. * * This can only be done by the logged in user. */ export const createUserMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< CreateUserResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await createUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInputMutation = ( options?: Partial>, ): MutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > => { const mutationOptions: MutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await createUsersWithListInput({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const loginUserQueryKey = (options?: Options) => createQueryKey('loginUser', options); /** * Logs user into the system. * * Log into the system. */ export const loginUserOptions = (options?: Options) => queryOptions< LoginUserResponse, DefaultError, LoginUserResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await loginUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: loginUserQueryKey(options), }); export const logoutUserQueryKey = (options?: Options) => createQueryKey('logoutUser', options); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUserOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await logoutUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: logoutUserQueryKey(options), }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUserMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getUserByNameQueryKey = (options: Options) => createQueryKey('getUserByName', options); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByNameOptions = (options: Options) => queryOptions< GetUserByNameResponse, DefaultError, GetUserByNameResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getUserByName({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getUserByNameQueryKey(options), }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUserMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await updateUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/index.html ================================================ OpenapiTsTanstackAngularQueryExperimental ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/main.ts ================================================ import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/src/styles.css ================================================ @import '@angular/material/prebuilt-themes/azure-blue.css'; /* You can add global styles to this file, and also import other style files */ html, body { height: 100%; } body { margin: 0; font-family: Roboto, 'Helvetica Neue', sans-serif; display: grid; place-content: center; } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/tsconfig.app.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/app", "types": [] }, "files": ["src/main.ts"], "include": ["src/**/*.d.ts"] } ================================================ FILE: examples/openapi-ts-tanstack-angular-query-experimental/tsconfig.json ================================================ /* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc", "strict": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noImplicitReturns": false, "noFallthroughCasesInSwitch": true, "skipLibCheck": true, "isolatedModules": true, "esModuleInterop": true, "sourceMap": true, "declaration": false, "experimentalDecorators": true, "moduleResolution": "bundler", "importHelpers": true, "target": "ES2022", "module": "ES2022", "lib": ["ES2022", "dom", "dom.iterable"] }, "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, "strictInjectionParameters": true, "strictInputAccessModifiers": true, "strictTemplates": true } } ================================================ FILE: examples/openapi-ts-tanstack-react-query/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: examples/openapi-ts-tanstack-react-query/CHANGELOG.md ================================================ # @example/openapi-ts-tanstack-react-query ## 0.0.39 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-fetch@0.13.1 ## 0.0.38 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-fetch@0.13.0 ## 0.0.37 ### Patch Changes - Updated dependencies [[`4d8c030`](https://github.com/hey-api/openapi-ts/commit/4d8c03038979c9a75315cc158789b3c198c62f90)]: - @hey-api/client-fetch@0.12.0 ## 0.0.36 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-fetch@0.11.0 ## 0.0.35 ### Patch Changes - Updated dependencies [[`1f99066`](https://github.com/hey-api/openapi-ts/commit/1f99066efbb2d0e6b9e3710c701293c2cc09d65e)]: - @hey-api/client-fetch@0.10.2 ## 0.0.34 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-fetch@0.10.1 ## 0.0.33 ### Patch Changes - Updated dependencies [[`fed9699`](https://github.com/hey-api/openapi-ts/commit/fed969985275621c7c2b65ffc760c7c66fafaf72)]: - @hey-api/client-fetch@0.10.0 ## 0.0.32 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-fetch@0.9.0 ## 0.0.31 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-fetch@0.8.4 ## 0.0.30 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-fetch@0.8.3 ## 0.0.29 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-fetch@0.8.2 ## 0.0.28 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-fetch@0.8.1 ## 0.0.27 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-fetch@0.8.0 ## 0.0.26 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31)]: - @hey-api/client-fetch@0.7.3 ## 0.0.25 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-fetch@0.7.2 ## 0.0.24 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-fetch@0.7.1 ## 0.0.23 ### Patch Changes - Updated dependencies [[`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107)]: - @hey-api/client-fetch@0.7.0 ## 0.0.22 ### Patch Changes - Updated dependencies [[`e2e1410`](https://github.com/hey-api/openapi-ts/commit/e2e1410b22c0c84c40d1b1803e9650d546350cb7)]: - @hey-api/client-fetch@0.6.0 ## 0.0.21 ### Patch Changes - Updated dependencies [[`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263), [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26)]: - @hey-api/client-fetch@0.5.7 ## 0.0.20 ### Patch Changes - Updated dependencies [[`ba56424`](https://github.com/hey-api/openapi-ts/commit/ba5642486cdd5461c2372c34b63019c02bc6874e)]: - @hey-api/client-fetch@0.5.6 ## 0.0.19 ### Patch Changes - Updated dependencies [[`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a)]: - @hey-api/client-fetch@0.5.5 ## 0.0.18 ### Patch Changes - Updated dependencies [[`cbf4e84`](https://github.com/hey-api/openapi-ts/commit/cbf4e84db7f3a47f19d8c3eaa87c71b27912c1a2)]: - @hey-api/client-fetch@0.5.4 ## 0.0.17 ### Patch Changes - Updated dependencies [[`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0)]: - @hey-api/client-fetch@0.5.3 ## 0.0.16 ### Patch Changes - Updated dependencies [[`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a)]: - @hey-api/client-fetch@0.5.2 ## 0.0.15 ### Patch Changes - Updated dependencies [[`fa8b0f1`](https://github.com/hey-api/openapi-ts/commit/fa8b0f11ed99c63f694a494944ccc2fbfa9706cc)]: - @hey-api/client-fetch@0.5.1 ## 0.0.14 ### Patch Changes - Updated dependencies [[`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df), [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df)]: - @hey-api/client-fetch@0.5.0 ## 0.0.13 ### Patch Changes - Updated dependencies [[`4c853d0`](https://github.com/hey-api/openapi-ts/commit/4c853d090b79245854d13831f64731db4a92978b)]: - @hey-api/client-fetch@0.4.4 ## 0.0.12 ### Patch Changes - Updated dependencies [[`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482)]: - @hey-api/client-fetch@0.4.3 ## 0.0.11 ### Patch Changes - [#1151](https://github.com/hey-api/openapi-ts/pull/1151) [`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update website domain, add license documentation - Updated dependencies [[`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5)]: - @hey-api/client-fetch@0.4.2 ## 0.0.10 ### Patch Changes - Updated dependencies [[`a0a5551`](https://github.com/hey-api/openapi-ts/commit/a0a55510d30a1a8dea0ade4908b5b13d51b5f9e6)]: - @hey-api/client-fetch@0.4.1 ## 0.0.9 ### Patch Changes - Updated dependencies [[`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa), [`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa)]: - @hey-api/client-fetch@0.4.0 ## 0.0.8 ### Patch Changes - Updated dependencies [[`7f986c2`](https://github.com/hey-api/openapi-ts/commit/7f986c2c7726ed8fbf16f8b235b7769c7d990502)]: - @hey-api/client-fetch@0.3.4 ## 0.0.7 ### Patch Changes - Updated dependencies [[`fe743c2`](https://github.com/hey-api/openapi-ts/commit/fe743c2d41c23bf7e1706bceedd6319299131197)]: - @hey-api/client-fetch@0.3.3 ## 0.0.6 ### Patch Changes - Updated dependencies [[`11a276a`](https://github.com/hey-api/openapi-ts/commit/11a276a1e35dde0735363e892d8142016fd87eec)]: - @hey-api/client-fetch@0.3.2 ## 0.0.5 ### Patch Changes - Updated dependencies [[`7ae2b1d`](https://github.com/hey-api/openapi-ts/commit/7ae2b1db047f3b6efe917a8b43ac7c851fb86c8f), [`2079c6e`](https://github.com/hey-api/openapi-ts/commit/2079c6e83a6b71e157c8e7ea56260b4e9ff8411d)]: - @hey-api/client-fetch@0.3.1 ## 0.0.4 ### Patch Changes - Updated dependencies [[`7ebc1d4`](https://github.com/hey-api/openapi-ts/commit/7ebc1d44af74db2522219d71d240325f6bc5689d)]: - @hey-api/client-fetch@0.3.0 ## 0.0.3 ### Patch Changes - [#1010](https://github.com/hey-api/openapi-ts/pull/1010) [`b6e58c6`](https://github.com/hey-api/openapi-ts/commit/b6e58c64d1b71897533a85d1738cd7ce7ede178d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: set query key base url from supplied client if provided ## 0.0.2 ### Patch Changes - [#978](https://github.com/hey-api/openapi-ts/pull/978) [`2e051a5`](https://github.com/hey-api/openapi-ts/commit/2e051a596302c2e103dca25951a07b4aae1e9e23) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add basic TanStack Query plugin description ## 0.0.1 ### Patch Changes - [#901](https://github.com/hey-api/openapi-ts/pull/901) [`5054875`](https://github.com/hey-api/openapi-ts/commit/505487582667fb2d9fe99a25ad53ea608ce5033d) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add TanStack React Query example - Updated dependencies [[`a8c84c0`](https://github.com/hey-api/openapi-ts/commit/a8c84c02dbb5ef1a59f5d414dff425e135c7a446), [`7825a2f`](https://github.com/hey-api/openapi-ts/commit/7825a2fba566a76c63775172ef0569ef375406b6)]: - @hey-api/client-fetch@0.2.4 ================================================ FILE: examples/openapi-ts-tanstack-react-query/index.html ================================================ Hey API + TanStack React Query Demo
    ================================================ FILE: examples/openapi-ts-tanstack-react-query/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-fetch', '@hey-api/schemas', { instance: true, name: '@hey-api/sdk', }, { enums: 'javascript', name: '@hey-api/typescript', }, '@tanstack/react-query', ], }); ================================================ FILE: examples/openapi-ts-tanstack-react-query/package.json ================================================ { "name": "@example/openapi-ts-tanstack-react-query", "version": "0.0.39", "private": true, "type": "module", "scripts": { "build": "tsgo --noEmit && vite build", "dev": "vite", "lint": "eslint . --report-unused-disable-directives --max-warnings 0", "openapi-ts": "openapi-ts", "preview": "vite preview", "typecheck": "tsgo --noEmit" }, "dependencies": { "@radix-ui/react-form": "0.1.1", "@radix-ui/react-icons": "1.3.2", "@radix-ui/themes": "3.1.6", "@tanstack/react-query": "5.73.3", "@tanstack/react-query-devtools": "5.73.3", "react": "19.0.0", "react-dom": "19.0.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@types/react": "19.0.1", "@types/react-dom": "19.0.1", "@typescript-eslint/eslint-plugin": "8.29.1", "@typescript-eslint/parser": "8.29.1", "@vitejs/plugin-react": "4.4.0-beta.1", "autoprefixer": "10.4.19", "eslint": "9.17.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.7", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1" } } ================================================ FILE: examples/openapi-ts-tanstack-react-query/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/App.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/App.tsx ================================================ import './App.css'; import * as Form from '@radix-ui/react-form'; import { DownloadIcon, PlusIcon, ReloadIcon } from '@radix-ui/react-icons'; import { Avatar, Box, Button, Card, Container, Flex, Heading, Section, Text, TextField, } from '@radix-ui/themes'; import { useMutation, useQuery } from '@tanstack/react-query'; import { useEffect, useState } from 'react'; import { addPetMutation, getPetByIdOptions, updatePetMutation, } from './client/@tanstack/react-query.gen'; import { createClient } from './client/client'; import { PetSchema } from './client/schemas.gen'; import type { Pet } from './client/types.gen'; const localClient = createClient({ // set default base url for requests made by this client baseUrl: 'https://petstore3.swagger.io/api/v3', /** * Set default headers only for requests made by this client. This is to * demonstrate local clients and their configuration taking precedence over * internal service client. */ headers: { Authorization: 'Bearer ', }, }); localClient.interceptors.request.use((request, options) => { // Middleware is great for adding authorization tokens to requests made to // protected paths. Headers are set randomly here to allow surfacing the // default headers, too. if (options.url === '/pet/{petId}' && options.method === 'GET' && Math.random() < 0.5) { request.headers.set('Authorization', 'Bearer '); } return request; }); function App() { const [pet, setPet] = useState(); const [petId, setPetId] = useState(); const [isRequiredNameError, setIsRequiredNameError] = useState(false); const addPet = useMutation({ ...addPetMutation(), onError: (error) => { console.log(error); setIsRequiredNameError(false); }, onSuccess: (data) => { setPet(data); setIsRequiredNameError(false); }, }); const updatePet = useMutation({ ...updatePetMutation(), onError: (error) => { console.log(error); }, onSuccess: (data) => { setPet(data); }, }); const { data, error } = useQuery({ ...getPetByIdOptions({ client: localClient, path: { petId: petId!, }, }), enabled: Boolean(petId), }); const onAddPet = async (formData: FormData) => { // simple form field validation to demonstrate using schemas if (PetSchema.required.includes('name') && !formData.get('name')) { setIsRequiredNameError(true); return; } addPet.mutate({ body: { category: { id: 0, name: formData.get('category') as string, }, id: 0, name: formData.get('name') as string, photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, }); }; const onGetPetById = async () => { // random id 1-10 setPetId(Math.floor(Math.random() * (10 - 1 + 1) + 1)); }; const onUpdatePet = async () => { updatePet.mutate({ body: { category: { id: 0, name: 'Cats', }, id: 2, name: 'Updated Kitty', photoUrls: ['string'], status: 'available', tags: [ { id: 0, name: 'string', }, ], }, // setting headers per request headers: { Authorization: 'Bearer ', }, }); }; useEffect(() => { if (error) { console.log(error); return; } setPet(data!); }, [data, error]); return (
    Hey API logo @hey-api/openapi-ts 🤝 TanStack React Query
    Name: {pet?.name ?? 'N/A'} Category: {pet?.category?.name ?? 'N/A'}
    { event.preventDefault(); onAddPet(new FormData(event.currentTarget)); }} >
    Name {isRequiredNameError && ( Please enter a name )}
    Category Please enter a category
    ); } export default App; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { type Options, Sdk } from '../sdk.gen'; import type { AddPetData, AddPetResponse, CreateUserData, CreateUserResponse, CreateUsersWithListInputData, CreateUsersWithListInputResponse, DeleteOrderData, DeletePetData, DeleteUserData, FindPetsByStatusData, FindPetsByStatusResponse, FindPetsByTagsData, FindPetsByTagsResponse, GetInventoryData, GetInventoryResponse, GetOrderByIdData, GetOrderByIdResponse, GetPetByIdData, GetPetByIdResponse, GetUserByNameData, GetUserByNameResponse, LoginUserData, LoginUserResponse, LogoutUserData, PlaceOrderData, PlaceOrderResponse, UpdatePetData, UpdatePetResponse, UpdatePetWithFormData, UpdatePetWithFormResponse, UpdateUserData, UploadFileData, UploadFileResponse, } from '../types.gen'; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPetMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().addPet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePetMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< UpdatePetResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().updatePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; }, ]; const createQueryKey = ( id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray, ): [QueryKey[0]] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl, } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const findPetsByStatusQueryKey = (options: Options) => createQueryKey('findPetsByStatus', options); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatusOptions = (options: Options) => queryOptions< FindPetsByStatusResponse, DefaultError, FindPetsByStatusResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().findPetsByStatus({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByStatusQueryKey(options), }); export const findPetsByTagsQueryKey = (options: Options) => createQueryKey('findPetsByTags', options); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTagsOptions = (options: Options) => queryOptions< FindPetsByTagsResponse, DefaultError, FindPetsByTagsResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().findPetsByTags({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByTagsQueryKey(options), }); /** * Deletes a pet. * * Delete a pet. */ export const deletePetMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().deletePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getPetByIdQueryKey = (options: Options) => createQueryKey('getPetById', options); /** * Find pet by ID. * * Returns a single pet. */ export const getPetByIdOptions = (options: Options) => queryOptions< GetPetByIdResponse, DefaultError, GetPetByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().getPetById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getPetByIdQueryKey(options), }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithFormMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< UpdatePetWithFormResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().updatePetWithForm({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Uploads an image. * * Upload image of the pet. */ export const uploadFileMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< UploadFileResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().uploadFile({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getInventoryQueryKey = (options?: Options) => createQueryKey('getInventory', options); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventoryOptions = (options?: Options) => queryOptions< GetInventoryResponse, DefaultError, GetInventoryResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().getInventory({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getInventoryQueryKey(options), }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrderMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< PlaceOrderResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().placeOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrderMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().deleteOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getOrderByIdQueryKey = (options: Options) => createQueryKey('getOrderById', options); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderByIdOptions = (options: Options) => queryOptions< GetOrderByIdResponse, DefaultError, GetOrderByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().getOrderById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getOrderByIdQueryKey(options), }); /** * Create user. * * This can only be done by the logged in user. */ export const createUserMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< CreateUserResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().createUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInputMutation = ( options?: Partial>, ): UseMutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > => { const mutationOptions: UseMutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().createUsersWithListInput({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const loginUserQueryKey = (options?: Options) => createQueryKey('loginUser', options); /** * Logs user into the system. * * Log into the system. */ export const loginUserOptions = (options?: Options) => queryOptions< LoginUserResponse, DefaultError, LoginUserResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().loginUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: loginUserQueryKey(options), }); export const logoutUserQueryKey = (options?: Options) => createQueryKey('logoutUser', options); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUserOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().logoutUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: logoutUserQueryKey(options), }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUserMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().deleteUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getUserByNameQueryKey = (options: Options) => createQueryKey('getUserByName', options); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByNameOptions = (options: Options) => queryOptions< GetUserByNameResponse, DefaultError, GetUserByNameResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await Sdk.__registry.get().getUserByName({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getUserByNameQueryKey(options), }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUserMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await Sdk.__registry.get().updateUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, Sdk } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new Sdk()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class Sdk extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string }) { super(args); Sdk.__registry.set(this, args?.key); } /** * Add a new pet to the store. * * Add a new pet to the store. */ public addPet(options: Options) { return (options.client ?? this.client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); } /** * Update an existing pet. * * Update an existing pet by Id. */ public updatePet( options: Options, ) { return (options.client ?? this.client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); } /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ public findPetsByStatus( options: Options, ) { return (options.client ?? this.client).get< FindPetsByStatusResponses, FindPetsByStatusErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); } /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ public findPetsByTags( options: Options, ) { return (options.client ?? this.client).get< FindPetsByTagsResponses, FindPetsByTagsErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); } /** * Deletes a pet. * * Delete a pet. */ public deletePet( options: Options, ) { return (options.client ?? this.client).delete< DeletePetResponses, DeletePetErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); } /** * Find pet by ID. * * Returns a single pet. */ public getPetById( options: Options, ) { return (options.client ?? this.client).get( { security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }, ); } /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ public updatePetWithForm( options: Options, ) { return (options.client ?? this.client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); } /** * Uploads an image. * * Upload image of the pet. */ public uploadFile( options: Options, ) { return (options.client ?? this.client).post< UploadFileResponses, UploadFileErrors, ThrowOnError >({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); } /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ public getInventory( options?: Options, ) { return (options?.client ?? this.client).get< GetInventoryResponses, GetInventoryErrors, ThrowOnError >({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); } /** * Place an order for a pet. * * Place a new order in the store. */ public placeOrder( options?: Options, ) { return (options?.client ?? this.client).post< PlaceOrderResponses, PlaceOrderErrors, ThrowOnError >({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); } /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ public deleteOrder( options: Options, ) { return (options.client ?? this.client).delete< DeleteOrderResponses, DeleteOrderErrors, ThrowOnError >({ url: '/store/order/{orderId}', ...options }); } /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ public getOrderById( options: Options, ) { return (options.client ?? this.client).get< GetOrderByIdResponses, GetOrderByIdErrors, ThrowOnError >({ url: '/store/order/{orderId}', ...options }); } /** * Create user. * * This can only be done by the logged in user. */ public createUser( options?: Options, ) { return (options?.client ?? this.client).post< CreateUserResponses, CreateUserErrors, ThrowOnError >({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); } /** * Creates list of users with given input array. * * Creates list of users with given input array. */ public createUsersWithListInput( options?: Options, ) { return (options?.client ?? this.client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); } /** * Logs user into the system. * * Log into the system. */ public loginUser( options?: Options, ) { return (options?.client ?? this.client).get({ url: '/user/login', ...options, }); } /** * Logs out current logged in user session. * * Log user out of the system. */ public logoutUser( options?: Options, ) { return (options?.client ?? this.client).get< LogoutUserResponses, LogoutUserErrors, ThrowOnError >({ url: '/user/logout', ...options }); } /** * Delete user resource. * * This can only be done by the logged in user. */ public deleteUser( options: Options, ) { return (options.client ?? this.client).delete< DeleteUserResponses, DeleteUserErrors, ThrowOnError >({ url: '/user/{username}', ...options }); } /** * Get user by user name. * * Get user detail based on username. */ public getUserByName( options: Options, ) { return (options.client ?? this.client).get< GetUserByNameResponses, GetUserByNameErrors, ThrowOnError >({ url: '/user/{username}', ...options }); } /** * Update user resource. * * This can only be done by the logged in user. */ public updateUser( options: Options, ) { return (options.client ?? this.client).put( { url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }, ); } } ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/main.tsx ================================================ import '@radix-ui/themes/styles.css'; import { Theme } from '@radix-ui/themes'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App.tsx'; import { client } from './client/client.gen'; import { Sdk } from './client/sdk.gen.ts'; const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 60000, }, }, }); // configure internal service client client.setConfig({ // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); new Sdk(); ReactDOM.createRoot(document.getElementById('root')!).render( , ); ================================================ FILE: examples/openapi-ts-tanstack-react-query/src/vite-env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-tanstack-react-query/tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{html,js,ts,jsx,tsx}'], theme: { extend: {}, }, }; ================================================ FILE: examples/openapi-ts-tanstack-react-query/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": false, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: examples/openapi-ts-tanstack-react-query/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: examples/openapi-ts-tanstack-react-query/vite.config.ts ================================================ import react from '@vitejs/plugin-react'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [react()], }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea *.suo *.ntvs* *.njsproj *.sln *.sw? node_modules # Output .output .vercel .svelte-kit /build # OS .DS_Store Thumbs.db # Env .env .env.* !.env.example !.env.test # Vite vite.config.js.timestamp-* vite.config.ts.timestamp-* ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/CHANGELOG.md ================================================ # @example/openapi-ts-tanstack-svelte-query ## 0.0.39 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-fetch@0.13.1 ## 0.0.38 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-fetch@0.13.0 ## 0.0.37 ### Patch Changes - Updated dependencies [[`4d8c030`](https://github.com/hey-api/openapi-ts/commit/4d8c03038979c9a75315cc158789b3c198c62f90)]: - @hey-api/client-fetch@0.12.0 ## 0.0.36 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-fetch@0.11.0 ## 0.0.35 ### Patch Changes - Updated dependencies [[`1f99066`](https://github.com/hey-api/openapi-ts/commit/1f99066efbb2d0e6b9e3710c701293c2cc09d65e)]: - @hey-api/client-fetch@0.10.2 ## 0.0.34 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-fetch@0.10.1 ## 0.0.33 ### Patch Changes - Updated dependencies [[`fed9699`](https://github.com/hey-api/openapi-ts/commit/fed969985275621c7c2b65ffc760c7c66fafaf72)]: - @hey-api/client-fetch@0.10.0 ## 0.0.32 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-fetch@0.9.0 ## 0.0.31 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-fetch@0.8.4 ## 0.0.30 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-fetch@0.8.3 ## 0.0.29 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-fetch@0.8.2 ## 0.0.28 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-fetch@0.8.1 ## 0.0.27 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-fetch@0.8.0 ## 0.0.26 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31)]: - @hey-api/client-fetch@0.7.3 ## 0.0.25 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-fetch@0.7.2 ## 0.0.24 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-fetch@0.7.1 ## 0.0.23 ### Patch Changes - Updated dependencies [[`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107)]: - @hey-api/client-fetch@0.7.0 ## 0.0.22 ### Patch Changes - Updated dependencies [[`e2e1410`](https://github.com/hey-api/openapi-ts/commit/e2e1410b22c0c84c40d1b1803e9650d546350cb7)]: - @hey-api/client-fetch@0.6.0 ## 0.0.21 ### Patch Changes - Updated dependencies [[`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263), [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26)]: - @hey-api/client-fetch@0.5.7 ## 0.0.20 ### Patch Changes - Updated dependencies [[`ba56424`](https://github.com/hey-api/openapi-ts/commit/ba5642486cdd5461c2372c34b63019c02bc6874e)]: - @hey-api/client-fetch@0.5.6 ## 0.0.19 ### Patch Changes - Updated dependencies [[`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a)]: - @hey-api/client-fetch@0.5.5 ## 0.0.18 ### Patch Changes - Updated dependencies [[`cbf4e84`](https://github.com/hey-api/openapi-ts/commit/cbf4e84db7f3a47f19d8c3eaa87c71b27912c1a2)]: - @hey-api/client-fetch@0.5.4 ## 0.0.17 ### Patch Changes - Updated dependencies [[`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0)]: - @hey-api/client-fetch@0.5.3 ## 0.0.16 ### Patch Changes - Updated dependencies [[`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a)]: - @hey-api/client-fetch@0.5.2 ## 0.0.15 ### Patch Changes - Updated dependencies [[`fa8b0f1`](https://github.com/hey-api/openapi-ts/commit/fa8b0f11ed99c63f694a494944ccc2fbfa9706cc)]: - @hey-api/client-fetch@0.5.1 ## 0.0.14 ### Patch Changes - Updated dependencies [[`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df), [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df)]: - @hey-api/client-fetch@0.5.0 ## 0.0.13 ### Patch Changes - Updated dependencies [[`4c853d0`](https://github.com/hey-api/openapi-ts/commit/4c853d090b79245854d13831f64731db4a92978b)]: - @hey-api/client-fetch@0.4.4 ## 0.0.12 ### Patch Changes - Updated dependencies [[`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482)]: - @hey-api/client-fetch@0.4.3 ## 0.0.11 ### Patch Changes - Updated dependencies [[`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5)]: - @hey-api/client-fetch@0.4.2 ## 0.0.10 ### Patch Changes - Updated dependencies [[`a0a5551`](https://github.com/hey-api/openapi-ts/commit/a0a55510d30a1a8dea0ade4908b5b13d51b5f9e6)]: - @hey-api/client-fetch@0.4.1 ## 0.0.9 ### Patch Changes - Updated dependencies [[`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa), [`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa)]: - @hey-api/client-fetch@0.4.0 ## 0.0.8 ### Patch Changes - Updated dependencies [[`7f986c2`](https://github.com/hey-api/openapi-ts/commit/7f986c2c7726ed8fbf16f8b235b7769c7d990502)]: - @hey-api/client-fetch@0.3.4 ## 0.0.7 ### Patch Changes - Updated dependencies [[`fe743c2`](https://github.com/hey-api/openapi-ts/commit/fe743c2d41c23bf7e1706bceedd6319299131197)]: - @hey-api/client-fetch@0.3.3 ## 0.0.6 ### Patch Changes - Updated dependencies [[`11a276a`](https://github.com/hey-api/openapi-ts/commit/11a276a1e35dde0735363e892d8142016fd87eec)]: - @hey-api/client-fetch@0.3.2 ## 0.0.5 ### Patch Changes - Updated dependencies [[`7ae2b1d`](https://github.com/hey-api/openapi-ts/commit/7ae2b1db047f3b6efe917a8b43ac7c851fb86c8f), [`2079c6e`](https://github.com/hey-api/openapi-ts/commit/2079c6e83a6b71e157c8e7ea56260b4e9ff8411d)]: - @hey-api/client-fetch@0.3.1 ## 0.0.4 ### Patch Changes - Updated dependencies [[`7ebc1d4`](https://github.com/hey-api/openapi-ts/commit/7ebc1d44af74db2522219d71d240325f6bc5689d)]: - @hey-api/client-fetch@0.3.0 ## 0.0.3 ### Patch Changes - [#1010](https://github.com/hey-api/openapi-ts/pull/1010) [`b6e58c6`](https://github.com/hey-api/openapi-ts/commit/b6e58c64d1b71897533a85d1738cd7ce7ede178d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: set query key base url from supplied client if provided ## 0.0.2 ### Patch Changes - [#978](https://github.com/hey-api/openapi-ts/pull/978) [`2e051a5`](https://github.com/hey-api/openapi-ts/commit/2e051a596302c2e103dca25951a07b4aae1e9e23) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add basic TanStack Query plugin description ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/README.md ================================================ # create-svelte Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte). ## Creating a project If you're seeing this, you've probably already done this step. Congrats! ```bash # create a new project in the current directory npm create svelte@latest # create a new project in my-app npm create svelte@latest my-app ``` ## Developing Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server: ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` ## Building To create a production version of your app: ```bash npm run build ``` You can preview the production build with `npm run preview`. > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment. ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-fetch', '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, '@tanstack/svelte-query', ], }); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/package.json ================================================ { "name": "@example/openapi-ts-tanstack-svelte-query", "version": "0.0.39", "private": true, "type": "module", "scripts": { "build": "vite build", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "dev": "vite dev", "format": "oxfmt .", "lint": "oxfmt --check . && eslint .", "openapi-ts": "openapi-ts", "prepare": "svelte-kit sync", "preview": "vite preview", "test": "vitest --watch=false" }, "dependencies": { "@tanstack/svelte-query": "5.73.3" }, "devDependencies": { "@fontsource/fira-mono": "5.0.0", "@hey-api/openapi-ts": "workspace:*", "@neoconfetti/svelte": "2.0.0", "@sveltejs/adapter-auto": "4.0.0", "@sveltejs/kit": "2.17.1", "@sveltejs/vite-plugin-svelte": "5.0.3", "@types/eslint": "9.6.0", "eslint": "9.17.0", "eslint-plugin-svelte": "2.36.0", "globals": "15.14.0", "oxfmt": "0.27.0", "svelte": "5.19.9", "svelte-check": "4.1.4", "typescript": "5.9.3", "typescript-eslint": "8.29.1", "vite": "7.3.1", "vitest": "4.0.18" } } ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/app.css ================================================ @import '@fontsource/fira-mono'; :root { --font-body: Arial, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; --font-mono: 'Fira Mono', monospace; --color-bg-0: rgb(202, 216, 228); --color-bg-1: hsl(209, 36%, 86%); --color-bg-2: hsl(224, 44%, 95%); --color-theme-1: #ff3e00; --color-theme-2: #4075a6; --color-text: rgba(0, 0, 0, 0.7); --column-width: 42rem; --column-margin-top: 4rem; font-family: var(--font-body); color: var(--color-text); } body { min-height: 100vh; margin: 0; background-attachment: fixed; background-color: var(--color-bg-1); background-size: 100vw 100vh; background-image: radial-gradient(50% 50% at 50% 50%, rgba(255, 255, 255, 0.75) 0%, rgba(255, 255, 255, 0) 100%), linear-gradient(180deg, var(--color-bg-0) 0%, var(--color-bg-1) 15%, var(--color-bg-2) 50%); } h1, h2, p { font-weight: 400; } p { line-height: 1.5; } a { color: var(--color-theme-1); text-decoration: none; } a:hover { text-decoration: underline; } h1 { font-size: 2rem; text-align: center; } h2 { font-size: 1rem; } pre { font-size: 16px; font-family: var(--font-mono); background-color: rgba(255, 255, 255, 0.45); border-radius: 3px; box-shadow: 2px 2px 6px rgb(255 255 255 / 25%); padding: 0.5em; overflow-x: auto; color: var(--color-text); } .text-column { display: flex; max-width: 48rem; flex: 0.6; flex-direction: column; justify-content: center; margin: 0 auto; } input, button { font-size: inherit; font-family: inherit; } button:focus:not(:focus-visible) { outline: none; } @media (min-width: 720px) { h1 { font-size: 2.4rem; } } .visually-hidden { border: 0; clip: rect(0 0 0 0); height: auto; margin: 0; overflow: hidden; padding: 0; position: absolute; width: 1px; white-space: nowrap; } ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/app.d.ts ================================================ // See https://kit.svelte.dev/docs/types#app // for information about these interfaces declare global { namespace App { // interface Error {} // interface Locals {} // interface PageData {} // interface PageState {} // interface Platform {} } } export {}; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/app.html ================================================ %sveltekit.head%
    %sveltekit.body%
    ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from '../sdk.gen'; import type { AddPetData, AddPetResponse, CreateUserData, CreateUserResponse, CreateUsersWithListInputData, CreateUsersWithListInputResponse, DeleteOrderData, DeletePetData, DeleteUserData, FindPetsByStatusData, FindPetsByStatusResponse, FindPetsByTagsData, FindPetsByTagsResponse, GetInventoryData, GetInventoryResponse, GetOrderByIdData, GetOrderByIdResponse, GetPetByIdData, GetPetByIdResponse, GetUserByNameData, GetUserByNameResponse, LoginUserData, LoginUserResponse, LogoutUserData, PlaceOrderData, PlaceOrderResponse, UpdatePetData, UpdatePetResponse, UpdatePetWithFormData, UpdatePetWithFormResponse, UpdateUserData, UploadFileData, UploadFileResponse, } from '../types.gen'; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPetMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await addPet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePetMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< UpdatePetResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await updatePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; }, ]; const createQueryKey = ( id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray, ): [QueryKey[0]] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl, } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const findPetsByStatusQueryKey = (options: Options) => createQueryKey('findPetsByStatus', options); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatusOptions = (options: Options) => queryOptions< FindPetsByStatusResponse, DefaultError, FindPetsByStatusResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await findPetsByStatus({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByStatusQueryKey(options), }); export const findPetsByTagsQueryKey = (options: Options) => createQueryKey('findPetsByTags', options); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTagsOptions = (options: Options) => queryOptions< FindPetsByTagsResponse, DefaultError, FindPetsByTagsResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await findPetsByTags({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByTagsQueryKey(options), }); /** * Deletes a pet. * * Delete a pet. */ export const deletePetMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deletePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getPetByIdQueryKey = (options: Options) => createQueryKey('getPetById', options); /** * Find pet by ID. * * Returns a single pet. */ export const getPetByIdOptions = (options: Options) => queryOptions< GetPetByIdResponse, DefaultError, GetPetByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getPetById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getPetByIdQueryKey(options), }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithFormMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< UpdatePetWithFormResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await updatePetWithForm({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Uploads an image. * * Upload image of the pet. */ export const uploadFileMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< UploadFileResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getInventoryQueryKey = (options?: Options) => createQueryKey('getInventory', options); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventoryOptions = (options?: Options) => queryOptions< GetInventoryResponse, DefaultError, GetInventoryResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getInventory({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getInventoryQueryKey(options), }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrderMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< PlaceOrderResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await placeOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrderMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getOrderByIdQueryKey = (options: Options) => createQueryKey('getOrderById', options); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderByIdOptions = (options: Options) => queryOptions< GetOrderByIdResponse, DefaultError, GetOrderByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getOrderById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getOrderByIdQueryKey(options), }); /** * Create user. * * This can only be done by the logged in user. */ export const createUserMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions< CreateUserResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await createUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInputMutation = ( options?: Partial>, ): MutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > => { const mutationOptions: MutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await createUsersWithListInput({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const loginUserQueryKey = (options?: Options) => createQueryKey('loginUser', options); /** * Logs user into the system. * * Log into the system. */ export const loginUserOptions = (options?: Options) => queryOptions< LoginUserResponse, DefaultError, LoginUserResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await loginUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: loginUserQueryKey(options), }); export const logoutUserQueryKey = (options?: Options) => createQueryKey('logoutUser', options); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUserOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await logoutUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: logoutUserQueryKey(options), }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUserMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getUserByNameQueryKey = (options: Options) => createQueryKey('getUserByName', options); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByNameOptions = (options: Options) => queryOptions< GetUserByNameResponse, DefaultError, GetUserByNameResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getUserByName({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getUserByNameQueryKey(options), }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUserMutation = ( options?: Partial>, ): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await updateUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/+layout.svelte ================================================
    ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/+page.svelte ================================================ Home

    Welcome to your new
    SvelteKit app

    {#if $query.isPending} Loading... {/if} {#if $query.error} Error... {/if} {#if $query.isSuccess} {$query.data.name} {/if}

    try editing src/routes/+page.svelte

    ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/+page.ts ================================================ // since there's no dynamic data here, we can prerender // it so that it gets served as a static asset in production export const prerender = true; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/Counter.svelte ================================================
    {Math.floor($displayed_count)}
    ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/Header.svelte ================================================
    ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/about/+page.svelte ================================================ About

    About this app

    This is a SvelteKit app. You can make your own by typing the following into your command line and following the prompts:

    npm create svelte@latest

    The page you're looking at is purely static HTML, with no client-side interactivity needed. Because of that, we don't need to load any JavaScript. Try viewing the page's source, or opening the devtools network panel and reloading.

    The Sverdle page illustrates SvelteKit's data loading and form handling. Try using it with JavaScript disabled!

    ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/about/+page.ts ================================================ import { dev } from '$app/environment'; // we don't need any JS on this page, though we'll load // it in dev so that we get hot module replacement export const csr = dev; // since there's no dynamic data here, we can prerender // it so that it gets served as a static asset in production export const prerender = true; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/+page.server.ts ================================================ import { fail } from '@sveltejs/kit'; import type { Actions, PageServerLoad } from './$types'; import { Game } from './game'; export const load = (({ cookies }) => { const game = new Game(cookies.get('sverdle')); return { /** * The correct answer, revealed if the game is over */ answer: game.answers.length >= 6 ? game.answer : null, /** * An array of strings like '__x_c' corresponding to the guesses, where 'x' means * an exact match, and 'c' means a close match (right letter, wrong place) */ answers: game.answers, /** * The player's guessed words so far */ guesses: game.guesses, }; }) satisfies PageServerLoad; export const actions = { /** * Modify game state in reaction to a guessed word. This logic always runs on * the server, so that people can't cheat by peeking at the JavaScript */ enter: async ({ cookies, request }) => { const game = new Game(cookies.get('sverdle')); const data = await request.formData(); const guess = data.getAll('guess') as string[]; if (!game.enter(guess)) { return fail(400, { badGuess: true }); } cookies.set('sverdle', game.toString(), { path: '/' }); }, restart: async ({ cookies }) => { cookies.delete('sverdle', { path: '/' }); }, /** * Modify game state in reaction to a keypress. If client-side JavaScript * is available, this will happen in the browser instead of here */ update: async ({ cookies, request }) => { const game = new Game(cookies.get('sverdle')); const data = await request.formData(); const key = data.get('key'); const i = game.answers.length; if (key === 'backspace') { game.guesses[i] = game.guesses[i].slice(0, -1); } else { game.guesses[i] += key; } cookies.set('sverdle', game.toString(), { path: '/' }); }, } satisfies Actions; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/+page.svelte ================================================ Sverdle

    Sverdle

    { // prevent default callback from resetting the form return ({ update }) => { update({ reset: false }); }; }} > How to play
    {#each Array.from(Array(6).keys()) as row (row)} {@const current = row === i}

    Row {row + 1}

    {#each Array.from(Array(5).keys()) as column (column)} {@const guess = current ? currentGuess : data.guesses[row]} {@const answer = data.answers[row]?.[column]} {@const value = guess?.[column] ?? ''} {@const selected = current && column === guess.length} {@const exact = answer === 'x'} {@const close = answer === 'c'} {@const missing = answer === '_'}
    {value} {#if exact} (correct) {:else if close} (present) {:else if missing} (absent) {:else} empty {/if}
    {/each}
    {/each}
    {#if won || data.answers.length >= 6} {#if !won && data.answer}

    the answer was "{data.answer}"

    {/if} {:else}
    {#each ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'] as row}
    {#each row as letter} {/each}
    {/each}
    {/if}
    {#if won}
    {/if} ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/game.test.ts ================================================ import { Game } from './game'; describe('game test', () => { it('returns true when a valid word is entered', () => { const game = new Game(); expect(game.enter('zorro'.split(''))).toBe(true); }); }); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/game.ts ================================================ import { allowed, words } from './words.server'; export class Game { index: number; guesses: string[]; answers: string[]; answer: string; /** * Create a game object from the player's cookie, or initialise a new game */ constructor(serialized: string | undefined = undefined) { if (serialized) { const [index, guesses, answers] = serialized.split('-'); this.index = +index; this.guesses = guesses ? guesses.split(' ') : []; this.answers = answers ? answers.split(' ') : []; } else { this.index = Math.floor(Math.random() * words.length); this.guesses = ['', '', '', '', '', '']; this.answers = []; } this.answer = words[this.index]; } /** * Update game state based on a guess of a five-letter word. Returns * true if the guess was valid, false otherwise */ enter(letters: string[]) { const word = letters.join(''); const valid = allowed.has(word); if (!valid) return false; this.guesses[this.answers.length] = word; const available = Array.from(this.answer); const answer = Array(5).fill('_'); // first, find exact matches for (let i = 0; i < 5; i += 1) { if (letters[i] === available[i]) { answer[i] = 'x'; available[i] = ' '; } } // then find close matches (this has to happen // in a second step, otherwise an early close // match can prevent a later exact match) for (let i = 0; i < 5; i += 1) { if (answer[i] === '_') { const index = available.indexOf(letters[i]); if (index !== -1) { answer[i] = 'c'; available[index] = ' '; } } } this.answers.push(answer.join('')); return true; } /** * Serialize game state so it can be set as a cookie */ toString() { return `${this.index}-${this.guesses.join(' ')}-${this.answers.join(' ')}`; } } ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/how-to-play/+page.svelte ================================================ How to play Sverdle

    How to play Sverdle

    Sverdle is a clone of Wordle, the word guessing game. To play, enter a five-letter English word. For example:

    r i t z y

    The y is in the right place. r and t are the right letters, but in the wrong place. The other letters are wrong, and can be discarded. Let's make another guess:

    p a r t y

    This time we guessed right! You have six guesses to get the word.

    Unlike the original Wordle, Sverdle runs on the server instead of in the browser, making it impossible to cheat. It uses <form> and cookies to submit data, meaning you can even play with JavaScript disabled!

    ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/how-to-play/+page.ts ================================================ import { dev } from '$app/environment'; // we don't need any JS on this page, though we'll load // it in dev so that we get hot module replacement export const csr = dev; // since there's no dynamic data here, we can prerender // it so that it gets served as a static asset in production export const prerender = true; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/reduced-motion.ts ================================================ import { readable } from 'svelte/store'; import { browser } from '$app/environment'; const reduced_motion_query = '(prefers-reduced-motion: reduce)'; const get_initial_motion_preference = () => { if (!browser) return false; return window.matchMedia(reduced_motion_query).matches; }; export const reduced_motion = readable(get_initial_motion_preference(), (set) => { if (browser) { const set_reduced_motion = (event: MediaQueryListEvent) => { set(event.matches); }; const media_query_list = window.matchMedia(reduced_motion_query); media_query_list.addEventListener('change', set_reduced_motion); return () => { media_query_list.removeEventListener('change', set_reduced_motion); }; } }); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/src/routes/sverdle/words.server.ts ================================================ /** The list of possible words */ export const words = [ 'aback', 'abase', 'abate', 'abbey', 'abbot', 'abhor', 'abide', 'abled', 'abode', 'abort', 'about', 'above', 'abuse', 'abyss', 'acorn', 'acrid', 'actor', 'acute', 'adage', 'adapt', 'adept', 'admin', 'admit', 'adobe', 'adopt', 'adore', 'adorn', 'adult', 'affix', 'afire', 'afoot', 'afoul', 'after', 'again', 'agape', 'agate', 'agent', 'agile', 'aging', 'aglow', 'agony', 'agora', 'agree', 'ahead', 'aider', 'aisle', 'alarm', 'album', 'alert', 'algae', 'alibi', 'alien', 'align', 'alike', 'alive', 'allay', 'alley', 'allot', 'allow', 'alloy', 'aloft', 'alone', 'along', 'aloof', 'aloud', 'alpha', 'altar', 'alter', 'amass', 'amaze', 'amber', 'amble', 'amend', 'amiss', 'amity', 'among', 'ample', 'amply', 'amuse', 'angel', 'anger', 'angle', 'angry', 'angst', 'anime', 'ankle', 'annex', 'annoy', 'annul', 'anode', 'antic', 'anvil', 'aorta', 'apart', 'aphid', 'aping', 'apnea', 'apple', 'apply', 'apron', 'aptly', 'arbor', 'ardor', 'arena', 'argue', 'arise', 'armor', 'aroma', 'arose', 'array', 'arrow', 'arson', 'artsy', 'ascot', 'ashen', 'aside', 'askew', 'assay', 'asset', 'atoll', 'atone', 'attic', 'audio', 'audit', 'augur', 'aunty', 'avail', 'avert', 'avian', 'avoid', 'await', 'awake', 'award', 'aware', 'awash', 'awful', 'awoke', 'axial', 'axiom', 'axion', 'azure', 'bacon', 'badge', 'badly', 'bagel', 'baggy', 'baker', 'baler', 'balmy', 'banal', 'banjo', 'barge', 'baron', 'basal', 'basic', 'basil', 'basin', 'basis', 'baste', 'batch', 'bathe', 'baton', 'batty', 'bawdy', 'bayou', 'beach', 'beady', 'beard', 'beast', 'beech', 'beefy', 'befit', 'began', 'begat', 'beget', 'begin', 'begun', 'being', 'belch', 'belie', 'belle', 'belly', 'below', 'bench', 'beret', 'berry', 'berth', 'beset', 'betel', 'bevel', 'bezel', 'bible', 'bicep', 'biddy', 'bigot', 'bilge', 'billy', 'binge', 'bingo', 'biome', 'birch', 'birth', 'bison', 'bitty', 'black', 'blade', 'blame', 'bland', 'blank', 'blare', 'blast', 'blaze', 'bleak', 'bleat', 'bleed', 'bleep', 'blend', 'bless', 'blimp', 'blind', 'blink', 'bliss', 'blitz', 'bloat', 'block', 'bloke', 'blond', 'blood', 'bloom', 'blown', 'bluer', 'bluff', 'blunt', 'blurb', 'blurt', 'blush', 'board', 'boast', 'bobby', 'boney', 'bongo', 'bonus', 'booby', 'boost', 'booth', 'booty', 'booze', 'boozy', 'borax', 'borne', 'bosom', 'bossy', 'botch', 'bough', 'boule', 'bound', 'bowel', 'boxer', 'brace', 'braid', 'brain', 'brake', 'brand', 'brash', 'brass', 'brave', 'bravo', 'brawl', 'brawn', 'bread', 'break', 'breed', 'briar', 'bribe', 'brick', 'bride', 'brief', 'brine', 'bring', 'brink', 'briny', 'brisk', 'broad', 'broil', 'broke', 'brood', 'brook', 'broom', 'broth', 'brown', 'brunt', 'brush', 'brute', 'buddy', 'budge', 'buggy', 'bugle', 'build', 'built', 'bulge', 'bulky', 'bully', 'bunch', 'bunny', 'burly', 'burnt', 'burst', 'bused', 'bushy', 'butch', 'butte', 'buxom', 'buyer', 'bylaw', 'cabal', 'cabby', 'cabin', 'cable', 'cacao', 'cache', 'cacti', 'caddy', 'cadet', 'cagey', 'cairn', 'camel', 'cameo', 'canal', 'candy', 'canny', 'canoe', 'canon', 'caper', 'caput', 'carat', 'cargo', 'carol', 'carry', 'carve', 'caste', 'catch', 'cater', 'catty', 'caulk', 'cause', 'cavil', 'cease', 'cedar', 'cello', 'chafe', 'chaff', 'chain', 'chair', 'chalk', 'champ', 'chant', 'chaos', 'chard', 'charm', 'chart', 'chase', 'chasm', 'cheap', 'cheat', 'check', 'cheek', 'cheer', 'chess', 'chest', 'chick', 'chide', 'chief', 'child', 'chili', 'chill', 'chime', 'china', 'chirp', 'chock', 'choir', 'choke', 'chord', 'chore', 'chose', 'chuck', 'chump', 'chunk', 'churn', 'chute', 'cider', 'cigar', 'cinch', 'circa', 'civic', 'civil', 'clack', 'claim', 'clamp', 'clang', 'clank', 'clash', 'clasp', 'class', 'clean', 'clear', 'cleat', 'cleft', 'clerk', 'click', 'cliff', 'climb', 'cling', 'clink', 'cloak', 'clock', 'clone', 'close', 'cloth', 'cloud', 'clout', 'clove', 'clown', 'cluck', 'clued', 'clump', 'clung', 'coach', 'coast', 'cobra', 'cocoa', 'colon', 'color', 'comet', 'comfy', 'comic', 'comma', 'conch', 'condo', 'conic', 'copse', 'coral', 'corer', 'corny', 'couch', 'cough', 'could', 'count', 'coupe', 'court', 'coven', 'cover', 'covet', 'covey', 'cower', 'coyly', 'crack', 'craft', 'cramp', 'crane', 'crank', 'crash', 'crass', 'crate', 'crave', 'crawl', 'craze', 'crazy', 'creak', 'cream', 'credo', 'creed', 'creek', 'creep', 'creme', 'crepe', 'crept', 'cress', 'crest', 'crick', 'cried', 'crier', 'crime', 'crimp', 'crisp', 'croak', 'crock', 'crone', 'crony', 'crook', 'cross', 'croup', 'crowd', 'crown', 'crude', 'cruel', 'crumb', 'crump', 'crush', 'crust', 'crypt', 'cubic', 'cumin', 'curio', 'curly', 'curry', 'curse', 'curve', 'curvy', 'cutie', 'cyber', 'cycle', 'cynic', 'daddy', 'daily', 'dairy', 'daisy', 'dally', 'dance', 'dandy', 'datum', 'daunt', 'dealt', 'death', 'debar', 'debit', 'debug', 'debut', 'decal', 'decay', 'decor', 'decoy', 'decry', 'defer', 'deign', 'deity', 'delay', 'delta', 'delve', 'demon', 'demur', 'denim', 'dense', 'depot', 'depth', 'derby', 'deter', 'detox', 'deuce', 'devil', 'diary', 'dicey', 'digit', 'dilly', 'dimly', 'diner', 'dingo', 'dingy', 'diode', 'dirge', 'dirty', 'disco', 'ditch', 'ditto', 'ditty', 'diver', 'dizzy', 'dodge', 'dodgy', 'dogma', 'doing', 'dolly', 'donor', 'donut', 'dopey', 'doubt', 'dough', 'dowdy', 'dowel', 'downy', 'dowry', 'dozen', 'draft', 'drain', 'drake', 'drama', 'drank', 'drape', 'drawl', 'drawn', 'dread', 'dream', 'dress', 'dried', 'drier', 'drift', 'drill', 'drink', 'drive', 'droit', 'droll', 'drone', 'drool', 'droop', 'dross', 'drove', 'drown', 'druid', 'drunk', 'dryer', 'dryly', 'duchy', 'dully', 'dummy', 'dumpy', 'dunce', 'dusky', 'dusty', 'dutch', 'duvet', 'dwarf', 'dwell', 'dwelt', 'dying', 'eager', 'eagle', 'early', 'earth', 'easel', 'eaten', 'eater', 'ebony', 'eclat', 'edict', 'edify', 'eerie', 'egret', 'eight', 'eject', 'eking', 'elate', 'elbow', 'elder', 'elect', 'elegy', 'elfin', 'elide', 'elite', 'elope', 'elude', 'email', 'embed', 'ember', 'emcee', 'empty', 'enact', 'endow', 'enema', 'enemy', 'enjoy', 'ennui', 'ensue', 'enter', 'entry', 'envoy', 'epoch', 'epoxy', 'equal', 'equip', 'erase', 'erect', 'erode', 'error', 'erupt', 'essay', 'ester', 'ether', 'ethic', 'ethos', 'etude', 'evade', 'event', 'every', 'evict', 'evoke', 'exact', 'exalt', 'excel', 'exert', 'exile', 'exist', 'expel', 'extol', 'extra', 'exult', 'eying', 'fable', 'facet', 'faint', 'fairy', 'faith', 'false', 'fancy', 'fanny', 'farce', 'fatal', 'fatty', 'fault', 'fauna', 'favor', 'feast', 'fecal', 'feign', 'fella', 'felon', 'femme', 'femur', 'fence', 'feral', 'ferry', 'fetal', 'fetch', 'fetid', 'fetus', 'fever', 'fewer', 'fiber', 'fibre', 'ficus', 'field', 'fiend', 'fiery', 'fifth', 'fifty', 'fight', 'filer', 'filet', 'filly', 'filmy', 'filth', 'final', 'finch', 'finer', 'first', 'fishy', 'fixer', 'fizzy', 'fjord', 'flack', 'flail', 'flair', 'flake', 'flaky', 'flame', 'flank', 'flare', 'flash', 'flask', 'fleck', 'fleet', 'flesh', 'flick', 'flier', 'fling', 'flint', 'flirt', 'float', 'flock', 'flood', 'floor', 'flora', 'floss', 'flour', 'flout', 'flown', 'fluff', 'fluid', 'fluke', 'flume', 'flung', 'flunk', 'flush', 'flute', 'flyer', 'foamy', 'focal', 'focus', 'foggy', 'foist', 'folio', 'folly', 'foray', 'force', 'forge', 'forgo', 'forte', 'forth', 'forty', 'forum', 'found', 'foyer', 'frail', 'frame', 'frank', 'fraud', 'freak', 'freed', 'freer', 'fresh', 'friar', 'fried', 'frill', 'frisk', 'fritz', 'frock', 'frond', 'front', 'frost', 'froth', 'frown', 'froze', 'fruit', 'fudge', 'fugue', 'fully', 'fungi', 'funky', 'funny', 'furor', 'furry', 'fussy', 'fuzzy', 'gaffe', 'gaily', 'gamer', 'gamma', 'gamut', 'gassy', 'gaudy', 'gauge', 'gaunt', 'gauze', 'gavel', 'gawky', 'gayer', 'gayly', 'gazer', 'gecko', 'geeky', 'geese', 'genie', 'genre', 'ghost', 'ghoul', 'giant', 'giddy', 'gipsy', 'girly', 'girth', 'given', 'giver', 'glade', 'gland', 'glare', 'glass', 'glaze', 'gleam', 'glean', 'glide', 'glint', 'gloat', 'globe', 'gloom', 'glory', 'gloss', 'glove', 'glyph', 'gnash', 'gnome', 'godly', 'going', 'golem', 'golly', 'gonad', 'goner', 'goody', 'gooey', 'goofy', 'goose', 'gorge', 'gouge', 'gourd', 'grace', 'grade', 'graft', 'grail', 'grain', 'grand', 'grant', 'grape', 'graph', 'grasp', 'grass', 'grate', 'grave', 'gravy', 'graze', 'great', 'greed', 'green', 'greet', 'grief', 'grill', 'grime', 'grimy', 'grind', 'gripe', 'groan', 'groin', 'groom', 'grope', 'gross', 'group', 'grout', 'grove', 'growl', 'grown', 'gruel', 'gruff', 'grunt', 'guard', 'guava', 'guess', 'guest', 'guide', 'guild', 'guile', 'guilt', 'guise', 'gulch', 'gully', 'gumbo', 'gummy', 'guppy', 'gusto', 'gusty', 'gypsy', 'habit', 'hairy', 'halve', 'handy', 'happy', 'hardy', 'harem', 'harpy', 'harry', 'harsh', 'haste', 'hasty', 'hatch', 'hater', 'haunt', 'haute', 'haven', 'havoc', 'hazel', 'heady', 'heard', 'heart', 'heath', 'heave', 'heavy', 'hedge', 'hefty', 'heist', 'helix', 'hello', 'hence', 'heron', 'hilly', 'hinge', 'hippo', 'hippy', 'hitch', 'hoard', 'hobby', 'hoist', 'holly', 'homer', 'honey', 'honor', 'horde', 'horny', 'horse', 'hotel', 'hotly', 'hound', 'house', 'hovel', 'hover', 'howdy', 'human', 'humid', 'humor', 'humph', 'humus', 'hunch', 'hunky', 'hurry', 'husky', 'hussy', 'hutch', 'hydro', 'hyena', 'hymen', 'hyper', 'icily', 'icing', 'ideal', 'idiom', 'idiot', 'idler', 'idyll', 'igloo', 'iliac', 'image', 'imbue', 'impel', 'imply', 'inane', 'inbox', 'incur', 'index', 'inept', 'inert', 'infer', 'ingot', 'inlay', 'inlet', 'inner', 'input', 'inter', 'intro', 'ionic', 'irate', 'irony', 'islet', 'issue', 'itchy', 'ivory', 'jaunt', 'jazzy', 'jelly', 'jerky', 'jetty', 'jewel', 'jiffy', 'joint', 'joist', 'joker', 'jolly', 'joust', 'judge', 'juice', 'juicy', 'jumbo', 'jumpy', 'junta', 'junto', 'juror', 'kappa', 'karma', 'kayak', 'kebab', 'khaki', 'kinky', 'kiosk', 'kitty', 'knack', 'knave', 'knead', 'kneed', 'kneel', 'knelt', 'knife', 'knock', 'knoll', 'known', 'koala', 'krill', 'label', 'labor', 'laden', 'ladle', 'lager', 'lance', 'lanky', 'lapel', 'lapse', 'large', 'larva', 'lasso', 'latch', 'later', 'lathe', 'latte', 'laugh', 'layer', 'leach', 'leafy', 'leaky', 'leant', 'leapt', 'learn', 'lease', 'leash', 'least', 'leave', 'ledge', 'leech', 'leery', 'lefty', 'legal', 'leggy', 'lemon', 'lemur', 'leper', 'level', 'lever', 'libel', 'liege', 'light', 'liken', 'lilac', 'limbo', 'limit', 'linen', 'liner', 'lingo', 'lipid', 'lithe', 'liver', 'livid', 'llama', 'loamy', 'loath', 'lobby', 'local', 'locus', 'lodge', 'lofty', 'logic', 'login', 'loopy', 'loose', 'lorry', 'loser', 'louse', 'lousy', 'lover', 'lower', 'lowly', 'loyal', 'lucid', 'lucky', 'lumen', 'lumpy', 'lunar', 'lunch', 'lunge', 'lupus', 'lurch', 'lurid', 'lusty', 'lying', 'lymph', 'lynch', 'lyric', 'macaw', 'macho', 'macro', 'madam', 'madly', 'mafia', 'magic', 'magma', 'maize', 'major', 'maker', 'mambo', 'mamma', 'mammy', 'manga', 'mange', 'mango', 'mangy', 'mania', 'manic', 'manly', 'manor', 'maple', 'march', 'marry', 'marsh', 'mason', 'masse', 'match', 'matey', 'mauve', 'maxim', 'maybe', 'mayor', 'mealy', 'meant', 'meaty', 'mecca', 'medal', 'media', 'medic', 'melee', 'melon', 'mercy', 'merge', 'merit', 'merry', 'metal', 'meter', 'metro', 'micro', 'midge', 'midst', 'might', 'milky', 'mimic', 'mince', 'miner', 'minim', 'minor', 'minty', 'minus', 'mirth', 'miser', 'missy', 'mocha', 'modal', 'model', 'modem', 'mogul', 'moist', 'molar', 'moldy', 'money', 'month', 'moody', 'moose', 'moral', 'moron', 'morph', 'mossy', 'motel', 'motif', 'motor', 'motto', 'moult', 'mound', 'mount', 'mourn', 'mouse', 'mouth', 'mover', 'movie', 'mower', 'mucky', 'mucus', 'muddy', 'mulch', 'mummy', 'munch', 'mural', 'murky', 'mushy', 'music', 'musky', 'musty', 'myrrh', 'nadir', 'naive', 'nanny', 'nasal', 'nasty', 'natal', 'naval', 'navel', 'needy', 'neigh', 'nerdy', 'nerve', 'never', 'newer', 'newly', 'nicer', 'niche', 'niece', 'night', 'ninja', 'ninny', 'ninth', 'noble', 'nobly', 'noise', 'noisy', 'nomad', 'noose', 'north', 'nosey', 'notch', 'novel', 'nudge', 'nurse', 'nutty', 'nylon', 'nymph', 'oaken', 'obese', 'occur', 'ocean', 'octal', 'octet', 'odder', 'oddly', 'offal', 'offer', 'often', 'olden', 'older', 'olive', 'ombre', 'omega', 'onion', 'onset', 'opera', 'opine', 'opium', 'optic', 'orbit', 'order', 'organ', 'other', 'otter', 'ought', 'ounce', 'outdo', 'outer', 'outgo', 'ovary', 'ovate', 'overt', 'ovine', 'ovoid', 'owing', 'owner', 'oxide', 'ozone', 'paddy', 'pagan', 'paint', 'paler', 'palsy', 'panel', 'panic', 'pansy', 'papal', 'paper', 'parer', 'parka', 'parry', 'parse', 'party', 'pasta', 'paste', 'pasty', 'patch', 'patio', 'patsy', 'patty', 'pause', 'payee', 'payer', 'peace', 'peach', 'pearl', 'pecan', 'pedal', 'penal', 'pence', 'penne', 'penny', 'perch', 'peril', 'perky', 'pesky', 'pesto', 'petal', 'petty', 'phase', 'phone', 'phony', 'photo', 'piano', 'picky', 'piece', 'piety', 'piggy', 'pilot', 'pinch', 'piney', 'pinky', 'pinto', 'piper', 'pique', 'pitch', 'pithy', 'pivot', 'pixel', 'pixie', 'pizza', 'place', 'plaid', 'plain', 'plait', 'plane', 'plank', 'plant', 'plate', 'plaza', 'plead', 'pleat', 'plied', 'plier', 'pluck', 'plumb', 'plume', 'plump', 'plunk', 'plush', 'poesy', 'point', 'poise', 'poker', 'polar', 'polka', 'polyp', 'pooch', 'poppy', 'porch', 'poser', 'posit', 'posse', 'pouch', 'pound', 'pouty', 'power', 'prank', 'prawn', 'preen', 'press', 'price', 'prick', 'pride', 'pried', 'prime', 'primo', 'print', 'prior', 'prism', 'privy', 'prize', 'probe', 'prone', 'prong', 'proof', 'prose', 'proud', 'prove', 'prowl', 'proxy', 'prude', 'prune', 'psalm', 'pubic', 'pudgy', 'puffy', 'pulpy', 'pulse', 'punch', 'pupal', 'pupil', 'puppy', 'puree', 'purer', 'purge', 'purse', 'pushy', 'putty', 'pygmy', 'quack', 'quail', 'quake', 'qualm', 'quark', 'quart', 'quash', 'quasi', 'queen', 'queer', 'quell', 'query', 'quest', 'queue', 'quick', 'quiet', 'quill', 'quilt', 'quirk', 'quite', 'quota', 'quote', 'quoth', 'rabbi', 'rabid', 'racer', 'radar', 'radii', 'radio', 'rainy', 'raise', 'rajah', 'rally', 'ralph', 'ramen', 'ranch', 'randy', 'range', 'rapid', 'rarer', 'raspy', 'ratio', 'ratty', 'raven', 'rayon', 'razor', 'reach', 'react', 'ready', 'realm', 'rearm', 'rebar', 'rebel', 'rebus', 'rebut', 'recap', 'recur', 'recut', 'reedy', 'refer', 'refit', 'regal', 'rehab', 'reign', 'relax', 'relay', 'relic', 'remit', 'renal', 'renew', 'repay', 'repel', 'reply', 'rerun', 'reset', 'resin', 'retch', 'retro', 'retry', 'reuse', 'revel', 'revue', 'rhino', 'rhyme', 'rider', 'ridge', 'rifle', 'right', 'rigid', 'rigor', 'rinse', 'ripen', 'riper', 'risen', 'riser', 'risky', 'rival', 'river', 'rivet', 'roach', 'roast', 'robin', 'robot', 'rocky', 'rodeo', 'roger', 'rogue', 'roomy', 'roost', 'rotor', 'rouge', 'rough', 'round', 'rouse', 'route', 'rover', 'rowdy', 'rower', 'royal', 'ruddy', 'ruder', 'rugby', 'ruler', 'rumba', 'rumor', 'rupee', 'rural', 'rusty', 'sadly', 'safer', 'saint', 'salad', 'sally', 'salon', 'salsa', 'salty', 'salve', 'salvo', 'sandy', 'saner', 'sappy', 'sassy', 'satin', 'satyr', 'sauce', 'saucy', 'sauna', 'saute', 'savor', 'savoy', 'savvy', 'scald', 'scale', 'scalp', 'scaly', 'scamp', 'scant', 'scare', 'scarf', 'scary', 'scene', 'scent', 'scion', 'scoff', 'scold', 'scone', 'scoop', 'scope', 'score', 'scorn', 'scour', 'scout', 'scowl', 'scram', 'scrap', 'scree', 'screw', 'scrub', 'scrum', 'scuba', 'sedan', 'seedy', 'segue', 'seize', 'semen', 'sense', 'sepia', 'serif', 'serum', 'serve', 'setup', 'seven', 'sever', 'sewer', 'shack', 'shade', 'shady', 'shaft', 'shake', 'shaky', 'shale', 'shall', 'shalt', 'shame', 'shank', 'shape', 'shard', 'share', 'shark', 'sharp', 'shave', 'shawl', 'shear', 'sheen', 'sheep', 'sheer', 'sheet', 'sheik', 'shelf', 'shell', 'shied', 'shift', 'shine', 'shiny', 'shire', 'shirk', 'shirt', 'shoal', 'shock', 'shone', 'shook', 'shoot', 'shore', 'shorn', 'short', 'shout', 'shove', 'shown', 'showy', 'shrew', 'shrub', 'shrug', 'shuck', 'shunt', 'shush', 'shyly', 'siege', 'sieve', 'sight', 'sigma', 'silky', 'silly', 'since', 'sinew', 'singe', 'siren', 'sissy', 'sixth', 'sixty', 'skate', 'skier', 'skiff', 'skill', 'skimp', 'skirt', 'skulk', 'skull', 'skunk', 'slack', 'slain', 'slang', 'slant', 'slash', 'slate', 'slave', 'sleek', 'sleep', 'sleet', 'slept', 'slice', 'slick', 'slide', 'slime', 'slimy', 'sling', 'slink', 'sloop', 'slope', 'slosh', 'sloth', 'slump', 'slung', 'slunk', 'slurp', 'slush', 'slyly', 'smack', 'small', 'smart', 'smash', 'smear', 'smell', 'smelt', 'smile', 'smirk', 'smite', 'smith', 'smock', 'smoke', 'smoky', 'smote', 'snack', 'snail', 'snake', 'snaky', 'snare', 'snarl', 'sneak', 'sneer', 'snide', 'sniff', 'snipe', 'snoop', 'snore', 'snort', 'snout', 'snowy', 'snuck', 'snuff', 'soapy', 'sober', 'soggy', 'solar', 'solid', 'solve', 'sonar', 'sonic', 'sooth', 'sooty', 'sorry', 'sound', 'south', 'sower', 'space', 'spade', 'spank', 'spare', 'spark', 'spasm', 'spawn', 'speak', 'spear', 'speck', 'speed', 'spell', 'spelt', 'spend', 'spent', 'sperm', 'spice', 'spicy', 'spied', 'spiel', 'spike', 'spiky', 'spill', 'spilt', 'spine', 'spiny', 'spire', 'spite', 'splat', 'split', 'spoil', 'spoke', 'spoof', 'spook', 'spool', 'spoon', 'spore', 'sport', 'spout', 'spray', 'spree', 'sprig', 'spunk', 'spurn', 'spurt', 'squad', 'squat', 'squib', 'stack', 'staff', 'stage', 'staid', 'stain', 'stair', 'stake', 'stale', 'stalk', 'stall', 'stamp', 'stand', 'stank', 'stare', 'stark', 'start', 'stash', 'state', 'stave', 'stead', 'steak', 'steal', 'steam', 'steed', 'steel', 'steep', 'steer', 'stein', 'stern', 'stick', 'stiff', 'still', 'stilt', 'sting', 'stink', 'stint', 'stock', 'stoic', 'stoke', 'stole', 'stomp', 'stone', 'stony', 'stood', 'stool', 'stoop', 'store', 'stork', 'storm', 'story', 'stout', 'stove', 'strap', 'straw', 'stray', 'strip', 'strut', 'stuck', 'study', 'stuff', 'stump', 'stung', 'stunk', 'stunt', 'style', 'suave', 'sugar', 'suing', 'suite', 'sulky', 'sully', 'sumac', 'sunny', 'super', 'surer', 'surge', 'surly', 'sushi', 'swami', 'swamp', 'swarm', 'swash', 'swath', 'swear', 'sweat', 'sweep', 'sweet', 'swell', 'swept', 'swift', 'swill', 'swine', 'swing', 'swirl', 'swish', 'swoon', 'swoop', 'sword', 'swore', 'sworn', 'swung', 'synod', 'syrup', 'tabby', 'table', 'taboo', 'tacit', 'tacky', 'taffy', 'taint', 'taken', 'taker', 'tally', 'talon', 'tamer', 'tango', 'tangy', 'taper', 'tapir', 'tardy', 'tarot', 'taste', 'tasty', 'tatty', 'taunt', 'tawny', 'teach', 'teary', 'tease', 'teddy', 'teeth', 'tempo', 'tenet', 'tenor', 'tense', 'tenth', 'tepee', 'tepid', 'terra', 'terse', 'testy', 'thank', 'theft', 'their', 'theme', 'there', 'these', 'theta', 'thick', 'thief', 'thigh', 'thing', 'think', 'third', 'thong', 'thorn', 'those', 'three', 'threw', 'throb', 'throw', 'thrum', 'thumb', 'thump', 'thyme', 'tiara', 'tibia', 'tidal', 'tiger', 'tight', 'tilde', 'timer', 'timid', 'tipsy', 'titan', 'tithe', 'title', 'toast', 'today', 'toddy', 'token', 'tonal', 'tonga', 'tonic', 'tooth', 'topaz', 'topic', 'torch', 'torso', 'torus', 'total', 'totem', 'touch', 'tough', 'towel', 'tower', 'toxic', 'toxin', 'trace', 'track', 'tract', 'trade', 'trail', 'train', 'trait', 'tramp', 'trash', 'trawl', 'tread', 'treat', 'trend', 'triad', 'trial', 'tribe', 'trice', 'trick', 'tried', 'tripe', 'trite', 'troll', 'troop', 'trope', 'trout', 'trove', 'truce', 'truck', 'truer', 'truly', 'trump', 'trunk', 'truss', 'trust', 'truth', 'tryst', 'tubal', 'tuber', 'tulip', 'tulle', 'tumor', 'tunic', 'turbo', 'tutor', 'twang', 'tweak', 'tweed', 'tweet', 'twice', 'twine', 'twirl', 'twist', 'twixt', 'tying', 'udder', 'ulcer', 'ultra', 'umbra', 'uncle', 'uncut', 'under', 'undid', 'undue', 'unfed', 'unfit', 'unify', 'union', 'unite', 'unity', 'unlit', 'unmet', 'unset', 'untie', 'until', 'unwed', 'unzip', 'upper', 'upset', 'urban', 'urine', 'usage', 'usher', 'using', 'usual', 'usurp', 'utile', 'utter', 'vague', 'valet', 'valid', 'valor', 'value', 'valve', 'vapid', 'vapor', 'vault', 'vaunt', 'vegan', 'venom', 'venue', 'verge', 'verse', 'verso', 'verve', 'vicar', 'video', 'vigil', 'vigor', 'villa', 'vinyl', 'viola', 'viper', 'viral', 'virus', 'visit', 'visor', 'vista', 'vital', 'vivid', 'vixen', 'vocal', 'vodka', 'vogue', 'voice', 'voila', 'vomit', 'voter', 'vouch', 'vowel', 'vying', 'wacky', 'wafer', 'wager', 'wagon', 'waist', 'waive', 'waltz', 'warty', 'waste', 'watch', 'water', 'waver', 'waxen', 'weary', 'weave', 'wedge', 'weedy', 'weigh', 'weird', 'welch', 'welsh', 'wench', 'whack', 'whale', 'wharf', 'wheat', 'wheel', 'whelp', 'where', 'which', 'whiff', 'while', 'whine', 'whiny', 'whirl', 'whisk', 'white', 'whole', 'whoop', 'whose', 'widen', 'wider', 'widow', 'width', 'wield', 'wight', 'willy', 'wimpy', 'wince', 'winch', 'windy', 'wiser', 'wispy', 'witch', 'witty', 'woken', 'woman', 'women', 'woody', 'wooer', 'wooly', 'woozy', 'wordy', 'world', 'worry', 'worse', 'worst', 'worth', 'would', 'wound', 'woven', 'wrack', 'wrath', 'wreak', 'wreck', 'wrest', 'wring', 'wrist', 'write', 'wrong', 'wrote', 'wrung', 'wryly', 'yacht', 'yearn', 'yeast', 'yield', 'young', 'youth', 'zebra', 'zesty', 'zonal', ]; /** The list of valid guesses, of which the list of possible words is a subset */ export const allowed = new Set([ ...words, 'aahed', 'aalii', 'aargh', 'aarti', 'abaca', 'abaci', 'abacs', 'abaft', 'abaka', 'abamp', 'aband', 'abash', 'abask', 'abaya', 'abbas', 'abbed', 'abbes', 'abcee', 'abeam', 'abear', 'abele', 'abers', 'abets', 'abies', 'abler', 'ables', 'ablet', 'ablow', 'abmho', 'abohm', 'aboil', 'aboma', 'aboon', 'abord', 'abore', 'abram', 'abray', 'abrim', 'abrin', 'abris', 'absey', 'absit', 'abuna', 'abune', 'abuts', 'abuzz', 'abyes', 'abysm', 'acais', 'acari', 'accas', 'accoy', 'acerb', 'acers', 'aceta', 'achar', 'ached', 'aches', 'achoo', 'acids', 'acidy', 'acing', 'acini', 'ackee', 'acker', 'acmes', 'acmic', 'acned', 'acnes', 'acock', 'acold', 'acred', 'acres', 'acros', 'acted', 'actin', 'acton', 'acyls', 'adaws', 'adays', 'adbot', 'addax', 'added', 'adder', 'addio', 'addle', 'adeem', 'adhan', 'adieu', 'adios', 'adits', 'adman', 'admen', 'admix', 'adobo', 'adown', 'adoze', 'adrad', 'adred', 'adsum', 'aduki', 'adunc', 'adust', 'advew', 'adyta', 'adzed', 'adzes', 'aecia', 'aedes', 'aegis', 'aeons', 'aerie', 'aeros', 'aesir', 'afald', 'afara', 'afars', 'afear', 'aflaj', 'afore', 'afrit', 'afros', 'agama', 'agami', 'agars', 'agast', 'agave', 'agaze', 'agene', 'agers', 'agger', 'aggie', 'aggri', 'aggro', 'aggry', 'aghas', 'agila', 'agios', 'agism', 'agist', 'agita', 'aglee', 'aglet', 'agley', 'agloo', 'aglus', 'agmas', 'agoge', 'agone', 'agons', 'agood', 'agria', 'agrin', 'agros', 'agued', 'agues', 'aguna', 'aguti', 'aheap', 'ahent', 'ahigh', 'ahind', 'ahing', 'ahint', 'ahold', 'ahull', 'ahuru', 'aidas', 'aided', 'aides', 'aidoi', 'aidos', 'aiery', 'aigas', 'aight', 'ailed', 'aimed', 'aimer', 'ainee', 'ainga', 'aioli', 'aired', 'airer', 'airns', 'airth', 'airts', 'aitch', 'aitus', 'aiver', 'aiyee', 'aizle', 'ajies', 'ajiva', 'ajuga', 'ajwan', 'akees', 'akela', 'akene', 'aking', 'akita', 'akkas', 'alaap', 'alack', 'alamo', 'aland', 'alane', 'alang', 'alans', 'alant', 'alapa', 'alaps', 'alary', 'alate', 'alays', 'albas', 'albee', 'alcid', 'alcos', 'aldea', 'alder', 'aldol', 'aleck', 'alecs', 'alefs', 'aleft', 'aleph', 'alews', 'aleye', 'alfas', 'algal', 'algas', 'algid', 'algin', 'algor', 'algum', 'alias', 'alifs', 'aline', 'alist', 'aliya', 'alkie', 'alkos', 'alkyd', 'alkyl', 'allee', 'allel', 'allis', 'allod', 'allyl', 'almah', 'almas', 'almeh', 'almes', 'almud', 'almug', 'alods', 'aloed', 'aloes', 'aloha', 'aloin', 'aloos', 'alowe', 'altho', 'altos', 'alula', 'alums', 'alure', 'alvar', 'alway', 'amahs', 'amain', 'amate', 'amaut', 'amban', 'ambit', 'ambos', 'ambry', 'ameba', 'ameer', 'amene', 'amens', 'ament', 'amias', 'amice', 'amici', 'amide', 'amido', 'amids', 'amies', 'amiga', 'amigo', 'amine', 'amino', 'amins', 'amirs', 'amlas', 'amman', 'ammon', 'ammos', 'amnia', 'amnic', 'amnio', 'amoks', 'amole', 'amort', 'amour', 'amove', 'amowt', 'amped', 'ampul', 'amrit', 'amuck', 'amyls', 'anana', 'anata', 'ancho', 'ancle', 'ancon', 'andro', 'anear', 'anele', 'anent', 'angas', 'anglo', 'anigh', 'anile', 'anils', 'anima', 'animi', 'anion', 'anise', 'anker', 'ankhs', 'ankus', 'anlas', 'annal', 'annas', 'annat', 'anoas', 'anole', 'anomy', 'ansae', 'antae', 'antar', 'antas', 'anted', 'antes', 'antis', 'antra', 'antre', 'antsy', 'anura', 'anyon', 'apace', 'apage', 'apaid', 'apayd', 'apays', 'apeak', 'apeek', 'apers', 'apert', 'apery', 'apgar', 'aphis', 'apian', 'apiol', 'apish', 'apism', 'apode', 'apods', 'apoop', 'aport', 'appal', 'appay', 'appel', 'appro', 'appui', 'appuy', 'apres', 'apses', 'apsis', 'apsos', 'apted', 'apter', 'aquae', 'aquas', 'araba', 'araks', 'arame', 'arars', 'arbas', 'arced', 'archi', 'arcos', 'arcus', 'ardeb', 'ardri', 'aread', 'areae', 'areal', 'arear', 'areas', 'areca', 'aredd', 'arede', 'arefy', 'areic', 'arene', 'arepa', 'arere', 'arete', 'arets', 'arett', 'argal', 'argan', 'argil', 'argle', 'argol', 'argon', 'argot', 'argus', 'arhat', 'arias', 'ariel', 'ariki', 'arils', 'ariot', 'arish', 'arked', 'arled', 'arles', 'armed', 'armer', 'armet', 'armil', 'arnas', 'arnut', 'aroba', 'aroha', 'aroid', 'arpas', 'arpen', 'arrah', 'arras', 'arret', 'arris', 'arroz', 'arsed', 'arses', 'arsey', 'arsis', 'artal', 'artel', 'artic', 'artis', 'aruhe', 'arums', 'arval', 'arvee', 'arvos', 'aryls', 'asana', 'ascon', 'ascus', 'asdic', 'ashed', 'ashes', 'ashet', 'asked', 'asker', 'askoi', 'askos', 'aspen', 'asper', 'aspic', 'aspie', 'aspis', 'aspro', 'assai', 'assam', 'asses', 'assez', 'assot', 'aster', 'astir', 'astun', 'asura', 'asway', 'aswim', 'asyla', 'ataps', 'ataxy', 'atigi', 'atilt', 'atimy', 'atlas', 'atman', 'atmas', 'atmos', 'atocs', 'atoke', 'atoks', 'atoms', 'atomy', 'atony', 'atopy', 'atria', 'atrip', 'attap', 'attar', 'atuas', 'audad', 'auger', 'aught', 'aulas', 'aulic', 'auloi', 'aulos', 'aumil', 'aunes', 'aunts', 'aurae', 'aural', 'aurar', 'auras', 'aurei', 'aures', 'auric', 'auris', 'aurum', 'autos', 'auxin', 'avale', 'avant', 'avast', 'avels', 'avens', 'avers', 'avgas', 'avine', 'avion', 'avise', 'aviso', 'avize', 'avows', 'avyze', 'awarn', 'awato', 'awave', 'aways', 'awdls', 'aweel', 'aweto', 'awing', 'awmry', 'awned', 'awner', 'awols', 'awork', 'axels', 'axile', 'axils', 'axing', 'axite', 'axled', 'axles', 'axman', 'axmen', 'axoid', 'axone', 'axons', 'ayahs', 'ayaya', 'ayelp', 'aygre', 'ayins', 'ayont', 'ayres', 'ayrie', 'azans', 'azide', 'azido', 'azine', 'azlon', 'azoic', 'azole', 'azons', 'azote', 'azoth', 'azuki', 'azurn', 'azury', 'azygy', 'azyme', 'azyms', 'baaed', 'baals', 'babas', 'babel', 'babes', 'babka', 'baboo', 'babul', 'babus', 'bacca', 'bacco', 'baccy', 'bacha', 'bachs', 'backs', 'baddy', 'baels', 'baffs', 'baffy', 'bafts', 'baghs', 'bagie', 'bahts', 'bahus', 'bahut', 'bails', 'bairn', 'baisa', 'baith', 'baits', 'baiza', 'baize', 'bajan', 'bajra', 'bajri', 'bajus', 'baked', 'baken', 'bakes', 'bakra', 'balas', 'balds', 'baldy', 'baled', 'bales', 'balks', 'balky', 'balls', 'bally', 'balms', 'baloo', 'balsa', 'balti', 'balun', 'balus', 'bambi', 'banak', 'banco', 'bancs', 'banda', 'bandh', 'bands', 'bandy', 'baned', 'banes', 'bangs', 'bania', 'banks', 'banns', 'bants', 'bantu', 'banty', 'banya', 'bapus', 'barbe', 'barbs', 'barby', 'barca', 'barde', 'bardo', 'bards', 'bardy', 'bared', 'barer', 'bares', 'barfi', 'barfs', 'baric', 'barks', 'barky', 'barms', 'barmy', 'barns', 'barny', 'barps', 'barra', 'barre', 'barro', 'barry', 'barye', 'basan', 'based', 'basen', 'baser', 'bases', 'basho', 'basij', 'basks', 'bason', 'basse', 'bassi', 'basso', 'bassy', 'basta', 'basti', 'basto', 'basts', 'bated', 'bates', 'baths', 'batik', 'batta', 'batts', 'battu', 'bauds', 'bauks', 'baulk', 'baurs', 'bavin', 'bawds', 'bawks', 'bawls', 'bawns', 'bawrs', 'bawty', 'bayed', 'bayer', 'bayes', 'bayle', 'bayts', 'bazar', 'bazoo', 'beads', 'beaks', 'beaky', 'beals', 'beams', 'beamy', 'beano', 'beans', 'beany', 'beare', 'bears', 'beath', 'beats', 'beaty', 'beaus', 'beaut', 'beaux', 'bebop', 'becap', 'becke', 'becks', 'bedad', 'bedel', 'bedes', 'bedew', 'bedim', 'bedye', 'beedi', 'beefs', 'beeps', 'beers', 'beery', 'beets', 'befog', 'begad', 'begar', 'begem', 'begot', 'begum', 'beige', 'beigy', 'beins', 'bekah', 'belah', 'belar', 'belay', 'belee', 'belga', 'bells', 'belon', 'belts', 'bemad', 'bemas', 'bemix', 'bemud', 'bends', 'bendy', 'benes', 'benet', 'benga', 'benis', 'benne', 'benni', 'benny', 'bento', 'bents', 'benty', 'bepat', 'beray', 'beres', 'bergs', 'berko', 'berks', 'berme', 'berms', 'berob', 'beryl', 'besat', 'besaw', 'besee', 'beses', 'besit', 'besom', 'besot', 'besti', 'bests', 'betas', 'beted', 'betes', 'beths', 'betid', 'beton', 'betta', 'betty', 'bever', 'bevor', 'bevue', 'bevvy', 'bewet', 'bewig', 'bezes', 'bezil', 'bezzy', 'bhais', 'bhaji', 'bhang', 'bhats', 'bhels', 'bhoot', 'bhuna', 'bhuts', 'biach', 'biali', 'bialy', 'bibbs', 'bibes', 'biccy', 'bices', 'bided', 'bider', 'bides', 'bidet', 'bidis', 'bidon', 'bield', 'biers', 'biffo', 'biffs', 'biffy', 'bifid', 'bigae', 'biggs', 'biggy', 'bigha', 'bight', 'bigly', 'bigos', 'bijou', 'biked', 'biker', 'bikes', 'bikie', 'bilbo', 'bilby', 'biled', 'biles', 'bilgy', 'bilks', 'bills', 'bimah', 'bimas', 'bimbo', 'binal', 'bindi', 'binds', 'biner', 'bines', 'bings', 'bingy', 'binit', 'binks', 'bints', 'biogs', 'biont', 'biota', 'biped', 'bipod', 'birds', 'birks', 'birle', 'birls', 'biros', 'birrs', 'birse', 'birsy', 'bises', 'bisks', 'bisom', 'bitch', 'biter', 'bites', 'bitos', 'bitou', 'bitsy', 'bitte', 'bitts', 'bivia', 'bivvy', 'bizes', 'bizzo', 'bizzy', 'blabs', 'blads', 'blady', 'blaer', 'blaes', 'blaff', 'blags', 'blahs', 'blain', 'blams', 'blart', 'blase', 'blash', 'blate', 'blats', 'blatt', 'blaud', 'blawn', 'blaws', 'blays', 'blear', 'blebs', 'blech', 'blees', 'blent', 'blert', 'blest', 'blets', 'bleys', 'blimy', 'bling', 'blini', 'blins', 'bliny', 'blips', 'blist', 'blite', 'blits', 'blive', 'blobs', 'blocs', 'blogs', 'blook', 'bloop', 'blore', 'blots', 'blows', 'blowy', 'blubs', 'blude', 'bluds', 'bludy', 'blued', 'blues', 'bluet', 'bluey', 'bluid', 'blume', 'blunk', 'blurs', 'blype', 'boabs', 'boaks', 'boars', 'boart', 'boats', 'bobac', 'bobak', 'bobas', 'bobol', 'bobos', 'bocca', 'bocce', 'bocci', 'boche', 'bocks', 'boded', 'bodes', 'bodge', 'bodhi', 'bodle', 'boeps', 'boets', 'boeuf', 'boffo', 'boffs', 'bogan', 'bogey', 'boggy', 'bogie', 'bogle', 'bogue', 'bogus', 'bohea', 'bohos', 'boils', 'boing', 'boink', 'boite', 'boked', 'bokeh', 'bokes', 'bokos', 'bolar', 'bolas', 'bolds', 'boles', 'bolix', 'bolls', 'bolos', 'bolts', 'bolus', 'bomas', 'bombe', 'bombo', 'bombs', 'bonce', 'bonds', 'boned', 'boner', 'bones', 'bongs', 'bonie', 'bonks', 'bonne', 'bonny', 'bonza', 'bonze', 'booai', 'booay', 'boobs', 'boody', 'booed', 'boofy', 'boogy', 'boohs', 'books', 'booky', 'bools', 'booms', 'boomy', 'boong', 'boons', 'boord', 'boors', 'boose', 'boots', 'boppy', 'borak', 'boral', 'boras', 'borde', 'bords', 'bored', 'boree', 'borel', 'borer', 'bores', 'borgo', 'boric', 'borks', 'borms', 'borna', 'boron', 'borts', 'borty', 'bortz', 'bosie', 'bosks', 'bosky', 'boson', 'bosun', 'botas', 'botel', 'botes', 'bothy', 'botte', 'botts', 'botty', 'bouge', 'bouks', 'boult', 'bouns', 'bourd', 'bourg', 'bourn', 'bouse', 'bousy', 'bouts', 'bovid', 'bowat', 'bowed', 'bower', 'bowes', 'bowet', 'bowie', 'bowls', 'bowne', 'bowrs', 'bowse', 'boxed', 'boxen', 'boxes', 'boxla', 'boxty', 'boyar', 'boyau', 'boyed', 'boyfs', 'boygs', 'boyla', 'boyos', 'boysy', 'bozos', 'braai', 'brach', 'brack', 'bract', 'brads', 'braes', 'brags', 'brail', 'braks', 'braky', 'brame', 'brane', 'brank', 'brans', 'brant', 'brast', 'brats', 'brava', 'bravi', 'braws', 'braxy', 'brays', 'braza', 'braze', 'bream', 'brede', 'breds', 'breem', 'breer', 'brees', 'breid', 'breis', 'breme', 'brens', 'brent', 'brere', 'brers', 'breve', 'brews', 'breys', 'brier', 'bries', 'brigs', 'briki', 'briks', 'brill', 'brims', 'brins', 'brios', 'brise', 'briss', 'brith', 'brits', 'britt', 'brize', 'broch', 'brock', 'brods', 'brogh', 'brogs', 'brome', 'bromo', 'bronc', 'brond', 'brool', 'broos', 'brose', 'brosy', 'brows', 'brugh', 'bruin', 'bruit', 'brule', 'brume', 'brung', 'brusk', 'brust', 'bruts', 'buats', 'buaze', 'bubal', 'bubas', 'bubba', 'bubbe', 'bubby', 'bubus', 'buchu', 'bucko', 'bucks', 'bucku', 'budas', 'budis', 'budos', 'buffa', 'buffe', 'buffi', 'buffo', 'buffs', 'buffy', 'bufos', 'bufty', 'buhls', 'buhrs', 'buiks', 'buist', 'bukes', 'bulbs', 'bulgy', 'bulks', 'bulla', 'bulls', 'bulse', 'bumbo', 'bumfs', 'bumph', 'bumps', 'bumpy', 'bunas', 'bunce', 'bunco', 'bunde', 'bundh', 'bunds', 'bundt', 'bundu', 'bundy', 'bungs', 'bungy', 'bunia', 'bunje', 'bunjy', 'bunko', 'bunks', 'bunns', 'bunts', 'bunty', 'bunya', 'buoys', 'buppy', 'buran', 'buras', 'burbs', 'burds', 'buret', 'burfi', 'burgh', 'burgs', 'burin', 'burka', 'burke', 'burks', 'burls', 'burns', 'buroo', 'burps', 'burqa', 'burro', 'burrs', 'burry', 'bursa', 'burse', 'busby', 'buses', 'busks', 'busky', 'bussu', 'busti', 'busts', 'busty', 'buteo', 'butes', 'butle', 'butoh', 'butts', 'butty', 'butut', 'butyl', 'buzzy', 'bwana', 'bwazi', 'byded', 'bydes', 'byked', 'bykes', 'byres', 'byrls', 'byssi', 'bytes', 'byway', 'caaed', 'cabas', 'caber', 'cabob', 'caboc', 'cabre', 'cacas', 'cacks', 'cacky', 'cadee', 'cades', 'cadge', 'cadgy', 'cadie', 'cadis', 'cadre', 'caeca', 'caese', 'cafes', 'caffs', 'caged', 'cager', 'cages', 'cagot', 'cahow', 'caids', 'cains', 'caird', 'cajon', 'cajun', 'caked', 'cakes', 'cakey', 'calfs', 'calid', 'calif', 'calix', 'calks', 'calla', 'calls', 'calms', 'calmy', 'calos', 'calpa', 'calps', 'calve', 'calyx', 'caman', 'camas', 'cames', 'camis', 'camos', 'campi', 'campo', 'camps', 'campy', 'camus', 'caned', 'caneh', 'caner', 'canes', 'cangs', 'canid', 'canna', 'canns', 'canso', 'canst', 'canto', 'cants', 'canty', 'capas', 'caped', 'capes', 'capex', 'caphs', 'capiz', 'caple', 'capon', 'capos', 'capot', 'capri', 'capul', 'carap', 'carbo', 'carbs', 'carby', 'cardi', 'cards', 'cardy', 'cared', 'carer', 'cares', 'caret', 'carex', 'carks', 'carle', 'carls', 'carns', 'carny', 'carob', 'carom', 'caron', 'carpi', 'carps', 'carrs', 'carse', 'carta', 'carte', 'carts', 'carvy', 'casas', 'casco', 'cased', 'cases', 'casks', 'casky', 'casts', 'casus', 'cates', 'cauda', 'cauks', 'cauld', 'cauls', 'caums', 'caups', 'cauri', 'causa', 'cavas', 'caved', 'cavel', 'caver', 'caves', 'cavie', 'cawed', 'cawks', 'caxon', 'ceaze', 'cebid', 'cecal', 'cecum', 'ceded', 'ceder', 'cedes', 'cedis', 'ceiba', 'ceili', 'ceils', 'celeb', 'cella', 'celli', 'cells', 'celom', 'celts', 'cense', 'cento', 'cents', 'centu', 'ceorl', 'cepes', 'cerci', 'cered', 'ceres', 'cerge', 'ceria', 'ceric', 'cerne', 'ceroc', 'ceros', 'certs', 'certy', 'cesse', 'cesta', 'cesti', 'cetes', 'cetyl', 'cezve', 'chace', 'chack', 'chaco', 'chado', 'chads', 'chaft', 'chais', 'chals', 'chams', 'chana', 'chang', 'chank', 'chape', 'chaps', 'chapt', 'chara', 'chare', 'chark', 'charr', 'chars', 'chary', 'chats', 'chave', 'chavs', 'chawk', 'chaws', 'chaya', 'chays', 'cheep', 'chefs', 'cheka', 'chela', 'chelp', 'chemo', 'chems', 'chere', 'chert', 'cheth', 'chevy', 'chews', 'chewy', 'chiao', 'chias', 'chibs', 'chica', 'chich', 'chico', 'chics', 'chiel', 'chiks', 'chile', 'chimb', 'chimo', 'chimp', 'chine', 'ching', 'chink', 'chino', 'chins', 'chips', 'chirk', 'chirl', 'chirm', 'chiro', 'chirr', 'chirt', 'chiru', 'chits', 'chive', 'chivs', 'chivy', 'chizz', 'choco', 'chocs', 'chode', 'chogs', 'choil', 'choko', 'choky', 'chola', 'choli', 'cholo', 'chomp', 'chons', 'choof', 'chook', 'choom', 'choon', 'chops', 'chota', 'chott', 'chout', 'choux', 'chowk', 'chows', 'chubs', 'chufa', 'chuff', 'chugs', 'chums', 'churl', 'churr', 'chuse', 'chuts', 'chyle', 'chyme', 'chynd', 'cibol', 'cided', 'cides', 'ciels', 'ciggy', 'cilia', 'cills', 'cimar', 'cimex', 'cinct', 'cines', 'cinqs', 'cions', 'cippi', 'circs', 'cires', 'cirls', 'cirri', 'cisco', 'cissy', 'cists', 'cital', 'cited', 'citer', 'cites', 'cives', 'civet', 'civie', 'civvy', 'clach', 'clade', 'clads', 'claes', 'clags', 'clame', 'clams', 'clans', 'claps', 'clapt', 'claro', 'clart', 'clary', 'clast', 'clats', 'claut', 'clave', 'clavi', 'claws', 'clays', 'cleck', 'cleek', 'cleep', 'clefs', 'clegs', 'cleik', 'clems', 'clepe', 'clept', 'cleve', 'clews', 'clied', 'clies', 'clift', 'clime', 'cline', 'clint', 'clipe', 'clips', 'clipt', 'clits', 'cloam', 'clods', 'cloff', 'clogs', 'cloke', 'clomb', 'clomp', 'clonk', 'clons', 'cloop', 'cloot', 'clops', 'clote', 'clots', 'clour', 'clous', 'clows', 'cloye', 'cloys', 'cloze', 'clubs', 'clues', 'cluey', 'clunk', 'clype', 'cnida', 'coact', 'coady', 'coala', 'coals', 'coaly', 'coapt', 'coarb', 'coate', 'coati', 'coats', 'cobbs', 'cobby', 'cobia', 'coble', 'cobza', 'cocas', 'cocci', 'cocco', 'cocks', 'cocky', 'cocos', 'codas', 'codec', 'coded', 'coden', 'coder', 'codes', 'codex', 'codon', 'coeds', 'coffs', 'cogie', 'cogon', 'cogue', 'cohab', 'cohen', 'cohoe', 'cohog', 'cohos', 'coifs', 'coign', 'coils', 'coins', 'coirs', 'coits', 'coked', 'cokes', 'colas', 'colby', 'colds', 'coled', 'coles', 'coley', 'colic', 'colin', 'colls', 'colly', 'colog', 'colts', 'colza', 'comae', 'comal', 'comas', 'combe', 'combi', 'combo', 'combs', 'comby', 'comer', 'comes', 'comix', 'commo', 'comms', 'commy', 'compo', 'comps', 'compt', 'comte', 'comus', 'coned', 'cones', 'coney', 'confs', 'conga', 'conge', 'congo', 'conia', 'conin', 'conks', 'conky', 'conne', 'conns', 'conte', 'conto', 'conus', 'convo', 'cooch', 'cooed', 'cooee', 'cooer', 'cooey', 'coofs', 'cooks', 'cooky', 'cools', 'cooly', 'coomb', 'cooms', 'coomy', 'coons', 'coops', 'coopt', 'coost', 'coots', 'cooze', 'copal', 'copay', 'coped', 'copen', 'coper', 'copes', 'coppy', 'copra', 'copsy', 'coqui', 'coram', 'corbe', 'corby', 'cords', 'cored', 'cores', 'corey', 'corgi', 'coria', 'corks', 'corky', 'corms', 'corni', 'corno', 'corns', 'cornu', 'corps', 'corse', 'corso', 'cosec', 'cosed', 'coses', 'coset', 'cosey', 'cosie', 'costa', 'coste', 'costs', 'cotan', 'coted', 'cotes', 'coths', 'cotta', 'cotts', 'coude', 'coups', 'courb', 'courd', 'coure', 'cours', 'couta', 'couth', 'coved', 'coves', 'covin', 'cowal', 'cowan', 'cowed', 'cowks', 'cowls', 'cowps', 'cowry', 'coxae', 'coxal', 'coxed', 'coxes', 'coxib', 'coyau', 'coyed', 'coyer', 'coypu', 'cozed', 'cozen', 'cozes', 'cozey', 'cozie', 'craal', 'crabs', 'crags', 'craic', 'craig', 'crake', 'crame', 'crams', 'crans', 'crape', 'craps', 'crapy', 'crare', 'craws', 'crays', 'creds', 'creel', 'crees', 'crems', 'crena', 'creps', 'crepy', 'crewe', 'crews', 'crias', 'cribs', 'cries', 'crims', 'crine', 'crios', 'cripe', 'crips', 'crise', 'crith', 'crits', 'croci', 'crocs', 'croft', 'crogs', 'cromb', 'crome', 'cronk', 'crons', 'crool', 'croon', 'crops', 'crore', 'crost', 'crout', 'crows', 'croze', 'cruck', 'crudo', 'cruds', 'crudy', 'crues', 'cruet', 'cruft', 'crunk', 'cruor', 'crura', 'cruse', 'crusy', 'cruve', 'crwth', 'cryer', 'ctene', 'cubby', 'cubeb', 'cubed', 'cuber', 'cubes', 'cubit', 'cuddy', 'cuffo', 'cuffs', 'cuifs', 'cuing', 'cuish', 'cuits', 'cukes', 'culch', 'culet', 'culex', 'culls', 'cully', 'culms', 'culpa', 'culti', 'cults', 'culty', 'cumec', 'cundy', 'cunei', 'cunit', 'cunts', 'cupel', 'cupid', 'cuppa', 'cuppy', 'curat', 'curbs', 'curch', 'curds', 'curdy', 'cured', 'curer', 'cures', 'curet', 'curfs', 'curia', 'curie', 'curli', 'curls', 'curns', 'curny', 'currs', 'cursi', 'curst', 'cusec', 'cushy', 'cusks', 'cusps', 'cuspy', 'cusso', 'cusum', 'cutch', 'cuter', 'cutes', 'cutey', 'cutin', 'cutis', 'cutto', 'cutty', 'cutup', 'cuvee', 'cuzes', 'cwtch', 'cyano', 'cyans', 'cycad', 'cycas', 'cyclo', 'cyder', 'cylix', 'cymae', 'cymar', 'cymas', 'cymes', 'cymol', 'cysts', 'cytes', 'cyton', 'czars', 'daals', 'dabba', 'daces', 'dacha', 'dacks', 'dadah', 'dadas', 'dados', 'daffs', 'daffy', 'dagga', 'daggy', 'dagos', 'dahls', 'daiko', 'daine', 'daint', 'daker', 'daled', 'dales', 'dalis', 'dalle', 'dalts', 'daman', 'damar', 'dames', 'damme', 'damns', 'damps', 'dampy', 'dancy', 'dangs', 'danio', 'danks', 'danny', 'dants', 'daraf', 'darbs', 'darcy', 'dared', 'darer', 'dares', 'darga', 'dargs', 'daric', 'daris', 'darks', 'darky', 'darns', 'darre', 'darts', 'darzi', 'dashi', 'dashy', 'datal', 'dated', 'dater', 'dates', 'datos', 'datto', 'daube', 'daubs', 'dauby', 'dauds', 'dault', 'daurs', 'dauts', 'daven', 'davit', 'dawah', 'dawds', 'dawed', 'dawen', 'dawks', 'dawns', 'dawts', 'dayan', 'daych', 'daynt', 'dazed', 'dazer', 'dazes', 'deads', 'deair', 'deals', 'deans', 'deare', 'dearn', 'dears', 'deary', 'deash', 'deave', 'deaws', 'deawy', 'debag', 'debby', 'debel', 'debes', 'debts', 'debud', 'debur', 'debus', 'debye', 'decad', 'decaf', 'decan', 'decko', 'decks', 'decos', 'dedal', 'deeds', 'deedy', 'deely', 'deems', 'deens', 'deeps', 'deere', 'deers', 'deets', 'deeve', 'deevs', 'defat', 'deffo', 'defis', 'defog', 'degas', 'degum', 'degus', 'deice', 'deids', 'deify', 'deils', 'deism', 'deist', 'deked', 'dekes', 'dekko', 'deled', 'deles', 'delfs', 'delft', 'delis', 'dells', 'delly', 'delos', 'delph', 'delts', 'deman', 'demes', 'demic', 'demit', 'demob', 'demoi', 'demos', 'dempt', 'denar', 'denay', 'dench', 'denes', 'denet', 'denis', 'dents', 'deoxy', 'derat', 'deray', 'dered', 'deres', 'derig', 'derma', 'derms', 'derns', 'derny', 'deros', 'derro', 'derry', 'derth', 'dervs', 'desex', 'deshi', 'desis', 'desks', 'desse', 'devas', 'devel', 'devis', 'devon', 'devos', 'devot', 'dewan', 'dewar', 'dewax', 'dewed', 'dexes', 'dexie', 'dhaba', 'dhaks', 'dhals', 'dhikr', 'dhobi', 'dhole', 'dholl', 'dhols', 'dhoti', 'dhows', 'dhuti', 'diact', 'dials', 'diane', 'diazo', 'dibbs', 'diced', 'dicer', 'dices', 'dicht', 'dicks', 'dicky', 'dicot', 'dicta', 'dicts', 'dicty', 'diddy', 'didie', 'didos', 'didst', 'diebs', 'diels', 'diene', 'diets', 'diffs', 'dight', 'dikas', 'diked', 'diker', 'dikes', 'dikey', 'dildo', 'dilli', 'dills', 'dimbo', 'dimer', 'dimes', 'dimps', 'dinar', 'dined', 'dines', 'dinge', 'dings', 'dinic', 'dinks', 'dinky', 'dinna', 'dinos', 'dints', 'diols', 'diota', 'dippy', 'dipso', 'diram', 'direr', 'dirke', 'dirks', 'dirls', 'dirts', 'disas', 'disci', 'discs', 'dishy', 'disks', 'disme', 'dital', 'ditas', 'dited', 'dites', 'ditsy', 'ditts', 'ditzy', 'divan', 'divas', 'dived', 'dives', 'divis', 'divna', 'divos', 'divot', 'divvy', 'diwan', 'dixie', 'dixit', 'diyas', 'dizen', 'djinn', 'djins', 'doabs', 'doats', 'dobby', 'dobes', 'dobie', 'dobla', 'dobra', 'dobro', 'docht', 'docks', 'docos', 'docus', 'doddy', 'dodos', 'doeks', 'doers', 'doest', 'doeth', 'doffs', 'dogan', 'doges', 'dogey', 'doggo', 'doggy', 'dogie', 'dohyo', 'doilt', 'doily', 'doits', 'dojos', 'dolce', 'dolci', 'doled', 'doles', 'dolia', 'dolls', 'dolma', 'dolor', 'dolos', 'dolts', 'domal', 'domed', 'domes', 'domic', 'donah', 'donas', 'donee', 'doner', 'donga', 'dongs', 'donko', 'donna', 'donne', 'donny', 'donsy', 'doobs', 'dooce', 'doody', 'dooks', 'doole', 'dools', 'dooly', 'dooms', 'doomy', 'doona', 'doorn', 'doors', 'doozy', 'dopas', 'doped', 'doper', 'dopes', 'dorad', 'dorba', 'dorbs', 'doree', 'dores', 'doric', 'doris', 'dorks', 'dorky', 'dorms', 'dormy', 'dorps', 'dorrs', 'dorsa', 'dorse', 'dorts', 'dorty', 'dosai', 'dosas', 'dosed', 'doseh', 'doser', 'doses', 'dosha', 'dotal', 'doted', 'doter', 'dotes', 'dotty', 'douar', 'douce', 'doucs', 'douks', 'doula', 'douma', 'doums', 'doups', 'doura', 'douse', 'douts', 'doved', 'doven', 'dover', 'doves', 'dovie', 'dowar', 'dowds', 'dowed', 'dower', 'dowie', 'dowle', 'dowls', 'dowly', 'downa', 'downs', 'dowps', 'dowse', 'dowts', 'doxed', 'doxes', 'doxie', 'doyen', 'doyly', 'dozed', 'dozer', 'dozes', 'drabs', 'drack', 'draco', 'draff', 'drags', 'drail', 'drams', 'drant', 'draps', 'drats', 'drave', 'draws', 'drays', 'drear', 'dreck', 'dreed', 'dreer', 'drees', 'dregs', 'dreks', 'drent', 'drere', 'drest', 'dreys', 'dribs', 'drice', 'dries', 'drily', 'drips', 'dript', 'droid', 'droil', 'droke', 'drole', 'drome', 'drony', 'droob', 'droog', 'drook', 'drops', 'dropt', 'drouk', 'drows', 'drubs', 'drugs', 'drums', 'drupe', 'druse', 'drusy', 'druxy', 'dryad', 'dryas', 'dsobo', 'dsomo', 'duads', 'duals', 'duans', 'duars', 'dubbo', 'ducal', 'ducat', 'duces', 'ducks', 'ducky', 'ducts', 'duddy', 'duded', 'dudes', 'duels', 'duets', 'duett', 'duffs', 'dufus', 'duing', 'duits', 'dukas', 'duked', 'dukes', 'dukka', 'dulce', 'dules', 'dulia', 'dulls', 'dulse', 'dumas', 'dumbo', 'dumbs', 'dumka', 'dumky', 'dumps', 'dunam', 'dunch', 'dunes', 'dungs', 'dungy', 'dunks', 'dunno', 'dunny', 'dunsh', 'dunts', 'duomi', 'duomo', 'duped', 'duper', 'dupes', 'duple', 'duply', 'duppy', 'dural', 'duras', 'dured', 'dures', 'durgy', 'durns', 'duroc', 'duros', 'duroy', 'durra', 'durrs', 'durry', 'durst', 'durum', 'durzi', 'dusks', 'dusts', 'duxes', 'dwaal', 'dwale', 'dwalm', 'dwams', 'dwang', 'dwaum', 'dweeb', 'dwile', 'dwine', 'dyads', 'dyers', 'dyked', 'dykes', 'dykey', 'dykon', 'dynel', 'dynes', 'dzhos', 'eagre', 'ealed', 'eales', 'eaned', 'eards', 'eared', 'earls', 'earns', 'earnt', 'earst', 'eased', 'easer', 'eases', 'easle', 'easts', 'eathe', 'eaved', 'eaves', 'ebbed', 'ebbet', 'ebons', 'ebook', 'ecads', 'eched', 'eches', 'echos', 'ecrus', 'edema', 'edged', 'edger', 'edges', 'edile', 'edits', 'educe', 'educt', 'eejit', 'eensy', 'eeven', 'eevns', 'effed', 'egads', 'egers', 'egest', 'eggar', 'egged', 'egger', 'egmas', 'ehing', 'eider', 'eidos', 'eigne', 'eiked', 'eikon', 'eilds', 'eisel', 'ejido', 'ekkas', 'elain', 'eland', 'elans', 'elchi', 'eldin', 'elemi', 'elfed', 'eliad', 'elint', 'elmen', 'eloge', 'elogy', 'eloin', 'elops', 'elpee', 'elsin', 'elute', 'elvan', 'elven', 'elver', 'elves', 'emacs', 'embar', 'embay', 'embog', 'embow', 'embox', 'embus', 'emeer', 'emend', 'emerg', 'emery', 'emeus', 'emics', 'emirs', 'emits', 'emmas', 'emmer', 'emmet', 'emmew', 'emmys', 'emoji', 'emong', 'emote', 'emove', 'empts', 'emule', 'emure', 'emyde', 'emyds', 'enarm', 'enate', 'ended', 'ender', 'endew', 'endue', 'enews', 'enfix', 'eniac', 'enlit', 'enmew', 'ennog', 'enoki', 'enols', 'enorm', 'enows', 'enrol', 'ensew', 'ensky', 'entia', 'enure', 'enurn', 'envoi', 'enzym', 'eorls', 'eosin', 'epact', 'epees', 'ephah', 'ephas', 'ephod', 'ephor', 'epics', 'epode', 'epopt', 'epris', 'eques', 'equid', 'erbia', 'erevs', 'ergon', 'ergos', 'ergot', 'erhus', 'erica', 'erick', 'erics', 'ering', 'erned', 'ernes', 'erose', 'erred', 'erses', 'eruct', 'erugo', 'eruvs', 'erven', 'ervil', 'escar', 'escot', 'esile', 'eskar', 'esker', 'esnes', 'esses', 'estoc', 'estop', 'estro', 'etage', 'etape', 'etats', 'etens', 'ethal', 'ethne', 'ethyl', 'etics', 'etnas', 'ettin', 'ettle', 'etuis', 'etwee', 'etyma', 'eughs', 'euked', 'eupad', 'euros', 'eusol', 'evens', 'evert', 'evets', 'evhoe', 'evils', 'evite', 'evohe', 'ewers', 'ewest', 'ewhow', 'ewked', 'exams', 'exeat', 'execs', 'exeem', 'exeme', 'exfil', 'exies', 'exine', 'exing', 'exits', 'exode', 'exome', 'exons', 'expat', 'expos', 'exude', 'exuls', 'exurb', 'eyass', 'eyers', 'eyots', 'eyras', 'eyres', 'eyrie', 'eyrir', 'ezine', 'fabby', 'faced', 'facer', 'faces', 'facia', 'facta', 'facts', 'faddy', 'faded', 'fader', 'fades', 'fadge', 'fados', 'faena', 'faery', 'faffs', 'faffy', 'faggy', 'fagin', 'fagot', 'faiks', 'fails', 'faine', 'fains', 'fairs', 'faked', 'faker', 'fakes', 'fakey', 'fakie', 'fakir', 'falaj', 'falls', 'famed', 'fames', 'fanal', 'fands', 'fanes', 'fanga', 'fango', 'fangs', 'fanks', 'fanon', 'fanos', 'fanum', 'faqir', 'farad', 'farci', 'farcy', 'fards', 'fared', 'farer', 'fares', 'farle', 'farls', 'farms', 'faros', 'farro', 'farse', 'farts', 'fasci', 'fasti', 'fasts', 'fated', 'fates', 'fatly', 'fatso', 'fatwa', 'faugh', 'fauld', 'fauns', 'faurd', 'fauts', 'fauve', 'favas', 'favel', 'faver', 'faves', 'favus', 'fawns', 'fawny', 'faxed', 'faxes', 'fayed', 'fayer', 'fayne', 'fayre', 'fazed', 'fazes', 'feals', 'feare', 'fears', 'feart', 'fease', 'feats', 'feaze', 'feces', 'fecht', 'fecit', 'fecks', 'fedex', 'feebs', 'feeds', 'feels', 'feens', 'feers', 'feese', 'feeze', 'fehme', 'feint', 'feist', 'felch', 'felid', 'fells', 'felly', 'felts', 'felty', 'femal', 'femes', 'femmy', 'fends', 'fendy', 'fenis', 'fenks', 'fenny', 'fents', 'feods', 'feoff', 'ferer', 'feres', 'feria', 'ferly', 'fermi', 'ferms', 'ferns', 'ferny', 'fesse', 'festa', 'fests', 'festy', 'fetas', 'feted', 'fetes', 'fetor', 'fetta', 'fetts', 'fetwa', 'feuar', 'feuds', 'feued', 'feyed', 'feyer', 'feyly', 'fezes', 'fezzy', 'fiars', 'fiats', 'fibro', 'fices', 'fiche', 'fichu', 'ficin', 'ficos', 'fides', 'fidge', 'fidos', 'fiefs', 'fient', 'fiere', 'fiers', 'fiest', 'fifed', 'fifer', 'fifes', 'fifis', 'figgy', 'figos', 'fiked', 'fikes', 'filar', 'filch', 'filed', 'files', 'filii', 'filks', 'fille', 'fillo', 'fills', 'filmi', 'films', 'filos', 'filum', 'finca', 'finds', 'fined', 'fines', 'finis', 'finks', 'finny', 'finos', 'fiord', 'fiqhs', 'fique', 'fired', 'firer', 'fires', 'firie', 'firks', 'firms', 'firns', 'firry', 'firth', 'fiscs', 'fisks', 'fists', 'fisty', 'fitch', 'fitly', 'fitna', 'fitte', 'fitts', 'fiver', 'fives', 'fixed', 'fixes', 'fixit', 'fjeld', 'flabs', 'flaff', 'flags', 'flaks', 'flamm', 'flams', 'flamy', 'flane', 'flans', 'flaps', 'flary', 'flats', 'flava', 'flawn', 'flaws', 'flawy', 'flaxy', 'flays', 'fleam', 'fleas', 'fleek', 'fleer', 'flees', 'flegs', 'fleme', 'fleur', 'flews', 'flexi', 'flexo', 'fleys', 'flics', 'flied', 'flies', 'flimp', 'flims', 'flips', 'flirs', 'flisk', 'flite', 'flits', 'flitt', 'flobs', 'flocs', 'floes', 'flogs', 'flong', 'flops', 'flors', 'flory', 'flosh', 'flota', 'flote', 'flows', 'flubs', 'flued', 'flues', 'fluey', 'fluky', 'flump', 'fluor', 'flurr', 'fluty', 'fluyt', 'flyby', 'flype', 'flyte', 'foals', 'foams', 'foehn', 'fogey', 'fogie', 'fogle', 'fogou', 'fohns', 'foids', 'foils', 'foins', 'folds', 'foley', 'folia', 'folic', 'folie', 'folks', 'folky', 'fomes', 'fonda', 'fonds', 'fondu', 'fones', 'fonly', 'fonts', 'foods', 'foody', 'fools', 'foots', 'footy', 'foram', 'forbs', 'forby', 'fordo', 'fords', 'forel', 'fores', 'forex', 'forks', 'forky', 'forme', 'forms', 'forts', 'forza', 'forze', 'fossa', 'fosse', 'fouat', 'fouds', 'fouer', 'fouet', 'foule', 'fouls', 'fount', 'fours', 'fouth', 'fovea', 'fowls', 'fowth', 'foxed', 'foxes', 'foxie', 'foyle', 'foyne', 'frabs', 'frack', 'fract', 'frags', 'fraim', 'franc', 'frape', 'fraps', 'frass', 'frate', 'frati', 'frats', 'fraus', 'frays', 'frees', 'freet', 'freit', 'fremd', 'frena', 'freon', 'frere', 'frets', 'fribs', 'frier', 'fries', 'frigs', 'frise', 'frist', 'frith', 'frits', 'fritt', 'frize', 'frizz', 'froes', 'frogs', 'frons', 'frore', 'frorn', 'frory', 'frosh', 'frows', 'frowy', 'frugs', 'frump', 'frush', 'frust', 'fryer', 'fubar', 'fubby', 'fubsy', 'fucks', 'fucus', 'fuddy', 'fudgy', 'fuels', 'fuero', 'fuffs', 'fuffy', 'fugal', 'fuggy', 'fugie', 'fugio', 'fugle', 'fugly', 'fugus', 'fujis', 'fulls', 'fumed', 'fumer', 'fumes', 'fumet', 'fundi', 'funds', 'fundy', 'fungo', 'fungs', 'funks', 'fural', 'furan', 'furca', 'furls', 'furol', 'furrs', 'furth', 'furze', 'furzy', 'fused', 'fusee', 'fusel', 'fuses', 'fusil', 'fusks', 'fusts', 'fusty', 'futon', 'fuzed', 'fuzee', 'fuzes', 'fuzil', 'fyces', 'fyked', 'fykes', 'fyles', 'fyrds', 'fytte', 'gabba', 'gabby', 'gable', 'gaddi', 'gades', 'gadge', 'gadid', 'gadis', 'gadje', 'gadjo', 'gadso', 'gaffs', 'gaged', 'gager', 'gages', 'gaids', 'gains', 'gairs', 'gaita', 'gaits', 'gaitt', 'gajos', 'galah', 'galas', 'galax', 'galea', 'galed', 'gales', 'galls', 'gally', 'galop', 'galut', 'galvo', 'gamas', 'gamay', 'gamba', 'gambe', 'gambo', 'gambs', 'gamed', 'games', 'gamey', 'gamic', 'gamin', 'gamme', 'gammy', 'gamps', 'ganch', 'gandy', 'ganef', 'ganev', 'gangs', 'ganja', 'ganof', 'gants', 'gaols', 'gaped', 'gaper', 'gapes', 'gapos', 'gappy', 'garbe', 'garbo', 'garbs', 'garda', 'gares', 'garis', 'garms', 'garni', 'garre', 'garth', 'garum', 'gases', 'gasps', 'gaspy', 'gasts', 'gatch', 'gated', 'gater', 'gates', 'gaths', 'gator', 'gauch', 'gaucy', 'gauds', 'gauje', 'gault', 'gaums', 'gaumy', 'gaups', 'gaurs', 'gauss', 'gauzy', 'gavot', 'gawcy', 'gawds', 'gawks', 'gawps', 'gawsy', 'gayal', 'gazal', 'gazar', 'gazed', 'gazes', 'gazon', 'gazoo', 'geals', 'geans', 'geare', 'gears', 'geats', 'gebur', 'gecks', 'geeks', 'geeps', 'geest', 'geist', 'geits', 'gelds', 'gelee', 'gelid', 'gelly', 'gelts', 'gemel', 'gemma', 'gemmy', 'gemot', 'genal', 'genas', 'genes', 'genet', 'genic', 'genii', 'genip', 'genny', 'genoa', 'genom', 'genro', 'gents', 'genty', 'genua', 'genus', 'geode', 'geoid', 'gerah', 'gerbe', 'geres', 'gerle', 'germs', 'germy', 'gerne', 'gesse', 'gesso', 'geste', 'gests', 'getas', 'getup', 'geums', 'geyan', 'geyer', 'ghast', 'ghats', 'ghaut', 'ghazi', 'ghees', 'ghest', 'ghyll', 'gibed', 'gibel', 'giber', 'gibes', 'gibli', 'gibus', 'gifts', 'gigas', 'gighe', 'gigot', 'gigue', 'gilas', 'gilds', 'gilet', 'gills', 'gilly', 'gilpy', 'gilts', 'gimel', 'gimme', 'gimps', 'gimpy', 'ginch', 'ginge', 'gings', 'ginks', 'ginny', 'ginzo', 'gipon', 'gippo', 'gippy', 'girds', 'girls', 'girns', 'giron', 'giros', 'girrs', 'girsh', 'girts', 'gismo', 'gisms', 'gists', 'gitch', 'gites', 'giust', 'gived', 'gives', 'gizmo', 'glace', 'glads', 'glady', 'glaik', 'glair', 'glams', 'glans', 'glary', 'glaum', 'glaur', 'glazy', 'gleba', 'glebe', 'gleby', 'glede', 'gleds', 'gleed', 'gleek', 'glees', 'gleet', 'gleis', 'glens', 'glent', 'gleys', 'glial', 'glias', 'glibs', 'gliff', 'glift', 'glike', 'glime', 'glims', 'glisk', 'glits', 'glitz', 'gloam', 'globi', 'globs', 'globy', 'glode', 'glogg', 'gloms', 'gloop', 'glops', 'glost', 'glout', 'glows', 'gloze', 'glued', 'gluer', 'glues', 'gluey', 'glugs', 'glume', 'glums', 'gluon', 'glute', 'gluts', 'gnarl', 'gnarr', 'gnars', 'gnats', 'gnawn', 'gnaws', 'gnows', 'goads', 'goafs', 'goals', 'goary', 'goats', 'goaty', 'goban', 'gobar', 'gobbi', 'gobbo', 'gobby', 'gobis', 'gobos', 'godet', 'godso', 'goels', 'goers', 'goest', 'goeth', 'goety', 'gofer', 'goffs', 'gogga', 'gogos', 'goier', 'gojis', 'golds', 'goldy', 'goles', 'golfs', 'golpe', 'golps', 'gombo', 'gomer', 'gompa', 'gonch', 'gonef', 'gongs', 'gonia', 'gonif', 'gonks', 'gonna', 'gonof', 'gonys', 'gonzo', 'gooby', 'goods', 'goofs', 'googs', 'gooks', 'gooky', 'goold', 'gools', 'gooly', 'goons', 'goony', 'goops', 'goopy', 'goors', 'goory', 'goosy', 'gopak', 'gopik', 'goral', 'goras', 'gored', 'gores', 'goris', 'gorms', 'gormy', 'gorps', 'gorse', 'gorsy', 'gosht', 'gosse', 'gotch', 'goths', 'gothy', 'gotta', 'gouch', 'gouks', 'goura', 'gouts', 'gouty', 'gowan', 'gowds', 'gowfs', 'gowks', 'gowls', 'gowns', 'goxes', 'goyim', 'goyle', 'graal', 'grabs', 'grads', 'graff', 'graip', 'grama', 'grame', 'gramp', 'grams', 'grana', 'grans', 'grapy', 'gravs', 'grays', 'grebe', 'grebo', 'grece', 'greek', 'grees', 'grege', 'grego', 'grein', 'grens', 'grese', 'greve', 'grews', 'greys', 'grice', 'gride', 'grids', 'griff', 'grift', 'grigs', 'grike', 'grins', 'griot', 'grips', 'gript', 'gripy', 'grise', 'grist', 'grisy', 'grith', 'grits', 'grize', 'groat', 'grody', 'grogs', 'groks', 'groma', 'grone', 'groof', 'grosz', 'grots', 'grouf', 'grovy', 'grows', 'grrls', 'grrrl', 'grubs', 'grued', 'grues', 'grufe', 'grume', 'grump', 'grund', 'gryce', 'gryde', 'gryke', 'grype', 'grypt', 'guaco', 'guana', 'guano', 'guans', 'guars', 'gucks', 'gucky', 'gudes', 'guffs', 'gugas', 'guids', 'guimp', 'guiro', 'gulag', 'gular', 'gulas', 'gules', 'gulet', 'gulfs', 'gulfy', 'gulls', 'gulph', 'gulps', 'gulpy', 'gumma', 'gummi', 'gumps', 'gundy', 'gunge', 'gungy', 'gunks', 'gunky', 'gunny', 'guqin', 'gurdy', 'gurge', 'gurls', 'gurly', 'gurns', 'gurry', 'gursh', 'gurus', 'gushy', 'gusla', 'gusle', 'gusli', 'gussy', 'gusts', 'gutsy', 'gutta', 'gutty', 'guyed', 'guyle', 'guyot', 'guyse', 'gwine', 'gyals', 'gyans', 'gybed', 'gybes', 'gyeld', 'gymps', 'gynae', 'gynie', 'gynny', 'gynos', 'gyoza', 'gypos', 'gyppo', 'gyppy', 'gyral', 'gyred', 'gyres', 'gyron', 'gyros', 'gyrus', 'gytes', 'gyved', 'gyves', 'haafs', 'haars', 'hable', 'habus', 'hacek', 'hacks', 'hadal', 'haded', 'hades', 'hadji', 'hadst', 'haems', 'haets', 'haffs', 'hafiz', 'hafts', 'haggs', 'hahas', 'haick', 'haika', 'haiks', 'haiku', 'hails', 'haily', 'hains', 'haint', 'hairs', 'haith', 'hajes', 'hajis', 'hajji', 'hakam', 'hakas', 'hakea', 'hakes', 'hakim', 'hakus', 'halal', 'haled', 'haler', 'hales', 'halfa', 'halfs', 'halid', 'hallo', 'halls', 'halma', 'halms', 'halon', 'halos', 'halse', 'halts', 'halva', 'halwa', 'hamal', 'hamba', 'hamed', 'hames', 'hammy', 'hamza', 'hanap', 'hance', 'hanch', 'hands', 'hangi', 'hangs', 'hanks', 'hanky', 'hansa', 'hanse', 'hants', 'haole', 'haoma', 'hapax', 'haply', 'happi', 'hapus', 'haram', 'hards', 'hared', 'hares', 'harim', 'harks', 'harls', 'harms', 'harns', 'haros', 'harps', 'harts', 'hashy', 'hasks', 'hasps', 'hasta', 'hated', 'hates', 'hatha', 'hauds', 'haufs', 'haugh', 'hauld', 'haulm', 'hauls', 'hault', 'hauns', 'hause', 'haver', 'haves', 'hawed', 'hawks', 'hawms', 'hawse', 'hayed', 'hayer', 'hayey', 'hayle', 'hazan', 'hazed', 'hazer', 'hazes', 'heads', 'heald', 'heals', 'heame', 'heaps', 'heapy', 'heare', 'hears', 'heast', 'heats', 'heben', 'hebes', 'hecht', 'hecks', 'heder', 'hedgy', 'heeds', 'heedy', 'heels', 'heeze', 'hefte', 'hefts', 'heids', 'heigh', 'heils', 'heirs', 'hejab', 'hejra', 'heled', 'heles', 'helio', 'hells', 'helms', 'helos', 'helot', 'helps', 'helve', 'hemal', 'hemes', 'hemic', 'hemin', 'hemps', 'hempy', 'hench', 'hends', 'henge', 'henna', 'henny', 'henry', 'hents', 'hepar', 'herbs', 'herby', 'herds', 'heres', 'herls', 'herma', 'herms', 'herns', 'heros', 'herry', 'herse', 'hertz', 'herye', 'hesps', 'hests', 'hetes', 'heths', 'heuch', 'heugh', 'hevea', 'hewed', 'hewer', 'hewgh', 'hexad', 'hexed', 'hexer', 'hexes', 'hexyl', 'heyed', 'hiant', 'hicks', 'hided', 'hider', 'hides', 'hiems', 'highs', 'hight', 'hijab', 'hijra', 'hiked', 'hiker', 'hikes', 'hikoi', 'hilar', 'hilch', 'hillo', 'hills', 'hilts', 'hilum', 'hilus', 'himbo', 'hinau', 'hinds', 'hings', 'hinky', 'hinny', 'hints', 'hiois', 'hiply', 'hired', 'hiree', 'hirer', 'hires', 'hissy', 'hists', 'hithe', 'hived', 'hiver', 'hives', 'hizen', 'hoaed', 'hoagy', 'hoars', 'hoary', 'hoast', 'hobos', 'hocks', 'hocus', 'hodad', 'hodja', 'hoers', 'hogan', 'hogen', 'hoggs', 'hoghs', 'hohed', 'hoick', 'hoied', 'hoiks', 'hoing', 'hoise', 'hokas', 'hoked', 'hokes', 'hokey', 'hokis', 'hokku', 'hokum', 'holds', 'holed', 'holes', 'holey', 'holks', 'holla', 'hollo', 'holme', 'holms', 'holon', 'holos', 'holts', 'homas', 'homed', 'homes', 'homey', 'homie', 'homme', 'homos', 'honan', 'honda', 'honds', 'honed', 'honer', 'hones', 'hongi', 'hongs', 'honks', 'honky', 'hooch', 'hoods', 'hoody', 'hooey', 'hoofs', 'hooka', 'hooks', 'hooky', 'hooly', 'hoons', 'hoops', 'hoord', 'hoors', 'hoosh', 'hoots', 'hooty', 'hoove', 'hopak', 'hoped', 'hoper', 'hopes', 'hoppy', 'horah', 'horal', 'horas', 'horis', 'horks', 'horme', 'horns', 'horst', 'horsy', 'hosed', 'hosel', 'hosen', 'hoser', 'hoses', 'hosey', 'hosta', 'hosts', 'hotch', 'hoten', 'hotty', 'houff', 'houfs', 'hough', 'houri', 'hours', 'houts', 'hovea', 'hoved', 'hoven', 'hoves', 'howbe', 'howes', 'howff', 'howfs', 'howks', 'howls', 'howre', 'howso', 'hoxed', 'hoxes', 'hoyas', 'hoyed', 'hoyle', 'hubby', 'hucks', 'hudna', 'hudud', 'huers', 'huffs', 'huffy', 'huger', 'huggy', 'huhus', 'huias', 'hulas', 'hules', 'hulks', 'hulky', 'hullo', 'hulls', 'hully', 'humas', 'humfs', 'humic', 'humps', 'humpy', 'hunks', 'hunts', 'hurds', 'hurls', 'hurly', 'hurra', 'hurst', 'hurts', 'hushy', 'husks', 'husos', 'hutia', 'huzza', 'huzzy', 'hwyls', 'hydra', 'hyens', 'hygge', 'hying', 'hykes', 'hylas', 'hyleg', 'hyles', 'hylic', 'hymns', 'hynde', 'hyoid', 'hyped', 'hypes', 'hypha', 'hyphy', 'hypos', 'hyrax', 'hyson', 'hythe', 'iambi', 'iambs', 'ibrik', 'icers', 'iched', 'iches', 'ichor', 'icier', 'icker', 'ickle', 'icons', 'ictal', 'ictic', 'ictus', 'idant', 'ideas', 'idees', 'ident', 'idled', 'idles', 'idola', 'idols', 'idyls', 'iftar', 'igapo', 'igged', 'iglus', 'ihram', 'ikans', 'ikats', 'ikons', 'ileac', 'ileal', 'ileum', 'ileus', 'iliad', 'ilial', 'ilium', 'iller', 'illth', 'imago', 'imams', 'imari', 'imaum', 'imbar', 'imbed', 'imide', 'imido', 'imids', 'imine', 'imino', 'immew', 'immit', 'immix', 'imped', 'impis', 'impot', 'impro', 'imshi', 'imshy', 'inapt', 'inarm', 'inbye', 'incel', 'incle', 'incog', 'incus', 'incut', 'indew', 'india', 'indie', 'indol', 'indow', 'indri', 'indue', 'inerm', 'infix', 'infos', 'infra', 'ingan', 'ingle', 'inion', 'inked', 'inker', 'inkle', 'inned', 'innit', 'inorb', 'inrun', 'inset', 'inspo', 'intel', 'intil', 'intis', 'intra', 'inula', 'inure', 'inurn', 'inust', 'invar', 'inwit', 'iodic', 'iodid', 'iodin', 'iotas', 'ippon', 'irade', 'irids', 'iring', 'irked', 'iroko', 'irone', 'irons', 'isbas', 'ishes', 'isled', 'isles', 'isnae', 'issei', 'istle', 'items', 'ither', 'ivied', 'ivies', 'ixias', 'ixnay', 'ixora', 'ixtle', 'izard', 'izars', 'izzat', 'jaaps', 'jabot', 'jacal', 'jacks', 'jacky', 'jaded', 'jades', 'jafas', 'jaffa', 'jagas', 'jager', 'jaggs', 'jaggy', 'jagir', 'jagra', 'jails', 'jaker', 'jakes', 'jakey', 'jalap', 'jalop', 'jambe', 'jambo', 'jambs', 'jambu', 'james', 'jammy', 'jamon', 'janes', 'janns', 'janny', 'janty', 'japan', 'japed', 'japer', 'japes', 'jarks', 'jarls', 'jarps', 'jarta', 'jarul', 'jasey', 'jaspe', 'jasps', 'jatos', 'jauks', 'jaups', 'javas', 'javel', 'jawan', 'jawed', 'jaxie', 'jeans', 'jeats', 'jebel', 'jedis', 'jeels', 'jeely', 'jeeps', 'jeers', 'jeeze', 'jefes', 'jeffs', 'jehad', 'jehus', 'jelab', 'jello', 'jells', 'jembe', 'jemmy', 'jenny', 'jeons', 'jerid', 'jerks', 'jerry', 'jesse', 'jests', 'jesus', 'jetes', 'jeton', 'jeune', 'jewed', 'jewie', 'jhala', 'jiaos', 'jibba', 'jibbs', 'jibed', 'jiber', 'jibes', 'jiffs', 'jiggy', 'jigot', 'jihad', 'jills', 'jilts', 'jimmy', 'jimpy', 'jingo', 'jinks', 'jinne', 'jinni', 'jinns', 'jirds', 'jirga', 'jirre', 'jisms', 'jived', 'jiver', 'jives', 'jivey', 'jnana', 'jobed', 'jobes', 'jocko', 'jocks', 'jocky', 'jocos', 'jodel', 'joeys', 'johns', 'joins', 'joked', 'jokes', 'jokey', 'jokol', 'joled', 'joles', 'jolls', 'jolts', 'jolty', 'jomon', 'jomos', 'jones', 'jongs', 'jonty', 'jooks', 'joram', 'jorum', 'jotas', 'jotty', 'jotun', 'joual', 'jougs', 'jouks', 'joule', 'jours', 'jowar', 'jowed', 'jowls', 'jowly', 'joyed', 'jubas', 'jubes', 'jucos', 'judas', 'judgy', 'judos', 'jugal', 'jugum', 'jujus', 'juked', 'jukes', 'jukus', 'julep', 'jumar', 'jumby', 'jumps', 'junco', 'junks', 'junky', 'jupes', 'jupon', 'jural', 'jurat', 'jurel', 'jures', 'justs', 'jutes', 'jutty', 'juves', 'juvie', 'kaama', 'kabab', 'kabar', 'kabob', 'kacha', 'kacks', 'kadai', 'kades', 'kadis', 'kafir', 'kagos', 'kagus', 'kahal', 'kaiak', 'kaids', 'kaies', 'kaifs', 'kaika', 'kaiks', 'kails', 'kaims', 'kaing', 'kains', 'kakas', 'kakis', 'kalam', 'kales', 'kalif', 'kalis', 'kalpa', 'kamas', 'kames', 'kamik', 'kamis', 'kamme', 'kanae', 'kanas', 'kandy', 'kaneh', 'kanes', 'kanga', 'kangs', 'kanji', 'kants', 'kanzu', 'kaons', 'kapas', 'kaphs', 'kapok', 'kapow', 'kapus', 'kaput', 'karas', 'karat', 'karks', 'karns', 'karoo', 'karos', 'karri', 'karst', 'karsy', 'karts', 'karzy', 'kasha', 'kasme', 'katal', 'katas', 'katis', 'katti', 'kaugh', 'kauri', 'kauru', 'kaury', 'kaval', 'kavas', 'kawas', 'kawau', 'kawed', 'kayle', 'kayos', 'kazis', 'kazoo', 'kbars', 'kebar', 'kebob', 'kecks', 'kedge', 'kedgy', 'keech', 'keefs', 'keeks', 'keels', 'keema', 'keeno', 'keens', 'keeps', 'keets', 'keeve', 'kefir', 'kehua', 'keirs', 'kelep', 'kelim', 'kells', 'kelly', 'kelps', 'kelpy', 'kelts', 'kelty', 'kembo', 'kembs', 'kemps', 'kempt', 'kempy', 'kenaf', 'kench', 'kendo', 'kenos', 'kente', 'kents', 'kepis', 'kerbs', 'kerel', 'kerfs', 'kerky', 'kerma', 'kerne', 'kerns', 'keros', 'kerry', 'kerve', 'kesar', 'kests', 'ketas', 'ketch', 'ketes', 'ketol', 'kevel', 'kevil', 'kexes', 'keyed', 'keyer', 'khadi', 'khafs', 'khans', 'khaph', 'khats', 'khaya', 'khazi', 'kheda', 'kheth', 'khets', 'khoja', 'khors', 'khoum', 'khuds', 'kiaat', 'kiack', 'kiang', 'kibbe', 'kibbi', 'kibei', 'kibes', 'kibla', 'kicks', 'kicky', 'kiddo', 'kiddy', 'kidel', 'kidge', 'kiefs', 'kiers', 'kieve', 'kievs', 'kight', 'kikes', 'kikoi', 'kiley', 'kilim', 'kills', 'kilns', 'kilos', 'kilps', 'kilts', 'kilty', 'kimbo', 'kinas', 'kinda', 'kinds', 'kindy', 'kines', 'kings', 'kinin', 'kinks', 'kinos', 'kiore', 'kipes', 'kippa', 'kipps', 'kirby', 'kirks', 'kirns', 'kirri', 'kisan', 'kissy', 'kists', 'kited', 'kiter', 'kites', 'kithe', 'kiths', 'kitul', 'kivas', 'kiwis', 'klang', 'klaps', 'klett', 'klick', 'klieg', 'kliks', 'klong', 'kloof', 'kluge', 'klutz', 'knags', 'knaps', 'knarl', 'knars', 'knaur', 'knawe', 'knees', 'knell', 'knish', 'knits', 'knive', 'knobs', 'knops', 'knosp', 'knots', 'knout', 'knowe', 'knows', 'knubs', 'knurl', 'knurr', 'knurs', 'knuts', 'koans', 'koaps', 'koban', 'kobos', 'koels', 'koffs', 'kofta', 'kogal', 'kohas', 'kohen', 'kohls', 'koine', 'kojis', 'kokam', 'kokas', 'koker', 'kokra', 'kokum', 'kolas', 'kolos', 'kombu', 'konbu', 'kondo', 'konks', 'kooks', 'kooky', 'koori', 'kopek', 'kophs', 'kopje', 'koppa', 'korai', 'koras', 'korat', 'kores', 'korma', 'koros', 'korun', 'korus', 'koses', 'kotch', 'kotos', 'kotow', 'koura', 'kraal', 'krabs', 'kraft', 'krais', 'krait', 'krang', 'krans', 'kranz', 'kraut', 'krays', 'kreep', 'kreng', 'krewe', 'krona', 'krone', 'kroon', 'krubi', 'krunk', 'ksars', 'kubie', 'kudos', 'kudus', 'kudzu', 'kufis', 'kugel', 'kuias', 'kukri', 'kukus', 'kulak', 'kulan', 'kulas', 'kulfi', 'kumis', 'kumys', 'kuris', 'kurre', 'kurta', 'kurus', 'kusso', 'kutas', 'kutch', 'kutis', 'kutus', 'kuzus', 'kvass', 'kvell', 'kwela', 'kyack', 'kyaks', 'kyang', 'kyars', 'kyats', 'kybos', 'kydst', 'kyles', 'kylie', 'kylin', 'kylix', 'kyloe', 'kynde', 'kynds', 'kypes', 'kyrie', 'kytes', 'kythe', 'laari', 'labda', 'labia', 'labis', 'labra', 'laced', 'lacer', 'laces', 'lacet', 'lacey', 'lacks', 'laddy', 'laded', 'lader', 'lades', 'laers', 'laevo', 'lagan', 'lahal', 'lahar', 'laich', 'laics', 'laids', 'laigh', 'laika', 'laiks', 'laird', 'lairs', 'lairy', 'laith', 'laity', 'laked', 'laker', 'lakes', 'lakhs', 'lakin', 'laksa', 'laldy', 'lalls', 'lamas', 'lambs', 'lamby', 'lamed', 'lamer', 'lames', 'lamia', 'lammy', 'lamps', 'lanai', 'lanas', 'lanch', 'lande', 'lands', 'lanes', 'lanks', 'lants', 'lapin', 'lapis', 'lapje', 'larch', 'lards', 'lardy', 'laree', 'lares', 'largo', 'laris', 'larks', 'larky', 'larns', 'larnt', 'larum', 'lased', 'laser', 'lases', 'lassi', 'lassu', 'lassy', 'lasts', 'latah', 'lated', 'laten', 'latex', 'lathi', 'laths', 'lathy', 'latke', 'latus', 'lauan', 'lauch', 'lauds', 'laufs', 'laund', 'laura', 'laval', 'lavas', 'laved', 'laver', 'laves', 'lavra', 'lavvy', 'lawed', 'lawer', 'lawin', 'lawks', 'lawns', 'lawny', 'laxed', 'laxer', 'laxes', 'laxly', 'layed', 'layin', 'layup', 'lazar', 'lazed', 'lazes', 'lazos', 'lazzi', 'lazzo', 'leads', 'leady', 'leafs', 'leaks', 'leams', 'leans', 'leany', 'leaps', 'leare', 'lears', 'leary', 'leats', 'leavy', 'leaze', 'leben', 'leccy', 'ledes', 'ledgy', 'ledum', 'leear', 'leeks', 'leeps', 'leers', 'leese', 'leets', 'leeze', 'lefte', 'lefts', 'leger', 'leges', 'legge', 'leggo', 'legit', 'lehrs', 'lehua', 'leirs', 'leish', 'leman', 'lemed', 'lemel', 'lemes', 'lemma', 'lemme', 'lends', 'lenes', 'lengs', 'lenis', 'lenos', 'lense', 'lenti', 'lento', 'leone', 'lepid', 'lepra', 'lepta', 'lered', 'leres', 'lerps', 'lesbo', 'leses', 'lests', 'letch', 'lethe', 'letup', 'leuch', 'leuco', 'leuds', 'leugh', 'levas', 'levee', 'leves', 'levin', 'levis', 'lewis', 'lexes', 'lexis', 'lezes', 'lezza', 'lezzy', 'liana', 'liane', 'liang', 'liard', 'liars', 'liart', 'liber', 'libra', 'libri', 'lichi', 'licht', 'licit', 'licks', 'lidar', 'lidos', 'liefs', 'liens', 'liers', 'lieus', 'lieve', 'lifer', 'lifes', 'lifts', 'ligan', 'liger', 'ligge', 'ligne', 'liked', 'liker', 'likes', 'likin', 'lills', 'lilos', 'lilts', 'liman', 'limas', 'limax', 'limba', 'limbi', 'limbs', 'limby', 'limed', 'limen', 'limes', 'limey', 'limma', 'limns', 'limos', 'limpa', 'limps', 'linac', 'linch', 'linds', 'lindy', 'lined', 'lines', 'liney', 'linga', 'lings', 'lingy', 'linin', 'links', 'linky', 'linns', 'linny', 'linos', 'lints', 'linty', 'linum', 'linux', 'lions', 'lipas', 'lipes', 'lipin', 'lipos', 'lippy', 'liras', 'lirks', 'lirot', 'lisks', 'lisle', 'lisps', 'lists', 'litai', 'litas', 'lited', 'liter', 'lites', 'litho', 'liths', 'litre', 'lived', 'liven', 'lives', 'livor', 'livre', 'llano', 'loach', 'loads', 'loafs', 'loams', 'loans', 'loast', 'loave', 'lobar', 'lobed', 'lobes', 'lobos', 'lobus', 'loche', 'lochs', 'locie', 'locis', 'locks', 'locos', 'locum', 'loden', 'lodes', 'loess', 'lofts', 'logan', 'loges', 'loggy', 'logia', 'logie', 'logoi', 'logon', 'logos', 'lohan', 'loids', 'loins', 'loipe', 'loirs', 'lokes', 'lolls', 'lolly', 'lolog', 'lomas', 'lomed', 'lomes', 'loner', 'longa', 'longe', 'longs', 'looby', 'looed', 'looey', 'loofa', 'loofs', 'looie', 'looks', 'looky', 'looms', 'loons', 'loony', 'loops', 'loord', 'loots', 'loped', 'loper', 'lopes', 'loppy', 'loral', 'loran', 'lords', 'lordy', 'lorel', 'lores', 'loric', 'loris', 'losed', 'losel', 'losen', 'loses', 'lossy', 'lotah', 'lotas', 'lotes', 'lotic', 'lotos', 'lotsa', 'lotta', 'lotte', 'lotto', 'lotus', 'loued', 'lough', 'louie', 'louis', 'louma', 'lound', 'louns', 'loupe', 'loups', 'loure', 'lours', 'loury', 'louts', 'lovat', 'loved', 'loves', 'lovey', 'lovie', 'lowan', 'lowed', 'lowes', 'lownd', 'lowne', 'lowns', 'lowps', 'lowry', 'lowse', 'lowts', 'loxed', 'loxes', 'lozen', 'luach', 'luaus', 'lubed', 'lubes', 'lubra', 'luces', 'lucks', 'lucre', 'ludes', 'ludic', 'ludos', 'luffa', 'luffs', 'luged', 'luger', 'luges', 'lulls', 'lulus', 'lumas', 'lumbi', 'lumme', 'lummy', 'lumps', 'lunas', 'lunes', 'lunet', 'lungi', 'lungs', 'lunks', 'lunts', 'lupin', 'lured', 'lurer', 'lures', 'lurex', 'lurgi', 'lurgy', 'lurks', 'lurry', 'lurve', 'luser', 'lushy', 'lusks', 'lusts', 'lusus', 'lutea', 'luted', 'luter', 'lutes', 'luvvy', 'luxed', 'luxer', 'luxes', 'lweis', 'lyams', 'lyard', 'lyart', 'lyase', 'lycea', 'lycee', 'lycra', 'lymes', 'lynes', 'lyres', 'lysed', 'lyses', 'lysin', 'lysis', 'lysol', 'lyssa', 'lyted', 'lytes', 'lythe', 'lytic', 'lytta', 'maaed', 'maare', 'maars', 'mabes', 'macas', 'maced', 'macer', 'maces', 'mache', 'machi', 'machs', 'macks', 'macle', 'macon', 'madge', 'madid', 'madre', 'maerl', 'mafic', 'mages', 'maggs', 'magot', 'magus', 'mahoe', 'mahua', 'mahwa', 'maids', 'maiko', 'maiks', 'maile', 'maill', 'mails', 'maims', 'mains', 'maire', 'mairs', 'maise', 'maist', 'makar', 'makes', 'makis', 'makos', 'malam', 'malar', 'malas', 'malax', 'males', 'malic', 'malik', 'malis', 'malls', 'malms', 'malmy', 'malts', 'malty', 'malus', 'malva', 'malwa', 'mamas', 'mamba', 'mamee', 'mamey', 'mamie', 'manas', 'manat', 'mandi', 'maneb', 'maned', 'maneh', 'manes', 'manet', 'mangs', 'manis', 'manky', 'manna', 'manos', 'manse', 'manta', 'manto', 'manty', 'manul', 'manus', 'mapau', 'maqui', 'marae', 'marah', 'maras', 'marcs', 'mardy', 'mares', 'marge', 'margs', 'maria', 'marid', 'marka', 'marks', 'marle', 'marls', 'marly', 'marms', 'maron', 'maror', 'marra', 'marri', 'marse', 'marts', 'marvy', 'masas', 'mased', 'maser', 'mases', 'mashy', 'masks', 'massa', 'massy', 'masts', 'masty', 'masus', 'matai', 'mated', 'mater', 'mates', 'maths', 'matin', 'matlo', 'matte', 'matts', 'matza', 'matzo', 'mauby', 'mauds', 'mauls', 'maund', 'mauri', 'mausy', 'mauts', 'mauzy', 'maven', 'mavie', 'mavin', 'mavis', 'mawed', 'mawks', 'mawky', 'mawns', 'mawrs', 'maxed', 'maxes', 'maxis', 'mayan', 'mayas', 'mayed', 'mayos', 'mayst', 'mazed', 'mazer', 'mazes', 'mazey', 'mazut', 'mbira', 'meads', 'meals', 'meane', 'means', 'meany', 'meare', 'mease', 'meath', 'meats', 'mebos', 'mechs', 'mecks', 'medii', 'medle', 'meeds', 'meers', 'meets', 'meffs', 'meins', 'meint', 'meiny', 'meith', 'mekka', 'melas', 'melba', 'melds', 'melic', 'melik', 'mells', 'melts', 'melty', 'memes', 'memos', 'menad', 'mends', 'mened', 'menes', 'menge', 'mengs', 'mensa', 'mense', 'mensh', 'menta', 'mento', 'menus', 'meous', 'meows', 'merch', 'mercs', 'merde', 'mered', 'merel', 'merer', 'meres', 'meril', 'meris', 'merks', 'merle', 'merls', 'merse', 'mesal', 'mesas', 'mesel', 'meses', 'meshy', 'mesic', 'mesne', 'meson', 'messy', 'mesto', 'meted', 'metes', 'metho', 'meths', 'metic', 'metif', 'metis', 'metol', 'metre', 'meuse', 'meved', 'meves', 'mewed', 'mewls', 'meynt', 'mezes', 'mezze', 'mezzo', 'mhorr', 'miaou', 'miaow', 'miasm', 'miaul', 'micas', 'miche', 'micht', 'micks', 'micky', 'micos', 'micra', 'middy', 'midgy', 'midis', 'miens', 'mieve', 'miffs', 'miffy', 'mifty', 'miggs', 'mihas', 'mihis', 'miked', 'mikes', 'mikra', 'mikva', 'milch', 'milds', 'miler', 'miles', 'milfs', 'milia', 'milko', 'milks', 'mille', 'mills', 'milor', 'milos', 'milpa', 'milts', 'milty', 'miltz', 'mimed', 'mimeo', 'mimer', 'mimes', 'mimsy', 'minae', 'minar', 'minas', 'mincy', 'minds', 'mined', 'mines', 'minge', 'mings', 'mingy', 'minis', 'minke', 'minks', 'minny', 'minos', 'mints', 'mired', 'mires', 'mirex', 'mirid', 'mirin', 'mirks', 'mirky', 'mirly', 'miros', 'mirvs', 'mirza', 'misch', 'misdo', 'mises', 'misgo', 'misos', 'missa', 'mists', 'misty', 'mitch', 'miter', 'mites', 'mitis', 'mitre', 'mitts', 'mixed', 'mixen', 'mixer', 'mixes', 'mixte', 'mixup', 'mizen', 'mizzy', 'mneme', 'moans', 'moats', 'mobby', 'mobes', 'mobey', 'mobie', 'moble', 'mochi', 'mochs', 'mochy', 'mocks', 'moder', 'modes', 'modge', 'modii', 'modus', 'moers', 'mofos', 'moggy', 'mohel', 'mohos', 'mohrs', 'mohua', 'mohur', 'moile', 'moils', 'moira', 'moire', 'moits', 'mojos', 'mokes', 'mokis', 'mokos', 'molal', 'molas', 'molds', 'moled', 'moles', 'molla', 'molls', 'molly', 'molto', 'molts', 'molys', 'momes', 'momma', 'mommy', 'momus', 'monad', 'monal', 'monas', 'monde', 'mondo', 'moner', 'mongo', 'mongs', 'monic', 'monie', 'monks', 'monos', 'monte', 'monty', 'moobs', 'mooch', 'moods', 'mooed', 'mooks', 'moola', 'mooli', 'mools', 'mooly', 'moong', 'moons', 'moony', 'moops', 'moors', 'moory', 'moots', 'moove', 'moped', 'moper', 'mopes', 'mopey', 'moppy', 'mopsy', 'mopus', 'morae', 'moras', 'morat', 'moray', 'morel', 'mores', 'moria', 'morne', 'morns', 'morra', 'morro', 'morse', 'morts', 'mosed', 'moses', 'mosey', 'mosks', 'mosso', 'moste', 'mosts', 'moted', 'moten', 'motes', 'motet', 'motey', 'moths', 'mothy', 'motis', 'motte', 'motts', 'motty', 'motus', 'motza', 'mouch', 'moues', 'mould', 'mouls', 'moups', 'moust', 'mousy', 'moved', 'moves', 'mowas', 'mowed', 'mowra', 'moxas', 'moxie', 'moyas', 'moyle', 'moyls', 'mozed', 'mozes', 'mozos', 'mpret', 'mucho', 'mucic', 'mucid', 'mucin', 'mucks', 'mucor', 'mucro', 'mudge', 'mudir', 'mudra', 'muffs', 'mufti', 'mugga', 'muggs', 'muggy', 'muhly', 'muids', 'muils', 'muirs', 'muist', 'mujik', 'mulct', 'muled', 'mules', 'muley', 'mulga', 'mulie', 'mulla', 'mulls', 'mulse', 'mulsh', 'mumms', 'mumps', 'mumsy', 'mumus', 'munga', 'munge', 'mungo', 'mungs', 'munis', 'munts', 'muntu', 'muons', 'muras', 'mured', 'mures', 'murex', 'murid', 'murks', 'murls', 'murly', 'murra', 'murre', 'murri', 'murrs', 'murry', 'murti', 'murva', 'musar', 'musca', 'mused', 'muser', 'muses', 'muset', 'musha', 'musit', 'musks', 'musos', 'musse', 'mussy', 'musth', 'musts', 'mutch', 'muted', 'muter', 'mutes', 'mutha', 'mutis', 'muton', 'mutts', 'muxed', 'muxes', 'muzak', 'muzzy', 'mvule', 'myall', 'mylar', 'mynah', 'mynas', 'myoid', 'myoma', 'myope', 'myops', 'myopy', 'mysid', 'mythi', 'myths', 'mythy', 'myxos', 'mzees', 'naams', 'naans', 'nabes', 'nabis', 'nabks', 'nabla', 'nabob', 'nache', 'nacho', 'nacre', 'nadas', 'naeve', 'naevi', 'naffs', 'nagas', 'naggy', 'nagor', 'nahal', 'naiad', 'naifs', 'naiks', 'nails', 'naira', 'nairu', 'naked', 'naker', 'nakfa', 'nalas', 'naled', 'nalla', 'named', 'namer', 'names', 'namma', 'namus', 'nanas', 'nance', 'nancy', 'nandu', 'nanna', 'nanos', 'nanua', 'napas', 'naped', 'napes', 'napoo', 'nappa', 'nappe', 'nappy', 'naras', 'narco', 'narcs', 'nards', 'nares', 'naric', 'naris', 'narks', 'narky', 'narre', 'nashi', 'natch', 'nates', 'natis', 'natty', 'nauch', 'naunt', 'navar', 'naves', 'navew', 'navvy', 'nawab', 'nazes', 'nazir', 'nazis', 'nduja', 'neafe', 'neals', 'neaps', 'nears', 'neath', 'neats', 'nebek', 'nebel', 'necks', 'neddy', 'needs', 'neeld', 'neele', 'neemb', 'neems', 'neeps', 'neese', 'neeze', 'negro', 'negus', 'neifs', 'neist', 'neive', 'nelis', 'nelly', 'nemas', 'nemns', 'nempt', 'nenes', 'neons', 'neper', 'nepit', 'neral', 'nerds', 'nerka', 'nerks', 'nerol', 'nerts', 'nertz', 'nervy', 'nests', 'netes', 'netop', 'netts', 'netty', 'neuks', 'neume', 'neums', 'nevel', 'neves', 'nevus', 'newbs', 'newed', 'newel', 'newie', 'newsy', 'newts', 'nexts', 'nexus', 'ngaio', 'ngana', 'ngati', 'ngoma', 'ngwee', 'nicad', 'nicht', 'nicks', 'nicol', 'nidal', 'nided', 'nides', 'nidor', 'nidus', 'niefs', 'nieve', 'nifes', 'niffs', 'niffy', 'nifty', 'niger', 'nighs', 'nihil', 'nikab', 'nikah', 'nikau', 'nills', 'nimbi', 'nimbs', 'nimps', 'niner', 'nines', 'ninon', 'nipas', 'nippy', 'niqab', 'nirls', 'nirly', 'nisei', 'nisse', 'nisus', 'niter', 'nites', 'nitid', 'niton', 'nitre', 'nitro', 'nitry', 'nitty', 'nival', 'nixed', 'nixer', 'nixes', 'nixie', 'nizam', 'nkosi', 'noahs', 'nobby', 'nocks', 'nodal', 'noddy', 'nodes', 'nodus', 'noels', 'noggs', 'nohow', 'noils', 'noily', 'noint', 'noirs', 'noles', 'nolls', 'nolos', 'nomas', 'nomen', 'nomes', 'nomic', 'nomoi', 'nomos', 'nonas', 'nonce', 'nones', 'nonet', 'nongs', 'nonis', 'nonny', 'nonyl', 'noobs', 'nooit', 'nooks', 'nooky', 'noons', 'noops', 'nopal', 'noria', 'noris', 'norks', 'norma', 'norms', 'nosed', 'noser', 'noses', 'notal', 'noted', 'noter', 'notes', 'notum', 'nould', 'noule', 'nouls', 'nouns', 'nouny', 'noups', 'novae', 'novas', 'novum', 'noway', 'nowed', 'nowls', 'nowts', 'nowty', 'noxal', 'noxes', 'noyau', 'noyed', 'noyes', 'nubby', 'nubia', 'nucha', 'nuddy', 'nuder', 'nudes', 'nudie', 'nudzh', 'nuffs', 'nugae', 'nuked', 'nukes', 'nulla', 'nulls', 'numbs', 'numen', 'nummy', 'nunny', 'nurds', 'nurdy', 'nurls', 'nurrs', 'nutso', 'nutsy', 'nyaff', 'nyala', 'nying', 'nyssa', 'oaked', 'oaker', 'oakum', 'oared', 'oases', 'oasis', 'oasts', 'oaten', 'oater', 'oaths', 'oaves', 'obang', 'obeah', 'obeli', 'obeys', 'obias', 'obied', 'obiit', 'obits', 'objet', 'oboes', 'obole', 'oboli', 'obols', 'occam', 'ocher', 'oches', 'ochre', 'ochry', 'ocker', 'ocrea', 'octad', 'octan', 'octas', 'octyl', 'oculi', 'odahs', 'odals', 'odeon', 'odeum', 'odism', 'odist', 'odium', 'odors', 'odour', 'odyle', 'odyls', 'ofays', 'offed', 'offie', 'oflag', 'ofter', 'ogams', 'ogeed', 'ogees', 'oggin', 'ogham', 'ogive', 'ogled', 'ogler', 'ogles', 'ogmic', 'ogres', 'ohias', 'ohing', 'ohmic', 'ohone', 'oidia', 'oiled', 'oiler', 'oinks', 'oints', 'ojime', 'okapi', 'okays', 'okehs', 'okras', 'oktas', 'oldie', 'oleic', 'olein', 'olent', 'oleos', 'oleum', 'olios', 'ollas', 'ollav', 'oller', 'ollie', 'ology', 'olpae', 'olpes', 'omasa', 'omber', 'ombus', 'omens', 'omers', 'omits', 'omlah', 'omovs', 'omrah', 'oncer', 'onces', 'oncet', 'oncus', 'onely', 'oners', 'onery', 'onium', 'onkus', 'onlay', 'onned', 'ontic', 'oobit', 'oohed', 'oomph', 'oonts', 'ooped', 'oorie', 'ooses', 'ootid', 'oozed', 'oozes', 'opahs', 'opals', 'opens', 'opepe', 'oping', 'oppos', 'opsin', 'opted', 'opter', 'orach', 'oracy', 'orals', 'orang', 'orant', 'orate', 'orbed', 'orcas', 'orcin', 'ordos', 'oread', 'orfes', 'orgia', 'orgic', 'orgue', 'oribi', 'oriel', 'orixa', 'orles', 'orlon', 'orlop', 'ormer', 'ornis', 'orpin', 'orris', 'ortho', 'orval', 'orzos', 'oscar', 'oshac', 'osier', 'osmic', 'osmol', 'ossia', 'ostia', 'otaku', 'otary', 'ottar', 'ottos', 'oubit', 'oucht', 'ouens', 'ouija', 'oulks', 'oumas', 'oundy', 'oupas', 'ouped', 'ouphe', 'ouphs', 'ourie', 'ousel', 'ousts', 'outby', 'outed', 'outre', 'outro', 'outta', 'ouzel', 'ouzos', 'ovals', 'ovels', 'ovens', 'overs', 'ovist', 'ovoli', 'ovolo', 'ovule', 'owche', 'owies', 'owled', 'owler', 'owlet', 'owned', 'owres', 'owrie', 'owsen', 'oxbow', 'oxers', 'oxeye', 'oxids', 'oxies', 'oxime', 'oxims', 'oxlip', 'oxter', 'oyers', 'ozeki', 'ozzie', 'paals', 'paans', 'pacas', 'paced', 'pacer', 'paces', 'pacey', 'pacha', 'packs', 'pacos', 'pacta', 'pacts', 'padis', 'padle', 'padma', 'padre', 'padri', 'paean', 'paedo', 'paeon', 'paged', 'pager', 'pages', 'pagle', 'pagod', 'pagri', 'paiks', 'pails', 'pains', 'paire', 'pairs', 'paisa', 'paise', 'pakka', 'palas', 'palay', 'palea', 'paled', 'pales', 'palet', 'palis', 'palki', 'palla', 'palls', 'pally', 'palms', 'palmy', 'palpi', 'palps', 'palsa', 'pampa', 'panax', 'pance', 'panda', 'pands', 'pandy', 'paned', 'panes', 'panga', 'pangs', 'panim', 'panko', 'panne', 'panni', 'panto', 'pants', 'panty', 'paoli', 'paolo', 'papas', 'papaw', 'papes', 'pappi', 'pappy', 'parae', 'paras', 'parch', 'pardi', 'pards', 'pardy', 'pared', 'paren', 'pareo', 'pares', 'pareu', 'parev', 'parge', 'pargo', 'paris', 'parki', 'parks', 'parky', 'parle', 'parly', 'parma', 'parol', 'parps', 'parra', 'parrs', 'parti', 'parts', 'parve', 'parvo', 'paseo', 'pases', 'pasha', 'pashm', 'paska', 'paspy', 'passe', 'pasts', 'pated', 'paten', 'pater', 'pates', 'paths', 'patin', 'patka', 'patly', 'patte', 'patus', 'pauas', 'pauls', 'pavan', 'paved', 'paven', 'paver', 'paves', 'pavid', 'pavin', 'pavis', 'pawas', 'pawaw', 'pawed', 'pawer', 'pawks', 'pawky', 'pawls', 'pawns', 'paxes', 'payed', 'payor', 'paysd', 'peage', 'peags', 'peaks', 'peaky', 'peals', 'peans', 'peare', 'pears', 'peart', 'pease', 'peats', 'peaty', 'peavy', 'peaze', 'pebas', 'pechs', 'pecke', 'pecks', 'pecky', 'pedes', 'pedis', 'pedro', 'peece', 'peeks', 'peels', 'peens', 'peeoy', 'peepe', 'peeps', 'peers', 'peery', 'peeve', 'peggy', 'peghs', 'peins', 'peise', 'peize', 'pekan', 'pekes', 'pekin', 'pekoe', 'pelas', 'pelau', 'peles', 'pelfs', 'pells', 'pelma', 'pelon', 'pelta', 'pelts', 'pends', 'pendu', 'pened', 'penes', 'pengo', 'penie', 'penis', 'penks', 'penna', 'penni', 'pents', 'peons', 'peony', 'pepla', 'pepos', 'peppy', 'pepsi', 'perai', 'perce', 'percs', 'perdu', 'perdy', 'perea', 'peres', 'peris', 'perks', 'perms', 'perns', 'perog', 'perps', 'perry', 'perse', 'perst', 'perts', 'perve', 'pervo', 'pervs', 'pervy', 'pesos', 'pests', 'pesty', 'petar', 'peter', 'petit', 'petre', 'petri', 'petti', 'petto', 'pewee', 'pewit', 'peyse', 'phage', 'phang', 'phare', 'pharm', 'pheer', 'phene', 'pheon', 'phese', 'phial', 'phish', 'phizz', 'phlox', 'phoca', 'phono', 'phons', 'phots', 'phpht', 'phuts', 'phyla', 'phyle', 'piani', 'pians', 'pibal', 'pical', 'picas', 'piccy', 'picks', 'picot', 'picra', 'picul', 'piend', 'piers', 'piert', 'pieta', 'piets', 'piezo', 'pight', 'pigmy', 'piing', 'pikas', 'pikau', 'piked', 'piker', 'pikes', 'pikey', 'pikis', 'pikul', 'pilae', 'pilaf', 'pilao', 'pilar', 'pilau', 'pilaw', 'pilch', 'pilea', 'piled', 'pilei', 'piler', 'piles', 'pilis', 'pills', 'pilow', 'pilum', 'pilus', 'pimas', 'pimps', 'pinas', 'pined', 'pines', 'pingo', 'pings', 'pinko', 'pinks', 'pinna', 'pinny', 'pinon', 'pinot', 'pinta', 'pints', 'pinup', 'pions', 'piony', 'pious', 'pioye', 'pioys', 'pipal', 'pipas', 'piped', 'pipes', 'pipet', 'pipis', 'pipit', 'pippy', 'pipul', 'pirai', 'pirls', 'pirns', 'pirog', 'pisco', 'pises', 'pisky', 'pisos', 'pissy', 'piste', 'pitas', 'piths', 'piton', 'pitot', 'pitta', 'piums', 'pixes', 'pized', 'pizes', 'plaas', 'plack', 'plage', 'plans', 'plaps', 'plash', 'plasm', 'plast', 'plats', 'platt', 'platy', 'playa', 'plays', 'pleas', 'plebe', 'plebs', 'plena', 'pleon', 'plesh', 'plews', 'plica', 'plies', 'plims', 'pling', 'plink', 'ploat', 'plods', 'plong', 'plonk', 'plook', 'plops', 'plots', 'plotz', 'plouk', 'plows', 'ploye', 'ploys', 'plues', 'pluff', 'plugs', 'plums', 'plumy', 'pluot', 'pluto', 'plyer', 'poach', 'poaka', 'poake', 'poboy', 'pocks', 'pocky', 'podal', 'poddy', 'podex', 'podge', 'podgy', 'podia', 'poems', 'poeps', 'poets', 'pogey', 'pogge', 'pogos', 'pohed', 'poilu', 'poind', 'pokal', 'poked', 'pokes', 'pokey', 'pokie', 'poled', 'poler', 'poles', 'poley', 'polio', 'polis', 'polje', 'polks', 'polls', 'polly', 'polos', 'polts', 'polys', 'pombe', 'pomes', 'pommy', 'pomos', 'pomps', 'ponce', 'poncy', 'ponds', 'pones', 'poney', 'ponga', 'pongo', 'pongs', 'pongy', 'ponks', 'ponts', 'ponty', 'ponzu', 'poods', 'pooed', 'poofs', 'poofy', 'poohs', 'pooja', 'pooka', 'pooks', 'pools', 'poons', 'poops', 'poopy', 'poori', 'poort', 'poots', 'poove', 'poovy', 'popes', 'poppa', 'popsy', 'porae', 'poral', 'pored', 'porer', 'pores', 'porge', 'porgy', 'porin', 'porks', 'porky', 'porno', 'porns', 'porny', 'porta', 'ports', 'porty', 'posed', 'poses', 'posey', 'posho', 'posts', 'potae', 'potch', 'poted', 'potes', 'potin', 'potoo', 'potsy', 'potto', 'potts', 'potty', 'pouff', 'poufs', 'pouke', 'pouks', 'poule', 'poulp', 'poult', 'poupe', 'poupt', 'pours', 'pouts', 'powan', 'powin', 'pownd', 'powns', 'powny', 'powre', 'poxed', 'poxes', 'poynt', 'poyou', 'poyse', 'pozzy', 'praam', 'prads', 'prahu', 'prams', 'prana', 'prang', 'praos', 'prase', 'prate', 'prats', 'pratt', 'praty', 'praus', 'prays', 'predy', 'preed', 'prees', 'preif', 'prems', 'premy', 'prent', 'preon', 'preop', 'preps', 'presa', 'prese', 'prest', 'preve', 'prexy', 'preys', 'prial', 'pricy', 'prief', 'prier', 'pries', 'prigs', 'prill', 'prima', 'primi', 'primp', 'prims', 'primy', 'prink', 'prion', 'prise', 'priss', 'proas', 'probs', 'prods', 'proem', 'profs', 'progs', 'proin', 'proke', 'prole', 'proll', 'promo', 'proms', 'pronk', 'props', 'prore', 'proso', 'pross', 'prost', 'prosy', 'proto', 'proul', 'prows', 'proyn', 'prunt', 'pruta', 'pryer', 'pryse', 'pseud', 'pshaw', 'psion', 'psoae', 'psoai', 'psoas', 'psora', 'psych', 'psyop', 'pubco', 'pubes', 'pubis', 'pucan', 'pucer', 'puces', 'pucka', 'pucks', 'puddy', 'pudge', 'pudic', 'pudor', 'pudsy', 'pudus', 'puers', 'puffa', 'puffs', 'puggy', 'pugil', 'puhas', 'pujah', 'pujas', 'pukas', 'puked', 'puker', 'pukes', 'pukey', 'pukka', 'pukus', 'pulao', 'pulas', 'puled', 'puler', 'pules', 'pulik', 'pulis', 'pulka', 'pulks', 'pulli', 'pulls', 'pully', 'pulmo', 'pulps', 'pulus', 'pumas', 'pumie', 'pumps', 'punas', 'punce', 'punga', 'pungs', 'punji', 'punka', 'punks', 'punky', 'punny', 'punto', 'punts', 'punty', 'pupae', 'pupas', 'pupus', 'purda', 'pured', 'pures', 'purin', 'puris', 'purls', 'purpy', 'purrs', 'pursy', 'purty', 'puses', 'pusle', 'pussy', 'putid', 'puton', 'putti', 'putto', 'putts', 'puzel', 'pwned', 'pyats', 'pyets', 'pygal', 'pyins', 'pylon', 'pyned', 'pynes', 'pyoid', 'pyots', 'pyral', 'pyran', 'pyres', 'pyrex', 'pyric', 'pyros', 'pyxed', 'pyxes', 'pyxie', 'pyxis', 'pzazz', 'qadis', 'qaids', 'qajaq', 'qanat', 'qapik', 'qibla', 'qophs', 'qorma', 'quads', 'quaff', 'quags', 'quair', 'quais', 'quaky', 'quale', 'quant', 'quare', 'quass', 'quate', 'quats', 'quayd', 'quays', 'qubit', 'quean', 'queme', 'quena', 'quern', 'queyn', 'queys', 'quich', 'quids', 'quiff', 'quims', 'quina', 'quine', 'quino', 'quins', 'quint', 'quipo', 'quips', 'quipu', 'quire', 'quirt', 'quist', 'quits', 'quoad', 'quods', 'quoif', 'quoin', 'quoit', 'quoll', 'quonk', 'quops', 'qursh', 'quyte', 'rabat', 'rabic', 'rabis', 'raced', 'races', 'rache', 'racks', 'racon', 'radge', 'radix', 'radon', 'raffs', 'rafts', 'ragas', 'ragde', 'raged', 'ragee', 'rager', 'rages', 'ragga', 'raggs', 'raggy', 'ragis', 'ragus', 'rahed', 'rahui', 'raias', 'raids', 'raiks', 'raile', 'rails', 'raine', 'rains', 'raird', 'raita', 'raits', 'rajas', 'rajes', 'raked', 'rakee', 'raker', 'rakes', 'rakia', 'rakis', 'rakus', 'rales', 'ramal', 'ramee', 'ramet', 'ramie', 'ramin', 'ramis', 'rammy', 'ramps', 'ramus', 'ranas', 'rance', 'rands', 'ranee', 'ranga', 'rangi', 'rangs', 'rangy', 'ranid', 'ranis', 'ranke', 'ranks', 'rants', 'raped', 'raper', 'rapes', 'raphe', 'rappe', 'rared', 'raree', 'rares', 'rarks', 'rased', 'raser', 'rases', 'rasps', 'rasse', 'rasta', 'ratal', 'ratan', 'ratas', 'ratch', 'rated', 'ratel', 'rater', 'rates', 'ratha', 'rathe', 'raths', 'ratoo', 'ratos', 'ratus', 'rauns', 'raupo', 'raved', 'ravel', 'raver', 'raves', 'ravey', 'ravin', 'rawer', 'rawin', 'rawly', 'rawns', 'raxed', 'raxes', 'rayah', 'rayas', 'rayed', 'rayle', 'rayne', 'razed', 'razee', 'razer', 'razes', 'razoo', 'readd', 'reads', 'reais', 'reaks', 'realo', 'reals', 'reame', 'reams', 'reamy', 'reans', 'reaps', 'rears', 'reast', 'reata', 'reate', 'reave', 'rebbe', 'rebec', 'rebid', 'rebit', 'rebop', 'rebuy', 'recal', 'recce', 'recco', 'reccy', 'recit', 'recks', 'recon', 'recta', 'recti', 'recto', 'redan', 'redds', 'reddy', 'reded', 'redes', 'redia', 'redid', 'redip', 'redly', 'redon', 'redos', 'redox', 'redry', 'redub', 'redux', 'redye', 'reech', 'reede', 'reeds', 'reefs', 'reefy', 'reeks', 'reeky', 'reels', 'reens', 'reest', 'reeve', 'refed', 'refel', 'reffo', 'refis', 'refix', 'refly', 'refry', 'regar', 'reges', 'reggo', 'regie', 'regma', 'regna', 'regos', 'regur', 'rehem', 'reifs', 'reify', 'reiki', 'reiks', 'reink', 'reins', 'reird', 'reist', 'reive', 'rejig', 'rejon', 'reked', 'rekes', 'rekey', 'relet', 'relie', 'relit', 'rello', 'reman', 'remap', 'remen', 'remet', 'remex', 'remix', 'renay', 'rends', 'reney', 'renga', 'renig', 'renin', 'renne', 'renos', 'rente', 'rents', 'reoil', 'reorg', 'repeg', 'repin', 'repla', 'repos', 'repot', 'repps', 'repro', 'reran', 'rerig', 'resat', 'resaw', 'resay', 'resee', 'reses', 'resew', 'resid', 'resit', 'resod', 'resow', 'resto', 'rests', 'resty', 'resus', 'retag', 'retax', 'retem', 'retia', 'retie', 'retox', 'revet', 'revie', 'rewan', 'rewax', 'rewed', 'rewet', 'rewin', 'rewon', 'rewth', 'rexes', 'rezes', 'rheas', 'rheme', 'rheum', 'rhies', 'rhime', 'rhine', 'rhody', 'rhomb', 'rhone', 'rhumb', 'rhyne', 'rhyta', 'riads', 'rials', 'riant', 'riata', 'ribas', 'ribby', 'ribes', 'riced', 'ricer', 'rices', 'ricey', 'richt', 'ricin', 'ricks', 'rides', 'ridgy', 'ridic', 'riels', 'riems', 'rieve', 'rifer', 'riffs', 'rifte', 'rifts', 'rifty', 'riggs', 'rigol', 'riled', 'riles', 'riley', 'rille', 'rills', 'rimae', 'rimed', 'rimer', 'rimes', 'rimus', 'rinds', 'rindy', 'rines', 'rings', 'rinks', 'rioja', 'riots', 'riped', 'ripes', 'ripps', 'rises', 'rishi', 'risks', 'risps', 'risus', 'rites', 'ritts', 'ritzy', 'rivas', 'rived', 'rivel', 'riven', 'rives', 'riyal', 'rizas', 'roads', 'roams', 'roans', 'roars', 'roary', 'roate', 'robed', 'robes', 'roble', 'rocks', 'roded', 'rodes', 'roguy', 'rohes', 'roids', 'roils', 'roily', 'roins', 'roist', 'rojak', 'rojis', 'roked', 'roker', 'rokes', 'rolag', 'roles', 'rolfs', 'rolls', 'romal', 'roman', 'romeo', 'romps', 'ronde', 'rondo', 'roneo', 'rones', 'ronin', 'ronne', 'ronte', 'ronts', 'roods', 'roofs', 'roofy', 'rooks', 'rooky', 'rooms', 'roons', 'roops', 'roopy', 'roosa', 'roose', 'roots', 'rooty', 'roped', 'roper', 'ropes', 'ropey', 'roque', 'roral', 'rores', 'roric', 'rorid', 'rorie', 'rorts', 'rorty', 'rosed', 'roses', 'roset', 'roshi', 'rosin', 'rosit', 'rosti', 'rosts', 'rotal', 'rotan', 'rotas', 'rotch', 'roted', 'rotes', 'rotis', 'rotls', 'roton', 'rotos', 'rotte', 'rouen', 'roues', 'roule', 'rouls', 'roums', 'roups', 'roupy', 'roust', 'routh', 'routs', 'roved', 'roven', 'roves', 'rowan', 'rowed', 'rowel', 'rowen', 'rowie', 'rowme', 'rownd', 'rowth', 'rowts', 'royne', 'royst', 'rozet', 'rozit', 'ruana', 'rubai', 'rubby', 'rubel', 'rubes', 'rubin', 'ruble', 'rubli', 'rubus', 'ruche', 'rucks', 'rudas', 'rudds', 'rudes', 'rudie', 'rudis', 'rueda', 'ruers', 'ruffe', 'ruffs', 'rugae', 'rugal', 'ruggy', 'ruing', 'ruins', 'rukhs', 'ruled', 'rules', 'rumal', 'rumbo', 'rumen', 'rumes', 'rumly', 'rummy', 'rumpo', 'rumps', 'rumpy', 'runch', 'runds', 'runed', 'runes', 'rungs', 'runic', 'runny', 'runts', 'runty', 'rupia', 'rurps', 'rurus', 'rusas', 'ruses', 'rushy', 'rusks', 'rusma', 'russe', 'rusts', 'ruths', 'rutin', 'rutty', 'ryals', 'rybat', 'ryked', 'rykes', 'rymme', 'rynds', 'ryots', 'ryper', 'saags', 'sabal', 'sabed', 'saber', 'sabes', 'sabha', 'sabin', 'sabir', 'sable', 'sabot', 'sabra', 'sabre', 'sacks', 'sacra', 'saddo', 'sades', 'sadhe', 'sadhu', 'sadis', 'sados', 'sadza', 'safed', 'safes', 'sagas', 'sager', 'sages', 'saggy', 'sagos', 'sagum', 'saheb', 'sahib', 'saice', 'saick', 'saics', 'saids', 'saiga', 'sails', 'saims', 'saine', 'sains', 'sairs', 'saist', 'saith', 'sajou', 'sakai', 'saker', 'sakes', 'sakia', 'sakis', 'sakti', 'salal', 'salat', 'salep', 'sales', 'salet', 'salic', 'salix', 'salle', 'salmi', 'salol', 'salop', 'salpa', 'salps', 'salse', 'salto', 'salts', 'salue', 'salut', 'saman', 'samas', 'samba', 'sambo', 'samek', 'samel', 'samen', 'sames', 'samey', 'samfu', 'sammy', 'sampi', 'samps', 'sands', 'saned', 'sanes', 'sanga', 'sangh', 'sango', 'sangs', 'sanko', 'sansa', 'santo', 'sants', 'saola', 'sapan', 'sapid', 'sapor', 'saran', 'sards', 'sared', 'saree', 'sarge', 'sargo', 'sarin', 'saris', 'sarks', 'sarky', 'sarod', 'saros', 'sarus', 'saser', 'sasin', 'sasse', 'satai', 'satay', 'sated', 'satem', 'sates', 'satis', 'sauba', 'sauch', 'saugh', 'sauls', 'sault', 'saunt', 'saury', 'sauts', 'saved', 'saver', 'saves', 'savey', 'savin', 'sawah', 'sawed', 'sawer', 'saxes', 'sayed', 'sayer', 'sayid', 'sayne', 'sayon', 'sayst', 'sazes', 'scabs', 'scads', 'scaff', 'scags', 'scail', 'scala', 'scall', 'scams', 'scand', 'scans', 'scapa', 'scape', 'scapi', 'scarp', 'scars', 'scart', 'scath', 'scats', 'scatt', 'scaud', 'scaup', 'scaur', 'scaws', 'sceat', 'scena', 'scend', 'schav', 'schmo', 'schul', 'schwa', 'sclim', 'scody', 'scogs', 'scoog', 'scoot', 'scopa', 'scops', 'scots', 'scoug', 'scoup', 'scowp', 'scows', 'scrab', 'scrae', 'scrag', 'scran', 'scrat', 'scraw', 'scray', 'scrim', 'scrip', 'scrob', 'scrod', 'scrog', 'scrow', 'scudi', 'scudo', 'scuds', 'scuff', 'scuft', 'scugs', 'sculk', 'scull', 'sculp', 'sculs', 'scums', 'scups', 'scurf', 'scurs', 'scuse', 'scuta', 'scute', 'scuts', 'scuzz', 'scyes', 'sdayn', 'sdein', 'seals', 'seame', 'seams', 'seamy', 'seans', 'seare', 'sears', 'sease', 'seats', 'seaze', 'sebum', 'secco', 'sechs', 'sects', 'seder', 'sedes', 'sedge', 'sedgy', 'sedum', 'seeds', 'seeks', 'seeld', 'seels', 'seely', 'seems', 'seeps', 'seepy', 'seers', 'sefer', 'segar', 'segni', 'segno', 'segol', 'segos', 'sehri', 'seifs', 'seils', 'seine', 'seirs', 'seise', 'seism', 'seity', 'seiza', 'sekos', 'sekts', 'selah', 'seles', 'selfs', 'sella', 'selle', 'sells', 'selva', 'semee', 'semes', 'semie', 'semis', 'senas', 'sends', 'senes', 'sengi', 'senna', 'senor', 'sensa', 'sensi', 'sente', 'senti', 'sents', 'senvy', 'senza', 'sepad', 'sepal', 'sepic', 'sepoy', 'septa', 'septs', 'serac', 'serai', 'seral', 'sered', 'serer', 'seres', 'serfs', 'serge', 'seric', 'serin', 'serks', 'seron', 'serow', 'serra', 'serre', 'serrs', 'serry', 'servo', 'sesey', 'sessa', 'setae', 'setal', 'seton', 'setts', 'sewan', 'sewar', 'sewed', 'sewel', 'sewen', 'sewin', 'sexed', 'sexer', 'sexes', 'sexto', 'sexts', 'seyen', 'shads', 'shags', 'shahs', 'shako', 'shakt', 'shalm', 'shaly', 'shama', 'shams', 'shand', 'shans', 'shaps', 'sharn', 'shash', 'shaul', 'shawm', 'shawn', 'shaws', 'shaya', 'shays', 'shchi', 'sheaf', 'sheal', 'sheas', 'sheds', 'sheel', 'shend', 'shent', 'sheol', 'sherd', 'shere', 'shero', 'shets', 'sheva', 'shewn', 'shews', 'shiai', 'shiel', 'shier', 'shies', 'shill', 'shily', 'shims', 'shins', 'ships', 'shirr', 'shirs', 'shish', 'shiso', 'shist', 'shite', 'shits', 'shiur', 'shiva', 'shive', 'shivs', 'shlep', 'shlub', 'shmek', 'shmoe', 'shoat', 'shoed', 'shoer', 'shoes', 'shogi', 'shogs', 'shoji', 'shojo', 'shola', 'shool', 'shoon', 'shoos', 'shope', 'shops', 'shorl', 'shote', 'shots', 'shott', 'showd', 'shows', 'shoyu', 'shred', 'shris', 'shrow', 'shtik', 'shtum', 'shtup', 'shule', 'shuln', 'shuls', 'shuns', 'shura', 'shute', 'shuts', 'shwas', 'shyer', 'sials', 'sibbs', 'sibyl', 'sices', 'sicht', 'sicko', 'sicks', 'sicky', 'sidas', 'sided', 'sider', 'sides', 'sidha', 'sidhe', 'sidle', 'sield', 'siens', 'sient', 'sieth', 'sieur', 'sifts', 'sighs', 'sigil', 'sigla', 'signa', 'signs', 'sijos', 'sikas', 'siker', 'sikes', 'silds', 'siled', 'silen', 'siler', 'siles', 'silex', 'silks', 'sills', 'silos', 'silts', 'silty', 'silva', 'simar', 'simas', 'simba', 'simis', 'simps', 'simul', 'sinds', 'sined', 'sines', 'sings', 'sinhs', 'sinks', 'sinky', 'sinus', 'siped', 'sipes', 'sippy', 'sired', 'siree', 'sires', 'sirih', 'siris', 'siroc', 'sirra', 'sirup', 'sisal', 'sises', 'sista', 'sists', 'sitar', 'sited', 'sites', 'sithe', 'sitka', 'situp', 'situs', 'siver', 'sixer', 'sixes', 'sixmo', 'sixte', 'sizar', 'sized', 'sizel', 'sizer', 'sizes', 'skags', 'skail', 'skald', 'skank', 'skart', 'skats', 'skatt', 'skaws', 'skean', 'skear', 'skeds', 'skeed', 'skeef', 'skeen', 'skeer', 'skees', 'skeet', 'skegg', 'skegs', 'skein', 'skelf', 'skell', 'skelm', 'skelp', 'skene', 'skens', 'skeos', 'skeps', 'skers', 'skets', 'skews', 'skids', 'skied', 'skies', 'skiey', 'skimo', 'skims', 'skink', 'skins', 'skint', 'skios', 'skips', 'skirl', 'skirr', 'skite', 'skits', 'skive', 'skivy', 'sklim', 'skoal', 'skody', 'skoff', 'skogs', 'skols', 'skool', 'skort', 'skosh', 'skran', 'skrik', 'skuas', 'skugs', 'skyed', 'skyer', 'skyey', 'skyfs', 'skyre', 'skyrs', 'skyte', 'slabs', 'slade', 'slaes', 'slags', 'slaid', 'slake', 'slams', 'slane', 'slank', 'slaps', 'slart', 'slats', 'slaty', 'slaws', 'slays', 'slebs', 'sleds', 'sleer', 'slews', 'sleys', 'slier', 'slily', 'slims', 'slipe', 'slips', 'slipt', 'slish', 'slits', 'slive', 'sloan', 'slobs', 'sloes', 'slogs', 'sloid', 'slojd', 'slomo', 'sloom', 'sloot', 'slops', 'slopy', 'slorm', 'slots', 'slove', 'slows', 'sloyd', 'slubb', 'slubs', 'slued', 'slues', 'sluff', 'slugs', 'sluit', 'slums', 'slurb', 'slurs', 'sluse', 'sluts', 'slyer', 'slype', 'smaak', 'smaik', 'smalm', 'smalt', 'smarm', 'smaze', 'smeek', 'smees', 'smeik', 'smeke', 'smerk', 'smews', 'smirr', 'smirs', 'smits', 'smogs', 'smoko', 'smolt', 'smoor', 'smoot', 'smore', 'smorg', 'smout', 'smowt', 'smugs', 'smurs', 'smush', 'smuts', 'snabs', 'snafu', 'snags', 'snaps', 'snarf', 'snark', 'snars', 'snary', 'snash', 'snath', 'snaws', 'snead', 'sneap', 'snebs', 'sneck', 'sneds', 'sneed', 'snees', 'snell', 'snibs', 'snick', 'snies', 'snift', 'snigs', 'snips', 'snipy', 'snirt', 'snits', 'snobs', 'snods', 'snoek', 'snoep', 'snogs', 'snoke', 'snood', 'snook', 'snool', 'snoot', 'snots', 'snowk', 'snows', 'snubs', 'snugs', 'snush', 'snyes', 'soaks', 'soaps', 'soare', 'soars', 'soave', 'sobas', 'socas', 'soces', 'socko', 'socks', 'socle', 'sodas', 'soddy', 'sodic', 'sodom', 'sofar', 'sofas', 'softa', 'softs', 'softy', 'soger', 'sohur', 'soils', 'soily', 'sojas', 'sojus', 'sokah', 'soken', 'sokes', 'sokol', 'solah', 'solan', 'solas', 'solde', 'soldi', 'soldo', 'solds', 'soled', 'solei', 'soler', 'soles', 'solon', 'solos', 'solum', 'solus', 'soman', 'somas', 'sonce', 'sonde', 'sones', 'songs', 'sonly', 'sonne', 'sonny', 'sonse', 'sonsy', 'sooey', 'sooks', 'sooky', 'soole', 'sools', 'sooms', 'soops', 'soote', 'soots', 'sophs', 'sophy', 'sopor', 'soppy', 'sopra', 'soral', 'soras', 'sorbo', 'sorbs', 'sorda', 'sordo', 'sords', 'sored', 'soree', 'sorel', 'sorer', 'sores', 'sorex', 'sorgo', 'sorns', 'sorra', 'sorta', 'sorts', 'sorus', 'soths', 'sotol', 'souce', 'souct', 'sough', 'souks', 'souls', 'soums', 'soups', 'soupy', 'sours', 'souse', 'souts', 'sowar', 'sowce', 'sowed', 'sowff', 'sowfs', 'sowle', 'sowls', 'sowms', 'sownd', 'sowne', 'sowps', 'sowse', 'sowth', 'soyas', 'soyle', 'soyuz', 'sozin', 'spacy', 'spado', 'spaed', 'spaer', 'spaes', 'spags', 'spahi', 'spail', 'spain', 'spait', 'spake', 'spald', 'spale', 'spall', 'spalt', 'spams', 'spane', 'spang', 'spans', 'spard', 'spars', 'spart', 'spate', 'spats', 'spaul', 'spawl', 'spaws', 'spayd', 'spays', 'spaza', 'spazz', 'speal', 'spean', 'speat', 'specs', 'spect', 'speel', 'speer', 'speil', 'speir', 'speks', 'speld', 'spelk', 'speos', 'spets', 'speug', 'spews', 'spewy', 'spial', 'spica', 'spick', 'spics', 'spide', 'spier', 'spies', 'spiff', 'spifs', 'spiks', 'spile', 'spims', 'spina', 'spink', 'spins', 'spirt', 'spiry', 'spits', 'spitz', 'spivs', 'splay', 'splog', 'spode', 'spods', 'spoom', 'spoor', 'spoot', 'spork', 'sposh', 'spots', 'sprad', 'sprag', 'sprat', 'spred', 'sprew', 'sprit', 'sprod', 'sprog', 'sprue', 'sprug', 'spuds', 'spued', 'spuer', 'spues', 'spugs', 'spule', 'spume', 'spumy', 'spurs', 'sputa', 'spyal', 'spyre', 'squab', 'squaw', 'squeg', 'squid', 'squit', 'squiz', 'stabs', 'stade', 'stags', 'stagy', 'staig', 'stane', 'stang', 'staph', 'staps', 'starn', 'starr', 'stars', 'stats', 'staun', 'staws', 'stays', 'stean', 'stear', 'stedd', 'stede', 'steds', 'steek', 'steem', 'steen', 'steil', 'stela', 'stele', 'stell', 'steme', 'stems', 'stend', 'steno', 'stens', 'stent', 'steps', 'stept', 'stere', 'stets', 'stews', 'stewy', 'steys', 'stich', 'stied', 'sties', 'stilb', 'stile', 'stime', 'stims', 'stimy', 'stipa', 'stipe', 'stire', 'stirk', 'stirp', 'stirs', 'stive', 'stivy', 'stoae', 'stoai', 'stoas', 'stoat', 'stobs', 'stoep', 'stogy', 'stoit', 'stoln', 'stoma', 'stond', 'stong', 'stonk', 'stonn', 'stook', 'stoor', 'stope', 'stops', 'stopt', 'stoss', 'stots', 'stott', 'stoun', 'stoup', 'stour', 'stown', 'stowp', 'stows', 'strad', 'strae', 'strag', 'strak', 'strep', 'strew', 'stria', 'strig', 'strim', 'strop', 'strow', 'stroy', 'strum', 'stubs', 'stude', 'studs', 'stull', 'stulm', 'stumm', 'stums', 'stuns', 'stupa', 'stupe', 'sture', 'sturt', 'styed', 'styes', 'styli', 'stylo', 'styme', 'stymy', 'styre', 'styte', 'subah', 'subas', 'subby', 'suber', 'subha', 'succi', 'sucks', 'sucky', 'sucre', 'sudds', 'sudor', 'sudsy', 'suede', 'suent', 'suers', 'suete', 'suets', 'suety', 'sugan', 'sughs', 'sugos', 'suhur', 'suids', 'suint', 'suits', 'sujee', 'sukhs', 'sukuk', 'sulci', 'sulfa', 'sulfo', 'sulks', 'sulph', 'sulus', 'sumis', 'summa', 'sumos', 'sumph', 'sumps', 'sunis', 'sunks', 'sunna', 'sunns', 'sunup', 'supes', 'supra', 'surah', 'sural', 'suras', 'surat', 'surds', 'sured', 'sures', 'surfs', 'surfy', 'surgy', 'surra', 'sused', 'suses', 'susus', 'sutor', 'sutra', 'sutta', 'swabs', 'swack', 'swads', 'swage', 'swags', 'swail', 'swain', 'swale', 'swaly', 'swamy', 'swang', 'swank', 'swans', 'swaps', 'swapt', 'sward', 'sware', 'swarf', 'swart', 'swats', 'swayl', 'sways', 'sweal', 'swede', 'sweed', 'sweel', 'sweer', 'swees', 'sweir', 'swelt', 'swerf', 'sweys', 'swies', 'swigs', 'swile', 'swims', 'swink', 'swipe', 'swire', 'swiss', 'swith', 'swits', 'swive', 'swizz', 'swobs', 'swole', 'swoln', 'swops', 'swopt', 'swots', 'swoun', 'sybbe', 'sybil', 'syboe', 'sybow', 'sycee', 'syces', 'sycon', 'syens', 'syker', 'sykes', 'sylis', 'sylph', 'sylva', 'symar', 'synch', 'syncs', 'synds', 'syned', 'synes', 'synth', 'syped', 'sypes', 'syphs', 'syrah', 'syren', 'sysop', 'sythe', 'syver', 'taals', 'taata', 'taber', 'tabes', 'tabid', 'tabis', 'tabla', 'tabor', 'tabun', 'tabus', 'tacan', 'taces', 'tacet', 'tache', 'tacho', 'tachs', 'tacks', 'tacos', 'tacts', 'taels', 'tafia', 'taggy', 'tagma', 'tahas', 'tahrs', 'taiga', 'taigs', 'taiko', 'tails', 'tains', 'taira', 'taish', 'taits', 'tajes', 'takas', 'takes', 'takhi', 'takin', 'takis', 'takky', 'talak', 'talaq', 'talar', 'talas', 'talcs', 'talcy', 'talea', 'taler', 'tales', 'talks', 'talky', 'talls', 'talma', 'talpa', 'taluk', 'talus', 'tamal', 'tamed', 'tames', 'tamin', 'tamis', 'tammy', 'tamps', 'tanas', 'tanga', 'tangi', 'tangs', 'tanhs', 'tanka', 'tanks', 'tanky', 'tanna', 'tansy', 'tanti', 'tanto', 'tanty', 'tapas', 'taped', 'tapen', 'tapes', 'tapet', 'tapis', 'tappa', 'tapus', 'taras', 'tardo', 'tared', 'tares', 'targa', 'targe', 'tarns', 'taroc', 'tarok', 'taros', 'tarps', 'tarre', 'tarry', 'tarsi', 'tarts', 'tarty', 'tasar', 'tased', 'taser', 'tases', 'tasks', 'tassa', 'tasse', 'tasso', 'tatar', 'tater', 'tates', 'taths', 'tatie', 'tatou', 'tatts', 'tatus', 'taube', 'tauld', 'tauon', 'taupe', 'tauts', 'tavah', 'tavas', 'taver', 'tawai', 'tawas', 'tawed', 'tawer', 'tawie', 'tawse', 'tawts', 'taxed', 'taxer', 'taxes', 'taxis', 'taxol', 'taxon', 'taxor', 'taxus', 'tayra', 'tazza', 'tazze', 'teade', 'teads', 'teaed', 'teaks', 'teals', 'teams', 'tears', 'teats', 'teaze', 'techs', 'techy', 'tecta', 'teels', 'teems', 'teend', 'teene', 'teens', 'teeny', 'teers', 'teffs', 'teggs', 'tegua', 'tegus', 'tehrs', 'teiid', 'teils', 'teind', 'teins', 'telae', 'telco', 'teles', 'telex', 'telia', 'telic', 'tells', 'telly', 'teloi', 'telos', 'temed', 'temes', 'tempi', 'temps', 'tempt', 'temse', 'tench', 'tends', 'tendu', 'tenes', 'tenge', 'tenia', 'tenne', 'tenno', 'tenny', 'tenon', 'tents', 'tenty', 'tenue', 'tepal', 'tepas', 'tepoy', 'terai', 'teras', 'terce', 'terek', 'teres', 'terfe', 'terfs', 'terga', 'terms', 'terne', 'terns', 'terry', 'terts', 'tesla', 'testa', 'teste', 'tests', 'tetes', 'teths', 'tetra', 'tetri', 'teuch', 'teugh', 'tewed', 'tewel', 'tewit', 'texas', 'texes', 'texts', 'thack', 'thagi', 'thaim', 'thale', 'thali', 'thana', 'thane', 'thang', 'thans', 'thanx', 'tharm', 'thars', 'thaws', 'thawy', 'thebe', 'theca', 'theed', 'theek', 'thees', 'thegn', 'theic', 'thein', 'thelf', 'thema', 'thens', 'theow', 'therm', 'thesp', 'thete', 'thews', 'thewy', 'thigs', 'thilk', 'thill', 'thine', 'thins', 'thiol', 'thirl', 'thoft', 'thole', 'tholi', 'thoro', 'thorp', 'thous', 'thowl', 'thrae', 'thraw', 'thrid', 'thrip', 'throe', 'thuds', 'thugs', 'thuja', 'thunk', 'thurl', 'thuya', 'thymi', 'thymy', 'tians', 'tiars', 'tical', 'ticca', 'ticed', 'tices', 'tichy', 'ticks', 'ticky', 'tiddy', 'tided', 'tides', 'tiers', 'tiffs', 'tifos', 'tifts', 'tiges', 'tigon', 'tikas', 'tikes', 'tikis', 'tikka', 'tilak', 'tiled', 'tiler', 'tiles', 'tills', 'tilly', 'tilth', 'tilts', 'timbo', 'timed', 'times', 'timon', 'timps', 'tinas', 'tinct', 'tinds', 'tinea', 'tined', 'tines', 'tinge', 'tings', 'tinks', 'tinny', 'tints', 'tinty', 'tipis', 'tippy', 'tired', 'tires', 'tirls', 'tiros', 'tirrs', 'titch', 'titer', 'titis', 'titre', 'titty', 'titup', 'tiyin', 'tiyns', 'tizes', 'tizzy', 'toads', 'toady', 'toaze', 'tocks', 'tocky', 'tocos', 'todde', 'toeas', 'toffs', 'toffy', 'tofts', 'tofus', 'togae', 'togas', 'toged', 'toges', 'togue', 'tohos', 'toile', 'toils', 'toing', 'toise', 'toits', 'tokay', 'toked', 'toker', 'tokes', 'tokos', 'tolan', 'tolar', 'tolas', 'toled', 'toles', 'tolls', 'tolly', 'tolts', 'tolus', 'tolyl', 'toman', 'tombs', 'tomes', 'tomia', 'tommy', 'tomos', 'tondi', 'tondo', 'toned', 'toner', 'tones', 'toney', 'tongs', 'tonka', 'tonks', 'tonne', 'tonus', 'tools', 'tooms', 'toons', 'toots', 'toped', 'topee', 'topek', 'toper', 'topes', 'tophe', 'tophi', 'tophs', 'topis', 'topoi', 'topos', 'toppy', 'toque', 'torah', 'toran', 'toras', 'torcs', 'tores', 'toric', 'torii', 'toros', 'torot', 'torrs', 'torse', 'torsi', 'torsk', 'torta', 'torte', 'torts', 'tosas', 'tosed', 'toses', 'toshy', 'tossy', 'toted', 'toter', 'totes', 'totty', 'touks', 'touns', 'tours', 'touse', 'tousy', 'touts', 'touze', 'touzy', 'towed', 'towie', 'towns', 'towny', 'towse', 'towsy', 'towts', 'towze', 'towzy', 'toyed', 'toyer', 'toyon', 'toyos', 'tozed', 'tozes', 'tozie', 'trabs', 'trads', 'tragi', 'traik', 'trams', 'trank', 'tranq', 'trans', 'trant', 'trape', 'traps', 'trapt', 'trass', 'trats', 'tratt', 'trave', 'trayf', 'trays', 'treck', 'treed', 'treen', 'trees', 'trefa', 'treif', 'treks', 'trema', 'trems', 'tress', 'trest', 'trets', 'trews', 'treyf', 'treys', 'triac', 'tride', 'trier', 'tries', 'triff', 'trigo', 'trigs', 'trike', 'trild', 'trill', 'trims', 'trine', 'trins', 'triol', 'trior', 'trios', 'trips', 'tripy', 'trist', 'troad', 'troak', 'troat', 'trock', 'trode', 'trods', 'trogs', 'trois', 'troke', 'tromp', 'trona', 'tronc', 'trone', 'tronk', 'trons', 'trooz', 'troth', 'trots', 'trows', 'troys', 'trued', 'trues', 'trugo', 'trugs', 'trull', 'tryer', 'tryke', 'tryma', 'tryps', 'tsade', 'tsadi', 'tsars', 'tsked', 'tsuba', 'tsubo', 'tuans', 'tuart', 'tuath', 'tubae', 'tubar', 'tubas', 'tubby', 'tubed', 'tubes', 'tucks', 'tufas', 'tuffe', 'tuffs', 'tufts', 'tufty', 'tugra', 'tuile', 'tuina', 'tuism', 'tuktu', 'tules', 'tulpa', 'tulsi', 'tumid', 'tummy', 'tumps', 'tumpy', 'tunas', 'tunds', 'tuned', 'tuner', 'tunes', 'tungs', 'tunny', 'tupek', 'tupik', 'tuple', 'tuque', 'turds', 'turfs', 'turfy', 'turks', 'turme', 'turms', 'turns', 'turnt', 'turps', 'turrs', 'tushy', 'tusks', 'tusky', 'tutee', 'tutti', 'tutty', 'tutus', 'tuxes', 'tuyer', 'twaes', 'twain', 'twals', 'twank', 'twats', 'tways', 'tweel', 'tween', 'tweep', 'tweer', 'twerk', 'twerp', 'twier', 'twigs', 'twill', 'twilt', 'twink', 'twins', 'twiny', 'twire', 'twirp', 'twite', 'twits', 'twoer', 'twyer', 'tyees', 'tyers', 'tyiyn', 'tykes', 'tyler', 'tymps', 'tynde', 'tyned', 'tynes', 'typal', 'typed', 'types', 'typey', 'typic', 'typos', 'typps', 'typto', 'tyran', 'tyred', 'tyres', 'tyros', 'tythe', 'tzars', 'udals', 'udons', 'ugali', 'ugged', 'uhlan', 'uhuru', 'ukase', 'ulama', 'ulans', 'ulema', 'ulmin', 'ulnad', 'ulnae', 'ulnar', 'ulnas', 'ulpan', 'ulvas', 'ulyie', 'ulzie', 'umami', 'umbel', 'umber', 'umble', 'umbos', 'umbre', 'umiac', 'umiak', 'umiaq', 'ummah', 'ummas', 'ummed', 'umped', 'umphs', 'umpie', 'umpty', 'umrah', 'umras', 'unais', 'unapt', 'unarm', 'unary', 'unaus', 'unbag', 'unban', 'unbar', 'unbed', 'unbid', 'unbox', 'uncap', 'unces', 'uncia', 'uncos', 'uncoy', 'uncus', 'undam', 'undee', 'undos', 'undug', 'uneth', 'unfix', 'ungag', 'unget', 'ungod', 'ungot', 'ungum', 'unhat', 'unhip', 'unica', 'units', 'unjam', 'unked', 'unket', 'unkid', 'unlaw', 'unlay', 'unled', 'unlet', 'unlid', 'unman', 'unmew', 'unmix', 'unpay', 'unpeg', 'unpen', 'unpin', 'unred', 'unrid', 'unrig', 'unrip', 'unsaw', 'unsay', 'unsee', 'unsew', 'unsex', 'unsod', 'untax', 'untin', 'unwet', 'unwit', 'unwon', 'upbow', 'upbye', 'updos', 'updry', 'upend', 'upjet', 'uplay', 'upled', 'uplit', 'upped', 'upran', 'uprun', 'upsee', 'upsey', 'uptak', 'upter', 'uptie', 'uraei', 'urali', 'uraos', 'urare', 'urari', 'urase', 'urate', 'urbex', 'urbia', 'urdee', 'ureal', 'ureas', 'uredo', 'ureic', 'urena', 'urent', 'urged', 'urger', 'urges', 'urial', 'urite', 'urman', 'urnal', 'urned', 'urped', 'ursae', 'ursid', 'urson', 'urubu', 'urvas', 'users', 'usnea', 'usque', 'usure', 'usury', 'uteri', 'uveal', 'uveas', 'uvula', 'vacua', 'vaded', 'vades', 'vagal', 'vagus', 'vails', 'vaire', 'vairs', 'vairy', 'vakas', 'vakil', 'vales', 'valis', 'valse', 'vamps', 'vampy', 'vanda', 'vaned', 'vanes', 'vangs', 'vants', 'vaped', 'vaper', 'vapes', 'varan', 'varas', 'vardy', 'varec', 'vares', 'varia', 'varix', 'varna', 'varus', 'varve', 'vasal', 'vases', 'vasts', 'vasty', 'vatic', 'vatus', 'vauch', 'vaute', 'vauts', 'vawte', 'vaxes', 'veale', 'veals', 'vealy', 'veena', 'veeps', 'veers', 'veery', 'vegas', 'veges', 'vegie', 'vegos', 'vehme', 'veils', 'veily', 'veins', 'veiny', 'velar', 'velds', 'veldt', 'veles', 'vells', 'velum', 'venae', 'venal', 'vends', 'vendu', 'veney', 'venge', 'venin', 'vents', 'venus', 'verbs', 'verra', 'verry', 'verst', 'verts', 'vertu', 'vespa', 'vesta', 'vests', 'vetch', 'vexed', 'vexer', 'vexes', 'vexil', 'vezir', 'vials', 'viand', 'vibes', 'vibex', 'vibey', 'viced', 'vices', 'vichy', 'viers', 'views', 'viewy', 'vifda', 'viffs', 'vigas', 'vigia', 'vilde', 'viler', 'villi', 'vills', 'vimen', 'vinal', 'vinas', 'vinca', 'vined', 'viner', 'vines', 'vinew', 'vinic', 'vinos', 'vints', 'viold', 'viols', 'vired', 'vireo', 'vires', 'virga', 'virge', 'virid', 'virls', 'virtu', 'visas', 'vised', 'vises', 'visie', 'visne', 'vison', 'visto', 'vitae', 'vitas', 'vitex', 'vitro', 'vitta', 'vivas', 'vivat', 'vivda', 'viver', 'vives', 'vizir', 'vizor', 'vleis', 'vlies', 'vlogs', 'voars', 'vocab', 'voces', 'voddy', 'vodou', 'vodun', 'voema', 'vogie', 'voids', 'voile', 'voips', 'volae', 'volar', 'voled', 'voles', 'volet', 'volks', 'volta', 'volte', 'volti', 'volts', 'volva', 'volve', 'vomer', 'voted', 'votes', 'vouge', 'voulu', 'vowed', 'vower', 'voxel', 'vozhd', 'vraic', 'vrils', 'vroom', 'vrous', 'vrouw', 'vrows', 'vuggs', 'vuggy', 'vughs', 'vughy', 'vulgo', 'vulns', 'vulva', 'vutty', 'waacs', 'wacke', 'wacko', 'wacks', 'wadds', 'waddy', 'waded', 'wader', 'wades', 'wadge', 'wadis', 'wadts', 'waffs', 'wafts', 'waged', 'wages', 'wagga', 'wagyu', 'wahoo', 'waide', 'waifs', 'waift', 'wails', 'wains', 'wairs', 'waite', 'waits', 'wakas', 'waked', 'waken', 'waker', 'wakes', 'wakfs', 'waldo', 'walds', 'waled', 'waler', 'wales', 'walie', 'walis', 'walks', 'walla', 'walls', 'wally', 'walty', 'wamed', 'wames', 'wamus', 'wands', 'waned', 'wanes', 'waney', 'wangs', 'wanks', 'wanky', 'wanle', 'wanly', 'wanna', 'wants', 'wanty', 'wanze', 'waqfs', 'warbs', 'warby', 'wards', 'wared', 'wares', 'warez', 'warks', 'warms', 'warns', 'warps', 'warre', 'warst', 'warts', 'wases', 'washy', 'wasms', 'wasps', 'waspy', 'wasts', 'watap', 'watts', 'wauff', 'waugh', 'wauks', 'waulk', 'wauls', 'waurs', 'waved', 'waves', 'wavey', 'wawas', 'wawes', 'wawls', 'waxed', 'waxer', 'waxes', 'wayed', 'wazir', 'wazoo', 'weald', 'weals', 'weamb', 'weans', 'wears', 'webby', 'weber', 'wecht', 'wedel', 'wedgy', 'weeds', 'weeke', 'weeks', 'weels', 'weems', 'weens', 'weeny', 'weeps', 'weepy', 'weest', 'weete', 'weets', 'wefte', 'wefts', 'weids', 'weils', 'weirs', 'weise', 'weize', 'wekas', 'welds', 'welke', 'welks', 'welkt', 'wells', 'welly', 'welts', 'wembs', 'wends', 'wenge', 'wenny', 'wents', 'weros', 'wersh', 'wests', 'wetas', 'wetly', 'wexed', 'wexes', 'whamo', 'whams', 'whang', 'whaps', 'whare', 'whata', 'whats', 'whaup', 'whaur', 'wheal', 'whear', 'wheen', 'wheep', 'wheft', 'whelk', 'whelm', 'whens', 'whets', 'whews', 'wheys', 'whids', 'whift', 'whigs', 'whilk', 'whims', 'whins', 'whios', 'whips', 'whipt', 'whirr', 'whirs', 'whish', 'whiss', 'whist', 'whits', 'whity', 'whizz', 'whomp', 'whoof', 'whoot', 'whops', 'whore', 'whorl', 'whort', 'whoso', 'whows', 'whump', 'whups', 'whyda', 'wicca', 'wicks', 'wicky', 'widdy', 'wides', 'wiels', 'wifed', 'wifes', 'wifey', 'wifie', 'wifty', 'wigan', 'wigga', 'wiggy', 'wikis', 'wilco', 'wilds', 'wiled', 'wiles', 'wilga', 'wilis', 'wilja', 'wills', 'wilts', 'wimps', 'winds', 'wined', 'wines', 'winey', 'winge', 'wings', 'wingy', 'winks', 'winna', 'winns', 'winos', 'winze', 'wiped', 'wiper', 'wipes', 'wired', 'wirer', 'wires', 'wirra', 'wised', 'wises', 'wisha', 'wisht', 'wisps', 'wists', 'witan', 'wited', 'wites', 'withe', 'withs', 'withy', 'wived', 'wiver', 'wives', 'wizen', 'wizes', 'woads', 'woald', 'wocks', 'wodge', 'woful', 'wojus', 'woker', 'wokka', 'wolds', 'wolfs', 'wolly', 'wolve', 'wombs', 'womby', 'womyn', 'wonga', 'wongi', 'wonks', 'wonky', 'wonts', 'woods', 'wooed', 'woofs', 'woofy', 'woold', 'wools', 'woons', 'woops', 'woopy', 'woose', 'woosh', 'wootz', 'words', 'works', 'worms', 'wormy', 'worts', 'wowed', 'wowee', 'woxen', 'wrang', 'wraps', 'wrapt', 'wrast', 'wrate', 'wrawl', 'wrens', 'wrick', 'wried', 'wrier', 'wries', 'writs', 'wroke', 'wroot', 'wroth', 'wryer', 'wuddy', 'wudus', 'wulls', 'wurst', 'wuses', 'wushu', 'wussy', 'wuxia', 'wyled', 'wyles', 'wynds', 'wynns', 'wyted', 'wytes', 'xebec', 'xenia', 'xenic', 'xenon', 'xeric', 'xerox', 'xerus', 'xoana', 'xrays', 'xylan', 'xylem', 'xylic', 'xylol', 'xylyl', 'xysti', 'xysts', 'yaars', 'yabas', 'yabba', 'yabby', 'yacca', 'yacka', 'yacks', 'yaffs', 'yager', 'yages', 'yagis', 'yahoo', 'yaird', 'yakka', 'yakow', 'yales', 'yamen', 'yampy', 'yamun', 'yangs', 'yanks', 'yapok', 'yapon', 'yapps', 'yappy', 'yarak', 'yarco', 'yards', 'yarer', 'yarfa', 'yarks', 'yarns', 'yarrs', 'yarta', 'yarto', 'yates', 'yauds', 'yauld', 'yaups', 'yawed', 'yawey', 'yawls', 'yawns', 'yawny', 'yawps', 'ybore', 'yclad', 'ycled', 'ycond', 'ydrad', 'ydred', 'yeads', 'yeahs', 'yealm', 'yeans', 'yeard', 'years', 'yecch', 'yechs', 'yechy', 'yedes', 'yeeds', 'yeesh', 'yeggs', 'yelks', 'yells', 'yelms', 'yelps', 'yelts', 'yenta', 'yente', 'yerba', 'yerds', 'yerks', 'yeses', 'yesks', 'yests', 'yesty', 'yetis', 'yetts', 'yeuks', 'yeuky', 'yeven', 'yeves', 'yewen', 'yexed', 'yexes', 'yfere', 'yiked', 'yikes', 'yills', 'yince', 'yipes', 'yippy', 'yirds', 'yirks', 'yirrs', 'yirth', 'yites', 'yitie', 'ylems', 'ylike', 'ylkes', 'ymolt', 'ympes', 'yobbo', 'yobby', 'yocks', 'yodel', 'yodhs', 'yodle', 'yogas', 'yogee', 'yoghs', 'yogic', 'yogin', 'yogis', 'yoick', 'yojan', 'yoked', 'yokel', 'yoker', 'yokes', 'yokul', 'yolks', 'yolky', 'yomim', 'yomps', 'yonic', 'yonis', 'yonks', 'yoofs', 'yoops', 'yores', 'yorks', 'yorps', 'youks', 'yourn', 'yours', 'yourt', 'youse', 'yowed', 'yowes', 'yowie', 'yowls', 'yowza', 'yrapt', 'yrent', 'yrivd', 'yrneh', 'ysame', 'ytost', 'yuans', 'yucas', 'yucca', 'yucch', 'yucko', 'yucks', 'yucky', 'yufts', 'yugas', 'yuked', 'yukes', 'yukky', 'yukos', 'yulan', 'yules', 'yummo', 'yummy', 'yumps', 'yupon', 'yuppy', 'yurta', 'yurts', 'yuzus', 'zabra', 'zacks', 'zaida', 'zaidy', 'zaire', 'zakat', 'zaman', 'zambo', 'zamia', 'zanja', 'zante', 'zanza', 'zanze', 'zappy', 'zarfs', 'zaris', 'zatis', 'zaxes', 'zayin', 'zazen', 'zeals', 'zebec', 'zebub', 'zebus', 'zedas', 'zeins', 'zendo', 'zerda', 'zerks', 'zeros', 'zests', 'zetas', 'zexes', 'zezes', 'zhomo', 'zibet', 'ziffs', 'zigan', 'zilas', 'zilch', 'zilla', 'zills', 'zimbi', 'zimbs', 'zinco', 'zincs', 'zincy', 'zineb', 'zines', 'zings', 'zingy', 'zinke', 'zinky', 'zippo', 'zippy', 'ziram', 'zitis', 'zizel', 'zizit', 'zlote', 'zloty', 'zoaea', 'zobos', 'zobus', 'zocco', 'zoeae', 'zoeal', 'zoeas', 'zoism', 'zoist', 'zombi', 'zonae', 'zonda', 'zoned', 'zoner', 'zones', 'zonks', 'zooea', 'zooey', 'zooid', 'zooks', 'zooms', 'zoons', 'zooty', 'zoppa', 'zoppo', 'zoril', 'zoris', 'zorro', 'zouks', 'zowee', 'zowie', 'zulus', 'zupan', 'zupas', 'zuppa', 'zurfs', 'zuzim', 'zygal', 'zygon', 'zymes', 'zymic', ]); ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/static/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/svelte.config.js ================================================ import adapter from '@sveltejs/adapter-auto'; import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list. // If your environment is not supported, or you settled on a specific environment, switch out the adapter. // See https://kit.svelte.dev/docs/adapters for more information about adapters. adapter: adapter(), }, // Consult https://kit.svelte.dev/docs/integrations#preprocessors // for more information about preprocessors preprocess: vitePreprocess(), }; export default config; ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/tsconfig.json ================================================ { "extends": "./.svelte-kit/tsconfig.json", "compilerOptions": { "allowJs": true, "checkJs": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "bundler", "resolveJsonModule": true, "skipLibCheck": true, "sourceMap": true, "strict": true, "types": ["vitest/globals"] } // Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias // except $lib which is handled by https://kit.svelte.dev/docs/configuration#files // // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes // from the referenced tsconfig.json - TypeScript does not merge them in } ================================================ FILE: examples/openapi-ts-tanstack-svelte-query/vite.config.ts ================================================ import { sveltekit } from '@sveltejs/kit/vite'; import { defineProject } from 'vitest/config'; export default async () => { const sveltekitPlugins = await sveltekit(); return defineProject({ plugins: [sveltekitPlugins], test: { include: ['src/**/*.{test,spec}.{js,ts}'], }, }); }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/.eslintrc.cjs ================================================ /* eslint-env node */ require('@rushstack/eslint-patch/modern-module-resolution'); module.exports = { extends: ['plugin:vue/vue3-essential', 'eslint:recommended', '@vue/eslint-config-typescript'], files: ['**/*.{vue,js,jsx,cjs,mjs,ts,tsx,cts,mts}'], parserOptions: { ecmaVersion: 'latest', }, }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules .DS_Store dist dist-ssr coverage *.local /cypress/videos/ /cypress/screenshots/ # Editor directories and files .vscode/* !.vscode/extensions.json .idea *.suo *.ntvs* *.njsproj *.sln *.sw? *.tsbuildinfo ================================================ FILE: examples/openapi-ts-tanstack-vue-query/.vscode/extensions.json ================================================ { "recommendations": ["Vue.volar", "dbaeumer.vscode-eslint", "oxc.oxc-vscode"] } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/CHANGELOG.md ================================================ # @example/openapi-ts-tanstack-vue-query ## 0.0.39 ### Patch Changes - Updated dependencies [[`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40)]: - @hey-api/client-fetch@0.13.1 ## 0.0.38 ### Patch Changes - Updated dependencies [[`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8)]: - @hey-api/client-fetch@0.13.0 ## 0.0.37 ### Patch Changes - Updated dependencies [[`4d8c030`](https://github.com/hey-api/openapi-ts/commit/4d8c03038979c9a75315cc158789b3c198c62f90)]: - @hey-api/client-fetch@0.12.0 ## 0.0.36 ### Patch Changes - Updated dependencies [[`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6)]: - @hey-api/client-fetch@0.11.0 ## 0.0.35 ### Patch Changes - Updated dependencies [[`1f99066`](https://github.com/hey-api/openapi-ts/commit/1f99066efbb2d0e6b9e3710c701293c2cc09d65e)]: - @hey-api/client-fetch@0.10.2 ## 0.0.34 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-fetch@0.10.1 ## 0.0.33 ### Patch Changes - Updated dependencies [[`fed9699`](https://github.com/hey-api/openapi-ts/commit/fed969985275621c7c2b65ffc760c7c66fafaf72)]: - @hey-api/client-fetch@0.10.0 ## 0.0.32 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-fetch@0.9.0 ## 0.0.31 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-fetch@0.8.4 ## 0.0.30 ### Patch Changes - Updated dependencies [[`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b)]: - @hey-api/client-fetch@0.8.3 ## 0.0.29 ### Patch Changes - Updated dependencies [[`b8cc9f8`](https://github.com/hey-api/openapi-ts/commit/b8cc9f8a5eaf4f4ff345abc49c14c6b96744c2ea)]: - @hey-api/client-fetch@0.8.2 ## 0.0.28 ### Patch Changes - Updated dependencies [[`7f0f4a7`](https://github.com/hey-api/openapi-ts/commit/7f0f4a76b06c8fafb33581b522faf8efc6fd85ac)]: - @hey-api/client-fetch@0.8.1 ## 0.0.27 ### Patch Changes - Updated dependencies [[`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2)]: - @hey-api/client-fetch@0.8.0 ## 0.0.26 ### Patch Changes - Updated dependencies [[`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49), [`603541e`](https://github.com/hey-api/openapi-ts/commit/603541e307dc2953da7dddd300176865629b50bb), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31), [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31)]: - @hey-api/client-fetch@0.7.3 ## 0.0.25 ### Patch Changes - Updated dependencies [[`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2)]: - @hey-api/client-fetch@0.7.2 ## 0.0.24 ### Patch Changes - Updated dependencies [[`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9), [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779)]: - @hey-api/client-fetch@0.7.1 ## 0.0.23 ### Patch Changes - Updated dependencies [[`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107)]: - @hey-api/client-fetch@0.7.0 ## 0.0.22 ### Patch Changes - Updated dependencies [[`e2e1410`](https://github.com/hey-api/openapi-ts/commit/e2e1410b22c0c84c40d1b1803e9650d546350cb7)]: - @hey-api/client-fetch@0.6.0 ## 0.0.21 ### Patch Changes - Updated dependencies [[`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263), [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26)]: - @hey-api/client-fetch@0.5.7 ## 0.0.20 ### Patch Changes - Updated dependencies [[`ba56424`](https://github.com/hey-api/openapi-ts/commit/ba5642486cdd5461c2372c34b63019c02bc6874e)]: - @hey-api/client-fetch@0.5.6 ## 0.0.19 ### Patch Changes - Updated dependencies [[`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a)]: - @hey-api/client-fetch@0.5.5 ## 0.0.18 ### Patch Changes - Updated dependencies [[`cbf4e84`](https://github.com/hey-api/openapi-ts/commit/cbf4e84db7f3a47f19d8c3eaa87c71b27912c1a2)]: - @hey-api/client-fetch@0.5.4 ## 0.0.17 ### Patch Changes - Updated dependencies [[`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0)]: - @hey-api/client-fetch@0.5.3 ## 0.0.16 ### Patch Changes - Updated dependencies [[`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a)]: - @hey-api/client-fetch@0.5.2 ## 0.0.15 ### Patch Changes - Updated dependencies [[`fa8b0f1`](https://github.com/hey-api/openapi-ts/commit/fa8b0f11ed99c63f694a494944ccc2fbfa9706cc)]: - @hey-api/client-fetch@0.5.1 ## 0.0.14 ### Patch Changes - Updated dependencies [[`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df), [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df)]: - @hey-api/client-fetch@0.5.0 ## 0.0.13 ### Patch Changes - Updated dependencies [[`4c853d0`](https://github.com/hey-api/openapi-ts/commit/4c853d090b79245854d13831f64731db4a92978b)]: - @hey-api/client-fetch@0.4.4 ## 0.0.12 ### Patch Changes - Updated dependencies [[`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482)]: - @hey-api/client-fetch@0.4.3 ## 0.0.11 ### Patch Changes - [#1151](https://github.com/hey-api/openapi-ts/pull/1151) [`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update website domain, add license documentation - Updated dependencies [[`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5)]: - @hey-api/client-fetch@0.4.2 ## 0.0.10 ### Patch Changes - Updated dependencies [[`a0a5551`](https://github.com/hey-api/openapi-ts/commit/a0a55510d30a1a8dea0ade4908b5b13d51b5f9e6)]: - @hey-api/client-fetch@0.4.1 ## 0.0.9 ### Patch Changes - Updated dependencies [[`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa), [`df5c690`](https://github.com/hey-api/openapi-ts/commit/df5c69048a03a1c7729a5200c586164287a8a6fa)]: - @hey-api/client-fetch@0.4.0 ## 0.0.8 ### Patch Changes - Updated dependencies [[`7f986c2`](https://github.com/hey-api/openapi-ts/commit/7f986c2c7726ed8fbf16f8b235b7769c7d990502)]: - @hey-api/client-fetch@0.3.4 ## 0.0.7 ### Patch Changes - Updated dependencies [[`fe743c2`](https://github.com/hey-api/openapi-ts/commit/fe743c2d41c23bf7e1706bceedd6319299131197)]: - @hey-api/client-fetch@0.3.3 ## 0.0.6 ### Patch Changes - Updated dependencies [[`11a276a`](https://github.com/hey-api/openapi-ts/commit/11a276a1e35dde0735363e892d8142016fd87eec)]: - @hey-api/client-fetch@0.3.2 ## 0.0.5 ### Patch Changes - Updated dependencies [[`7ae2b1d`](https://github.com/hey-api/openapi-ts/commit/7ae2b1db047f3b6efe917a8b43ac7c851fb86c8f), [`2079c6e`](https://github.com/hey-api/openapi-ts/commit/2079c6e83a6b71e157c8e7ea56260b4e9ff8411d)]: - @hey-api/client-fetch@0.3.1 ## 0.0.4 ### Patch Changes - Updated dependencies [[`7ebc1d4`](https://github.com/hey-api/openapi-ts/commit/7ebc1d44af74db2522219d71d240325f6bc5689d)]: - @hey-api/client-fetch@0.3.0 ## 0.0.3 ### Patch Changes - [#1010](https://github.com/hey-api/openapi-ts/pull/1010) [`b6e58c6`](https://github.com/hey-api/openapi-ts/commit/b6e58c64d1b71897533a85d1738cd7ce7ede178d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: set query key base url from supplied client if provided ## 0.0.2 ### Patch Changes - [#978](https://github.com/hey-api/openapi-ts/pull/978) [`2e051a5`](https://github.com/hey-api/openapi-ts/commit/2e051a596302c2e103dca25951a07b4aae1e9e23) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add basic TanStack Query plugin description ## 0.0.1 ### Patch Changes - [#901](https://github.com/hey-api/openapi-ts/pull/901) [`8ac24a6`](https://github.com/hey-api/openapi-ts/commit/8ac24a63eca2b890899ba9f6fa908b6ed0ae80d3) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: add TanStack Vue Query example - Updated dependencies [[`a8c84c0`](https://github.com/hey-api/openapi-ts/commit/a8c84c02dbb5ef1a59f5d414dff425e135c7a446), [`7825a2f`](https://github.com/hey-api/openapi-ts/commit/7825a2fba566a76c63775172ef0569ef375406b6)]: - @hey-api/client-fetch@0.2.4 ================================================ FILE: examples/openapi-ts-tanstack-vue-query/README.md ================================================ # vue-project This template should help get you started developing with Vue 3 in Vite. ## Recommended IDE Setup [VSCode](https://code.visualstudio.com) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur). ## Type Support for `.vue` Imports in TS TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types. ## Customize configuration See [Vite Configuration Reference](https://vitejs.dev/config). ## Project Setup ```sh pnpm install ``` ### Compile and Hot-Reload for Development ```sh pnpm dev ``` ### Type-Check, Compile and Minify for Production ```sh pnpm build ``` ### Run Unit Tests with [Vitest](https://vitest.dev) ```sh pnpm test:unit ``` ### Lint with [ESLint](https://eslint.org) ```sh pnpm lint ``` ================================================ FILE: examples/openapi-ts-tanstack-vue-query/env.d.ts ================================================ /// ================================================ FILE: examples/openapi-ts-tanstack-vue-query/index.html ================================================ Hey API + TanStack Vue Query Demo
    ================================================ FILE: examples/openapi-ts-tanstack-vue-query/openapi-ts.config.ts ================================================ import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', logs: { path: './logs', }, output: { path: './src/client', postProcess: ['oxfmt', 'eslint'], }, plugins: [ '@hey-api/client-fetch', '@hey-api/schemas', '@hey-api/sdk', { enums: 'javascript', name: '@hey-api/typescript', }, '@tanstack/vue-query', ], }); ================================================ FILE: examples/openapi-ts-tanstack-vue-query/package.json ================================================ { "name": "@example/openapi-ts-tanstack-vue-query", "version": "0.0.39", "private": true, "type": "module", "scripts": { "build-only": "vite build", "build": "run-p typecheck \"build-only {@}\" --", "dev": "vite", "format": "oxfmt src/", "lint": "eslint . --fix", "openapi-ts": "openapi-ts", "preview": "vite preview", "test:unit": "vitest", "typecheck": "vue-tsc --build --force" }, "dependencies": { "@tanstack/vue-query": "5.73.3", "@tanstack/vue-query-devtools": "5.73.3", "pinia": "3.0.3", "vue": "3.5.13", "vue-router": "4.5.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@rushstack/eslint-patch": "1.10.5", "@tsconfig/node24": "24.0.4", "@types/jsdom": "27.0.0", "@types/node": "24.10.10", "@vitejs/plugin-vue": "6.0.4", "@vitejs/plugin-vue-jsx": "5.1.4", "@vue/eslint-config-typescript": "14.6.0", "@vue/test-utils": "2.4.6", "@vue/tsconfig": "0.8.1", "autoprefixer": "10.4.20", "eslint": "9.17.0", "eslint-plugin-vue": "9.32.0", "jsdom": "28.0.0", "npm-run-all2": "6.2.0", "oxfmt": "0.27.0", "postcss": "8.4.41", "tailwindcss": "3.4.9", "typescript": "5.9.3", "vite": "7.3.1", "vite-plugin-vue-devtools": "8.0.2", "vitest": "4.0.18", "vue-tsc": "3.2.4" } } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/postcss.config.js ================================================ export default { plugins: { autoprefixer: {}, tailwindcss: {}, }, }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/App.vue ================================================ ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/assets/main.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; body { @apply bg-[#111113]; } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from '../sdk.gen'; import type { AddPetData, AddPetResponse, CreateUserData, CreateUserResponse, CreateUsersWithListInputData, CreateUsersWithListInputResponse, DeleteOrderData, DeletePetData, DeleteUserData, FindPetsByStatusData, FindPetsByStatusResponse, FindPetsByTagsData, FindPetsByTagsResponse, GetInventoryData, GetInventoryResponse, GetOrderByIdData, GetOrderByIdResponse, GetPetByIdData, GetPetByIdResponse, GetUserByNameData, GetUserByNameResponse, LoginUserData, LoginUserResponse, LogoutUserData, PlaceOrderData, PlaceOrderResponse, UpdatePetData, UpdatePetResponse, UpdatePetWithFormData, UpdatePetWithFormResponse, UpdateUserData, UploadFileData, UploadFileResponse, } from '../types.gen'; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPetMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await addPet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePetMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< UpdatePetResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await updatePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; }, ]; const createQueryKey = ( id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray, ): [QueryKey[0]] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl, } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const findPetsByStatusQueryKey = (options: Options) => createQueryKey('findPetsByStatus', options); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatusOptions = (options: Options) => queryOptions< FindPetsByStatusResponse, DefaultError, FindPetsByStatusResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await findPetsByStatus({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByStatusQueryKey(options), }); export const findPetsByTagsQueryKey = (options: Options) => createQueryKey('findPetsByTags', options); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTagsOptions = (options: Options) => queryOptions< FindPetsByTagsResponse, DefaultError, FindPetsByTagsResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await findPetsByTags({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: findPetsByTagsQueryKey(options), }); /** * Deletes a pet. * * Delete a pet. */ export const deletePetMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deletePet({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getPetByIdQueryKey = (options: Options) => createQueryKey('getPetById', options); /** * Find pet by ID. * * Returns a single pet. */ export const getPetByIdOptions = (options: Options) => queryOptions< GetPetByIdResponse, DefaultError, GetPetByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getPetById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getPetByIdQueryKey(options), }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithFormMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< UpdatePetWithFormResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await updatePetWithForm({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Uploads an image. * * Upload image of the pet. */ export const uploadFileMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< UploadFileResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getInventoryQueryKey = (options?: Options) => createQueryKey('getInventory', options); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventoryOptions = (options?: Options) => queryOptions< GetInventoryResponse, DefaultError, GetInventoryResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getInventory({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getInventoryQueryKey(options), }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrderMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< PlaceOrderResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await placeOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrderMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteOrder({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getOrderByIdQueryKey = (options: Options) => createQueryKey('getOrderById', options); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderByIdOptions = (options: Options) => queryOptions< GetOrderByIdResponse, DefaultError, GetOrderByIdResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getOrderById({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getOrderByIdQueryKey(options), }); /** * Create user. * * This can only be done by the logged in user. */ export const createUserMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions< CreateUserResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await createUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInputMutation = ( options?: Partial>, ): UseMutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > => { const mutationOptions: UseMutationOptions< CreateUsersWithListInputResponse, DefaultError, Options > = { mutationFn: async (fnOptions) => { const { data } = await createUsersWithListInput({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const loginUserQueryKey = (options?: Options) => createQueryKey('loginUser', options); /** * Logs user into the system. * * Log into the system. */ export const loginUserOptions = (options?: Options) => queryOptions< LoginUserResponse, DefaultError, LoginUserResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await loginUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: loginUserQueryKey(options), }); export const logoutUserQueryKey = (options?: Options) => createQueryKey('logoutUser', options); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUserOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await logoutUser({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: logoutUserQueryKey(options), }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUserMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; export const getUserByNameQueryKey = (options: Options) => createQueryKey('getUserByName', options); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByNameOptions = (options: Options) => queryOptions< GetUserByNameResponse, DefaultError, GetUserByNameResponse, ReturnType >({ queryFn: async ({ queryKey, signal }) => { const { data } = await getUserByName({ ...options, ...queryKey[0], signal, throwOnError: true, }); return data; }, queryKey: getUserByNameQueryKey(options), }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUserMutation = ( options?: Partial>, ): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await updateUser({ ...options, ...fnOptions, throwOnError: true, }); return data; }, }; return mutationOptions; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export const client = createClient( createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { addPet, createUser, createUsersWithListInput, deleteOrder, deletePet, deleteUser, findPetsByStatus, findPetsByTags, getInventory, getOrderById, getPetById, getUserByName, loginUser, logoutUser, type Options, placeOrder, updatePet, updatePetWithForm, updateUser, uploadFile, } from './sdk.gen'; export type { AddPetData, AddPetErrors, AddPetResponse, AddPetResponses, ApiResponse, Category, ClientOptions, CreateUserData, CreateUserErrors, CreateUserResponse, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponse, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponse, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponse, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponse, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponse, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponse, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponse, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponse, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, Order, Pet, Pet2, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponse, PlaceOrderResponses, Tag, UpdatePetData, UpdatePetErrors, UpdatePetResponse, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponse, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponse, UploadFileResponses, User, UserArray, } from './types.gen'; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const OrderSchema = { properties: { complete: { type: 'boolean', }, id: { example: 10, format: 'int64', type: 'integer', }, petId: { example: 198772, format: 'int64', type: 'integer', }, quantity: { example: 7, format: 'int32', type: 'integer', }, shipDate: { format: 'date-time', type: 'string', }, status: { description: 'Order Status', enum: ['placed', 'approved', 'delivered'], example: 'approved', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Order', xml: { name: 'order', }, } as const; export const CategorySchema = { properties: { id: { example: 1, format: 'int64', type: 'integer', }, name: { example: 'Dogs', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Category', xml: { name: 'category', }, } as const; export const UserSchema = { properties: { email: { example: 'john@email.com', type: 'string', }, firstName: { example: 'John', type: 'string', }, id: { example: 10, format: 'int64', type: 'integer', }, lastName: { example: 'James', type: 'string', }, password: { example: '12345', type: 'string', }, phone: { example: '12345', type: 'string', }, userStatus: { description: 'User Status', example: 1, format: 'int32', type: 'integer', }, username: { example: 'theUser', type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.User', xml: { name: 'user', }, } as const; export const TagSchema = { properties: { id: { format: 'int64', type: 'integer', }, name: { type: 'string', }, }, type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Tag', xml: { name: 'tag', }, } as const; export const PetSchema = { properties: { category: { $ref: '#/components/schemas/Category', }, id: { example: 10, format: 'int64', type: 'integer', }, name: { example: 'doggie', type: 'string', }, photoUrls: { items: { type: 'string', xml: { name: 'photoUrl', }, }, type: 'array', xml: { wrapped: true, }, }, status: { description: 'pet status in the store', enum: ['available', 'pending', 'sold'], type: 'string', }, tags: { items: { $ref: '#/components/schemas/Tag', }, type: 'array', xml: { wrapped: true, }, }, }, required: ['name', 'photoUrls'], type: 'object', 'x-swagger-router-model': 'io.swagger.petstore.model.Pet', xml: { name: 'pet', }, } as const; export const ApiResponseSchema = { properties: { code: { format: 'int32', type: 'integer', }, message: { type: 'string', }, type: { type: 'string', }, }, type: 'object', xml: { name: '##default', }, } as const; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AddPetData, AddPetErrors, AddPetResponses, CreateUserData, CreateUserErrors, CreateUserResponses, CreateUsersWithListInputData, CreateUsersWithListInputErrors, CreateUsersWithListInputResponses, DeleteOrderData, DeleteOrderErrors, DeleteOrderResponses, DeletePetData, DeletePetErrors, DeletePetResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, FindPetsByStatusData, FindPetsByStatusErrors, FindPetsByStatusResponses, FindPetsByTagsData, FindPetsByTagsErrors, FindPetsByTagsResponses, GetInventoryData, GetInventoryErrors, GetInventoryResponses, GetOrderByIdData, GetOrderByIdErrors, GetOrderByIdResponses, GetPetByIdData, GetPetByIdErrors, GetPetByIdResponses, GetUserByNameData, GetUserByNameErrors, GetUserByNameResponses, LoginUserData, LoginUserErrors, LoginUserResponses, LogoutUserData, LogoutUserErrors, LogoutUserResponses, PlaceOrderData, PlaceOrderErrors, PlaceOrderResponses, UpdatePetData, UpdatePetErrors, UpdatePetResponses, UpdatePetWithFormData, UpdatePetWithFormErrors, UpdatePetWithFormResponses, UpdateUserData, UpdateUserErrors, UpdateUserResponses, UploadFileData, UploadFileErrors, UploadFileResponses, } from './types.gen'; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Add a new pet to the store. * * Add a new pet to the store. */ export const addPet = ( options: Options, ) => (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Update an existing pet. * * Update an existing pet by Id. */ export const updatePet = ( options: Options, ) => (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); /** * Finds Pets by status. * * Multiple status values can be provided with comma separated strings. */ export const findPetsByStatus = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, }); /** * Finds Pets by tags. * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export const findPetsByTags = ( options: Options, ) => (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, }); /** * Deletes a pet. * * Delete a pet. */ export const deletePet = ( options: Options, ) => (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Find pet by ID. * * Returns a single pet. */ export const getPetById = ( options: Options, ) => (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, ], url: '/pet/{petId}', ...options, }); /** * Updates a pet in the store with form data. * * Updates a pet resource based on the form data. */ export const updatePetWithForm = ( options: Options, ) => (options.client ?? client).post< UpdatePetWithFormResponses, UpdatePetWithFormErrors, ThrowOnError >({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, }); /** * Uploads an image. * * Upload image of the pet. */ export const uploadFile = ( options: Options, ) => (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers, }, }); /** * Returns pet inventories by status. * * Returns a map of status codes to quantities. */ export const getInventory = ( options?: Options, ) => (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, }); /** * Place an order for a pet. * * Place a new order in the store. */ export const placeOrder = ( options?: Options, ) => (options?.client ?? client).post({ url: '/store/order', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Delete purchase order by identifier. * * For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors. */ export const deleteOrder = ( options: Options, ) => (options.client ?? client).delete({ url: '/store/order/{orderId}', ...options, }); /** * Find purchase order by ID. * * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export const getOrderById = ( options: Options, ) => (options.client ?? client).get({ url: '/store/order/{orderId}', ...options, }); /** * Create user. * * This can only be done by the logged in user. */ export const createUser = ( options?: Options, ) => (options?.client ?? client).post({ url: '/user', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Creates list of users with given input array. * * Creates list of users with given input array. */ export const createUsersWithListInput = ( options?: Options, ) => (options?.client ?? client).post< CreateUsersWithListInputResponses, CreateUsersWithListInputErrors, ThrowOnError >({ url: '/user/createWithList', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }); /** * Logs user into the system. * * Log into the system. */ export const loginUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/login', ...options, }); /** * Logs out current logged in user session. * * Log user out of the system. */ export const logoutUser = ( options?: Options, ) => (options?.client ?? client).get({ url: '/user/logout', ...options, }); /** * Delete user resource. * * This can only be done by the logged in user. */ export const deleteUser = ( options: Options, ) => (options.client ?? client).delete({ url: '/user/{username}', ...options, }); /** * Get user by user name. * * Get user detail based on username. */ export const getUserByName = ( options: Options, ) => (options.client ?? client).get({ url: '/user/{username}', ...options, }); /** * Update user resource. * * This can only be done by the logged in user. */ export const updateUser = ( options: Options, ) => (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://petstore3.swagger.io/api/v3' | (string & {}); }; export type Order = { complete?: boolean; id?: number; petId?: number; quantity?: number; shipDate?: string; /** * Order Status */ status?: 'placed' | 'approved' | 'delivered'; }; export type Category = { id?: number; name?: string; }; export type User = { email?: string; firstName?: string; id?: number; lastName?: string; password?: string; phone?: string; /** * User Status */ userStatus?: number; username?: string; }; export type Tag = { id?: number; name?: string; }; export type Pet = { category?: Category; id?: number; name: string; photoUrls: Array; /** * pet status in the store */ status?: 'available' | 'pending' | 'sold'; tags?: Array; }; export type ApiResponse = { code?: number; message?: string; type?: string; }; export type Pet2 = Pet; /** * List of user object */ export type UserArray = Array; export type AddPetData = { /** * Create a new pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type AddPetErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type AddPetResponses = { /** * Successful operation */ 200: Pet; }; export type AddPetResponse = AddPetResponses[keyof AddPetResponses]; export type UpdatePetData = { /** * Update an existent pet in the store */ body: Pet; path?: never; query?: never; url: '/pet'; }; export type UpdatePetErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetResponses = { /** * Successful operation */ 200: Pet; }; export type UpdatePetResponse = UpdatePetResponses[keyof UpdatePetResponses]; export type FindPetsByStatusData = { body?: never; path?: never; query: { /** * Status values that need to be considered for filter */ status: 'available' | 'pending' | 'sold'; }; url: '/pet/findByStatus'; }; export type FindPetsByStatusErrors = { /** * Invalid status value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByStatusResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; path?: never; query: { /** * Tags to filter by */ tags: Array; }; url: '/pet/findByTags'; }; export type FindPetsByTagsErrors = { /** * Invalid tag value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type FindPetsByTagsResponses = { /** * successful operation */ 200: Array; }; export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; headers?: { api_key?: string; }; path: { /** * Pet id to delete */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type DeletePetErrors = { /** * Invalid pet value */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type DeletePetResponses = { /** * Pet deleted */ 200: unknown; }; export type GetPetByIdData = { body?: never; path: { /** * ID of pet to return */ petId: number; }; query?: never; url: '/pet/{petId}'; }; export type GetPetByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetPetByIdResponses = { /** * successful operation */ 200: Pet; }; export type GetPetByIdResponse = GetPetByIdResponses[keyof GetPetByIdResponses]; export type UpdatePetWithFormData = { body?: never; path: { /** * ID of pet that needs to be updated */ petId: number; }; query?: { /** * Name of pet that needs to be updated */ name?: string; /** * Status of pet that needs to be updated */ status?: string; }; url: '/pet/{petId}'; }; export type UpdatePetWithFormErrors = { /** * Invalid input */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type UpdatePetWithFormResponses = { /** * successful operation */ 200: Pet; }; export type UpdatePetWithFormResponse = UpdatePetWithFormResponses[keyof UpdatePetWithFormResponses]; export type UploadFileData = { body?: Blob | File; path: { /** * ID of pet to update */ petId: number; }; query?: { /** * Additional Metadata */ additionalMetadata?: string; }; url: '/pet/{petId}/uploadImage'; }; export type UploadFileErrors = { /** * No file uploaded */ 400: unknown; /** * Pet not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UploadFileResponses = { /** * successful operation */ 200: ApiResponse; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type GetInventoryData = { body?: never; path?: never; query?: never; url: '/store/inventory'; }; export type GetInventoryErrors = { /** * Unexpected error */ default: unknown; }; export type GetInventoryResponses = { /** * successful operation */ 200: { [key: string]: number; }; }; export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; path?: never; query?: never; url: '/store/order'; }; export type PlaceOrderErrors = { /** * Invalid input */ 400: unknown; /** * Validation exception */ 422: unknown; /** * Unexpected error */ default: unknown; }; export type PlaceOrderResponses = { /** * successful operation */ 200: Order; }; export type PlaceOrderResponse = PlaceOrderResponses[keyof PlaceOrderResponses]; export type DeleteOrderData = { body?: never; path: { /** * ID of the order that needs to be deleted */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type DeleteOrderErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteOrderResponses = { /** * order deleted */ 200: unknown; }; export type GetOrderByIdData = { body?: never; path: { /** * ID of order that needs to be fetched */ orderId: number; }; query?: never; url: '/store/order/{orderId}'; }; export type GetOrderByIdErrors = { /** * Invalid ID supplied */ 400: unknown; /** * Order not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetOrderByIdResponses = { /** * successful operation */ 200: Order; }; export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** * Created user object */ body?: User; path?: never; query?: never; url: '/user'; }; export type CreateUserErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUserResponses = { /** * successful operation */ 200: User; }; export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; export type CreateUsersWithListInputData = { body?: Array; path?: never; query?: never; url: '/user/createWithList'; }; export type CreateUsersWithListInputErrors = { /** * Unexpected error */ default: unknown; }; export type CreateUsersWithListInputResponses = { /** * Successful operation */ 200: User; }; export type CreateUsersWithListInputResponse = CreateUsersWithListInputResponses[keyof CreateUsersWithListInputResponses]; export type LoginUserData = { body?: never; path?: never; query?: { /** * The password for login in clear text */ password?: string; /** * The user name for login */ username?: string; }; url: '/user/login'; }; export type LoginUserErrors = { /** * Invalid username/password supplied */ 400: unknown; /** * Unexpected error */ default: unknown; }; export type LoginUserResponses = { /** * successful operation */ 200: string; }; export type LoginUserResponse = LoginUserResponses[keyof LoginUserResponses]; export type LogoutUserData = { body?: never; path?: never; query?: never; url: '/user/logout'; }; export type LogoutUserErrors = { /** * Unexpected error */ default: unknown; }; export type LogoutUserResponses = { /** * successful operation */ 200: unknown; }; export type DeleteUserData = { body?: never; path: { /** * The name that needs to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type DeleteUserErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type DeleteUserResponses = { /** * User deleted */ 200: unknown; }; export type GetUserByNameData = { body?: never; path: { /** * The name that needs to be fetched. Use user1 for testing */ username: string; }; query?: never; url: '/user/{username}'; }; export type GetUserByNameErrors = { /** * Invalid username supplied */ 400: unknown; /** * User not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type GetUserByNameResponses = { /** * successful operation */ 200: User; }; export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** * Update an existent user in the store */ body?: User; path: { /** * name that need to be deleted */ username: string; }; query?: never; url: '/user/{username}'; }; export type UpdateUserErrors = { /** * bad request */ 400: unknown; /** * user not found */ 404: unknown; /** * Unexpected error */ default: unknown; }; export type UpdateUserResponses = { /** * successful operation */ 200: unknown; }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/main.ts ================================================ import './assets/main.css'; import { VueQueryPlugin } from '@tanstack/vue-query'; import { createPinia } from 'pinia'; import { createApp } from 'vue'; import App from './App.vue'; import { client } from './client/client.gen'; import router from './router'; // configure internal service client client.setConfig({ // set default base url for requests baseUrl: 'https://petstore3.swagger.io/api/v3', // set default headers for requests headers: { Authorization: 'Bearer ', }, }); const app = createApp(App); app.use(createPinia()); app.use(router); app.use(VueQueryPlugin); app.mount('#app'); ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/router/index.ts ================================================ import { createRouter, createWebHistory } from 'vue-router'; import TanstackExample from '@/views/TanstackExample.vue'; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { component: TanstackExample, name: 'home', path: '/', }, ], }); export default router; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/src/views/TanstackExample.vue ================================================ ================================================ FILE: examples/openapi-ts-tanstack-vue-query/tailwind.config.ts ================================================ import type { Config } from 'tailwindcss'; export default { content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], theme: { extend: {}, }, } satisfies Config; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/tsconfig.app.json ================================================ { "extends": "@vue/tsconfig/tsconfig.dom.json", "include": ["./env.d.ts", "./src/**/*", "./src/**/*.vue"], "exclude": ["./src/**/__tests__/*"], "compilerOptions": { "composite": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/tsconfig.json ================================================ { "files": [], "references": [ { "path": "./tsconfig.node.json" }, { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.vitest.json" } ] } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/tsconfig.node.json ================================================ { "extends": "@tsconfig/node24/tsconfig.json", "include": [ "vite.config.*", "vitest.config.*", "cypress.config.*", "nightwatch.conf.*", "playwright.config.*" ], "compilerOptions": { "composite": true, "noEmit": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", "module": "ESNext", "moduleResolution": "Bundler", "types": ["node"] } } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/tsconfig.vitest.json ================================================ { "extends": "./tsconfig.app.json", "exclude": [], "compilerOptions": { "composite": true, "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo", "lib": [], "types": ["node", "jsdom"] } } ================================================ FILE: examples/openapi-ts-tanstack-vue-query/vite.config.ts ================================================ import { fileURLToPath, URL } from 'node:url'; import vue from '@vitejs/plugin-vue'; import vueJsx from '@vitejs/plugin-vue-jsx'; import vueDevTools from 'vite-plugin-vue-devtools'; /** @type {import('vite').UserConfig} */ export default { build: { sourcemap: true, target: 'esnext', }, esbuild: { target: 'esnext', }, optimizeDeps: { esbuildOptions: { target: 'esnext', }, }, plugins: [vue(), vueJsx(), vueDevTools()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, }; ================================================ FILE: examples/openapi-ts-tanstack-vue-query/vitest.config.ts ================================================ import { configDefaults, defineProject, mergeConfig } from 'vitest/config'; import viteConfig from './vite.config'; export default mergeConfig( viteConfig, defineProject({ test: { environment: 'jsdom', exclude: [...configDefaults.exclude, 'e2e/**'], }, }), ); ================================================ FILE: lint-staged.config.js ================================================ export default { '*': ['pnpm format', 'pnpm lint:fix'], }; ================================================ FILE: package.json ================================================ { "name": "openapi-ts-monorepo", "version": "0.1.0", "private": true, "description": "Public @hey-api monorepo", "homepage": "https://heyapi.dev", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "type": "module", "scripts": { "build": "turbo run build", "changeset": "changeset", "examples:check": "sh ./scripts/examples-check.sh", "examples:generate": "sh ./scripts/examples-generate.sh", "format": "oxfmt .", "format:next": "oxfmt . && uv run ruff format packages/openapi-python/src/py-compiler/__snapshots__", "lint": "oxfmt --check . && eslint .", "lint:next": "oxfmt --check . && eslint . && uv run ruff check packages/openapi-python/src/py-compiler/__snapshots__", "lint:fix": "oxfmt . && eslint . --fix", "lint:fix:next": "oxfmt . && eslint . --fix && uv run ruff check --fix packages/openapi-python/src/py-compiler/__snapshots__", "prepare": "husky", "test:changelog": "vitest run __tests__/*.test.ts", "test:changelog:watch": "vitest watch __tests__/*.test.ts", "test:coverage": "turbo run build && vitest run --coverage", "test:update": "turbo run build && vitest watch --update", "test:watch": "turbo run build && vitest watch", "test": "turbo run build && vitest", "typecheck": "turbo run typecheck", "td": "turbo run dev --filter", "tt": "turbo run build && vitest run --project", "tw": "turbo run build && vitest watch --project", "tu": "turbo run build && vitest watch --update --project", "tb": "turbo run build --filter", "ty": "turbo run typecheck --filter", "dev:ts": "cd dev && HEYAPI_CODEGEN_ENV=development tsx watch --clear-screen=false ../packages/openapi-ts/src/run.ts", "dev:py": "cd dev && HEYAPI_CODEGEN_ENV=development tsx watch --clear-screen=false ../packages/openapi-python/src/run.ts" }, "devDependencies": { "@arethetypeswrong/cli": "0.18.2", "@changesets/cli": "2.30.0", "@changesets/get-github-info": "0.8.0", "@changesets/parse": "0.4.3", "@changesets/types": "6.1.0", "@eslint/js": "9.39.2", "@hey-api/custom-client": "workspace:*", "@hey-api/openapi-ts": "workspace:*", "@types/node": "24.10.10", "@typescript-eslint/eslint-plugin": "8.54.0", "@typescript/native-preview": "7.0.0-dev.20260315.1", "@vitest/coverage-v8": "4.1.0", "eslint": "9.39.2", "eslint-plugin-simple-import-sort": "12.1.1", "eslint-plugin-sort-destructure-keys": "3.0.0", "eslint-plugin-sort-keys-fix": "1.1.2", "eslint-plugin-typescript-sort-keys": "3.3.0", "eslint-plugin-vue": "10.7.0", "globals": "17.4.0", "husky": "9.1.7", "lint-staged": "16.4.0", "oxfmt": "0.40.0", "tsdown": "0.21.3", "tsx": "4.21.0", "turbo": "2.8.17", "typescript": "5.9.3", "typescript-eslint": "8.54.0", "vitest": "4.1.0" }, "engines": { "node": ">=20.19.0" }, "packageManager": "pnpm@10.32.1" } ================================================ FILE: packages/codegen-core/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/codegen-core/CHANGELOG.md ================================================ # @hey-api/codegen-core ## 0.7.4 ### Patch Changes - **planner**: language-aware declaration sharing check ([#3606](https://github.com/hey-api/openapi-ts/pull/3606)) ([`86c7115`](https://github.com/hey-api/openapi-ts/commit/86c71151671b00821746659fa3be715224a28894)) by [@mrlubos](https://github.com/mrlubos) ## 0.7.3 ### Patch Changes - **internal**: remove TypeScript from peer dependencies ([#3566](https://github.com/hey-api/openapi-ts/pull/3566)) ([`b5f1e4b`](https://github.com/hey-api/openapi-ts/commit/b5f1e4b5f64cbf0bad2eff888177ac9c1881ba3e)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/types@0.1.4 ## 0.7.2 ### Patch Changes - **log**: make group optional in warn method ([#3540](https://github.com/hey-api/openapi-ts/pull/3540)) ([`0512650`](https://github.com/hey-api/openapi-ts/commit/0512650988ce3c411492172e6bbe300f5440408f)) by [@mrlubos](https://github.com/mrlubos) ## 0.7.1 ### Patch Changes - **internal**: log symbol meta if name is falsy ([#3448](https://github.com/hey-api/openapi-ts/pull/3448)) ([`c50f7bc`](https://github.com/hey-api/openapi-ts/commit/c50f7bcf5676f2783a412288d243aeaeabd9f8bd)) by [@mrlubos](https://github.com/mrlubos) ## 0.7.0 ### Minor Changes - **BREAKING:** **symbol**: replace `exportFrom` array with `getExportFromFilePath()` function ([#3322](https://github.com/hey-api/openapi-ts/pull/3322)) ([`bfd43ec`](https://github.com/hey-api/openapi-ts/commit/bfd43ec6d638bfc97b6905dd9dee2c911ccea3e0)) by [@mrlubos](https://github.com/mrlubos) ### Updated Symbol interface The `exportFrom` property has been replaced with the `getExportFromFilePath()` function. This allows you to dynamically determine export paths based on symbol properties. This is a low-level feature, so you're most likely unaffected. ## 0.6.1 ### Patch Changes - **planner**: fix duplicate import when same symbol is imported as both type and value ([#3291](https://github.com/hey-api/openapi-ts/pull/3291)) ([`3c08e38`](https://github.com/hey-api/openapi-ts/commit/3c08e38b4daa5c1f4829bdfb7f088d73b0e0f1f1)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.6.0 ### Minor Changes - **BREAKING**: Drop CommonJS (CJS) support. This package is now **ESM-only**. ([#3251](https://github.com/hey-api/openapi-ts/pull/3251)) ([`7f19d59`](https://github.com/hey-api/openapi-ts/commit/7f19d5921dadfa96ecae84a5298b7aee1daee56d)) by [@mrlubos](https://github.com/mrlubos) ### Removed CommonJS (CJS) support `@hey-api/codegen-core` is now ESM-only. This change simplifies the codebase, improves tree-shaking, and enables better integration with modern bundlers and TypeScript tooling. CommonJS entry points (`require()`, `module.exports`) are no longer supported. If you are in a CJS environment, you can still load the package dynamically using `import()` like: ```js const { Project } = await import("@hey-api/codegen-core"); ``` If you have previously written: ```js const { Project } = require("@hey-api/codegen-core"); ``` Migrate by updating your static imports: ```js import { Project } from "@hey-api/codegen-core"; ``` If your environment cannot use ESM, pin to a previous version. ### Patch Changes ### Updated Dependencies: - @hey-api/types@0.1.3 ## 0.5.5 ### Patch Changes - **config**: export `loadConfigFile` function (moved from `@hey-api/openapi-ts`) ([#3244](https://github.com/hey-api/openapi-ts/pull/3244)) ([`4f52bce`](https://github.com/hey-api/openapi-ts/commit/4f52bce79d8ac6573472f32a05b7f70913b90605)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/types@0.1.2 ## 0.5.4 ### Patch Changes - **internal**: move logger to codegen-core ([#3235](https://github.com/hey-api/openapi-ts/pull/3235)) ([`88532f0`](https://github.com/hey-api/openapi-ts/commit/88532f01200e1111818e82a4af7bd5cf8cf26e3b)) by [@mrlubos](https://github.com/mrlubos) ## 0.5.3 ### Patch Changes - **deps**: move @hey-api/types to dependencies to fix broken types ([#3232](https://github.com/hey-api/openapi-ts/pull/3232)) ([`edfce48`](https://github.com/hey-api/openapi-ts/commit/edfce4875cb9279d3ab8bfd438ff177e8ba7845c)) by [@mrlubos](https://github.com/mrlubos) ## 0.5.2 ### Patch Changes - **build**: do not minify bundles for better code readability and debugging ([#3186](https://github.com/hey-api/openapi-ts/pull/3186)) ([`4d46130`](https://github.com/hey-api/openapi-ts/commit/4d46130b53d9d8d5d3c178343a1b4fc3645b2628)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.5.1 ### Patch Changes - **project**: expose `.plan()` method ([#3175](https://github.com/hey-api/openapi-ts/pull/3175)) ([`b985053`](https://github.com/hey-api/openapi-ts/commit/b985053ffa64accc4ff01b7c0f301bb5cd84ff48)) by [@mrlubos](https://github.com/mrlubos) ## 0.5.0 ### Minor Changes - **core**: Structure API ([#3109](https://github.com/hey-api/openapi-ts/pull/3109)) ([`815a3de`](https://github.com/hey-api/openapi-ts/commit/815a3de0af434c28ac6d13ff92b85ce1fc146999)) by [@mrlubos](https://github.com/mrlubos) ### Patch Changes - **types**: document default values for `importKind` and `kind` ([#3147](https://github.com/hey-api/openapi-ts/pull/3147)) ([`ab80a4b`](https://github.com/hey-api/openapi-ts/commit/ab80a4b2c37423c522aa864afbcb688db76615ba)) by [@mrlubos](https://github.com/mrlubos) - **fix**: simplify symbol merging logic ([#3169](https://github.com/hey-api/openapi-ts/pull/3169)) ([`77bf81a`](https://github.com/hey-api/openapi-ts/commit/77bf81a13e49a13b6d052ef81e663df0f3b60b5a)) by [@mrlubos](https://github.com/mrlubos) ## 0.4.0 ### Minor Changes - **symbols**: remove `placeholder` property ([#2990](https://github.com/hey-api/openapi-ts/pull/2990)) ([`c3a81e8`](https://github.com/hey-api/openapi-ts/commit/c3a81e89ba5ed3f373409582c5f814e1d10cae06)) by [@mrlubos](https://github.com/mrlubos) ## 0.3.3 ### Patch Changes - fix: remove most of readonly properties to allow mutating in place ([#2919](https://github.com/hey-api/openapi-ts/pull/2919)) ([`34ee973`](https://github.com/hey-api/openapi-ts/commit/34ee973be30a9cbc66fd8463fe6f5961db0f3d37)) by [@mrlubos](https://github.com/mrlubos) - fix: update types ([#2909](https://github.com/hey-api/openapi-ts/pull/2909)) ([`d9dd389`](https://github.com/hey-api/openapi-ts/commit/d9dd38927ce5c7901ce46bfe439454935b2053fa)) by [@mrlubos](https://github.com/mrlubos) ## 0.3.2 ### Patch Changes - feat: add `.query()` method to symbol registry ([#2873](https://github.com/hey-api/openapi-ts/pull/2873)) ([`1cfc8f2`](https://github.com/hey-api/openapi-ts/commit/1cfc8f2b4673b53e0b1fff43f3d2078dcd595ca2)) by [@mrlubos](https://github.com/mrlubos) ## 0.3.1 ### Patch Changes - feat: add `isRegistered()` method to file and symbol registry ([#2812](https://github.com/hey-api/openapi-ts/pull/2812)) ([`022f7dd`](https://github.com/hey-api/openapi-ts/commit/022f7dd0bcb74d2da855f393e2175645aa670351)) by [@mrlubos](https://github.com/mrlubos) ## 0.3.0 ### Minor Changes - feat: bump minimum Node version to 20.19.0 ([#2775](https://github.com/hey-api/openapi-ts/pull/2775)) ([`7c7702a`](https://github.com/hey-api/openapi-ts/commit/7c7702a9ed3bda0d75ef28d35d4284e3b6318b26)) by [@mrlubos](https://github.com/mrlubos) ## 0.2.0 ### Minor Changes - feat: Symbol API ([#2664](https://github.com/hey-api/openapi-ts/pull/2664)) ([`e1ede9c`](https://github.com/hey-api/openapi-ts/commit/e1ede9cabf52b5bbcb9195570deff58db8f43dbb)) by [@mrlubos](https://github.com/mrlubos) ## 0.1.0 ### Minor Changes - feat: expand Symbol API ([#2582](https://github.com/hey-api/openapi-ts/pull/2582)) ([`10aea89`](https://github.com/hey-api/openapi-ts/commit/10aea8910771ff72ef9b08d4eacdd6b028833c4c)) by [@mrlubos](https://github.com/mrlubos) ## 0.0.1 ### Patch Changes - feat: initial release ================================================ FILE: packages/codegen-core/LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/codegen-core/README.md ================================================

    Codegen Core

    🧱 TypeScript framework for generating files.


    MIT License CI status

    ## Notice This is an internal framework. Visit [Hey API](https://heyapi.dev/) to discover our products. ## License Released under the [MIT License](https://github.com/hey-api/openapi-ts/blob/main/LICENSE.md). ================================================ FILE: packages/codegen-core/package.json ================================================ { "name": "@hey-api/codegen-core", "version": "0.7.4", "description": "🧱 TypeScript framework for generating files.", "keywords": [ "codegen", "generator", "javascript", "node", "typescript" ], "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "files": [ "dist", "LICENSE.md", "README.md" ], "type": "module", "main": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "types": "./dist/index.d.mts", "import": "./dist/index.mjs" }, "./package.json": "./package.json" }, "scripts": { "build": "tsdown && pnpm check-exports", "check-exports": "attw --pack . --profile esm-only --ignore-rules cjs-resolves-to-esm", "dev": "tsdown --watch", "prepublishOnly": "pnpm build", "typecheck": "tsgo --noEmit" }, "dependencies": { "@hey-api/types": "workspace:*", "ansi-colors": "4.1.3", "c12": "3.3.3", "color-support": "1.1.3" }, "devDependencies": { "eslint": "9.39.1", "typescript": "5.9.3" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/codegen-core/src/__tests__/data/file.ts ================================================ /* @ts-nocheck */ type _heyapi_5_ = string; type _heyapi_4_ = () => _heyapi_5_; /** * something about _heyapi_1_. Did you know that __heyapi_1__? */ export class _heyapi_1_ { // _heyapi_1_ is great! _heyapi_2_(_heyapi_12_: ReturnType<_heyapi_4_>): _heyapi_5_ { return _heyapi_12_; } } ================================================ FILE: packages/codegen-core/src/__tests__/exports.test.ts ================================================ import * as index from '../index'; const constExports = [ 'defaultExtensions', 'defaultModuleEntryNames', 'defaultNameConflictResolvers', 'File', 'fromRef', 'fromRefs', 'detectInteractiveSession', 'isNode', 'isNodeRef', 'isRef', 'isSymbol', 'isSymbolRef', 'loadConfigFile', 'log', 'Logger', 'mergeConfigs', 'nodeBrand', 'Project', 'ref', 'refs', 'simpleNameConflictResolver', 'Symbol', 'symbolBrand', 'underscoreNameConflictResolver', ]; // Type-level test: will fail to compile if any type export is missing or renamed export type _TypeExports = [ index.AnalysisContext, index.BindingKind, index.ExportMember, index.ExportModule, index.Extensions, index.File, index.FileIn, index.FromRef, index.FromRefs, index.ImportMember, index.ImportModule, index.IProject, index.Language, index.ModuleEntryNames, index.NameConflictResolver, index.NameConflictResolvers, index.Node, index.NodeName, index.NodeNameSanitizer, index.NodeRelationship, index.NodeScope, index.Output, index.Project, index.ProjectRenderMeta, index.Ref, index.Refs, index.RenderContext, index.Renderer, index.StructureInsert, index.StructureItem, index.StructureLocation, index.StructureModel, index.StructureNode, index.StructureShell, index.StructureShellResult, index.Symbol, index.SymbolIdentifier, index.SymbolIn, index.SymbolMeta, ]; describe('index exports', () => { it('should export all expected symbols', () => { for (const key of constExports) { expect(index).toHaveProperty(key); } }); }); ================================================ FILE: packages/codegen-core/src/__tests__/files.test.ts ================================================ import { File } from '../files/file'; import { FileRegistry } from '../files/registry'; const mockProject = {} as any; describe('FileRegistry', () => { it('register() creates a new File with incrementing id', () => { const registry = new FileRegistry(mockProject); const f1 = registry.register({ language: 'typescript', logicalFilePath: 'foo.ts', }); const f2 = registry.register({ language: 'typescript', logicalFilePath: 'bar.ts', }); expect(f1).toBeInstanceOf(File); expect(f2).toBeInstanceOf(File); expect(f2.id).toBe(f1.id + 1); }); it('register() updates name if file already exists', () => { const registry = new FileRegistry(mockProject); const f1 = registry.register({ language: 'typescript', logicalFilePath: 'dup.ts', name: 'First', }); const f2 = registry.register({ language: 'typescript', logicalFilePath: 'dup.ts', name: 'Second', }); expect(f1).toBe(f2); // same File instance expect(f1.name).toBe('Second'); // name updated }); it('get() returns the registered File or undefined', () => { const registry = new FileRegistry(mockProject); const f = registry.register({ language: 'ts', logicalFilePath: 'get.ts' }); expect(registry.get({ language: 'ts', logicalFilePath: 'get.ts' })).toBe(f); expect(registry.get({ language: 'ts', logicalFilePath: 'missing.ts' })).toBeUndefined(); }); it('isRegistered() returns true only for existing files', () => { const registry = new FileRegistry(mockProject); registry.register({ language: 'ts', logicalFilePath: 'check.ts' }); expect(registry.isRegistered({ language: 'ts', logicalFilePath: 'check.ts' })).toBe(true); expect(registry.isRegistered({ language: 'ts', logicalFilePath: 'other.ts' })).toBe(false); }); it('registered() iterates over all files', () => { const registry = new FileRegistry(mockProject); const files = [ registry.register({ language: 'ts', logicalFilePath: 'a.ts' }), registry.register({ language: 'ts', logicalFilePath: 'b.ts' }), ]; const iterated = [...registry.registered()]; expect(iterated).toEqual(files); }); it('handles external flag in key generation', () => { const registry = new FileRegistry(mockProject); const f1 = registry.register({ external: true, language: 'ts', logicalFilePath: 'ext.ts', }); const f2 = registry.register({ external: false, language: 'ts', logicalFilePath: 'ext.ts', }); expect(f1).not.toBe(f2); expect( registry.isRegistered({ external: true, language: 'ts', logicalFilePath: 'ext.ts', }), ).toBe(true); expect( registry.isRegistered({ external: false, language: 'ts', logicalFilePath: 'ext.ts', }), ).toBe(true); }); it('language influences key generation', () => { const registry = new FileRegistry(mockProject); const tsFile = registry.register({ language: 'ts', logicalFilePath: 'file', }); const jsFile = registry.register({ language: 'js', logicalFilePath: 'file', }); expect(tsFile).not.toBe(jsFile); expect(registry.isRegistered({ language: 'ts', logicalFilePath: 'file' })).toBe(true); expect(registry.isRegistered({ language: 'js', logicalFilePath: 'file' })).toBe(true); }); }); ================================================ FILE: packages/codegen-core/src/__tests__/logger.test.ts ================================================ import { Logger } from '../logger'; describe('Logger', () => { describe('report', () => { it('should handle unended events gracefully', () => { const logger = new Logger(); // Create an event but don't end it logger.timeEvent('test-event-1'); // Create another event and end it const event2 = logger.timeEvent('test-event-2'); event2.timeEnd(); // report() should not throw even though event1 was never ended expect(() => logger.report(false)).not.toThrow(); const measure = logger.report(false); expect(measure).toBeDefined(); expect(measure?.duration).toBeGreaterThanOrEqual(0); }); it('should handle nested unended events', () => { const logger = new Logger(); const parent = logger.timeEvent('parent'); logger.timeEvent('child1'); // Don't end child1 const child2 = logger.timeEvent('child2'); child2.timeEnd(); parent.timeEnd(); // report() should not throw even though child1 was never ended expect(() => logger.report(false)).not.toThrow(); const measure = logger.report(false); expect(measure).toBeDefined(); }); it('should handle all events properly ended', () => { const logger = new Logger(); const event1 = logger.timeEvent('event1'); const event2 = logger.timeEvent('event2'); event1.timeEnd(); event2.timeEnd(); expect(() => logger.report(false)).not.toThrow(); const measure = logger.report(false); expect(measure).toBeDefined(); expect(measure?.duration).toBeGreaterThanOrEqual(0); }); it('should return undefined when no events exist', () => { const logger = new Logger(); const measure = logger.report(false); expect(measure).toBeUndefined(); }); }); }); ================================================ FILE: packages/codegen-core/src/__tests__/planner.test.ts ================================================ import type { INode } from '../nodes/node'; import { Project } from '../project/project'; import { ref } from '../refs/refs'; import type { Symbol } from '../symbols/symbol'; import type { SymbolKind } from '../symbols/types'; /** * Creates a mock node for testing. */ const createMockNode = (args: { dependencies?: Array; filePath: string; language?: 'typescript' | 'javascript'; name: string; project: Project; symbolKind?: SymbolKind; }): { node: INode; symbol: Symbol } => { const { dependencies = [], filePath, language = 'typescript', name, project, symbolKind = 'var', } = args; const symbol = project.symbols.register({ exported: true, getFilePath: () => filePath, kind: symbolKind, name, }); const node: INode = { analyze: (ctx) => { for (const dep of dependencies) { ctx.addDependency(ref(dep)); } }, clone() { return this; }, exported: true, language, name: ref(name) as INode['name'], scope: 'value', symbol, toAst: () => ({}), '~brand': 'test-node', }; symbol.setNode(node); project.nodes.add(node); return { node, symbol }; }; describe('Planner imports deduplication', () => { it('produces a single value import when there is 1 imported symbol as value', () => { const project = new Project({ root: '/root' }); // Create source file with exported symbol const { symbol: sourceSymbol } = createMockNode({ filePath: 'source', name: 'MyValue', project, symbolKind: 'var', }); // Create consumer file that imports the source symbol as value createMockNode({ dependencies: [sourceSymbol], filePath: 'consumer', name: 'Consumer', project, }); project.plan(); const consumerFile = [...project.files.registered()].find((f) => f.name === 'consumer'); expect(consumerFile).toBeDefined(); const imports = consumerFile!.imports; expect(imports).toHaveLength(1); expect(imports[0]!.imports).toHaveLength(1); expect(imports[0]!.imports[0]!.isTypeOnly).toBe(false); expect(imports[0]!.imports[0]!.localName).toBe('MyValue'); }); it('produces a single type import when there is 1 imported symbol as type', () => { const project = new Project({ root: '/root' }); // Create source file with exported type symbol const { symbol: sourceSymbol } = createMockNode({ filePath: 'source', name: 'MyType', project, symbolKind: 'type', }); // Create consumer file that imports the source symbol as type createMockNode({ dependencies: [sourceSymbol], filePath: 'consumer', name: 'Consumer', project, }); project.plan(); const consumerFile = [...project.files.registered()].find((f) => f.name === 'consumer'); expect(consumerFile).toBeDefined(); const imports = consumerFile!.imports; expect(imports).toHaveLength(1); expect(imports[0]!.imports).toHaveLength(1); expect(imports[0]!.imports[0]!.isTypeOnly).toBe(true); expect(imports[0]!.imports[0]!.localName).toBe('MyType'); }); it('produces a single value import when there are 2 imported symbols as values with same name', () => { const project = new Project({ root: '/root' }); // Create source file with exported symbol const { symbol: sourceSymbol } = createMockNode({ filePath: 'source', name: 'MyValue', project, symbolKind: 'var', }); // Create consumer file that imports the source symbol twice as value const consumerSymbol = project.symbols.register({ exported: true, getFilePath: () => 'consumer', kind: 'var', name: 'Consumer', }); const consumerNode: INode = { analyze: (ctx) => { ctx.addDependency(ref(sourceSymbol)); ctx.addDependency(ref(sourceSymbol)); }, clone() { return this; }, exported: true, language: 'typescript', name: ref('Consumer') as INode['name'], scope: 'value', symbol: consumerSymbol, toAst: () => ({}), '~brand': 'test-node', }; consumerSymbol.setNode(consumerNode); project.nodes.add(consumerNode); project.plan(); const consumerFile = [...project.files.registered()].find((f) => f.name === 'consumer'); expect(consumerFile).toBeDefined(); const imports = consumerFile!.imports; expect(imports).toHaveLength(1); expect(imports[0]!.imports).toHaveLength(1); expect(imports[0]!.imports[0]!.isTypeOnly).toBe(false); expect(imports[0]!.imports[0]!.localName).toBe('MyValue'); }); it('produces a single type import when there are 2 imported symbols as types with same name', () => { const project = new Project({ root: '/root' }); // Create source file with exported type symbol const { symbol: sourceSymbol } = createMockNode({ filePath: 'source', name: 'MyType', project, symbolKind: 'type', }); // Create consumer file that imports the source symbol twice as type const consumerSymbol = project.symbols.register({ exported: true, getFilePath: () => 'consumer', kind: 'var', name: 'Consumer', }); const consumerNode: INode = { analyze: (ctx) => { ctx.addDependency(ref(sourceSymbol)); ctx.addDependency(ref(sourceSymbol)); }, clone() { return this; }, exported: true, language: 'typescript', name: ref('Consumer') as INode['name'], scope: 'value', symbol: consumerSymbol, toAst: () => ({}), '~brand': 'test-node', }; consumerSymbol.setNode(consumerNode); project.nodes.add(consumerNode); project.plan(); const consumerFile = [...project.files.registered()].find((f) => f.name === 'consumer'); expect(consumerFile).toBeDefined(); const imports = consumerFile!.imports; expect(imports).toHaveLength(1); expect(imports[0]!.imports).toHaveLength(1); expect(imports[0]!.imports[0]!.isTypeOnly).toBe(true); expect(imports[0]!.imports[0]!.localName).toBe('MyType'); }); it('produces a single value import when there are 2 imported symbols, 1 as type and 1 as value, with same name', () => { const project = new Project({ root: '/root' }); // Create source file with exported type symbol const { symbol: typeSymbol } = createMockNode({ filePath: 'source', name: 'MySymbol', project, symbolKind: 'type', }); // Create source file with exported value symbol with same name const { symbol: valueSymbol } = createMockNode({ filePath: 'source', name: 'MySymbol', project, symbolKind: 'var', }); // Create consumer file that imports both symbols (type and value with same name) const consumerSymbol = project.symbols.register({ exported: true, getFilePath: () => 'consumer', kind: 'var', name: 'Consumer', }); const consumerNode: INode = { analyze: (ctx) => { ctx.addDependency(ref(typeSymbol)); ctx.addDependency(ref(valueSymbol)); }, clone() { return this; }, exported: true, language: 'typescript', name: ref('Consumer') as INode['name'], scope: 'value', symbol: consumerSymbol, toAst: () => ({}), '~brand': 'test-node', }; consumerSymbol.setNode(consumerNode); project.nodes.add(consumerNode); project.plan(); const consumerFile = [...project.files.registered()].find((f) => f.name === 'consumer'); expect(consumerFile).toBeDefined(); const imports = consumerFile!.imports; expect(imports).toHaveLength(1); expect(imports[0]!.imports).toHaveLength(1); expect(imports[0]!.imports[0]!.isTypeOnly).toBe(false); expect(imports[0]!.imports[0]!.localName).toBe('MySymbol'); }); }); ================================================ FILE: packages/codegen-core/src/__tests__/project.test.ts ================================================ import { canDeclarationsShareIdentifier } from '../project/namespace'; import { Project } from '../project/project'; import type { SymbolKind } from '../symbols/types'; // Mock Planner so we control what files appear in project.files vi.mock('../planner/planner', () => { const MockPlanner = vi.fn(function (this: any, project: Project) { this.plan = vi.fn(() => { // planner is responsible for creating files const file = project.files.register({ logicalFilePath: 'root/a', }); file.setFinalPath('/root/a.ts'); file.setRenderer({ render: vi.fn(() => 'RENDERED'), supports: () => true, }); }); }); return { Planner: MockPlanner }; }); describe('Project', () => { const makeProject = (overrides: any = {}) => new Project({ renderers: [], root: '/root', ...overrides, }); it('calls Planner.plan() before rendering', () => { const p = makeProject(); p.render(); }); it('renders files created by the planner', () => { const p = makeProject(); const out = p.render(); expect(out).toEqual([{ content: 'RENDERED', path: '/root/a.ts' }]); }); it('passes correct ctx to renderer.render()', () => { const p = makeProject(); p.render({ hello: true }); const file = [...p.files.registered()][0]!; const renderer = file.renderer!; expect(renderer.render).toHaveBeenCalledWith({ file, meta: { hello: true }, project: p, }); }); }); describe('canDeclarationsShareIdentifier', () => { const kinds: ReadonlyArray = [ 'class', 'enum', 'function', 'interface', 'namespace', 'type', 'var', ]; it('matches TypeScript declaration merging matrix', () => { const allowed = new Set([ 'interface|interface', 'class|interface', 'class|namespace', 'enum|namespace', 'function|namespace', 'namespace|namespace', 'function|type', 'type|var', ]); for (const a of kinds) { for (const b of kinds) { expect(canDeclarationsShareIdentifier('typescript', a, b)).toBe( allowed.has([a, b].sort().join('|')), ); } } }); it('returns false for Python declaration pairs', () => { for (const a of kinds) { for (const b of kinds) { expect(canDeclarationsShareIdentifier('python', a, b)).toBe(false); } } }); }); ================================================ FILE: packages/codegen-core/src/__tests__/refs.test.ts ================================================ import { fromRef, fromRefs, ref, refs } from '../refs/refs'; import type { Refs } from '../refs/types'; describe('ref', () => { it('wraps a primitive value', () => { expect(ref(42)).toEqual({ '~ref': 42 }); expect(ref('x')).toEqual({ '~ref': 'x' }); }); it('wraps an object', () => { const obj = { foo: 1 }; expect(ref(obj)).toEqual({ '~ref': obj }); }); }); describe('fromRef', () => { it('unwraps a primitive value', () => { expect(fromRef({ '~ref': 42 })).toBe(42); expect(fromRef({ '~ref': 'x' })).toBe('x'); }); it('unwraps an object', () => { const obj = { foo: 1 }; expect(fromRef({ '~ref': obj })).toBe(obj); }); }); describe('ref <-> fromRef roundtrip', () => { it('roundtrips value -> ref -> value', () => { expect(fromRef(ref(123))).toBe(123); const obj = { foo: 'bar' }; expect(fromRef(ref(obj))).toBe(obj); }); }); describe('refs', () => { it('wraps primitives', () => { expect(refs({ a: 1, b: 'x' })).toEqual({ a: { '~ref': 1 }, b: { '~ref': 'x' }, }); }); it('wraps empty object', () => { expect(refs({})).toEqual({}); }); it('wraps nested objects shallowly', () => { const input = { a: { foo: 1 }, b: [1, 2] }; const value = refs(input); expect(value.a['~ref']).toEqual({ foo: 1 }); expect(value.b['~ref']).toEqual([1, 2]); }); }); describe('fromRefs', () => { it('unwraps primitives', () => { expect(fromRefs({ a: { '~ref': 1 }, b: { '~ref': 'x' } })).toEqual({ a: 1, b: 'x', }); }); it('unwraps empty object', () => { expect(fromRefs({})).toEqual({}); }); it('unwraps nested objects shallowly', () => { const input: Refs = { a: { '~ref': { foo: 1 } }, b: { '~ref': [1, 2] }, }; expect(fromRefs(input)).toEqual({ a: { foo: 1 }, b: [1, 2] }); }); }); describe('refs <-> fromRefs roundtrip', () => { it('roundtrips plain -> refs -> plain', () => { const obj = { a: 1, b: 'x', c: [1, 2], d: { foo: 2 } }; expect(fromRefs(refs(obj))).toEqual(obj); }); it('roundtrips refs -> plain -> refs', () => { const value: Refs = { a: { '~ref': 1 }, b: { '~ref': 'x' }, c: { '~ref': [1, 2] }, }; expect(refs(fromRefs(value))).toEqual(value); }); }); ================================================ FILE: packages/codegen-core/src/__tests__/symbols.test.ts ================================================ import { SymbolRegistry } from '../symbols/registry'; import { Symbol } from '../symbols/symbol'; const meta = (m: any) => m as any; describe('SymbolRegistry', () => { it('register() assigns increasing IDs and stores symbols', () => { const r = new SymbolRegistry(); const a = r.register({ meta: meta({ kind: 'x' }), name: 'A' }); const b = r.register({ meta: meta({ kind: 'y' }), name: 'B' }); expect(a.id).toBe(0); expect(b.id).toBe(1); expect(r.get(0)).toBe(a); expect(r.get(1)).toBe(b); }); it('query() returns symbols matching meta', () => { const r = new SymbolRegistry(); const a = r.register({ meta: meta({ nested: { x: 1 }, type: 'foo' }), name: 'A', }); r.register({ meta: meta({ type: 'bar' }), name: 'B' }); const results = r.query(meta({ nested: { x: 1 }, type: 'foo' })); expect(results).toEqual([a]); }); it('query() returns empty array when no matches', () => { const r = new SymbolRegistry(); r.register({ meta: meta({ type: 'x' }), name: 'A' }); expect(r.query(meta({ type: 'nope' }))).toEqual([]); }); it('reference() returns stub if not registered', () => { const r = new SymbolRegistry(); const stub = r.reference(meta({ id: 1, kind: 'x' })); expect(stub).toBeInstanceOf(Symbol); expect(r.isRegistered(stub.id)).toBe(false); // same meta → same stub const again = r.reference(meta({ id: 1, kind: 'x' })); expect(again).toBe(stub); }); it('reference() stub is replaced when real symbol registers', () => { const r = new SymbolRegistry(); const stub = r.reference(meta({ group: 'abc', tag: 1 })); const real = r.register({ meta: meta({ group: 'abc', tag: 1 }), name: 'Real', }); // Stub should now canonicalize to the real one expect(stub.canonical).toBe(real); expect(r.get(stub.id)).toBe(stub); // Queries should now return the real one expect(r.query(meta({ group: 'abc', tag: 1 }))).toEqual([real]); }); it('isRegistered() returns true only for registered symbols', () => { const r = new SymbolRegistry(); const stub = r.reference(meta({ foo: 1 })); const real = r.register({ meta: meta({ foo: 1 }), name: 'X' }); expect(r.isRegistered(stub.id)).toBe(false); expect(r.isRegistered(real.id)).toBe(true); }); it('registered() iterates over only registered symbols (not stubs)', () => { const r = new SymbolRegistry(); r.reference(meta({ x: 1 })); // stub const a = r.register({ meta: meta({ x: 2 }), name: 'A' }); const b = r.register({ meta: meta({ x: 3 }), name: 'B' }); expect([...r.registered()]).toEqual([a, b]); }); it('cache invalidates when new symbol matches cached query', () => { const r = new SymbolRegistry(); // prime cache expect(r.query(meta({ type: 'foo' }))).toEqual([]); const a = r.register({ meta: meta({ type: 'foo' }), name: 'A' }); // now query again → cache should be invalidated → return new entry expect(r.query(meta({ type: 'foo' }))).toEqual([a]); }); it('nested meta keys are indexed correctly', () => { const r = new SymbolRegistry(); const a = r.register({ meta: meta({ a: { b: { c: 123 } } }), name: 'A', }); const result = r.query(meta({ a: { b: { c: 123 } } })); expect(result).toEqual([a]); }); }); ================================================ FILE: packages/codegen-core/src/bindings.ts ================================================ import type { File } from './files/file'; import type { BindingKind } from './symbols/types'; export interface ExportMember { /** * Name under which the symbol is exported in this file. * * export { Foo as Bar } from "./models" * * exportedName === "Bar" */ exportedName: string; /** Whether this export is type-only. */ isTypeOnly: boolean; /** Export flavor. */ kind: BindingKind; /** The exported name of the symbol in its source file. */ sourceName: string; } export type ExportModule = Pick & { /** Whether this module can export all symbols: `export * from 'module'`. */ canExportAll: boolean; /** Members exported from this module. */ exports: Array; /** Source file. */ from: File; /** Namespace export: `export * as ns from 'module'`. Mutually exclusive with `exports`. */ namespaceExport?: string; }; export interface ImportMember { /** Whether this import is type-only. */ isTypeOnly: boolean; /** * The name this symbol will have locally in this file. * This is where aliasing is applied: * * import { Foo as Foo$2 } from "./x" * * localName === "Foo$2" */ localName: string; /** The exported name of the symbol in its source file. */ sourceName: string; } export type ImportModule = Pick & Pick, 'localName'> & { /** Source file. */ from: File; /** List of symbols imported from this module. */ imports: Array; /** Import flavor. */ kind: BindingKind; }; ================================================ FILE: packages/codegen-core/src/brands.ts ================================================ export const fileBrand = 'heyapi.file'; export const nodeBrand = 'heyapi.node'; export const symbolBrand = 'heyapi.symbol'; ================================================ FILE: packages/codegen-core/src/config/interactive.ts ================================================ /** * Detect if the current session is interactive based on TTY status and environment variables. * This is used as a fallback when the user doesn't explicitly set the interactive option. * @internal */ export function detectInteractiveSession(): boolean { return Boolean( process.stdin.isTTY && process.stdout.isTTY && !process.env.CI && !process.env.NO_INTERACTIVE && !process.env.NO_INTERACTION, ); } ================================================ FILE: packages/codegen-core/src/config/load.ts ================================================ import type { AnyObject, MaybeArray } from '@hey-api/types'; import { loadConfig } from 'c12'; import type { Logger } from '../logger'; import { mergeConfigs } from './merge'; export async function loadConfigFile({ configFile, logger, name, userConfig, }: { configFile: string | undefined; logger: Logger; name: string; userConfig: T; }): Promise<{ configFile: string | undefined; configs: ReadonlyArray; foundConfig: boolean; }> { const eventC12 = logger.timeEvent('c12'); const { config: fileConfig, configFile: loadedConfigFile } = await loadConfig>({ configFile, name, }); eventC12.timeEnd(); const fileConfigs = fileConfig instanceof Array ? fileConfig : [fileConfig]; const mergedConfigs = fileConfigs.map((config) => mergeConfigs(config, userConfig)); const foundConfig = fileConfigs.some((config) => Object.keys(config).length > 0); return { configFile: loadedConfigFile, configs: mergedConfigs, foundConfig }; } ================================================ FILE: packages/codegen-core/src/config/merge.ts ================================================ import type { AnyObject } from '@hey-api/types'; function isPlainObject(value: unknown): value is AnyObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } export function mergeConfigs( configA: T | undefined, configB: T | undefined, ): T { const a = (configA || {}) as AnyObject; const b = (configB || {}) as AnyObject; const result: AnyObject = { ...a }; for (const key of Object.keys(b)) { const valueA = a[key]; const valueB = b[key]; if (isPlainObject(valueA) && isPlainObject(valueB)) { result[key] = mergeConfigs(valueA, valueB); } else { result[key] = valueB; } } return result as T; } ================================================ FILE: packages/codegen-core/src/extensions.ts ================================================ /** * Arbitrary metadata passed to the project's render function. * * Implementers should extend this interface for their own needs. */ export interface IProjectRenderMeta { [key: string]: unknown; } /** * Additional metadata about the symbol. * * Implementers should extend this interface for their own needs. */ export interface ISymbolMeta { [key: string]: unknown; } ================================================ FILE: packages/codegen-core/src/files/file.ts ================================================ import path from 'node:path'; import type { ExportModule, ImportModule } from '../bindings'; import { fileBrand } from '../brands'; import type { Language } from '../languages/types'; import { log } from '../log'; import type { INode } from '../nodes/node'; import type { NameScopes } from '../planner/scope'; import type { IProject } from '../project/types'; import type { Renderer } from '../renderer'; import type { IFileIn } from './types'; export class File { /** * Exports from this file. */ private _exports: Array = []; /** * File extension (e.g. `.ts`). */ private _extension?: string; /** * Actual emitted file path, including extension and directories. */ private _finalPath?: string; /** * Imports to this file. */ private _imports: Array = []; /** * Language of the file. */ private _language?: Language; /** * Logical, extension-free path used for planning and routing. */ private _logicalFilePath: string; /** * Base name of the file (without extension). */ private _name?: string; /** * Syntax nodes contained in this file. */ private _nodes: Array = []; /** * Renderer assigned to this file. */ private _renderer?: Renderer; /** Brand used for identifying files. */ readonly '~brand' = fileBrand; /** All names defined in this file, including local scopes. */ allNames: NameScopes = new Map(); /** Whether this file is external to the project. */ external: boolean; /** Unique identifier for the file. */ readonly id: number; /** The project this file belongs to. */ readonly project: IProject; /** Names declared at the top level of the file. */ topLevelNames: NameScopes = new Map(); constructor(input: IFileIn, id: number, project: IProject) { this.external = input.external ?? false; this.id = id; if (input.language !== undefined) this._language = input.language; this._logicalFilePath = input.logicalFilePath.split(path.sep).join('/'); if (input.name !== undefined) this._name = input.name; this.project = project; } /** * Exports from this file. */ get exports(): ReadonlyArray { return [...this._exports]; } /** * Read-only accessor for the file extension. */ get extension(): string | undefined { if (this.external) return; if (this._extension) return this._extension; const language = this.language; const extension = language ? this.project.extensions[language] : undefined; if (extension && extension[0]) return extension[0]; return; } /** * Read-only accessor for the final emitted path. * * If undefined, the file has not yet been assigned a final path * or is external to the project and should not be emitted. */ get finalPath(): string | undefined { if (this._finalPath) return this._finalPath; const dirs = this._logicalFilePath ? this._logicalFilePath.split('/').slice(0, -1) : []; return [...dirs, `${this.name}${this.extension ?? ''}`].join('/'); } /** * Imports to this file. */ get imports(): ReadonlyArray { return [...this._imports]; } /** * Language of the file; inferred from nodes or fallback if not set explicitly. */ get language(): Language | undefined { if (this._language) return this._language; if (this._nodes[0]) return this._nodes[0].language; return; } /** * Logical, extension-free path used for planning and routing. */ get logicalFilePath(): string { return this._logicalFilePath; } /** * Base name of the file (without extension). * * If no name was set explicitly, it is inferred from the logical file path. */ get name(): string { if (this._name) return this._name; const name = this._logicalFilePath.split('/').pop(); if (name) return name; const message = `File ${this.toString()} has no name`; log.debug(message, 'file'); throw new Error(message); } /** * Syntax nodes contained in this file. */ get nodes(): ReadonlyArray { return [...this._nodes]; } /** * Renderer assigned to this file. */ get renderer(): Renderer | undefined { return this._renderer; } /** * Add an export group to the file. */ addExport(group: ExportModule): void { this._exports.push(group); } /** * Add an import group to the file. */ addImport(group: ImportModule): void { this._imports.push(group); } /** * Add a syntax node to the file. */ addNode(node: Node): void { this._nodes.push(node); node.file = this; } /** * Sets the file extension. */ setExtension(extension: string): void { this._extension = extension; } /** * Sets the final emitted path of the file. */ setFinalPath(path: string): void { this._finalPath = path; } /** * Sets the language of the file. */ setLanguage(lang: Language): void { this._language = lang; } /** * Sets the name of the file. */ setName(name: string): void { this._name = name; } /** * Sets the renderer assigned to this file. */ setRenderer(renderer: Renderer): void { this._renderer = renderer; } /** * Returns a debug‑friendly string representation identifying the file. */ toString(): string { return `[File ${this._logicalFilePath}#${this.id}]`; } } ================================================ FILE: packages/codegen-core/src/files/registry.ts ================================================ import path from 'node:path'; import type { IProject } from '../project/types'; import { File } from './file'; import type { FileKeyArgs, IFileIn, IFileRegistry } from './types'; type FileId = number; type FileKey = string; export class FileRegistry implements IFileRegistry { private _id: FileId = 0; private _values: Map = new Map(); private readonly project: IProject; constructor(project: IProject) { this.project = project; } get(args: FileKeyArgs): File | undefined { return this._values.get(this.createFileKey(args)); } isRegistered(args: FileKeyArgs): boolean { return this._values.has(this.createFileKey(args)); } get nextId(): FileId { return this._id++; } register(file: IFileIn): File { const key = this.createFileKey(file); let result = this._values.get(key); if (result) { if (file.name) { result.setName(file.name); } } else { result = new File(file, this.nextId, this.project); } this._values.set(key, result); return result; } *registered(): IterableIterator { for (const file of this._values.values()) { yield file; } } private createFileKey(args: FileKeyArgs): string { const logicalPath = args.logicalFilePath.split(path.sep).join('/'); return `${args.external ? 'ext:' : ''}${logicalPath}${args.language ? `:${args.language}` : ''}`; } } ================================================ FILE: packages/codegen-core/src/files/rules.ts ================================================ // TODO: use this later export interface Rules { /** Whether two exported names may collide. */ allowExportNameShadowing: boolean; /** Whether a local symbol can shadow another local name without error. */ allowLocalNameShadowing: boolean; /** Whether the language requires file-scoped name uniqueness. */ fileScopedNamesMustBeUnique: boolean; /** Whether `import { X } from "mod"` introduces a local binding `X`. */ importCreatesLocalBinding: boolean; /** Whether `export { X } from "mod"` introduces a local binding `X`. */ reexportCreatesLocalBinding: boolean; /** Whether the language distinguishes type-only imports. */ supportsTypeImports: boolean; } ================================================ FILE: packages/codegen-core/src/files/types.ts ================================================ import type { Language } from '../languages/types'; import type { File } from './file'; export type FileKeyArgs = Pick, 'logicalFilePath'> & Pick, 'external' | 'language'>; export type IFileIn = { /** * Indicates whether the file is external, meaning it is not generated * as part of the project but is referenced (e.g., a module from * node_modules). * * @example true */ external?: boolean; /** * Language of the file. * * @example "typescript" */ language?: Language; /** * Logical, extension-free path used for planning and routing. * * @example "src/models/user" */ logicalFilePath: string; /** * The desired name for the file within the project. If there are multiple files * with the same desired name, this might not end up being the actual name. * * @example "UserModel" */ name?: string; }; export interface IFileRegistry { /** * Get a file. * * @returns The file, or undefined if not found. */ get(args: FileKeyArgs): File | undefined; /** * Returns whether a file is registered in the registry. * * @returns True if the file is registered, false otherwise. */ isRegistered(args: FileKeyArgs): boolean; /** * Returns the current file ID and increments it. * * @returns File ID before being incremented */ readonly nextId: number; /** * Register a file globally. * * @param file File to register. * @returns Newly registered file if created, merged file otherwise. */ register(file: IFileIn): File; /** * Get all files in the order they were registered. * * @returns Array of all registered files, in insert order. */ registered(): IterableIterator; } ================================================ FILE: packages/codegen-core/src/guards.ts ================================================ import { nodeBrand, symbolBrand } from './brands'; import type { INode } from './nodes/node'; import type { Ref } from './refs/types'; import type { Symbol } from './symbols/symbol'; export function isBrand(value: unknown, brand: string): value is INode { if (!value || typeof value !== 'object') return false; return (value as any)['~brand'] === brand; } export function isNode(value: unknown): value is INode { if (!value || typeof value !== 'object') return false; return isBrand(value, nodeBrand); } export function isNodeRef(value: Ref): value is Ref { return isBrand(value['~ref'], nodeBrand); } export function isSymbol(value: unknown): value is Symbol { return isBrand(value, symbolBrand); } export function isSymbolRef(value: Ref): value is Ref { return isBrand(value['~ref'], symbolBrand); } ================================================ FILE: packages/codegen-core/src/index.ts ================================================ export type { ExportMember, ExportModule, ImportMember, ImportModule } from './bindings'; export { nodeBrand, symbolBrand } from './brands'; export { detectInteractiveSession } from './config/interactive'; export { loadConfigFile } from './config/load'; export { mergeConfigs } from './config/merge'; export type { IProjectRenderMeta as ProjectRenderMeta, ISymbolMeta as SymbolMeta, } from './extensions'; export { File } from './files/file'; export type { IFileIn as FileIn } from './files/types'; export { isNode, isNodeRef, isSymbol, isSymbolRef } from './guards'; export { defaultExtensions } from './languages/extensions'; export { defaultModuleEntryNames } from './languages/modules'; export { defaultNameConflictResolvers } from './languages/resolvers'; export type { Extensions, Language, ModuleEntryNames, NameConflictResolvers, } from './languages/types'; export { log } from './log'; export { Logger } from './logger'; export type { INode as Node, NodeName, NodeNameSanitizer, NodeRelationship, NodeScope, } from './nodes/node'; export type { IOutput as Output } from './output'; export { simpleNameConflictResolver, underscoreNameConflictResolver } from './planner/resolvers'; export type { IAnalysisContext as AnalysisContext, NameConflictResolver } from './planner/types'; export { Project } from './project/project'; export type { IProject } from './project/types'; export { fromRef, fromRefs, isRef, ref, refs } from './refs/refs'; export type { FromRef, FromRefs, Ref, Refs } from './refs/types'; export type { RenderContext, Renderer } from './renderer'; export { StructureModel } from './structure/model'; export { StructureNode } from './structure/node'; export type { StructureInsert, StructureItem, StructureLocation, StructureShell, StructureShellResult, } from './structure/types'; export { Symbol } from './symbols/symbol'; export type { BindingKind, ISymbolIdentifier as SymbolIdentifier, ISymbolIn as SymbolIn, } from './symbols/types'; ================================================ FILE: packages/codegen-core/src/languages/extensions.ts ================================================ import type { Extensions } from './types'; export const defaultExtensions: Extensions = { c: ['.c'], 'c#': ['.cs'], 'c++': ['.cpp', '.hpp'], css: ['.css'], dart: ['.dart'], go: ['.go'], haskell: ['.hs'], html: ['.html'], java: ['.java'], javascript: ['.js', '.jsx'], json: ['.json'], kotlin: ['.kt'], lua: ['.lua'], markdown: ['.md'], matlab: ['.m'], perl: ['.pl'], php: ['.php'], python: ['.py'], r: ['.r'], ruby: ['.rb'], rust: ['.rs'], scala: ['.scala'], shell: ['.sh'], sql: ['.sql'], swift: ['.swift'], typescript: ['.ts', '.tsx'], yaml: ['.yaml', '.yml'], }; ================================================ FILE: packages/codegen-core/src/languages/modules.ts ================================================ import type { ModuleEntryNames } from './types'; export const defaultModuleEntryNames: ModuleEntryNames = { javascript: 'index', python: '__init__', typescript: 'index', }; ================================================ FILE: packages/codegen-core/src/languages/resolvers.ts ================================================ import { underscoreNameConflictResolver } from '../planner/resolvers'; import type { NameConflictResolvers } from './types'; export const defaultNameConflictResolvers: NameConflictResolvers = { php: underscoreNameConflictResolver, python: underscoreNameConflictResolver, ruby: underscoreNameConflictResolver, }; ================================================ FILE: packages/codegen-core/src/languages/types.ts ================================================ import type { AnyString } from '@hey-api/types'; import type { NameConflictResolver } from '../planner/types'; /** * Map of extensions for each language. * * @example * ```ts * const exts: Extensions = { * typescript: ['.ts', '.tsx'], * python: ['.py'], * }; * ``` */ export type Extensions = Partial>>; export type Language = | 'c' | 'c#' | 'c++' | 'css' | 'dart' | 'go' | 'haskell' | 'html' | 'java' | 'javascript' | 'json' | 'kotlin' | 'lua' | 'markdown' | 'matlab' | 'perl' | 'php' | 'python' | 'r' | 'ruby' | 'rust' | 'scala' | 'shell' | 'sql' | 'swift' | 'typescript' | 'yaml' | AnyString; // other/custom language /** * Map of module entry names for each language. * * @example * ```ts * const entries: ModuleEntryNames = { * typescript: 'index', * python: '__init__', * }; * ``` */ export type ModuleEntryNames = Partial>; export type NameConflictResolvers = Partial>; ================================================ FILE: packages/codegen-core/src/log.ts ================================================ import type { MaybeArray, MaybeFunc } from '@hey-api/types'; import colors from 'ansi-colors'; // @ts-expect-error import colorSupport from 'color-support'; colors.enabled = colorSupport().hasBasic; const DEBUG_NAMESPACE = 'heyapi'; const NO_WARNINGS = /^(1|true|yes|on)$/i.test(process.env.HEYAPI_DISABLE_WARNINGS ?? ''); const DebugGroups = { analyzer: colors.greenBright, dsl: colors.cyanBright, file: colors.yellowBright, registry: colors.blueBright, symbol: colors.magentaBright, } as const; const WarnGroups = { deprecated: colors.magentaBright, } as const; let cachedDebugGroups: Set | undefined; function getDebugGroups(): Set { if (cachedDebugGroups) return cachedDebugGroups; const value = process.env.DEBUG; cachedDebugGroups = new Set(value ? value.split(',').map((x) => x.trim().toLowerCase()) : []); return cachedDebugGroups; } /** * Tracks which deprecations have been shown to avoid spam. */ const shownDeprecations = new Set(); function debug(message: string, group: keyof typeof DebugGroups) { const groups = getDebugGroups(); if ( !( groups.has('*') || groups.has(`${DEBUG_NAMESPACE}:*`) || groups.has(`${DEBUG_NAMESPACE}:${group}`) || groups.has(group) ) ) { return; } const color = DebugGroups[group] ?? colors.whiteBright; const prefix = color(`${DEBUG_NAMESPACE}:${group}`); console.debug(`${prefix} ${message}`); } function warn(message: string, group?: keyof typeof WarnGroups) { if (NO_WARNINGS) return; const color = group ? WarnGroups[group] : colors.yellowBright; console.warn(color(`${message}`)); } function warnDeprecated({ context, field, replacement, }: { context?: string; field: string; replacement?: MaybeFunc<(field: string) => MaybeArray>; }) { const key = context ? `${context}:${field}:${JSON.stringify(replacement)}` : `${field}:${JSON.stringify(replacement)}`; if (shownDeprecations.has(key)) return; shownDeprecations.add(key); let message = `\`${field}\` is deprecated.`; if (replacement) { const reps = typeof replacement === 'function' ? replacement(field) : replacement; const repArray = reps instanceof Array ? reps : [reps]; const repString = repArray.map((r) => `\`${r}\``).join(' or '); message += ` Use ${repString} instead.`; } const prefix = context ? `[${context}] ` : ''; warn(`${prefix}${message}`, 'deprecated'); } export const log = { debug, warn, warnDeprecated, }; ================================================ FILE: packages/codegen-core/src/logger.ts ================================================ import colors from 'ansi-colors'; interface LoggerEvent { end?: PerformanceMark; events: Array; id: string; // unique internal key name: string; start: PerformanceMark; } interface Severity { color: colors.StyleFunction; type: 'duration' | 'percentage'; } interface StoredEventResult { position: ReadonlyArray; } let loggerCounter = 0; const nameToId = (name: string) => `${name}-${loggerCounter++}`; const idEnd = (id: string) => `${id}-end`; const idLength = (id: string) => `${id}-length`; const idStart = (id: string) => `${id}-start`; const getSeverity = (duration: number, percentage: number): Severity | undefined => { if (duration > 200) { return { color: colors.red, type: 'duration', }; } if (percentage > 30) { return { color: colors.red, type: 'percentage', }; } if (duration > 50) { return { color: colors.yellow, type: 'duration', }; } if (percentage > 10) { return { color: colors.yellow, type: 'percentage', }; } return; }; export class Logger { private events: Array = []; private end(result: StoredEventResult): void { let event: LoggerEvent | undefined; let events = this.events; for (const index of result.position) { event = events[index]; if (event?.events) { events = event.events; } } if (event && !event.end) { event.end = performance.mark(idEnd(event.id)); } } /** * Recursively end all unended events in the event tree. * This ensures all events have end marks before measuring. */ private endAllEvents(events: Array): void { for (const event of events) { if (!event.end) { event.end = performance.mark(idEnd(event.id)); } if (event.events.length > 0) { this.endAllEvents(event.events); } } } report(print: boolean = true): PerformanceMeasure | undefined { const firstEvent = this.events[0]; if (!firstEvent) return; // Ensure all events are ended before reporting this.endAllEvents(this.events); const lastEvent = this.events[this.events.length - 1]!; const name = 'root'; const id = nameToId(name); try { const measure = performance.measure( idLength(id), idStart(firstEvent.id), idEnd(lastEvent.id), ); if (print) { this.reportEvent({ end: lastEvent.end, events: this.events, id, indent: 0, measure, name, start: firstEvent!.start, }); } return measure; } catch { // If measuring fails (e.g., marks don't exist), silently skip reporting // to avoid crashing the application return; } } private reportEvent({ indent, ...parent }: LoggerEvent & { indent: number; measure: PerformanceMeasure; }): void { const color = !indent ? colors.cyan : colors.gray; const lastIndex = parent.events.length - 1; parent.events.forEach((event, index) => { try { const measure = performance.measure(idLength(event.id), idStart(event.id), idEnd(event.id)); const duration = Math.ceil(measure.duration * 100) / 100; const percentage = Math.ceil((measure.duration / parent.measure.duration) * 100 * 100) / 100; const severity = indent ? getSeverity(duration, percentage) : undefined; let durationLabel = `${duration.toFixed(2).padStart(8)}ms`; if (severity?.type === 'duration') { durationLabel = severity.color(durationLabel); } const branch = index === lastIndex ? '└─ ' : '├─ '; const prefix = !indent ? '' : '│ '.repeat(indent - 1) + branch; const maxLength = 38 - prefix.length; const percentageBranch = !indent ? '' : '↳ '; const percentagePrefix = indent ? ' '.repeat(indent - 1) + percentageBranch : ''; let percentageLabel = `${percentagePrefix}${percentage.toFixed(2)}%`; if (severity?.type === 'percentage') { percentageLabel = severity.color(percentageLabel); } const jobPrefix = colors.gray('[root] '); console.log( `${jobPrefix}${colors.gray(prefix)}${color( `${event.name.padEnd(maxLength)} ${durationLabel} (${percentageLabel})`, )}`, ); this.reportEvent({ ...event, indent: indent + 1, measure }); } catch { // If measuring fails (e.g., marks don't exist), silently skip this event // to avoid crashing the application } }); } private start(id: string): PerformanceMark { return performance.mark(idStart(id)); } private storeEvent({ result, ...event }: Pick & { result: StoredEventResult; }): void { const lastEventIndex = event.events.length - 1; const lastEvent = event.events[lastEventIndex]; if (lastEvent && !lastEvent.end) { result.position = [...result.position, lastEventIndex]; this.storeEvent({ ...event, events: lastEvent.events, result }); return; } const length = event.events.push({ ...event, events: [] }); result.position = [...result.position, length - 1]; } timeEvent(name: string) { const id = nameToId(name); const start = this.start(id); const event: LoggerEvent = { events: this.events, id, name, start, }; const result: StoredEventResult = { position: [], }; this.storeEvent({ ...event, result }); return { mark: start, timeEnd: () => this.end(result), }; } } ================================================ FILE: packages/codegen-core/src/nodes/node.ts ================================================ import type { File } from '../files/file'; import type { Language } from '../languages/types'; import type { IAnalysisContext } from '../planner/types'; import type { Ref } from '../refs/types'; import type { Symbol } from '../symbols/symbol'; export type MaybeRef = T | Ref; export type NodeName = MaybeRef; export type NodeNameSanitizer = (name: string) => string; export type NodeRelationship = 'container' | 'reference'; export type NodeScope = 'type' | 'value'; export interface INode { /** Perform semantic analysis. */ analyze(ctx: IAnalysisContext): void; /** Create a shallow copy of this node. */ clone(): this; /** Whether this node is exported from its file. */ exported?: boolean; /** The file this node belongs to. */ file?: File; /** The programming language associated with this node */ language: Language; /** The display name of this node. */ readonly name: Ref & { set(value: NodeName): void; toString(): string; }; /** Optional function to sanitize the node name. */ readonly nameSanitizer?: NodeNameSanitizer; /** Whether this node is a root node in the file. */ root?: boolean; /** The scope of this node. */ scope?: NodeScope; /** Semantic children in the structure hierarchy. */ structuralChildren?: Map; /** Semantic parents in the structure hierarchy. */ structuralParents?: Map; /** The symbol associated with this node. */ symbol?: Symbol; /** Convert this node into AST representation. */ toAst(): T; /** Brand used for renderer dispatch. */ readonly '~brand': string; } ================================================ FILE: packages/codegen-core/src/nodes/registry.ts ================================================ import { fromRef, ref } from '../refs/refs'; import type { Ref } from '../refs/types'; import type { INode } from './node'; import type { INodeRegistry } from './types'; export class NodeRegistry implements INodeRegistry { private list: Array> = []; add(node: INode | null): number { const index = this.list.push(ref(node)); return index - 1; } *all(): Iterable { for (const r of this.list) { const node = fromRef(r); if (node) yield node; } } remove(index: number): void { this.list[index] = ref(null); } update(index: number, node: INode | null): void { this.list[index] = ref(node); } } ================================================ FILE: packages/codegen-core/src/nodes/types.ts ================================================ import type { INode } from './node'; export interface INodeRegistry { /** * Register a syntax node. * * @returns The index of the registered node. */ add(node: INode | null): number; /** * All nodes in insertion order. */ all(): Iterable; /** * Remove a node by its index. * * @param index Index of the node to remove. */ remove(index: number): void; /** * Update a node at the given index. * * @param index Index of the node to update. * @param node New node to set. */ update(index: number, node: INode | null): void; } ================================================ FILE: packages/codegen-core/src/output.ts ================================================ export interface IOutput { /** * The main content of the file to output. * * A raw string representing source code. * * @example "function foo(): void {\n // implementation\n}\n" */ content: string; /** * Logical output path (used for writing the file). * * @example "models/user.ts" */ path: string; } ================================================ FILE: packages/codegen-core/src/planner/analyzer.ts ================================================ import { isNodeRef, isSymbolRef } from '../guards'; import type { INode, NodeRelationship } from '../nodes/node'; import { fromRef, isRef, ref } from '../refs/refs'; import type { Ref } from '../refs/types'; import type { Symbol } from '../symbols/symbol'; import type { NameScopes, Scope } from './scope'; import { createScope } from './scope'; import type { IAnalysisContext, Input } from './types'; export class AnalysisContext implements IAnalysisContext { /** * Stack of parent nodes during analysis. * * The top of the stack is the current semantic container. */ private _parentStack: Array = []; scope: Scope; scopes: Scope = createScope(); symbol?: Symbol; constructor(node: INode) { this._parentStack.push(node); this.scope = this.scopes; this.symbol = node.symbol; } /** * Get the current semantic parent (top of stack). */ get currentParent(): INode | undefined { return this._parentStack[this._parentStack.length - 1]; } /** * Register a child node under the current parent. */ addChild(child: INode, relationship: NodeRelationship = 'container'): void { const parent = this.currentParent; if (!parent) return; if (!parent.structuralChildren) { parent.structuralChildren = new Map(); } parent.structuralChildren.set(child, relationship); if (!child.structuralParents) { child.structuralParents = new Map(); } child.structuralParents.set(parent, relationship); } addDependency(symbol: Ref): void { if (this.symbol !== fromRef(symbol)) { this.scope.symbols.push(symbol); } } analyze(input: Input): void { const value = isRef(input) ? input : ref(input); if (isSymbolRef(value)) { const symbol = fromRef(value); // avoid adding self as child if (symbol.node && this.currentParent !== symbol.node) { this.addChild(symbol.node, 'reference'); } this.addDependency(value); } else if (isNodeRef(value)) { const node = fromRef(value); this.addChild(node, 'container'); this.pushParent(node); node.analyze(this); this.popParent(); } } localNames(scope: Scope): NameScopes { const names: NameScopes = new Map(); for (const [name, kinds] of scope.localNames) { names.set(name, new Set(kinds)); } if (scope.parent) { const parentNames = this.localNames(scope.parent); for (const [name, kinds] of parentNames) { if (!names.has(name)) { names.set(name, kinds); } else { const existingKinds = names.get(name)!; for (const kind of kinds) { existingKinds.add(kind); } } } } return names; } /** * Pop the current semantic parent. * Call this when exiting a container node. */ popParent(): void { this._parentStack.pop(); } popScope(): void { this.scope = this.scope.parent ?? this.scope; } /** * Push a node as the current semantic parent. */ pushParent(node: INode): void { this._parentStack.push(node); } pushScope(): void { const scope = createScope({ parent: this.scope }); this.scope.children.push(scope); this.scope = scope; } walkScopes( callback: (symbol: Ref, scope: Scope) => void, scope: Scope = this.scopes, ): void { this.scope = scope; for (const symbol of scope.symbols) { callback(symbol, scope); } for (const child of scope.children) { scope = child; this.walkScopes(callback, scope); } this.scope = this.scopes; } } export class Analyzer { private nodeCache = new WeakMap(); analyzeNode(node: INode): AnalysisContext { const cached = this.nodeCache.get(node); if (cached) return cached; node.root = true; const ctx = new AnalysisContext(node); node.analyze(ctx); this.nodeCache.set(node, ctx); return ctx; } analyze(nodes: Iterable, callback?: (ctx: AnalysisContext, node: INode) => void): void { for (const node of nodes) { const ctx = this.analyzeNode(node); callback?.(ctx, node); } } } ================================================ FILE: packages/codegen-core/src/planner/planner.ts ================================================ import path from 'node:path'; import type { ExportModule, ImportModule } from '../bindings'; import type { IProjectRenderMeta } from '../extensions'; import type { File } from '../files/file'; import type { INode } from '../nodes/node'; import { canDeclarationsShareIdentifier } from '../project/namespace'; import type { IProject } from '../project/types'; import { fromRef } from '../refs/refs'; import type { RenderContext } from '../renderer'; import type { Symbol } from '../symbols/symbol'; import type { SymbolKind } from '../symbols/types'; import type { AnalysisContext } from './analyzer'; import { Analyzer } from './analyzer'; import type { AssignOptions, Scope } from './scope'; import { createScope } from './scope'; const isTypeOnlyKind = (kind: SymbolKind) => kind === 'type' || kind === 'interface'; export class Planner { private readonly analyzer = new Analyzer(); private readonly cacheResolvedNames = new Set(); private readonly project: IProject; constructor(project: IProject) { this.project = project; } /** * Executes the planning phase for the project. */ plan(meta?: IProjectRenderMeta) { this.cacheResolvedNames.clear(); this.allocateFiles(); this.assignLocalNames(); this.resolveFilePaths(meta); this.planExports(); this.planImports(); } /** * Creates and assigns a file to every node, re-export, * and external dependency. */ private allocateFiles(): void { this.analyzer.analyze(this.project.nodes.all(), (ctx, node) => { const symbol = node.symbol; if (!symbol) return; const file = this.project.files.register({ external: false, language: node.language, logicalFilePath: symbol.getFilePath?.(symbol) || this.project.defaultFileName, }); file.addNode(node); symbol.setFile(file); for (const logicalFilePath of symbol.getExportFromFilePath?.(symbol) ?? []) { this.project.files.register({ external: false, language: file.language, logicalFilePath, }); } ctx.walkScopes((dependency) => { const dep = fromRef(dependency); if (dep.external && dep.isCanonical && !dep.file) { const file = this.project.files.register({ external: true, language: dep.node?.language, logicalFilePath: dep.external, }); dep.setFile(file); } }); }); } /** * Assigns final names to all symbols. * * First assigns top-level (file-scoped) symbol names, then local symbols. */ private assignLocalNames(): void { this.analyzer.analyze(this.project.nodes.all(), (ctx, node) => { const symbol = node.symbol; if (!symbol) return; this.assignTopLevelName({ ctx, node, symbol }); }); this.analyzer.analyze(this.project.nodes.all(), (ctx, node) => { const file = node.file; if (!file) return; ctx.walkScopes((dependency) => { const dep = fromRef(dependency); // top-level or external symbol if (dep.file) return; // TODO: pass node this.assignLocalName({ ctx, file, scopesToUpdate: [createScope({ localNames: file.allNames })], symbol: dep, }); }); }); } /** * Resolves and sets final file paths for all non-external files. Attaches renderers. * * Uses the project's fileName function if provided, otherwise uses the file's current name. * * Resolves final paths relative to the project's root directory. */ private resolveFilePaths(meta?: IProjectRenderMeta): void { for (const file of this.project.files.registered()) { if (file.external) { file.setFinalPath(file.logicalFilePath); continue; } const finalName = this.project.fileName?.(file.name) || file.name; file.setName(finalName); const finalPath = file.finalPath; if (finalPath) { file.setFinalPath(path.resolve(this.project.root, finalPath)); } const ctx: RenderContext = { file, meta, project: this.project }; const renderer = this.project.renderers.find((r) => r.supports(ctx)); if (renderer) file.setRenderer(renderer); } } /** * Plans exports by analyzing all exported symbols. * * Registers re-export targets as files and creates new exported symbols for them. * * Assigns names to re-exported symbols and collects re-export metadata, * distinguishing type-only exports based on symbol kinds. */ private planExports(): void { const seenByFile = new Map; symbol: Symbol }>>(); const sourceFile = new Map(); this.analyzer.analyze(this.project.nodes.all(), (ctx, node) => { if (!node.exported) return; const symbol = node.symbol; if (!symbol) return; const file = node.file; if (!file) return; for (const logicalFilePath of symbol.getExportFromFilePath?.(symbol) ?? []) { const target = this.project.files.register({ external: false, language: node.language, logicalFilePath, }); if (target.id === file.id) continue; let fileMap = seenByFile.get(target); if (!fileMap) { fileMap = new Map(); seenByFile.set(target, fileMap); } const exp = this.project.symbols.register({ exported: true, external: symbol.external, importKind: symbol.importKind, kind: symbol.kind, name: symbol.finalName, }); exp.setFile(target); sourceFile.set(exp.id, file); // TODO: pass node this.assignTopLevelName({ ctx, symbol: exp }); let entry = fileMap.get(exp.finalName); if (!entry) { entry = { kinds: new Set(), symbol: exp }; fileMap.set(exp.finalName, entry); } entry.kinds.add(exp.kind); } }); for (const [file, fileMap] of seenByFile) { const exports = new Map(); for (const [, entry] of fileMap) { const source = sourceFile.get(entry.symbol.id)!; let exp = exports.get(source); if (!exp) { exp = { canExportAll: true, exports: [], from: source, isTypeOnly: true, }; } const isTypeOnly = [...entry.kinds].every((kind) => isTypeOnlyKind(kind)); const exportedName = entry.symbol.finalName; exp.exports.push({ exportedName, isTypeOnly, kind: entry.symbol.importKind, sourceName: entry.symbol.name, }); if (entry.symbol.name !== entry.symbol.finalName) { exp.canExportAll = false; } if (!isTypeOnly) { exp.isTypeOnly = false; } exports.set(source, exp); } for (const [, exp] of exports) { file.addExport(exp); } } } /** * Plans imports by analyzing symbol dependencies across files. * * For external dependencies, assigns top-level names. * * Creates or reuses import symbols for dependencies from other files, * assigning names and updating import metadata including type-only flags. */ private planImports(): void { const seenByFile = new Map< File, Map< string, { dep: Symbol; kinds: Set; symbol: Symbol; } > >(); this.analyzer.analyze(this.project.nodes.all(), (ctx) => { const symbol = ctx.symbol; if (!symbol) return; const file = symbol.file; if (!file) return; let fileMap = seenByFile.get(file); if (!fileMap) { fileMap = new Map(); seenByFile.set(file, fileMap); } ctx.walkScopes((dependency) => { const dep = fromRef(dependency); if (!dep.file || dep.file.id === file.id) return; if (dep.external) { // TODO: pass node this.assignTopLevelName({ ctx, symbol: dep }); } const fromFileId = dep.file.id; const importedName = dep.finalName; const kind = dep.importKind; const key = `${fromFileId}|${importedName}|${kind}`; let entry = fileMap.get(key); if (!entry) { const imp = this.project.symbols.register({ exported: dep.exported, external: dep.external, importKind: dep.importKind, kind: dep.kind, name: dep.finalName, }); imp.setFile(file); // TODO: pass node this.assignTopLevelName({ ctx, scope: createScope({ localNames: imp.file!.allNames }), symbol: imp, }); entry = { dep, kinds: new Set(), symbol: imp, }; fileMap.set(key, entry); } entry.kinds.add(dep.kind); dependency['~ref'] = entry.symbol; }); }); for (const [file, fileMap] of seenByFile) { const imports = new Map(); for (const [, entry] of fileMap) { const source = entry.dep.file!; let imp = imports.get(source); if (!imp) { imp = { from: source, imports: [], isTypeOnly: true, kind: 'named', }; } const isTypeOnly = [...entry.kinds].every((kind) => isTypeOnlyKind(kind)); if (entry.symbol.importKind === 'namespace') { imp.imports = []; imp.kind = 'namespace'; imp.localName = entry.symbol.finalName; } else if (entry.symbol.importKind === 'default') { imp.kind = 'default'; imp.localName = entry.symbol.finalName; } else { imp.imports.push({ isTypeOnly, localName: entry.symbol.finalName, sourceName: entry.dep.finalName, }); } if (!isTypeOnly) { imp.isTypeOnly = false; } imports.set(source, imp); } for (const [, imp] of imports) { file.addImport(imp); } } } /** * Assigns the final name to a top-level (file-scoped) symbol. * * Uses the symbol's file top-level names as the default scope, * and updates all relevant name scopes including the file's allNames and local scopes. * * Supports optional overrides for the naming scope and scopes to update. */ private assignTopLevelName( args: Partial & { ctx: AnalysisContext; debug?: boolean; node?: INode; symbol: Symbol; }, ): void { if (!args.symbol.file) return; this.assignSymbolName({ ...args, file: args.symbol.file, scope: args?.scope ?? createScope({ localNames: args.symbol.file.topLevelNames }), scopesToUpdate: [ createScope({ localNames: args.symbol.file.allNames }), args.ctx.scopes, ...(args?.scopesToUpdate ?? []), ], }); } /** * Assigns the final name to a non-top-level (local) symbol. * * Uses the provided scope or derives it from the current analysis context's local names. * * Updates all provided name scopes accordingly. */ private assignLocalName( args: Pick, 'scope'> & Pick & { ctx: AnalysisContext; debug?: boolean; /** The file the symbol belongs to. */ file: File; node?: INode; symbol: Symbol; }, ): void { this.assignSymbolName({ ...args, scope: args.scope ?? args.ctx.scope, }); } /** * Assigns the final name to a symbol within the provided name scope. * * Resolves name conflicts until a unique name is found. * * Updates all specified name scopes with the assigned final name. */ private assignSymbolName( args: AssignOptions & { ctx: AnalysisContext; debug?: boolean; /** The file the symbol belongs to. */ file: File; node?: INode; symbol: Symbol; }, ): void { const { ctx, file, node, scope, scopesToUpdate, symbol } = args; if (this.cacheResolvedNames.has(symbol.id)) return; const baseName = symbol.name; let finalName = node?.nameSanitizer?.(baseName) ?? symbol.node?.nameSanitizer?.(baseName) ?? baseName; let attempt = 1; const localNames = ctx.localNames(scope); while (true) { const language = node?.language || symbol.node?.language || file.language; const kinds = [...(localNames.get(finalName) ?? [])]; const ok = kinds.every((kind) => canDeclarationsShareIdentifier(language, symbol.kind, kind)); if (ok) break; const resolver = (language ? this.project.nameConflictResolvers[language] : undefined) ?? this.project.defaultNameConflictResolver; const resolvedName = resolver({ attempt, baseName }); if (!resolvedName) { throw new Error(`Unresolvable name conflict: ${symbol.toString()}`); } finalName = node?.nameSanitizer?.(resolvedName) ?? symbol.node?.nameSanitizer?.(resolvedName) ?? resolvedName; attempt = attempt + 1; } symbol.setFinalName(finalName); this.cacheResolvedNames.add(symbol.id); const updateScopes = [scope, ...scopesToUpdate]; for (const scope of updateScopes) { this.updateScope(symbol, scope); } } /** * Updates the provided name scope with the symbol's final name and kind. * * Ensures the name scope tracks all kinds associated with a given name. */ private updateScope(symbol: Symbol, scope: Scope): void { const name = symbol.finalName; const cache = scope.localNames.get(name) ?? new Set(); cache.add(symbol.kind); scope.localNames.set(name, cache); } } ================================================ FILE: packages/codegen-core/src/planner/resolvers.ts ================================================ import type { NameConflictResolver } from './types'; export const simpleNameConflictResolver: NameConflictResolver = ({ attempt, baseName }) => attempt === 0 ? baseName : `${baseName}${attempt + 1}`; export const underscoreNameConflictResolver: NameConflictResolver = ({ attempt, baseName }) => attempt === 0 ? baseName : `${baseName}_${attempt + 1}`; ================================================ FILE: packages/codegen-core/src/planner/scope.ts ================================================ import type { Ref } from '../refs/types'; import type { Symbol } from '../symbols/symbol'; import type { SymbolKind } from '../symbols/types'; export type NameScopes = Map>; export type Scope = { /** Child scopes. */ children: Array; /** Resolved names in this scope. */ localNames: NameScopes; /** Parent scope, if any. */ parent?: Scope; /** Symbols registered in this scope. */ symbols: Array>; }; export type AssignOptions = { /** The primary scope in which to assign a symbol's final name. */ scope: Scope; /** Additional scopes to update as side effects when assigning a symbol's final name. */ scopesToUpdate: ReadonlyArray; }; export const createScope = ( args: { localNames?: NameScopes; parent?: Scope; } = {}, ): Scope => ({ children: [], localNames: args.localNames || new Map(), parent: args.parent, symbols: [], }); ================================================ FILE: packages/codegen-core/src/planner/types.ts ================================================ import type { Ref } from '../refs/types'; import type { Symbol } from '../symbols/symbol'; import type { NameScopes, Scope } from './scope'; export type Input = Ref | object | string | number | undefined; export type NameConflictResolver = (args: { attempt: number; baseName: string }) => string | null; export interface IAnalysisContext { /** Register a dependency on another symbol. */ addDependency(symbol: Ref): void; /** Register a dependency on another symbol or analyze further. */ analyze(input: Input): void; /** Get local names in the current scope. */ localNames(scope: Scope): NameScopes; /** Pop the current local scope. */ popScope(): void; /** Push a new local scope. */ pushScope(): void; /** Current local scope. */ scope: Scope; /** Stack of local name scopes. */ scopes: Scope; /** Top-level symbol for the current analysis pass. */ symbol?: Symbol; /** Walks all symbols in the scope tree in depth-first order. */ walkScopes(callback: (symbol: Ref, scope: Scope) => void, scope?: Scope): void; } ================================================ FILE: packages/codegen-core/src/project/namespace.ts ================================================ import type { Language } from '../languages/types'; import type { SymbolKind } from '../symbols/types'; const typescriptMergeKindRank: Record = { class: 3, enum: 4, function: 5, interface: 1, namespace: 0, type: 2, var: 6, }; /** * Returns true if two declarations of given kinds * are allowed to share the same identifier in TypeScript. */ function canTypeScriptDeclarationsShareIdentifier(a: SymbolKind, b: SymbolKind): boolean { // sort based on TypeScript merge precedence so `a` is always the weaker merge candidate // ensures that asymmetric merges like `type + var` are correctly handled if (typescriptMergeKindRank[a] > typescriptMergeKindRank[b]) { [a, b] = [b, a]; } switch (a) { case 'interface': return b === 'class' || b === 'interface'; case 'namespace': return b === 'class' || b === 'enum' || b === 'function' || b === 'namespace'; case 'type': // type can only merge with value-only declarations return b === 'function' || b === 'var'; default: return false; } } export function canDeclarationsShareIdentifier( language: Language | undefined, a: SymbolKind, b: SymbolKind, ): boolean { if (language === 'typescript') { return canTypeScriptDeclarationsShareIdentifier(a, b); } return false; } ================================================ FILE: packages/codegen-core/src/project/project.ts ================================================ import path from 'node:path'; import type { IProjectRenderMeta } from '../extensions'; import { FileRegistry } from '../files/registry'; import { defaultExtensions } from '../languages/extensions'; import { defaultModuleEntryNames } from '../languages/modules'; import { defaultNameConflictResolvers } from '../languages/resolvers'; import type { Extensions, ModuleEntryNames, NameConflictResolvers } from '../languages/types'; import { NodeRegistry } from '../nodes/registry'; import type { IOutput } from '../output'; import { Planner } from '../planner/planner'; import { simpleNameConflictResolver } from '../planner/resolvers'; import type { NameConflictResolver } from '../planner/types'; import type { Renderer } from '../renderer'; import { SymbolRegistry } from '../symbols/registry'; import type { IProject } from './types'; export class Project implements IProject { private _isPlanned = false; readonly files: FileRegistry; readonly nodes = new NodeRegistry(); readonly symbols = new SymbolRegistry(); readonly defaultFileName: string; readonly defaultNameConflictResolver: NameConflictResolver; readonly extensions: Extensions; readonly fileName?: (name: string) => string; readonly moduleEntryNames: ModuleEntryNames; readonly nameConflictResolvers: NameConflictResolvers; readonly renderers: ReadonlyArray; readonly root: string; constructor( args: Pick< Partial, | 'defaultFileName' | 'defaultNameConflictResolver' | 'extensions' | 'fileName' | 'moduleEntryNames' | 'nameConflictResolvers' | 'renderers' > & Pick, ) { const fileName = args.fileName; this.defaultFileName = args.defaultFileName ?? 'main'; this.defaultNameConflictResolver = args.defaultNameConflictResolver ?? simpleNameConflictResolver; this.extensions = { ...defaultExtensions, ...args.extensions, }; this.fileName = typeof fileName === 'string' ? () => fileName : fileName; this.files = new FileRegistry(this); this.moduleEntryNames = { ...defaultModuleEntryNames, ...args.moduleEntryNames, }; this.nameConflictResolvers = { ...defaultNameConflictResolvers, ...args.nameConflictResolvers, }; this.renderers = args.renderers ?? []; this.root = path.resolve(args.root).replace(/[/\\]+$/, ''); } plan(meta?: IProjectRenderMeta): void { if (this._isPlanned) return; new Planner(this).plan(meta); this._isPlanned = true; } render(meta?: IProjectRenderMeta): ReadonlyArray { if (!this._isPlanned) this.plan(meta); const files: Array = []; for (const file of this.files.registered()) { if (!file.external && file.finalPath && file.renderer) { const content = file.renderer.render({ file, meta, project: this }); files.push({ content, path: file.finalPath }); } } return files; } } ================================================ FILE: packages/codegen-core/src/project/types.ts ================================================ import type { IProjectRenderMeta } from '../extensions'; import type { IFileRegistry } from '../files/types'; import type { Extensions, ModuleEntryNames, NameConflictResolvers } from '../languages/types'; import type { INodeRegistry } from '../nodes/types'; import type { IOutput } from '../output'; import type { NameConflictResolver } from '../planner/types'; import type { Renderer } from '../renderer'; import type { ISymbolRegistry } from '../symbols/types'; /** * Represents a code generation project consisting of codegen files. * * Manages imports, symbols, and output generation across the project. */ export interface IProject { /** * The default file to assign symbols without a specific file selector. * * @default 'main' */ readonly defaultFileName: string; /** Default name conflict resolver used when a file has no specific resolver. */ readonly defaultNameConflictResolver: NameConflictResolver; /** * Maps language to array of extensions. First element is used by default. * * @example * ```ts * const exts: Extensions = { * typescript: ['.ts', '.tsx'], * python: ['.py'], * }; * ``` */ readonly extensions: Extensions; /** * Function to transform file names before they are used. * * @param name The original file name. * @returns The transformed file name. */ readonly fileName?: (name: string) => string; /** Centralized file registry for the project. */ readonly files: IFileRegistry; /** * Map of module entry names for each language. * * @example * ```ts * const entries: ModuleEntryNames = { * typescript: 'index', * python: '__init__', * }; * ``` */ readonly moduleEntryNames: ModuleEntryNames; /** * Map of language-specific name conflict resolvers for files in the project. * * @example * ```ts * const resolvers: NameConflictResolvers = { * typescript: myTypeScriptResolver, * python: myPythonResolver, * }; * ``` */ readonly nameConflictResolvers: NameConflictResolvers; /** Centralized node registry for the project. */ readonly nodes: INodeRegistry; /** * Finalizes the project structure, resolving nodes, symbols, and dependencies. * * @param meta Arbitrary metadata. * @returns void */ plan(meta?: IProjectRenderMeta): void; /** * Produces output representations for all files in the project. * * @param meta Arbitrary metadata. * @returns Array of outputs ready for writing or further processing. * @example * project.render().forEach(output => writeFile(output)); */ render(meta?: IProjectRenderMeta): ReadonlyArray; /** * List of available renderers. * * @example * [new TypeScriptRenderer()] */ readonly renderers: ReadonlyArray; /** The absolute path to the root folder of the project. */ readonly root: string; /** Centralized symbol registry for the project. */ readonly symbols: ISymbolRegistry; } ================================================ FILE: packages/codegen-core/src/refs/refs.ts ================================================ import type { FromRef, FromRefs, Ref, Refs } from './types'; /** * Wraps a single value in a Ref object. * * If the value is already a Ref, returns it as-is (idempotent). * * @example * ```ts * const r = ref(123); // { '~ref': 123 } * console.log(r['~ref']); // 123 * * const r2 = ref(r); // { '~ref': 123 } (not double-wrapped) * ``` */ export const ref = (value: T): Ref => { if (isRef(value)) { return value as Ref; } return { '~ref': value } as Ref; }; /** * Converts a plain object to an object of Refs (deep, per property). * * @example * ```ts * const obj = { a: 1, b: "x" }; * const refs = refs(obj); // { a: { '~ref': 1 }, b: { '~ref': "x" } } * ``` */ export const refs = >(obj: T): Refs => { const result = {} as Refs; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { result[key] = ref(obj[key]); } } return result; }; /** * Unwraps a single Ref object to its value. * * @example * ```ts * const r = { '~ref': 42 }; * const n = fromRef(r); // 42 * console.log(n); // 42 * ``` */ export const fromRef = | undefined>(ref: T): FromRef => ref?.['~ref'] as FromRef; /** * Converts an object of Refs back to a plain object (unwraps all refs). * * @example * ```ts * const refs = { a: { '~ref': 1 }, b: { '~ref': "x" } }; * const plain = fromRefs(refs); // { a: 1, b: "x" } * ``` */ export const fromRefs = >>(obj: T): FromRefs => { const result = {} as FromRefs; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { result[key] = fromRef(obj[key]!) as (typeof result)[typeof key]; } } return result; }; /** * Checks whether a value is a Ref object. * * @param value Value to check * @returns True if the value is a Ref object. */ export const isRef = (value: unknown): value is Ref => typeof value === 'object' && value !== null && '~ref' in value; ================================================ FILE: packages/codegen-core/src/refs/types.ts ================================================ /** * Ref wrapper which ensures a stable reference for a value. * * @example * ```ts * type NumRef = Ref; // { '~ref': number } * const num: NumRef = { '~ref': 42 }; * console.log(num['~ref']); // 42 * ``` */ export type Ref = T extends { ['~ref']: unknown } ? T : { '~ref': T }; /** * Maps every property of `T` to a `Ref` of that property. * * @example * ```ts * type Foo = { a: number; b: string }; * type Refs = Refs; // { a: Ref; b: Ref } * const refs: Refs = { a: { '~ref': 1 }, b: { '~ref': 'x' } }; * console.log(refs.a['~ref'], refs.b['~ref']); // 1 'x' * ``` */ export type Refs = { [K in keyof T]: Ref; }; /** * Unwraps a Ref to its value type. * * @example * ```ts * type N = FromRef<{ '~ref': number }>; // number * ``` */ export type FromRef = T extends { '~ref': infer U } ? U : T; /** * Maps every property of a Ref-wrapped object back to its plain value. * * @example * ```ts * type Foo = { a: number; b: string }; * type Refs = Refs; // { a: Ref; b: Ref } * type Foo2 = FromRefs; // { a: number; b: string } * ``` */ export type FromRefs = { [K in keyof T]: T[K] extends Ref ? U : T[K]; }; ================================================ FILE: packages/codegen-core/src/renderer.ts ================================================ import type { IProjectRenderMeta } from './extensions'; import type { File } from './files/file'; import type { INode } from './nodes/node'; import type { IProject } from './project/types'; export interface RenderContext { /** * The current file. */ file: File; /** * Arbitrary metadata. */ meta?: IProjectRenderMeta; /** * The project the file belongs to. */ project: IProject; } export interface Renderer { /** Renders the given file. */ render(ctx: RenderContext): string; /** Returns whether this renderer can render the given file. */ supports(ctx: RenderContext): boolean; } ================================================ FILE: packages/codegen-core/src/structure/model.ts ================================================ import { StructureNode } from './node'; import type { StructureInsert } from './types'; export class StructureModel { /** Root nodes mapped by their names. */ private _roots: Map = new Map(); /** Node for data without a specific root. */ private _virtualRoot?: StructureNode; /** * Get all root nodes. */ get roots(): ReadonlyArray { const roots = Array.from(this._roots.values()); if (this._virtualRoot) roots.unshift(this._virtualRoot); return roots; } /** * Insert data into the structure. */ insert(args: StructureInsert): void { const { data, locations, source } = args; for (const location of locations) { const { path, shell } = location; const fullPath = path.filter((s): s is string => Boolean(s)); const segments = fullPath.slice(0, -1); const name = fullPath[fullPath.length - 1]; if (!name) { throw new Error('Cannot insert data without path.'); } let cursor: StructureNode | null = null; for (const segment of segments) { if (!cursor) { cursor = this.root(segment); } else { cursor = cursor.child(segment); } if (shell && !cursor.shell) { cursor.shell = shell; cursor.shellSource = source; } } if (!cursor) { cursor = this.root(null); } cursor.items.push({ data, location: fullPath, source }); } } /** * Gets or creates a root by name. * * If the root doesn't exist, it's created automatically. * * @param name - The name of the root * @returns The root instance */ root(name: string | null): StructureNode { if (!name) { return (this._virtualRoot ??= new StructureNode('', undefined, { virtual: true, })); } if (!this._roots.has(name)) { this._roots.set(name, new StructureNode(name)); } return this._roots.get(name)!; } /** * Walk all nodes in the structure (depth-first, post-order). * * @returns Generator of all structure nodes */ *walk(): Generator { if (this._virtualRoot) { yield* this._virtualRoot.walk(); } for (const root of this._roots.values()) { yield* root.walk(); } } } ================================================ FILE: packages/codegen-core/src/structure/node.ts ================================================ import type { StructureItem, StructureShell } from './types'; export class StructureNode { /** Nested nodes within this node. */ children: Map = new Map(); /** Items contained in this node. */ items: Array = []; /** The name of this node (e.g., "Users", "Accounts"). */ name: string; /** Parent node in the hierarchy. Undefined if this is the root node. */ parent?: StructureNode; /** Shell claimed for this node. */ shell?: StructureShell; /** Source of the claimed shell. */ shellSource?: symbol; /** True if this is a virtual root. */ virtual: boolean; constructor( name: string, parent?: StructureNode, options?: { virtual?: boolean; }, ) { this.name = name; this.parent = parent; this.virtual = options?.virtual ?? false; } get isRoot(): boolean { return !this.parent; } /** * Gets or creates a child node. * * If the child doesn't exist, it's created automatically. * * @param name - The name of the child node * @returns The child node instance */ child(name: string): StructureNode { if (!this.children.has(name)) { this.children.set(name, new StructureNode(name, this)); } return this.children.get(name)!; } /** * Gets the full path of this node in the hierarchy. * * @returns An array of node names from the root to this node */ getPath(): ReadonlyArray { const path: Array = []; // eslint-disable-next-line @typescript-eslint/no-this-alias let cursor: StructureNode | undefined = this; while (cursor) { path.unshift(cursor.name); cursor = cursor.parent; } return path; } /** * Yields items from a specific source with typed data. * * @param source - The source symbol to filter by * @returns Generator of items from that source */ *itemsFrom(source: symbol): Generator { for (const item of this.items) { if (item.source === source) { yield item as StructureItem & { data: T }; } } } /** * Walk all nodes in the structure (depth-first, post-order). * * @returns Generator of all structure nodes */ *walk(): Generator { for (const node of this.children.values()) { yield* node.walk(); } yield this; } } ================================================ FILE: packages/codegen-core/src/structure/types.ts ================================================ import type { INode } from '../nodes/node'; import type { StructureNode } from './node'; export interface StructureInsert { /** Inserted data. */ data: unknown; /** Locations where the data should be inserted. */ locations: ReadonlyArray; /** Source of the inserted data. */ source: symbol; } export interface StructureItem extends Pick { /** Location of this item within the structure. */ location: ReadonlyArray; } export interface StructureLocation { /** Path within the structure where the data should be inserted. */ path: ReadonlyArray; /** Shell to apply at this location. */ shell?: StructureShell; } export interface StructureShell { define: (node: StructureNode) => StructureShellResult; } export interface StructureShellResult { dependencies?: Array; node: INode; } ================================================ FILE: packages/codegen-core/src/symbols/registry.ts ================================================ import type { ISymbolMeta } from '../extensions'; import { Symbol } from './symbol'; import type { ISymbolIdentifier, ISymbolIn, ISymbolRegistry } from './types'; type IndexEntry = [string, unknown]; type IndexKeySpace = ReadonlyArray; type QueryCacheKey = string; type SymbolId = number; export class SymbolRegistry implements ISymbolRegistry { private _id: SymbolId = 0; private _indices: Map>> = new Map(); private _queryCache: Map> = new Map(); private _queryCacheDependencies: Map> = new Map(); private _registered: Set = new Set(); private _stubs: Set = new Set(); private _stubCache: Map = new Map(); private _values: Map = new Map(); get(identifier: ISymbolIdentifier): Symbol | undefined { return typeof identifier === 'number' ? this._values.get(identifier) : this.query(identifier)[0]; } isRegistered(identifier: ISymbolIdentifier): boolean { const symbol = this.get(identifier); return symbol ? this._registered.has(symbol.id) : false; } get nextId(): SymbolId { return this._id++; } query(filter: ISymbolMeta): ReadonlyArray { const cacheKey = this.buildCacheKey(filter); const cachedIds = this._queryCache.get(cacheKey); if (cachedIds) { return cachedIds.map((symbolId) => this._values.get(symbolId)!); } const sets: Array> = []; const indexKeySpace = this.buildIndexKeySpace(filter); const cacheDependencies = new Set(); let missed = false; for (const indexEntry of indexKeySpace) { cacheDependencies.add(this.serializeIndexEntry(indexEntry)); const values = this._indices.get(indexEntry[0]); if (!values) { missed = true; break; } const set = values.get(indexEntry[1]); if (!set) { missed = true; break; } sets.push(set); } if (missed || !sets.length) { this._queryCacheDependencies.set(cacheKey, cacheDependencies); this._queryCache.set(cacheKey, []); return []; } let result = new Set(sets[0]); for (const set of sets.slice(1)) { result = new Set([...result].filter((symbolId) => set.has(symbolId))); } const resultIds = [...result]; this._queryCacheDependencies.set(cacheKey, cacheDependencies); this._queryCache.set(cacheKey, resultIds); return resultIds.map((symbolId) => this._values.get(symbolId)!); } reference(meta: ISymbolMeta): Symbol { const [registered] = this.query(meta); if (registered) return registered; const cacheKey = this.buildCacheKey(meta); const cachedId = this._stubCache.get(cacheKey); if (cachedId !== undefined) return this._values.get(cachedId)!; const stub = new Symbol({ meta, name: '' }, this.nextId); this._values.set(stub.id, stub); this._stubs.add(stub.id); this._stubCache.set(cacheKey, stub.id); return stub; } register(symbol: ISymbolIn): Symbol { const result = new Symbol(symbol, this.nextId); this._values.set(result.id, result); this._registered.add(result.id); if (result.meta) { const indexKeySpace = this.buildIndexKeySpace(result.meta); this.indexSymbol(result.id, indexKeySpace); this.invalidateCache(indexKeySpace); this.replaceStubs(result, indexKeySpace); } return result; } *registered(): IterableIterator { for (const id of this._registered.values()) { yield this._values.get(id)!; } } private buildCacheKey(filter: ISymbolMeta): QueryCacheKey { const indexKeySpace = this.buildIndexKeySpace(filter); return indexKeySpace .map((indexEntry) => this.serializeIndexEntry(indexEntry)) .sort() // ensure order-insensitivity .join('|'); } private buildIndexKeySpace(meta: ISymbolMeta, prefix = ''): IndexKeySpace { const entries: Array = []; for (const [key, value] of Object.entries(meta)) { const path = prefix ? `${prefix}.${key}` : key; if (value && typeof value === 'object' && !Array.isArray(value)) { entries.push(...this.buildIndexKeySpace(value as ISymbolMeta, path)); } else { entries.push([path, value]); } } return entries; } private indexSymbol(symbolId: SymbolId, indexKeySpace: IndexKeySpace): void { for (const [key, value] of indexKeySpace) { if (!this._indices.has(key)) this._indices.set(key, new Map()); const values = this._indices.get(key)!; const set = values.get(value) ?? new Set(); set.add(symbolId); values.set(value, set); } } private invalidateCache(indexKeySpace: IndexKeySpace): void { const changed = indexKeySpace.map((indexEntry) => this.serializeIndexEntry(indexEntry)); for (const [cacheKey, cacheDependencies] of this._queryCacheDependencies.entries()) { for (const key of changed) { if (cacheDependencies.has(key)) { this._queryCacheDependencies.delete(cacheKey); this._queryCache.delete(cacheKey); break; } } } } private isSubset(sub: IndexKeySpace, sup: IndexKeySpace): boolean { const supMap = new Map(sup); for (const [key, value] of sub) { if (!supMap.has(key) || supMap.get(key) !== value) { return false; } } return true; } private replaceStubs(symbol: Symbol, indexKeySpace: IndexKeySpace): void { for (const stubId of this._stubs.values()) { const stub = this._values.get(stubId); if (stub?.meta && this.isSubset(this.buildIndexKeySpace(stub.meta), indexKeySpace)) { const cacheKey = this.buildCacheKey(stub.meta); this._stubCache.delete(cacheKey); this._stubs.delete(stubId); stub.setCanonical(symbol); } } } private serializeIndexEntry(indexEntry: IndexEntry): string { return `${indexEntry[0]}:${JSON.stringify(indexEntry[1])}`; } } ================================================ FILE: packages/codegen-core/src/symbols/symbol.ts ================================================ import { symbolBrand } from '../brands'; import type { ISymbolMeta } from '../extensions'; import type { File } from '../files/file'; import { log } from '../log'; import type { INode } from '../nodes/node'; import type { BindingKind, ISymbolIn, SymbolKind } from './types'; export class Symbol { /** * Canonical symbol this stub resolves to, if any. * * Stubs created during DSL construction may later be associated * with a fully registered symbol. Once set, all property lookups * should defer to the canonical symbol. */ private _canonical?: Symbol; /** * True if this symbol is exported from its defining file. * * @default false */ private _exported: boolean; /** * External module name if this symbol is imported from a module not managed * by the project (e.g. "zod", "lodash"). * * @default undefined */ private _external?: string; /** * The file this symbol is ultimately emitted into. * * Only top-level symbols have an assigned file. */ private _file?: File; /** * The alias-resolved, conflict-free emitted name. */ private _finalName?: string; /** * Custom strategy to determine from which file path(s) this symbol is re-exported. * * @returns The file path(s) that re-export this symbol, or undefined if none. */ private _getExportFromFilePath?: (symbol: Symbol) => ReadonlyArray | undefined; /** * Custom strategy to determine file output path. * * @returns The file path to output the symbol to, or undefined to fallback to default behavior. */ private _getFilePath?: (symbol: Symbol) => string | undefined; /** * How this symbol should be imported (namespace/default/named). * * @default 'named' */ private _importKind: BindingKind; /** * Kind of symbol (class, type, alias, etc.). * * @default 'var' */ private _kind: SymbolKind; /** * Arbitrary user metadata. * * @default undefined */ private _meta?: ISymbolMeta; /** * Intended user-facing name before conflict resolution. * * @example "UserModel" */ private _name: string; /** * Node that defines this symbol. */ private _node?: Node; /** Brand used for identifying symbols. */ readonly '~brand' = symbolBrand; /** Globally unique, stable symbol ID. */ readonly id: number; constructor(input: ISymbolIn, id: number) { this._exported = input.exported ?? false; this._external = input.external; this._getExportFromFilePath = input.getExportFromFilePath; this._getFilePath = input.getFilePath; this.id = id; this._importKind = input.importKind ?? 'named'; this._kind = input.kind ?? 'var'; this._meta = input.meta; this._name = input.name; } /** * Returns the canonical symbol for this instance. * * If this symbol was created as a stub, this getter returns * the fully registered canonical symbol. Otherwise, it returns * the symbol itself. */ get canonical(): Symbol { return this._canonical ?? this; } /** * Indicates whether this symbol is exported from its defining file. */ get exported(): boolean { return this.canonical._exported; } /** * External module from which this symbol originates, if any. */ get external(): string | undefined { return this.canonical._external; } /** * Read‑only accessor for the assigned output file. * * Only top-level symbols have an assigned file. */ get file(): File | undefined { return this.canonical._file; } /** * Read‑only accessor for the resolved final emitted name. */ get finalName(): string { if (!this.canonical._finalName) { const message = `Symbol finalName has not been resolved yet for ${this.canonical.toString()}`; log.debug(message, 'symbol'); throw new Error(message); } return this.canonical._finalName; } /** * Custom re-export file path resolver, if provided. */ get getExportFromFilePath(): ((symbol: Symbol) => ReadonlyArray | undefined) | undefined { return this.canonical._getExportFromFilePath; } /** * Custom file path resolver, if provided. */ get getFilePath(): ((symbol: Symbol) => string | undefined) | undefined { return this.canonical._getFilePath; } /** * How this symbol should be imported (named/default/namespace). */ get importKind(): BindingKind { return this.canonical._importKind; } /** * Indicates whether this is a canonical symbol (not a stub). */ get isCanonical(): boolean { return !this._canonical || this._canonical === this; } /** * The symbol's kind (class, type, alias, variable, etc.). */ get kind(): SymbolKind { return this.canonical._kind; } /** * Arbitrary user‑provided metadata associated with this symbol. */ get meta(): ISymbolMeta | undefined { return this.canonical._meta; } /** * User-intended name before aliasing or conflict resolution. */ get name(): string { return this.canonical._name; } /** * Read‑only accessor for the defining node. */ get node(): Node | undefined { return this.canonical._node as Node | undefined; } /** * Marks this symbol as a stub and assigns its canonical symbol. * * After calling this, all semantic queries (name, kind, file, * meta, etc.) should reflect the canonical symbol's values. * * @param symbol — The canonical symbol this stub should resolve to. */ setCanonical(symbol: Symbol): void { this._canonical = symbol; } /** * Marks the symbol as exported from its file. * * @param exported — Whether the symbol is exported. */ setExported(exported: boolean): void { this.assertCanonical(); this._exported = exported; } /** * Assigns the output file this symbol will be emitted into. * * This may only be set once. */ setFile(file: File): void { this.assertCanonical(); if (this._file && this._file !== file) { const message = `Symbol ${this.canonical.toString()} is already assigned to a different file.`; log.debug(message, 'symbol'); throw new Error(message); } this._file = file; } /** * Assigns the conflict‑resolved final local name for this symbol. * * This may only be set once. */ setFinalName(name: string): void { this.assertCanonical(); if (this._finalName && this._finalName !== name) { const message = `Symbol finalName has already been resolved for ${this.canonical.toString()}.`; log.debug(message, 'symbol'); throw new Error(message); } this._finalName = name; } /** * Sets how this symbol should be imported. * * @param kind — The import strategy (named/default/namespace). */ setImportKind(kind: BindingKind): void { this.assertCanonical(); this._importKind = kind; } /** * Sets the symbol's kind (class, type, alias, variable, etc.). * * @param kind — The new symbol kind. */ setKind(kind: SymbolKind): void { this.assertCanonical(); this._kind = kind; } /** * Updates the intended user‑facing name for this symbol. * * @param name — The new name. */ setName(name: string): void { this.assertCanonical(); this._name = name; } /** * Binds the node that defines this symbol. * * This may only be set once. */ setNode(node: Node): void { this.assertCanonical(); if (this._node && this._node !== node) { const message = `Symbol ${this.canonical.toString()} is already bound to a different node.`; log.debug(message, 'symbol'); // TODO: symbol <> node relationship needs to be refactor to 1:many // disabled in the meantime or it would throw // throw new Error(message); } this._node = node; node.symbol = this; } /** * Returns a debug‑friendly string representation identifying the symbol. */ toString(): string { const canonical = this.canonical; if (canonical._finalName && canonical._finalName !== canonical._name) { return `[Symbol ${canonical._name} → ${canonical._finalName}#${canonical.id}]`; } return `[Symbol ${canonical._name || canonical._meta !== undefined ? JSON.stringify(canonical._meta) : ''}#${canonical.id}]`; } /** * Ensures this symbol is canonical before allowing mutation. * * A symbol that has been marked as a stub (i.e., its `_canonical` points * to a different symbol) may not be mutated. This guard throws an error * if any setter attempts to modify a stub, preventing accidental writes * to non‑canonical instances. * * @throws {Error} If the symbol is a stub and is being mutated. */ private assertCanonical(): void { if (this._canonical && this._canonical !== this) { const message = `Illegal mutation of stub symbol ${this.toString()} → canonical: ${this._canonical.toString()}`; log.debug(message, 'symbol'); throw new Error(message); } } } ================================================ FILE: packages/codegen-core/src/symbols/types.ts ================================================ import type { ISymbolMeta } from '../extensions'; import type { Symbol } from './symbol'; export type BindingKind = 'default' | 'named' | 'namespace'; export type ISymbolIdentifier = number | ISymbolMeta; export type SymbolKind = 'class' | 'enum' | 'function' | 'interface' | 'namespace' | 'type' | 'var'; export type ISymbolIn = { /** * Whether this symbol is exported from its own file. * * @default false */ exported?: boolean; /** * External module name if this symbol is imported from a module not managed * by the project (e.g. "zod", "lodash"). * * @default undefined */ external?: string; /** * Optional output strategy to override default behavior. * * @returns The file path(s) that re-export this symbol, or undefined if none. */ getExportFromFilePath?: Symbol['getExportFromFilePath']; /** * Optional output strategy to override default behavior. * * @returns The file path to output the symbol to, or undefined to fallback to default behavior. */ getFilePath?: Symbol['getFilePath']; /** * Kind of import if this symbol represents an import. * * @default 'named' */ importKind?: BindingKind; /** * Kind of symbol. * * @default 'var' */ kind?: SymbolKind; /** * Arbitrary metadata about the symbol. * * @default undefined */ meta?: ISymbolMeta; /** * The intended, user-facing name of the symbol before any conflict resolution. * It is **not** guaranteed to be the final emitted name — aliasing may occur if the * file contains conflicting local identifiers or other symbols with the same intended name. * * @example "UserModel" */ name: string; }; export interface ISymbolRegistry { /** * Get a symbol. * * @param identifier Symbol identifier to reference. * @returns The symbol, or undefined if not found. */ get(identifier: ISymbolIdentifier): Symbol | undefined; /** * Returns whether a symbol is registered in the registry. * * @param identifier Symbol identifier to check. * @returns True if the symbol is registered, false otherwise. */ isRegistered(identifier: ISymbolIdentifier): boolean; /** * Returns the current symbol ID and increments it. * * @returns Symbol ID before being incremented. */ readonly nextId: number; /** * Queries symbols by metadata filter. * * @param filter Metadata filter to query symbols by. * @returns Array of symbols matching the filter. */ query(filter: ISymbolMeta): ReadonlyArray; /** * References a symbol. * * @param meta Metadata filter to reference symbol by. * @returns The referenced symbol. */ reference(meta: ISymbolMeta): Symbol; /** * Register a symbol globally. * * Deduplicates identical symbols by ID. * * @param symbol Symbol to register. * @returns The registered symbol. */ register(symbol: ISymbolIn): Symbol; /** * Get all symbols in the order they were registered. * * @returns Array of all registered symbols, in insert order. */ registered(): IterableIterator; } ================================================ FILE: packages/codegen-core/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "composite": true, "outDir": "dist", "rootDir": "src", "types": ["vitest/globals", "node"] }, "include": ["src"], "references": [{ "path": "../types" }] } ================================================ FILE: packages/codegen-core/tsdown.config.ts ================================================ import { defineConfig } from 'tsdown'; export default defineConfig({ clean: true, dts: true, entry: ['src/index.ts'], format: ['esm'], minify: false, sourcemap: true, treeshake: true, }); ================================================ FILE: packages/codegen-core/turbo.json ================================================ { "$schema": "../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/custom-client/CHANGELOG.md ================================================ # @hey-api/custom-client ## 0.1.1 ### Patch Changes - [#2165](https://github.com/hey-api/openapi-ts/pull/2165) [`f23f3ae`](https://github.com/hey-api/openapi-ts/commit/f23f3ae874385e758eb8d43bb4e274c9858a4e40) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): do not serialize path param name in url ## 0.1.0 ### Minor Changes - [#2148](https://github.com/hey-api/openapi-ts/pull/2148) [`10d2e03`](https://github.com/hey-api/openapi-ts/commit/10d2e03b8295e4e887fab8d023aa823699efbae8) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: export `buildClientParams` function ## 0.0.1 ### Patch Changes - [#2039](https://github.com/hey-api/openapi-ts/pull/2039) [`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e) Thanks [@Le0Developer](https://github.com/Le0Developer)! - fix(clients): fix query string encoding with empty lists/objects ================================================ FILE: packages/custom-client/LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/custom-client/package.json ================================================ { "name": "@hey-api/custom-client", "version": "0.1.1", "private": true, "description": "Custom client for `@hey-api/openapi-ts` codegen. Used for testing.", "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "files": [ "dist", "LICENSE.md", "src" ], "type": "module", "sideEffects": false, "main": "./dist/index.cjs", "module": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "import": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" }, "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } }, "./plugin": { "import": { "types": "./dist/plugin.d.mts", "default": "./dist/plugin.mjs" }, "require": { "types": "./dist/plugin.d.cts", "default": "./dist/plugin.cjs" } }, "./package.json": "./package.json" }, "scripts": { "build": "tsdown && rollup -c && pnpm check-exports", "check-exports": "attw --profile node16 --pack .", "dev": "tsdown --watch", "prepublishOnly": "pnpm build" }, "devDependencies": { "@hey-api/codegen-core": "workspace:*", "@hey-api/openapi-ts": "workspace:*", "rollup": "4.56.0", "rollup-plugin-dts": "6.1.1" }, "peerDependencies": { "@hey-api/codegen-core": "<2", "@hey-api/openapi-ts": "<2" } } ================================================ FILE: packages/custom-client/rollup.config.mjs ================================================ import path from 'node:path'; import { defineConfig } from 'rollup'; import dts from 'rollup-plugin-dts'; const files = ['index.d.mts', 'index.d.cts', 'plugin.d.mts', 'plugin.d.cts']; export default files.map((file) => defineConfig({ external: (id) => { const normalizedId = id.split(path.sep).join('/'); return !normalizedId.startsWith('/') && !/^[a-zA-Z]:\//.test(normalizedId); }, input: `./dist/${file}`, output: { file: `./dist/${file}`, format: 'es', }, plugins: [ dts({ respectExternal: true, }), ], }), ); ================================================ FILE: packages/custom-client/src/__tests__/client.test.ts ================================================ import { createClient } from '../client'; describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); }); describe('zero-length body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('returns empty object for zero-length JSON response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/json', }, status: 200, }); const mockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty object for empty JSON response without Content-Length header (status 200)', async () => { // Simulates a server returning an empty body with status 200 and no Content-Length header // This is the scenario described in the issue where response.json() throws const mockResponse = new Response('', { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty object for empty response without Content-Length header and no Content-Type (defaults to JSON)', async () => { // Tests the auto-detection behavior when no Content-Type is provided const mockResponse = new Response('', { status: 200, }); const mockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); // When parseAs is 'auto' and no Content-Type header exists, it should handle empty body gracefully expect(result.data).toBeDefined(); }); }); ================================================ FILE: packages/custom-client/src/__tests__/utils.test.ts ================================================ import type { Auth } from '../core/auth'; import { getParseAs, setAuthParams } from '../utils'; describe('getParseAs', () => { const scenarios: Array<{ content: Parameters[0]; parseAs: ReturnType; }> = [ { content: null, parseAs: 'stream', }, { content: 'application/json', parseAs: 'json', }, { content: 'application/ld+json', parseAs: 'json', }, { content: 'application/ld+json;charset=utf-8', parseAs: 'json', }, { content: 'application/ld+json; charset=utf-8', parseAs: 'json', }, { content: 'multipart/form-data', parseAs: 'formData', }, { content: 'application/*', parseAs: 'blob', }, { content: 'audio/*', parseAs: 'blob', }, { content: 'image/*', parseAs: 'blob', }, { content: 'video/*', parseAs: 'blob', }, { content: 'text/*', parseAs: 'text', }, { content: 'unsupported', parseAs: undefined, }, ]; it.each(scenarios)('detects $content as $parseAs', async ({ content, parseAs }) => { expect(getParseAs(content)).toEqual(parseAs); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Authorization')).toBe('foo'); expect(query).toEqual({}); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets an API key in a cookie', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'cookie', name: 'baz', type: 'apiKey', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Cookie')).toBe('baz=foo'); expect(query).toEqual({}); }); it('sets only one specific header', async () => { const auth = vi.fn(({ name }: Auth) => { if (name === 'baz') { return 'foo'; } return 'buz'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { name: 'fiz', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(headers.get('fiz')).toBe('buz'); expect(Object.keys(query).length).toBe(0); }); }); ================================================ FILE: packages/custom-client/src/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/custom-client/src/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/custom-client/src/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/custom-client/src/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string | undefined; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/custom-client/src/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/custom-client/src/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/custom-client/src/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export { buildClientParams } from './core/params'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/custom-client/src/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: '@hey-api/custom-client'; }; export type CustomClientPlugin = DefinePlugin; export const defaultConfig: CustomClientPlugin['Config'] = { ...clientDefaultMeta, config: { ...clientDefaultConfig, bundle: false, }, handler: clientPluginHandler as unknown as CustomClientPlugin['Handler'], name: '@hey-api/custom-client', }; /** * Type helper for `@hey-api/custom-client` plugin, returns {@link Plugin.Config} object */ export const customClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/custom-client/src/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: Pick & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/custom-client/src/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/custom-client/tsconfig.base.json ================================================ { "compilerOptions": { "declaration": true, "esModuleInterop": true, "module": "ESNext", "moduleResolution": "Bundler", "noImplicitOverride": true, "noUncheckedIndexedAccess": true, "noUnusedLocals": true, "strict": true, "target": "ES2022", "useUnknownInCatchVariables": false } } ================================================ FILE: packages/custom-client/tsconfig.json ================================================ { "extends": "./tsconfig.base.json", "compilerOptions": { "declaration": false, "esModuleInterop": true, "types": ["vitest/globals"] } } ================================================ FILE: packages/custom-client/tsdown.config.ts ================================================ import { defineConfig } from 'tsdown'; export default defineConfig({ clean: true, dts: true, entry: ['src/index.ts', 'src/plugin.ts'], format: ['cjs', 'esm'], minify: false, shims: false, sourcemap: true, treeshake: true, }); ================================================ FILE: packages/json-schema-ref-parser/.gitignore ================================================ .gen ================================================ FILE: packages/json-schema-ref-parser/CHANGELOG.md ================================================ # @hey-api/json-schema-ref-parser ## 1.3.1 ### Patch Changes - **parser**: prefer unprefixed schema names from external files ([#3417](https://github.com/hey-api/openapi-ts/pull/3417)) ([`f3a264b`](https://github.com/hey-api/openapi-ts/commit/f3a264b2c5d7af06bb44fa0350ef613bde3aff87)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: fix: resolve sibling schemas from external files during bundling ([#3422](https://github.com/hey-api/openapi-ts/pull/3422)) ([`19fd80a`](https://github.com/hey-api/openapi-ts/commit/19fd80aff26b1198d6838d48357702c39ad05501)) by [@j-westover](https://github.com/j-westover) - **input**: fix: avoid prefixing sources if paths do not collide on operations ([#3436](https://github.com/hey-api/openapi-ts/pull/3436)) ([`b1a419a`](https://github.com/hey-api/openapi-ts/commit/b1a419a835c312a1f8bf36a5b781109368041220)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 1.3.0 ### Minor Changes - **feat**: clean up dependencies ([#3386](https://github.com/hey-api/openapi-ts/pull/3386)) ([`e979b78`](https://github.com/hey-api/openapi-ts/commit/e979b789a052f7bbcfe4474ff8db2f733e23f2bb)) by [@mrlubos](https://github.com/mrlubos) ### Patch Changes - **fix**: pass seen references through crawl stack ([#3387](https://github.com/hey-api/openapi-ts/pull/3387)) ([`072a9ae`](https://github.com/hey-api/openapi-ts/commit/072a9ae7f336d5c3e5d70085ded21366eeed186d)) by [@mrlubos](https://github.com/mrlubos) ================================================ FILE: packages/json-schema-ref-parser/README.md ================================================ # JSON Schema $Ref Parser #### Parse, Resolve, and Dereference JSON Schema $ref pointers ## Installation Install using [npm](https://docs.npmjs.com/about-npm/): ```bash npm install @hey-api/json-schema-ref-parser yarn add @hey-api/json-schema-ref-parser bun add @hey-api/json-schema-ref-parser ``` ## The Problem: You've got a JSON Schema with `$ref` pointers to other files and/or URLs. Maybe you know all the referenced files ahead of time. Maybe you don't. Maybe some are local files, and others are remote URLs. Maybe they are a mix of JSON and YAML format. Maybe some of the files contain cross-references to each other. ```json { "definitions": { "person": { // references an external file "$ref": "schemas/people/Bruce-Wayne.json" }, "place": { // references a sub-schema in an external file "$ref": "schemas/places.yaml#/definitions/Gotham-City" }, "thing": { // references a URL "$ref": "http://wayne-enterprises.com/things/batmobile" }, "color": { // references a value in an external file via an internal reference "$ref": "#/definitions/thing/properties/colors/black-as-the-night" } } } ``` ## The Solution: JSON Schema $Ref Parser is a full [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) and [JSON Pointer](https://tools.ietf.org/html/rfc6901) implementation that crawls even the most complex [JSON Schemas](http://json-schema.org/latest/json-schema-core.html) and gives you simple, straightforward JavaScript objects. - Use **JSON** or **YAML** schemas — or even a mix of both! - Supports `$ref` pointers to external files and URLs, as well as custom sources such as databases - Can bundle multiple files into a single schema that only has _internal_ `$ref` pointers - Can dereference your schema, producing a plain-old JavaScript object that's easy to work with - Supports circular references, nested references, back-references, and cross-references between files - Maintains object reference equality — `$ref` pointers to the same value always resolve to the same object instance - Compatible with Node LTS and beyond, and all major web browsers on Windows, Mac, and Linux ### New in this fork (@hey-api) - **Multiple inputs with `bundleMany`**: Merge and bundle several OpenAPI/JSON Schema inputs (files, URLs, or raw objects) into a single schema. Components are prefixed to avoid name collisions, paths are namespaced on conflict, and `$ref`s are rewritten accordingly. ```javascript import { $RefParser } from '@hey-api/json-schema-ref-parser'; const parser = new $RefParser(); const merged = await parser.bundleMany({ pathOrUrlOrSchemas: [ './specs/a.yaml', 'https://example.com/b.yaml', { openapi: '3.1.0', info: { title: 'Inline' }, paths: {} }, ], }); // merged.components.* will contain prefixed names like a_, b_, etc. ``` - **Dereference hooks**: Fine-tune dereferencing with `excludedPathMatcher(path) => boolean` to skip subpaths and `onDereference(path, value, parent, parentPropName)` to observe replacements. ```javascript const parser = new $RefParser(); parser.options.dereference.excludedPathMatcher = (p) => p.includes('/example/'); parser.options.dereference.onDereference = (p, v) => { // inspect p / v as needed }; await parser.dereference({ pathOrUrlOrSchema: './openapi.yaml' }); ``` - **Smart input resolution**: You can pass a file path, URL, or raw schema object. If a raw schema includes `$id`, it is used as the base URL for resolving relative `$ref`s. ```javascript await new $RefParser().bundle({ pathOrUrlOrSchema: { $id: 'https://api.example.com/openapi.json', openapi: '3.1.0', paths: { '/ping': { get: { responses: { 200: { description: 'ok' } } } }, }, }, }); ``` ================================================ FILE: packages/json-schema-ref-parser/package.json ================================================ { "name": "@hey-api/json-schema-ref-parser", "version": "1.3.1", "description": "Parse, Resolve, and Dereference JSON Schema $ref pointers", "keywords": [ "$ref", "dereference", "json", "json-pointer", "json-schema", "jsonschema", "resolve", "schema" ], "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "files": [ "src", "dist", "cjs" ], "type": "module", "main": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "types": "./dist/index.d.mts", "import": "./dist/index.mjs" }, "./package.json": "./package.json" }, "scripts": { "build": "tsdown && pnpm check-exports", "check-exports": "attw --pack . --profile esm-only --ignore-rules cjs-resolves-to-esm", "dev": "tsdown --watch", "prepublishOnly": "pnpm build", "typecheck": "tsgo --noEmit" }, "dependencies": { "@jsdevtools/ono": "7.1.3", "@types/json-schema": "7.0.15", "yaml": "2.8.2" }, "devDependencies": { "typescript": "5.9.3" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/__snapshots__/circular-ref-with-description.json ================================================ { "schemas": { "Foo": { "$ref": "#/schemas/Bar" }, "Bar": { "description": "ok", "$ref": "#/schemas/Foo" } } } ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/__snapshots__/main-with-external-siblings.json ================================================ { "openapi": "3.0.0", "info": { "title": "Test API", "version": "1.0.0" }, "paths": { "/resolution": { "get": { "summary": "Get resolution step", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResolutionStep" } } } } } } }, "/action": { "get": { "summary": "Get action info", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ActionInfo" } } } } } } } }, "components": { "schemas": { "ActionInfo": { "type": "object", "properties": { "ActionId": { "type": "string" } } }, "ResolutionStep": { "type": "object", "properties": { "ResolutionType": { "oneOf": [ { "$ref": "#/components/schemas/ResolutionType" } ] }, "ActionName": { "type": "string" } } }, "ResolutionType": { "type": "string", "enum": [ "ContactVendor", "ResetToDefaults", "RetryOperation" ] } } } } ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/__snapshots__/multiple-refs.json ================================================ { "paths": { "/test1/{pathId}": { "get": { "summary": "First endpoint using the same pathId schema", "parameters": [ { "$ref": "#/components/parameters/pathId" } ], "responses": { "200": { "description": "Test 1 response" } } } }, "/test2/{pathId}": { "get": { "summary": "Second endpoint using the same pathId schema", "parameters": [ { "$ref": "#/components/parameters/pathId" } ], "responses": { "200": { "description": "Test 2 response" } } } } }, "components": { "parameters": { "pathId": { "name": "pathId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid", "description": "Unique identifier for the path" } } } } } ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/__snapshots__/redfish-like.json ================================================ { "openapi": "3.0.0", "info": { "title": "Redfish-like API", "version": "1.0.0", "description": "Test API simulating Redfish structure with versioned schemas" }, "paths": { "/redfish/v1/Systems": { "get": { "summary": "Get Systems", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResolutionStep_v1_0_1_ResolutionStep" } } } }, "default": { "description": "Error" } } } }, "/redfish/v1/Actions": { "post": { "summary": "Submit Action", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResolutionStep_v1_0_1_ActionParameters" } } } } } } } }, "components": { "schemas": { "ResolutionStep_v1_0_1_ActionParameters": { "type": "object", "properties": { "ActionId": { "type": "string" }, "ActionType": { "$ref": "#/components/schemas/ResolutionStep_v1_0_1_ResolutionType" } } }, "ResolutionStep_v1_0_1_ResolutionStep": { "type": "object", "properties": { "ResolutionType": { "oneOf": [ { "$ref": "#/components/schemas/ResolutionStep_v1_0_1_ResolutionType" } ] }, "ActionName": { "type": "string", "description": "Name of the action" } } }, "ResolutionStep_v1_0_1_ResolutionType": { "type": "string", "enum": [ "ContactVendor", "ResetToDefaults", "RetryOperation" ], "description": "Types of resolution actions" } } } } ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/bundle.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { $RefParser } from '..'; import { getSpecsPath } from './utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const getSnapshotsPath = () => path.join(__dirname, '__snapshots__'); const getTempSnapshotsPath = () => path.join(__dirname, '.gen', 'snapshots'); /** * Helper function to compare a bundled schema with a snapshot file. * Handles writing the schema to a temp file and comparing with the snapshot. * * @param schema - The bundled schema to compare * @param snapshotName - The name of the snapshot file (e.g., 'circular-ref-with-description.json') */ const expectBundledSchemaToMatchSnapshot = async (schema: unknown, snapshotName: string) => { const outputPath = path.join(getTempSnapshotsPath(), snapshotName); const snapshotPath = path.join(getSnapshotsPath(), snapshotName); // Ensure directory exists fs.mkdirSync(path.dirname(outputPath), { recursive: true }); // Write the bundled result const content = JSON.stringify(schema, null, 2); fs.writeFileSync(outputPath, content); // Compare with snapshot await expect(content).toMatchFileSnapshot(snapshotPath); }; describe('bundle', () => { it('handles circular reference with description', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join( getSpecsPath(), 'json-schema-ref-parser', 'circular-ref-with-description.json', ); const schema = await refParser.bundle({ pathOrUrlOrSchema }); await expectBundledSchemaToMatchSnapshot(schema, 'circular-ref-with-description.json'); }); it('bundles multiple references to the same file correctly', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join( getSpecsPath(), 'json-schema-ref-parser', 'multiple-refs.json', ); const schema = await refParser.bundle({ pathOrUrlOrSchema }); await expectBundledSchemaToMatchSnapshot(schema, 'multiple-refs.json'); }); it('hoists sibling schemas from external files', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join( getSpecsPath(), 'json-schema-ref-parser', 'main-with-external-siblings.json', ); const schema = await refParser.bundle({ pathOrUrlOrSchema }); await expectBundledSchemaToMatchSnapshot(schema, 'main-with-external-siblings.json'); }); it('hoists sibling schemas from YAML files with versioned names (Redfish-like)', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join( getSpecsPath(), 'json-schema-ref-parser', 'redfish-like.yaml', ); const schema = await refParser.bundle({ pathOrUrlOrSchema }); await expectBundledSchemaToMatchSnapshot(schema, 'redfish-like.json'); }); describe('sibling schema resolution', () => { const specsDir = path.join(getSpecsPath(), 'json-schema-ref-parser'); const findSchemaByValue = ( schemas: Record, predicate: (value: any) => boolean, ): [string, any] | undefined => { for (const [name, value] of Object.entries(schemas)) { if (predicate(value)) { return [name, value]; } } return undefined; }; it('hoists sibling schemas through a bare $ref wrapper chain', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join(specsDir, 'sibling-schema-root.json'); const schema = (await refParser.bundle({ pathOrUrlOrSchema })) as any; expect(schema.components).toBeDefined(); expect(schema.components.schemas).toBeDefined(); const schemas = schema.components.schemas; const mainSchema = findSchemaByValue( schemas, (v) => v.type === 'object' && v.properties?.name, ); expect(mainSchema).toBeDefined(); const [mainName, mainValue] = mainSchema!; expect(mainValue.type).toBe('object'); expect(mainValue.properties.name).toEqual({ type: 'string' }); const enumSchema = findSchemaByValue( schemas, (v) => Array.isArray(v.enum) && v.enum.includes('active'), ); expect(enumSchema).toBeDefined(); const [enumName, enumValue] = enumSchema!; expect(enumValue.type).toBe('string'); expect(enumValue.enum).toEqual(['active', 'inactive', 'pending']); // The main schema's status property should reference the hoisted enum expect(mainValue.properties.status.$ref).toBe(`#/components/schemas/${enumName}`); // The root path's schema ref should point to the hoisted main schema const rootRef = schema.paths['/test'].get.responses['200'].content['application/json'].schema; expect(rootRef.$ref).toBe(`#/components/schemas/${mainName}`); }); it('hoists sibling schemas through an extended $ref wrapper chain', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join(specsDir, 'sibling-schema-extended-root.json'); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { const schema = (await refParser.bundle({ pathOrUrlOrSchema })) as any; expect(schema.components).toBeDefined(); expect(schema.components.schemas).toBeDefined(); const schemas = schema.components.schemas; // The main schema should be hoisted (with the extra description merged in) const mainSchema = findSchemaByValue( schemas, (v) => v.description === 'Wrapper that extends the versioned schema' || (v.type === 'object' && v.properties?.name), ); expect(mainSchema).toBeDefined(); // The sibling enum must also be hoisted (this was the bug — it was lost before the fix) const enumSchema = findSchemaByValue( schemas, (v) => Array.isArray(v.enum) && v.enum.includes('active'), ); expect(enumSchema).toBeDefined(); const [, enumValue] = enumSchema!; expect(enumValue.type).toBe('string'); expect(enumValue.enum).toEqual(['active', 'inactive', 'pending']); // No "Skipping unresolvable $ref" warnings should have been emitted const unresolvableWarnings = warnSpy.mock.calls.filter( (args) => typeof args[0] === 'string' && args[0].includes('Skipping unresolvable $ref'), ); expect(unresolvableWarnings).toHaveLength(0); } finally { warnSpy.mockRestore(); } }); it('hoists sibling schemas from a direct reference (no wrapper)', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join(specsDir, 'sibling-schema-direct-root.json'); const schema = (await refParser.bundle({ pathOrUrlOrSchema })) as any; expect(schema.components).toBeDefined(); expect(schema.components.schemas).toBeDefined(); const schemas = schema.components.schemas; const mainSchema = findSchemaByValue( schemas, (v) => v.type === 'object' && v.properties?.name, ); expect(mainSchema).toBeDefined(); const enumSchema = findSchemaByValue( schemas, (v) => Array.isArray(v.enum) && v.enum.includes('active'), ); expect(enumSchema).toBeDefined(); const [enumName, enumValue] = enumSchema!; expect(enumValue.enum).toEqual(['active', 'inactive', 'pending']); const [, mainValue] = mainSchema!; expect(mainValue.properties.status.$ref).toBe(`#/components/schemas/${enumName}`); }); it('hoists multiple sibling schemas through an extended wrapper', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join(specsDir, 'sibling-schema-multi-root.json'); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { const schema = (await refParser.bundle({ pathOrUrlOrSchema })) as any; expect(schema.components).toBeDefined(); expect(schema.components.schemas).toBeDefined(); const schemas = schema.components.schemas; const mainSchema = findSchemaByValue( schemas, (v) => v.type === 'object' && v.properties?.health, ); expect(mainSchema).toBeDefined(); const statusEnum = findSchemaByValue( schemas, (v) => Array.isArray(v.enum) && v.enum.includes('enabled'), ); expect(statusEnum).toBeDefined(); expect(statusEnum![1].enum).toEqual(['enabled', 'disabled', 'standby']); const healthEnum = findSchemaByValue( schemas, (v) => Array.isArray(v.enum) && v.enum.includes('ok'), ); expect(healthEnum).toBeDefined(); expect(healthEnum![1].enum).toEqual(['ok', 'warning', 'critical']); const [, mainValue] = mainSchema!; expect(mainValue.properties.status.$ref).toBe(`#/components/schemas/${statusEnum![0]}`); expect(mainValue.properties.health.$ref).toBe(`#/components/schemas/${healthEnum![0]}`); const unresolvableWarnings = warnSpy.mock.calls.filter( (args) => typeof args[0] === 'string' && args[0].includes('Skipping unresolvable $ref'), ); expect(unresolvableWarnings).toHaveLength(0); } finally { warnSpy.mockRestore(); } }); it('handles multiple external files with same-named sibling schemas', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join(specsDir, 'sibling-schema-collision-root.json'); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { const schema = (await refParser.bundle({ pathOrUrlOrSchema })) as any; expect(schema.components).toBeDefined(); expect(schema.components.schemas).toBeDefined(); const schemas = schema.components.schemas; const schemaNames = Object.keys(schemas); const mainSchemaKey = schemaNames.find((name) => name.includes('MainSchema')); const otherSchemaKey = schemaNames.find((name) => name.includes('OtherSchema')); expect(mainSchemaKey).toBeDefined(); expect(otherSchemaKey).toBeDefined(); const statusSchemas = schemaNames.filter((name) => name.includes('Status')); expect(statusSchemas.length).toBeGreaterThanOrEqual(2); const statusValues = statusSchemas.map((name) => schemas[name]); const stringStatus = statusValues.find((v: any) => v.type === 'string'); const integerStatus = statusValues.find((v: any) => v.type === 'integer'); expect(stringStatus).toBeDefined(); expect(integerStatus).toBeDefined(); expect(stringStatus!.enum).toEqual(['active', 'inactive']); expect(integerStatus!.enum).toEqual([0, 1, 2]); const mainSchemaValue = schemas[mainSchemaKey!]; const mainStatusRef = mainSchemaValue.properties.status.$ref; expect(mainStatusRef).toMatch(/^#\/components\/schemas\/.*Status/); const referencedStatus = schemas[mainStatusRef.replace('#/components/schemas/', '')]; expect(referencedStatus).toBeDefined(); expect(referencedStatus.type).toBe('string'); expect(referencedStatus.enum).toEqual(['active', 'inactive']); const otherSchemaValue = schemas[otherSchemaKey!]; const otherStatusRef = otherSchemaValue.properties.code.$ref; expect(otherStatusRef).toMatch(/^#\/components\/schemas\/.*Status/); const referencedOtherStatus = schemas[otherStatusRef.replace('#/components/schemas/', '')]; expect(referencedOtherStatus).toBeDefined(); expect(referencedOtherStatus.type).toBe('integer'); expect(referencedOtherStatus.enum).toEqual([0, 1, 2]); const unresolvableWarnings = warnSpy.mock.calls.filter( (args) => typeof args[0] === 'string' && args[0].includes('Skipping unresolvable $ref'), ); expect(unresolvableWarnings).toHaveLength(0); } finally { warnSpy.mockRestore(); } }); }); describe('mergeMany', () => { it('merges paths with non-conflicting methods under the same path', async () => { const refParser = new $RefParser(); const spec1 = { info: { title: 'Spec 1', version: '1.0.0' }, paths: { '/pet/{petId}': { post: { operationId: 'updatePetWithForm', responses: { '405': { description: 'Invalid input' } }, }, }, }, swagger: '2.0', }; const spec2 = { info: { title: 'Spec 2', version: '1.0.0' }, paths: { '/pet/{petId}': { delete: { operationId: 'deletePet', responses: { '400': { description: 'Invalid ID supplied' }, '404': { description: 'Pet not found' }, }, }, }, }, swagger: '2.0', }; const merged = (await refParser.bundleMany({ pathOrUrlOrSchemas: [spec1, spec2] })) as any; // Both methods should be under the same path (no prefix added) expect(merged.paths['/pet/{petId}']).toBeDefined(); expect(merged.paths['/pet/{petId}'].post).toBeDefined(); expect(merged.paths['/pet/{petId}'].delete).toBeDefined(); // No prefixed path should be created const pathKeys = Object.keys(merged.paths); expect(pathKeys).toHaveLength(1); }); it('adds prefix to path when HTTP methods conflict', async () => { const refParser = new $RefParser(); const spec1 = { info: { title: 'Spec 1', version: '1.0.0' }, paths: { '/pet/{petId}': { get: { operationId: 'getPetById', responses: { '200': { description: 'OK' } }, }, }, }, swagger: '2.0', }; const spec2 = { info: { title: 'Spec 2', version: '1.0.0' }, paths: { '/pet/{petId}': { get: { operationId: 'getPet', responses: { '200': { description: 'Success' } }, }, }, }, swagger: '2.0', }; const merged = (await refParser.bundleMany({ pathOrUrlOrSchemas: [spec1, spec2] })) as any; // The conflicting path should be prefixed const pathKeys = Object.keys(merged.paths); expect(pathKeys).toHaveLength(2); expect(merged.paths['/pet/{petId}']).toBeDefined(); const prefixedKey = pathKeys.find((k) => k !== '/pet/{petId}'); expect(prefixedKey).toBeDefined(); expect(merged.paths[prefixedKey!].get).toBeDefined(); }); }); }); ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/index.test.ts ================================================ import path from 'node:path'; import { getResolvedInput } from '../index'; describe('getResolvedInput', () => { it('handles url', async () => { const pathOrUrlOrSchema = 'https://foo.com'; const resolvedInput = await getResolvedInput({ pathOrUrlOrSchema }); expect(resolvedInput.type).toBe('url'); expect(resolvedInput.schema).toBeUndefined(); expect(resolvedInput.path).toBe('https://foo.com/'); }); it('handles file', async () => { const pathOrUrlOrSchema = './path/to/openapi.json'; const resolvedInput = await getResolvedInput({ pathOrUrlOrSchema }); expect(resolvedInput.type).toBe('file'); expect(resolvedInput.schema).toBeUndefined(); expect(path.normalize(resolvedInput.path).toLowerCase()).toBe( path.normalize(path.resolve('./path/to/openapi.json')).toLowerCase(), ); }); it('handles raw spec', async () => { const pathOrUrlOrSchema = { info: { version: '1.0.0', }, openapi: '3.1.0', paths: {}, }; const resolvedInput = await getResolvedInput({ pathOrUrlOrSchema }); expect(resolvedInput.type).toBe('json'); expect(resolvedInput.schema).toEqual({ info: { version: '1.0.0', }, openapi: '3.1.0', paths: {}, }); expect(resolvedInput.path).toBe(''); }); }); ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/pointer.test.ts ================================================ import path from 'node:path'; import { $RefParser } from '..'; import { getSpecsPath } from './utils'; describe('pointer', () => { it('inlines internal JSON Pointer refs under #/paths/ for OpenAPI bundling', async () => { const refParser = new $RefParser(); const pathOrUrlOrSchema = path.join( getSpecsPath(), 'json-schema-ref-parser', 'openapi-paths-ref.json', ); const schema = (await refParser.bundle({ pathOrUrlOrSchema })) as any; // The GET endpoint should have its schema defined inline const getSchema = schema.paths['/foo'].get.responses['200'].content['application/json'].schema; expect(getSchema.$ref).toBeUndefined(); expect(getSchema.type).toBe('object'); expect(getSchema.properties.bar.type).toBe('string'); // The POST endpoint should have its schema inlined (copied) instead of a $ref const postSchema = schema.paths['/foo'].post.responses['200'].content['application/json'].schema; expect(postSchema.$ref).toBe( '#/paths/~1foo/get/responses/200/content/application~1json/schema', ); expect(postSchema.type).toBeUndefined(); expect(postSchema.properties?.bar?.type).toBeUndefined(); // Both schemas should be identical objects expect(postSchema).not.toBe(getSchema); }); }); ================================================ FILE: packages/json-schema-ref-parser/src/__tests__/utils.ts ================================================ import path from 'node:path'; export const getSpecsPath = (): string => path.join(__dirname, '..', '..', '..', '..', 'specs'); ================================================ FILE: packages/json-schema-ref-parser/src/bundle.ts ================================================ import type { $RefParser } from '.'; import type { ParserOptions } from './options'; import Pointer from './pointer'; import $Ref from './ref'; import type $Refs from './refs'; import type { JSONSchema } from './types'; import { MissingPointerError } from './util/errors'; import * as url from './util/url'; export interface InventoryEntry { $ref: any; circular: any; depth: any; extended: any; external: any; file: any; hash: any; indirections: any; key: any; originalContainerType?: 'schemas' | 'parameters' | 'requestBodies' | 'responses' | 'headers'; parent: any; pathFromRoot: any; value: any; } /** * Fast lookup using Map instead of linear search with deep equality */ const createInventoryLookup = () => { const lookup = new Map(); const objectIds = new WeakMap(); // Use WeakMap to avoid polluting objects let idCounter = 0; const getObjectId = (obj: any) => { if (!objectIds.has(obj)) { objectIds.set(obj, `obj_${++idCounter}`); } return objectIds.get(obj)!; }; const createInventoryKey = ($refParent: any, $refKey: any) => // Use WeakMap-based lookup to avoid polluting the actual schema objects `${getObjectId($refParent)}_${$refKey}`; return { add: (entry: InventoryEntry) => { const key = createInventoryKey(entry.parent, entry.key); lookup.set(key, entry); }, find: ($refParent: any, $refKey: any) => { const key = createInventoryKey($refParent, $refKey); const result = lookup.get(key); return result; }, remove: (entry: InventoryEntry) => { const key = createInventoryKey(entry.parent, entry.key); lookup.delete(key); }, }; }; /** * Determine the container type from a JSON Pointer path. * Analyzes the path tokens to identify the appropriate OpenAPI component container. * * @param path - The JSON Pointer path to analyze * @returns The container type: "schemas", "parameters", "requestBodies", "responses", or "headers" */ const getContainerTypeFromPath = ( path: string, ): 'schemas' | 'parameters' | 'requestBodies' | 'responses' | 'headers' => { const tokens = Pointer.parse(path); const has = (t: string) => tokens.includes(t); // Prefer more specific containers first if (has('parameters')) { return 'parameters'; } if (has('requestBody')) { return 'requestBodies'; } if (has('headers')) { return 'headers'; } if (has('responses')) { return 'responses'; } if (has('schema')) { return 'schemas'; } // default: treat as schema-like return 'schemas'; }; /** * Inventories the given JSON Reference (i.e. records detailed information about it so we can * optimize all $refs in the schema), and then crawls the resolved value. */ const inventory$Ref = ({ $refKey, $refParent, $refs, indirections, inventory, inventoryLookup, options, path, pathFromRoot, resolvedRefs = new Map(), visitedObjects = new WeakSet(), }: { /** * The key in `$refParent` that is a JSON Reference */ $refKey: string | null; /** * The object that contains a JSON Reference as one of its keys */ $refParent: any; $refs: $Refs; /** * unknown */ indirections: number; /** * An array of already-inventoried $ref pointers */ inventory: Array; /** * Fast lookup for inventory entries */ inventoryLookup: ReturnType; options: ParserOptions; /** * The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash */ path: string; /** * The path of the JSON Reference at `$refKey`, from the schema root */ pathFromRoot: string; /** * Cache for resolved $ref targets to avoid redundant resolution */ resolvedRefs?: Map; /** * Set of already visited objects to avoid infinite loops and redundant processing */ visitedObjects?: WeakSet; }) => { const $ref = $refKey === null ? $refParent : $refParent[$refKey]; const $refPath = url.resolve(path, $ref.$ref); // Check cache first to avoid redundant resolution let pointer = resolvedRefs.get($refPath); if (!pointer) { try { pointer = $refs._resolve($refPath, pathFromRoot, options); } catch (error) { if (error instanceof MissingPointerError) { // The ref couldn't be resolved in the target file. This commonly // happens when a wrapper file redirects via $ref to a versioned // file, and the bundler's crawl path retains the wrapper URL. // Try resolving the hash fragment against other files in $refs // that might contain the target schema. const hash = url.getHash($refPath); if (hash) { const baseFile = url.stripHash($refPath); for (const filePath of Object.keys($refs._$refs)) { if (filePath === baseFile) continue; try { pointer = $refs._resolve(filePath + hash, pathFromRoot, options); if (pointer) break; } catch { // try next file } } } if (!pointer) { console.warn(`Skipping unresolvable $ref: ${$refPath}`); return; } } else { throw error; } } if (pointer) { resolvedRefs.set($refPath, pointer); } } if (pointer === null) return; const parsed = Pointer.parse(pathFromRoot); const depth = parsed.length; const file = url.stripHash(pointer.path); const hash = url.getHash(pointer.path); const external = file !== $refs._root$Ref.path; const extended = $Ref.isExtended$Ref($ref); indirections += pointer.indirections; // Check if this exact location (parent + key + pathFromRoot) has already been inventoried const existingEntry = inventoryLookup.find($refParent, $refKey); if (existingEntry && existingEntry.pathFromRoot === pathFromRoot) { // This exact location has already been inventoried, so we don't need to process it again if (depth < existingEntry.depth || indirections < existingEntry.indirections) { removeFromInventory(inventory, existingEntry); inventoryLookup.remove(existingEntry); } else { return; } } const newEntry: InventoryEntry = { $ref, // The JSON Reference (e.g. {$ref: string}) circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself) depth, // How far from the JSON Schema root is this $ref pointer? extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref") external, // Does this $ref pointer point to a file other than the main JSON Schema file? file, // The file that the $ref pointer resolves to hash, // The hash within `file` that the $ref pointer resolves to indirections, // The number of indirect references that were traversed to resolve the value key: $refKey, // The resolved value of the $ref pointer originalContainerType: external ? getContainerTypeFromPath(pointer.path) : undefined, // The key in `parent` that is the $ref pointer parent: $refParent, // The object that contains this $ref pointer pathFromRoot, // The path to the $ref pointer, from the JSON Schema root value: pointer.value, // The original container type in the external file }; inventory.push(newEntry); inventoryLookup.add(newEntry); // Recursively crawl the resolved value. // When the resolution followed a $ref chain to a different file, // use the resolved file as the base path so that local $ref values // (e.g. #/components/schemas/SiblingSchema) inside the resolved // value resolve against the correct file. if (!existingEntry || external) { let crawlPath = pointer.path; const originalFile = url.stripHash($refPath); if (file !== originalFile) { crawlPath = file + url.getHash(pointer.path); } crawl({ $refs, indirections: indirections + 1, inventory, inventoryLookup, key: null, options, parent: pointer.value, path: crawlPath, pathFromRoot, resolvedRefs, visitedObjects, }); } }; /** * Recursively crawls the given value, and inventories all JSON references. */ const crawl = ({ $refs, indirections, inventory, inventoryLookup, key, options, parent, path, pathFromRoot, resolvedRefs = new Map(), visitedObjects = new WeakSet(), }: { $refs: $Refs; indirections: number; /** * An array of already-inventoried $ref pointers */ inventory: Array; /** * Fast lookup for inventory entries */ inventoryLookup: ReturnType; /** * The property key of `parent` to be crawled */ key: string | null; options: ParserOptions; /** * The object containing the value to crawl. If the value is not an object or array, it will be ignored. */ parent: object | $RefParser; /** * The full path of the property being crawled, possibly with a JSON Pointer in the hash */ path: string; /** * The path of the property being crawled, from the schema root */ pathFromRoot: string; /** * Cache for resolved $ref targets to avoid redundant resolution */ resolvedRefs?: Map; /** * Set of already visited objects to avoid infinite loops and redundant processing */ visitedObjects?: WeakSet; }) => { const obj = key === null ? parent : parent[key as keyof typeof parent]; if (obj && typeof obj === 'object' && !ArrayBuffer.isView(obj)) { // Early exit if we've already processed this exact object if (visitedObjects.has(obj)) return; if ($Ref.isAllowed$Ref(obj)) { inventory$Ref({ $refKey: key, $refParent: parent, $refs, indirections, inventory, inventoryLookup, options, path, pathFromRoot, resolvedRefs, visitedObjects, }); } else { // Mark this object as visited BEFORE processing its children visitedObjects.add(obj); // Crawl the object in a specific order that's optimized for bundling. // This is important because it determines how `pathFromRoot` gets built, // which later determines which keys get dereferenced and which ones get remapped const keys = Object.keys(obj).sort((a, b) => { // Most people will expect references to be bundled into the "definitions" property, // so we always crawl that property first, if it exists. if (a === 'definitions') { return -1; } else if (b === 'definitions') { return 1; } else { // Otherwise, crawl the keys based on their length. // This produces the shortest possible bundled references return a.length - b.length; } }) as Array; for (const key of keys) { const keyPath = Pointer.join(path, key); const keyPathFromRoot = Pointer.join(pathFromRoot, key); const value = obj[key]; if ($Ref.isAllowed$Ref(value)) { inventory$Ref({ $refKey: key, $refParent: obj, $refs, indirections, inventory, inventoryLookup, options, path, pathFromRoot: keyPathFromRoot, resolvedRefs, visitedObjects, }); } else { crawl({ $refs, indirections, inventory, inventoryLookup, key, options, parent: obj, path: keyPath, pathFromRoot: keyPathFromRoot, resolvedRefs, visitedObjects, }); } } } } }; /** * Remap external refs by hoisting resolved values into a shared container in the root schema * and pointing all occurrences to those internal definitions. Internal refs remain internal. */ function remap(parser: $RefParser, inventory: Array) { const root = parser.schema as any; // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them inventory.sort((a: InventoryEntry, b: InventoryEntry) => { if (a.file !== b.file) { // Group all the $refs that point to the same file return a.file < b.file ? -1 : +1; } else if (a.hash !== b.hash) { // Group all the $refs that point to the same part of the file return a.hash < b.hash ? -1 : +1; } else if (a.circular !== b.circular) { // If the $ref points to itself, then sort it higher than other $refs that point to this $ref return a.circular ? -1 : +1; } else if (a.extended !== b.extended) { // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value return a.extended ? +1 : -1; } else if (a.indirections !== b.indirections) { // Sort direct references higher than indirect references return a.indirections - b.indirections; } else if (a.depth !== b.depth) { // Sort $refs by how close they are to the JSON Schema root return a.depth - b.depth; } else { // Determine how far each $ref is from the "definitions" property. // Most people will expect references to be bundled into the the "definitions" property if possible. const aDefinitionsIndex = a.pathFromRoot.lastIndexOf('/definitions'); const bDefinitionsIndex = b.pathFromRoot.lastIndexOf('/definitions'); if (aDefinitionsIndex !== bDefinitionsIndex) { // Give higher priority to the $ref that's closer to the "definitions" property return bDefinitionsIndex - aDefinitionsIndex; } else { // All else is equal, so use the shorter path, which will produce the shortest possible reference return a.pathFromRoot.length - b.pathFromRoot.length; } } }); // Ensure or return a container by component type. Prefer OpenAPI-aware placement; // otherwise use existing root containers; otherwise create components/*. const ensureContainer = ( type: 'schemas' | 'parameters' | 'requestBodies' | 'responses' | 'headers', ) => { const isOas3 = !!(root && typeof root === 'object' && typeof root.openapi === 'string'); const isOas2 = !!(root && typeof root === 'object' && typeof root.swagger === 'string'); if (isOas3) { if (!root.components || typeof root.components !== 'object') { root.components = {}; } if (!root.components[type] || typeof root.components[type] !== 'object') { root.components[type] = {}; } return { obj: root.components[type], prefix: `#/components/${type}` } as const; } if (isOas2) { if (type === 'schemas') { if (!root.definitions || typeof root.definitions !== 'object') { root.definitions = {}; } return { obj: root.definitions, prefix: '#/definitions' } as const; } if (type === 'parameters') { if (!root.parameters || typeof root.parameters !== 'object') { root.parameters = {}; } return { obj: root.parameters, prefix: '#/parameters' } as const; } if (type === 'responses') { if (!root.responses || typeof root.responses !== 'object') { root.responses = {}; } return { obj: root.responses, prefix: '#/responses' } as const; } // requestBodies/headers don't exist as reusable containers in OAS2; fallback to definitions if (!root.definitions || typeof root.definitions !== 'object') { root.definitions = {}; } return { obj: root.definitions, prefix: '#/definitions' } as const; } // No explicit version: prefer existing containers if (root && typeof root === 'object') { if (root.components && typeof root.components === 'object') { if (!root.components[type] || typeof root.components[type] !== 'object') { root.components[type] = {}; } return { obj: root.components[type], prefix: `#/components/${type}` } as const; } if (root.definitions && typeof root.definitions === 'object') { return { obj: root.definitions, prefix: '#/definitions' } as const; } // Create components/* by default if nothing exists if (!root.components || typeof root.components !== 'object') { root.components = {}; } if (!root.components[type] || typeof root.components[type] !== 'object') { root.components[type] = {}; } return { obj: root.components[type], prefix: `#/components/${type}` } as const; } // Fallback root.definitions = root.definitions || {}; return { obj: root.definitions, prefix: '#/definitions' } as const; }; /** * Choose the appropriate component container for bundling. * Prioritizes the original container type from external files over usage location. * * @param entry - The inventory entry containing reference information * @returns The container type to use for bundling */ const chooseComponent = (entry: InventoryEntry) => { // If we have the original container type from the external file, use it if (entry.originalContainerType) { return entry.originalContainerType; } // Fallback to usage path for internal references or when original type is not available return getContainerTypeFromPath(entry.pathFromRoot); }; // Track names per (container prefix) and per target const targetToNameByPrefix = new Map>(); const usedNamesByObj = new Map>(); const sanitize = (name: string) => name.replace(/[^A-Za-z0-9_-]/g, '_'); const baseName = (filePath: string) => { try { const withoutHash = filePath.split('#')[0]!; const parts = withoutHash.split('/'); const filename = parts[parts.length - 1] || 'schema'; const dot = filename.lastIndexOf('.'); return sanitize(dot > 0 ? filename.substring(0, dot) : filename); } catch { return 'schema'; } }; const lastToken = (hash: string) => { if (!hash || hash === '#') { return 'root'; } const tokens = hash.replace(/^#\//, '').split('/'); return sanitize(tokens[tokens.length - 1] || 'root'); }; const uniqueName = (containerObj: any, proposed: string) => { if (!usedNamesByObj.has(containerObj)) { usedNamesByObj.set(containerObj, new Set(Object.keys(containerObj || {}))); } const used = usedNamesByObj.get(containerObj)!; let name = proposed; let i = 2; while (used.has(name)) { name = `${proposed}_${i++}`; } used.add(name); return name; }; for (const entry of inventory) { // Safety check: ensure entry and entry.$ref are valid objects if (!entry || !entry.$ref || typeof entry.$ref !== 'object') { continue; } // Keep internal refs internal. However, if the $ref extends the resolved value // (i.e. it has additional properties in addition to "$ref"), then we must // preserve the original $ref rather than rewriting it to the resolved hash. if (!entry.external) { if (!entry.extended && entry.$ref && typeof entry.$ref === 'object') { entry.$ref.$ref = entry.hash; } continue; } // Avoid changing direct self-references; keep them internal if (entry.circular) { if (entry.$ref && typeof entry.$ref === 'object') { entry.$ref.$ref = entry.pathFromRoot; } continue; } // Choose appropriate container based on original location in external file const component = chooseComponent(entry); const { obj: container, prefix } = ensureContainer(component); const targetKey = `${entry.file}::${entry.hash}`; if (!targetToNameByPrefix.has(prefix)) { targetToNameByPrefix.set(prefix, new Map()); } const namesForPrefix = targetToNameByPrefix.get(prefix)!; let defName = namesForPrefix.get(targetKey); if (!defName) { // If the external file is one of the original input sources, prefer its assigned prefix let proposedBase = baseName(entry.file); try { const parserAny: any = parser as any; if ( parserAny && parserAny.sourcePathToPrefix && typeof parserAny.sourcePathToPrefix.get === 'function' ) { const withoutHash = (entry.file || '').split('#')[0]; const mapped = parserAny.sourcePathToPrefix.get(withoutHash); if (mapped && typeof mapped === 'string') { proposedBase = mapped; } } } catch { // Ignore errors } // Try without prefix first (cleaner names) const schemaName = lastToken(entry.hash); let proposed = schemaName; // Check if this name would conflict with existing schemas from other files if (!usedNamesByObj.has(container)) { usedNamesByObj.set(container, new Set(Object.keys(container || {}))); } const used = usedNamesByObj.get(container)!; // If the name is already used, add the file prefix if (used.has(proposed)) { proposed = `${proposedBase}_${schemaName}`; } defName = uniqueName(container, proposed); namesForPrefix.set(targetKey, defName); // Store the resolved value under the container container[defName] = entry.value; } // Point the occurrence to the internal definition, preserving extensions const refPath = `${prefix}/${defName}`; if (entry.extended && entry.$ref && typeof entry.$ref === 'object') { entry.$ref.$ref = refPath; } else { entry.parent[entry.key] = { $ref: refPath }; } } } function removeFromInventory(inventory: Array, entry: any) { const index = inventory.indexOf(entry); inventory.splice(index, 1); } /** * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that * only has *internal* references, not any *external* references. * This method mutates the JSON schema object, adding new references and re-mapping existing ones. * * @param parser * @param options */ export function bundle(parser: $RefParser, options: ParserOptions): void { const inventory: Array = []; const inventoryLookup = createInventoryLookup(); const visitedObjects = new WeakSet(); const resolvedRefs = new Map(); crawl({ $refs: parser.$refs, indirections: 0, inventory, inventoryLookup, key: 'schema', options, parent: parser, path: parser.$refs._root$Ref.path + '#', pathFromRoot: '#', resolvedRefs, visitedObjects, }); remap(parser, inventory); } ================================================ FILE: packages/json-schema-ref-parser/src/dereference.ts ================================================ import { ono } from '@jsdevtools/ono'; import type { DereferenceOptions, ParserOptions } from './options'; import Pointer from './pointer'; import $Ref from './ref'; import type $Refs from './refs'; import type { JSONSchema } from './types'; import { TimeoutError } from './util/errors'; import * as url from './util/url'; /** * Recursively crawls the given value, and dereferences any JSON references. * * @param obj - The value to crawl. If it's not an object or array, it will be ignored. * @param path - The full path of `obj`, possibly with a JSON Pointer in the hash * @param pathFromRoot - The path of `obj` from the schema root * @param parents - An array of the parent objects that have already been dereferenced * @param processedObjects - An array of all the objects that have already been processed * @param dereferencedCache - An map of all the dereferenced objects * @param $refs * @param options * @param startTime - The time when the dereferencing started * @returns */ function crawl( obj: any, path: string, pathFromRoot: string, parents: Set, processedObjects: Set, dereferencedCache: any, $refs: $Refs, options: ParserOptions, startTime: number, ) { let dereferenced; const result = { circular: false, value: obj, }; if (options && options.timeoutMs) { if (Date.now() - startTime > options.timeoutMs) { throw new TimeoutError(options.timeoutMs); } } const derefOptions = (options.dereference || {}) as DereferenceOptions; const isExcludedPath = derefOptions.excludedPathMatcher || (() => false); if (derefOptions?.circular === 'ignore' || !processedObjects.has(obj)) { if ( obj && typeof obj === 'object' && !ArrayBuffer.isView(obj) && !isExcludedPath(pathFromRoot) ) { parents.add(obj); processedObjects.add(obj); if ($Ref.isAllowed$Ref(obj)) { dereferenced = dereference$Ref( obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, ); result.circular = dereferenced.circular; result.value = dereferenced.value; } else { for (const key of Object.keys(obj)) { const keyPath = Pointer.join(path, key); const keyPathFromRoot = Pointer.join(pathFromRoot, key); if (isExcludedPath(keyPathFromRoot)) { continue; } const value = obj[key]; let circular = false; if ($Ref.isAllowed$Ref(value)) { dereferenced = dereference$Ref( value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, ); circular = dereferenced.circular; // Avoid pointless mutations; breaks frozen objects to no profit if (obj[key] !== dereferenced.value) { obj[key] = dereferenced.value; derefOptions?.onDereference?.(value.$ref, obj[key], obj, key); } } else { if (!parents.has(value)) { dereferenced = crawl( value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, ); circular = dereferenced.circular; // Avoid pointless mutations; breaks frozen objects to no profit if (obj[key] !== dereferenced.value) { obj[key] = dereferenced.value; } } else { circular = foundCircularReference(keyPath, $refs, options); } } // Set the "isCircular" flag if this or any other property is circular result.circular = result.circular || circular; } } parents.delete(obj); } } return result; } /** * Dereferences the given JSON Reference, and then crawls the resulting value. * * @param $ref - The JSON Reference to resolve * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash * @param pathFromRoot - The path of `$ref` from the schema root * @param parents - An array of the parent objects that have already been dereferenced * @param processedObjects - An array of all the objects that have already been dereferenced * @param dereferencedCache - An map of all the dereferenced objects * @param $refs * @param options * @returns */ function dereference$Ref( $ref: any, path: string, pathFromRoot: string, parents: Set, processedObjects: any, dereferencedCache: any, $refs: $Refs, options: ParserOptions, startTime: number, ) { const $refPath = url.resolve(path, $ref.$ref); const cache = dereferencedCache.get($refPath); if (cache && !cache.circular) { const refKeys = Object.keys($ref); if (refKeys.length > 1) { const extraKeys = {}; for (const key of refKeys) { if (key !== '$ref' && !(key in cache.value)) { // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message extraKeys[key] = $ref[key]; } } return { circular: cache.circular, value: Object.assign({}, structuredClone(cache.value), extraKeys), }; } // Return a deep-cloned value so each occurrence is an independent copy return { circular: cache.circular, value: structuredClone(cache.value) }; } const pointer = $refs._resolve($refPath, path, options); if (pointer === null) { return { circular: false, value: null, }; } // Check for circular references const directCircular = pointer.circular; let circular = directCircular || parents.has(pointer.value); if (circular) { foundCircularReference(path, $refs, options); } // Dereference the JSON reference let dereferencedValue = $Ref.dereference($ref, pointer.value); // Crawl the dereferenced value (unless it's circular) if (!circular) { // Determine if the dereferenced value is circular const dereferenced = crawl( dereferencedValue, pointer.path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, ); circular = dereferenced.circular; dereferencedValue = dereferenced.value; } if (circular && !directCircular && options.dereference?.circular === 'ignore') { // The user has chosen to "ignore" circular references, so don't change the value dereferencedValue = $ref; } if (directCircular) { // The pointer is a DIRECT circular reference (i.e. it references itself). // So replace the $ref path with the absolute path from the JSON Schema root dereferencedValue.$ref = pathFromRoot; } const dereferencedObject = { circular, value: dereferencedValue, }; // only cache if no extra properties than $ref if (Object.keys($ref).length === 1) { dereferencedCache.set($refPath, dereferencedObject); } return dereferencedObject; } /** * Called when a circular reference is found. * It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false. * * @param keyPath - The JSON Reference path of the circular reference * @param $refs * @param options * @returns - always returns true, to indicate that a circular reference was found */ function foundCircularReference(keyPath: any, $refs: any, options: any) { $refs.circular = true; if (!options.dereference.circular) { throw ono.reference(`Circular $ref pointer found at ${keyPath}`); } return true; } ================================================ FILE: packages/json-schema-ref-parser/src/index.ts ================================================ import { ono } from '@jsdevtools/ono'; import { bundle as _bundle } from './bundle'; import { getJsonSchemaRefParserDefaultOptions } from './options'; import { newFile, parseFile } from './parse'; import $Refs from './refs'; import { resolveExternal } from './resolve-external'; import { fileResolver } from './resolvers/file'; import { urlResolver } from './resolvers/url'; import type { JSONSchema } from './types'; import { isHandledError, JSONParserErrorGroup } from './util/errors'; import * as url from './util/url'; interface ResolvedInput { path: string; schema: string | JSONSchema | Buffer | Awaited | undefined; type: 'file' | 'json' | 'url'; } export function getResolvedInput({ pathOrUrlOrSchema, }: { pathOrUrlOrSchema: JSONSchema | string | unknown; }): ResolvedInput { if (!pathOrUrlOrSchema) { throw ono(`Expected a file path, URL, or object. Got ${pathOrUrlOrSchema}`); } const resolvedInput: ResolvedInput = { path: typeof pathOrUrlOrSchema === 'string' ? pathOrUrlOrSchema : '', schema: undefined, type: 'url', }; // If the path is a filesystem path, then convert it to a URL. // NOTE: According to the JSON Reference spec, these should already be URLs, // but, in practice, many people use local filesystem paths instead. // So we're being generous here and doing the conversion automatically. // This is not intended to be a 100% bulletproof solution. // If it doesn't work for your use-case, then use a URL instead. if (resolvedInput.path && url.isFileSystemPath(resolvedInput.path)) { resolvedInput.path = url.fromFileSystemPath(resolvedInput.path); resolvedInput.type = 'file'; } else if (!resolvedInput.path && pathOrUrlOrSchema && typeof pathOrUrlOrSchema === 'object') { if ('$id' in pathOrUrlOrSchema && pathOrUrlOrSchema.$id) { // when schema id has defined an URL should use that hostname to request the references, // instead of using the current page URL const { hostname, protocol } = new URL(pathOrUrlOrSchema.$id as string); resolvedInput.path = `${protocol}//${hostname}:${protocol === 'https:' ? 443 : 80}`; resolvedInput.type = 'url'; } else { resolvedInput.schema = pathOrUrlOrSchema; resolvedInput.type = 'json'; } } if (resolvedInput.type !== 'json') { // resolve the absolute path of the schema resolvedInput.path = url.resolve(url.cwd(), resolvedInput.path); } return resolvedInput; } // NOTE: previously used helper removed as unused /** * This class parses a JSON schema, builds a map of its JSON references and their resolved values, * and provides methods for traversing, manipulating, and dereferencing those references. */ export class $RefParser { /** * The resolved JSON references * * @type {$Refs} * @readonly */ $refs = new $Refs(); public options = getJsonSchemaRefParserDefaultOptions(); /** * The parsed (and possibly dereferenced) JSON schema object * * @type {object} * @readonly */ public schema: JSONSchema | null = null; public schemaMany: JSONSchema[] = []; public schemaManySources: string[] = []; public sourcePathToPrefix: Map = new Map(); /** * Bundles all referenced files/URLs into a single schema that only has internal `$ref` pointers. This lets you split-up your schema however you want while you're building it, but easily combine all those files together when it's time to package or distribute the schema to other people. The resulting schema size will be small, since it will still contain internal JSON references rather than being fully-dereferenced. * * This also eliminates the risk of circular references, so the schema can be safely serialized using `JSON.stringify()`. * * See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#bundleschema-options-callback * * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file. */ public async bundle({ arrayBuffer, fetch, pathOrUrlOrSchema, resolvedInput, }: { arrayBuffer?: ArrayBuffer; fetch?: RequestInit; pathOrUrlOrSchema: JSONSchema | string | unknown; resolvedInput?: ResolvedInput; }): Promise { await this.parse({ arrayBuffer, fetch, pathOrUrlOrSchema, resolvedInput, }); await resolveExternal(this, this.options); const errors = JSONParserErrorGroup.getParserErrors(this); if (errors.length > 0) { throw new JSONParserErrorGroup(this); } _bundle(this, this.options); const errors2 = JSONParserErrorGroup.getParserErrors(this); if (errors2.length > 0) { throw new JSONParserErrorGroup(this); } return this.schema!; } /** * Bundles multiple roots (files/URLs/objects) into a single schema by creating a synthetic root * that references each input, resolving all externals, and then hoisting via the existing bundler. */ public async bundleMany({ arrayBuffer, fetch, pathOrUrlOrSchemas, resolvedInputs, }: { arrayBuffer?: ArrayBuffer[]; fetch?: RequestInit; pathOrUrlOrSchemas: Array; resolvedInputs?: ResolvedInput[]; }): Promise { await this.parseMany({ arrayBuffer, fetch, pathOrUrlOrSchemas, resolvedInputs }); this.mergeMany(); await resolveExternal(this, this.options); const errors = JSONParserErrorGroup.getParserErrors(this); if (errors.length > 0) { throw new JSONParserErrorGroup(this); } _bundle(this, this.options); // Merged root is ready for bundling const errors2 = JSONParserErrorGroup.getParserErrors(this); if (errors2.length > 0) { throw new JSONParserErrorGroup(this); } return this.schema!; } /** * Parses the given JSON schema. * This method does not resolve any JSON references. * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. * * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file. * @returns - The returned promise resolves with the parsed JSON schema object. */ public async parse({ arrayBuffer, fetch, pathOrUrlOrSchema, resolvedInput: _resolvedInput, }: { arrayBuffer?: ArrayBuffer; fetch?: RequestInit; pathOrUrlOrSchema: JSONSchema | string | unknown; resolvedInput?: ResolvedInput; }): Promise<{ schema: JSONSchema }> { const resolvedInput = _resolvedInput || getResolvedInput({ pathOrUrlOrSchema }); const { path, type } = resolvedInput; let { schema } = resolvedInput; // reset everything this.schema = null; this.$refs = new $Refs(); if (schema) { // immediately add a new $Ref with the schema object as value const $ref = this.$refs._add(path); $ref.pathType = url.isFileSystemPath(path) ? 'file' : 'http'; $ref.value = schema; } else if (type !== 'json') { const file = newFile(path); // Add a new $Ref for this file, even though we don't have the value yet. // This ensures that we don't simultaneously read & parse the same file multiple times const $refAdded = this.$refs._add(file.url); $refAdded.pathType = type; try { const resolver = type === 'file' ? fileResolver : urlResolver; await resolver.handler({ arrayBuffer, fetch, file, }); const parseResult = await parseFile(file, this.options.parse); $refAdded.value = parseResult.result; schema = parseResult.result; } catch (error) { if (isHandledError(error)) { $refAdded.value = error; } throw error; } } if (schema === null || typeof schema !== 'object' || Buffer.isBuffer(schema)) { throw ono.syntax(`"${this.$refs._root$Ref.path || schema}" is not a valid JSON Schema`); } this.schema = schema; return { schema, }; } private async parseMany({ arrayBuffer, fetch, pathOrUrlOrSchemas, resolvedInputs: _resolvedInputs, }: { arrayBuffer?: ArrayBuffer[]; fetch?: RequestInit; pathOrUrlOrSchemas: Array; resolvedInputs?: ResolvedInput[]; }): Promise<{ schemaMany: JSONSchema[] }> { const resolvedInputs = [...(_resolvedInputs || [])]; resolvedInputs.push( ...(pathOrUrlOrSchemas.map((schema) => getResolvedInput({ pathOrUrlOrSchema: schema })) || []), ); this.schemaMany = []; this.schemaManySources = []; this.sourcePathToPrefix = new Map(); for (let i = 0; i < resolvedInputs.length; i++) { const resolvedInput = resolvedInputs[i]!; const { path, type } = resolvedInput; let { schema } = resolvedInput; if (schema) { // keep schema as-is } else if (type !== 'json') { const file = newFile(path); // Add a new $Ref for this file, even though we don't have the value yet. // This ensures that we don't simultaneously read & parse the same file multiple times const $refAdded = this.$refs._add(file.url); $refAdded.pathType = type; try { const resolver = type === 'file' ? fileResolver : urlResolver; await resolver.handler({ arrayBuffer: arrayBuffer?.[i], fetch, file, }); const parseResult = await parseFile(file, this.options.parse); $refAdded.value = parseResult.result; schema = parseResult.result; } catch (error) { if (isHandledError(error)) { $refAdded.value = error; } throw error; } } if (schema === null || typeof schema !== 'object' || Buffer.isBuffer(schema)) { throw ono.syntax(`"${this.$refs._root$Ref.path || schema}" is not a valid JSON Schema`); } this.schemaMany.push(schema); this.schemaManySources.push(path && path.length ? path : url.cwd()); } return { schemaMany: this.schemaMany, }; } public mergeMany(): JSONSchema { const schemas = this.schemaMany || []; if (schemas.length === 0) { throw ono('mergeMany called with no schemas. Did you run parseMany?'); } const merged: any = {}; // Determine spec version: prefer first occurrence of openapi, else swagger let chosenOpenapi: string | undefined; let chosenSwagger: string | undefined; for (const s of schemas) { if (!chosenOpenapi && s && typeof (s as any).openapi === 'string') { chosenOpenapi = (s as any).openapi; } if (!chosenSwagger && s && typeof (s as any).swagger === 'string') { chosenSwagger = (s as any).swagger; } if (chosenOpenapi && chosenSwagger) { break; } } if (typeof chosenOpenapi === 'string') { merged.openapi = chosenOpenapi; } else if (typeof chosenSwagger === 'string') { merged.swagger = chosenSwagger; } // Merge info: take first non-empty per-field across inputs const infoAccumulator: any = {}; for (const s of schemas) { const info = (s as any)?.info; if (info && typeof info === 'object') { for (const [k, v] of Object.entries(info)) { if (infoAccumulator[k] === undefined && v !== undefined) { infoAccumulator[k] = JSON.parse(JSON.stringify(v)); } } } } if (Object.keys(infoAccumulator).length > 0) { merged.info = infoAccumulator; } // Merge servers: union by url+description const servers: any[] = []; const seenServers = new Set(); for (const s of schemas) { const arr = (s as any)?.servers; if (Array.isArray(arr)) { for (const srv of arr) { if (srv && typeof srv === 'object') { const key = `${srv.url || ''}|${srv.description || ''}`; if (!seenServers.has(key)) { seenServers.add(key); servers.push(JSON.parse(JSON.stringify(srv))); } } } } } if (servers.length > 0) { merged.servers = servers; } merged.paths = {}; merged.components = {}; const componentSections = [ 'schemas', 'parameters', 'requestBodies', 'responses', 'headers', 'securitySchemes', 'examples', 'links', 'callbacks', ]; for (const sec of componentSections) { merged.components[sec] = {}; } const tagNameSet = new Set(); const tags: any[] = []; const usedOpIds = new Set(); const baseName = (p: string) => { try { const withoutHash = p.split('#')[0]!; const parts = withoutHash.split('/'); const filename = parts[parts.length - 1] || 'schema'; const dot = filename.lastIndexOf('.'); const raw = dot > 0 ? filename.substring(0, dot) : filename; return raw.replace(/[^A-Za-z0-9_-]/g, '_'); } catch { return 'schema'; } }; const unique = (set: Set, proposed: string) => { let name = proposed; let i = 2; while (set.has(name)) { name = `${proposed}_${i++}`; } set.add(name); return name; }; const rewriteRef = (ref: string, refMap: Map): string => { // OAS3: #/components/{section}/{name}... let m = ref.match(/^#\/components\/([^/]+)\/([^/]+)(.*)$/); if (m) { const base = `#/components/${m[1]}/${m[2]}`; const mapped = refMap.get(base); if (mapped) { return mapped + (m[3] || ''); } } // OAS2: #/definitions/{name}... m = ref.match(/^#\/definitions\/([^/]+)(.*)$/); if (m) { const base = `#/components/schemas/${m[1]}`; const mapped = refMap.get(base); if (mapped) { // map definitions -> components/schemas return mapped + (m[2] || ''); } } return ref; }; const cloneAndRewrite = ( obj: any, refMap: Map, tagMap: Map, opIdPrefix: string, basePath: string, ): any => { if (obj === null || obj === undefined) { return obj; } if (Array.isArray(obj)) { return obj.map((v) => cloneAndRewrite(v, refMap, tagMap, opIdPrefix, basePath)); } if (typeof obj !== 'object') { return obj; } const out: any = {}; for (const [k, v] of Object.entries(obj)) { if (k === '$ref' && typeof v === 'string') { const s = v as string; if (s.startsWith('#')) { out[k] = rewriteRef(s, refMap); } else { const proto = url.getProtocol(s); if (proto === undefined) { // relative external ref -> absolutize against source base path out[k] = url.resolve(basePath + '#', s); } else { out[k] = s; } } } else if (k === 'tags' && Array.isArray(v) && v.every((x) => typeof x === 'string')) { out[k] = v.map((t) => tagMap.get(t) || t); } else if (k === 'operationId' && typeof v === 'string') { out[k] = unique(usedOpIds, `${opIdPrefix}_${v}`); } else { out[k] = cloneAndRewrite(v as any, refMap, tagMap, opIdPrefix, basePath); } } return out; }; for (let i = 0; i < schemas.length; i++) { const schema: any = schemas[i] || {}; const sourcePath = this.schemaManySources[i] || `multi://input/${i + 1}`; const prefix = baseName(sourcePath); // Track prefix for this source path (strip hash). Only map real file/http paths const withoutHash = url.stripHash(sourcePath); const protocol = url.getProtocol(withoutHash); if ( protocol === undefined || protocol === 'file' || protocol === 'http' || protocol === 'https' ) { this.sourcePathToPrefix.set(withoutHash, prefix); } const refMap = new Map(); const tagMap = new Map(); const srcComponents = (schema.components || {}) as any; for (const sec of componentSections) { const group = srcComponents[sec] || {}; for (const [name] of Object.entries(group)) { const newName = `${prefix}_${name}`; refMap.set(`#/components/${sec}/${name}`, `#/components/${sec}/${newName}`); } } const srcTags: any[] = Array.isArray(schema.tags) ? schema.tags : []; for (const t of srcTags) { if (!t || typeof t !== 'object' || typeof t.name !== 'string') { continue; } const desired = t.name; const finalName = tagNameSet.has(desired) ? `${prefix}_${desired}` : desired; tagNameSet.add(finalName); tagMap.set(desired, finalName); if (!tags.find((x) => x && x.name === finalName)) { tags.push({ ...t, name: finalName }); } } for (const sec of componentSections) { const group = (schema.components && schema.components[sec]) || {}; for (const [name, val] of Object.entries(group)) { const newName = `${prefix}_${name}`; merged.components[sec][newName] = cloneAndRewrite( val, refMap, tagMap, prefix, url.stripHash(sourcePath), ); } } const HTTP_METHODS = new Set([ 'delete', 'get', 'head', 'options', 'patch', 'post', 'put', 'trace', ]); const srcPaths = (schema.paths || {}) as Record; for (const [p, item] of Object.entries(srcPaths)) { if (merged.paths[p]) { const newMethods = Object.keys(item as object).filter((k) => HTTP_METHODS.has(k)); const hasMethodConflict = newMethods.some((m) => merged.paths[p][m] !== undefined); const rewritten = cloneAndRewrite( item, refMap, tagMap, prefix, url.stripHash(sourcePath), ); if (hasMethodConflict) { const trimmed = p.startsWith('/') ? p.substring(1) : p; merged.paths[`/${prefix}/${trimmed}`] = rewritten; } else { Object.assign(merged.paths[p], rewritten); } } else { merged.paths[p] = cloneAndRewrite( item, refMap, tagMap, prefix, url.stripHash(sourcePath), ); } } } if (tags.length > 0) { merged.tags = tags; } // Rebuild $refs root using the first input's path to preserve external resolution semantics const rootPath = this.schemaManySources[0] || url.cwd(); this.$refs = new $Refs(); const rootRef = this.$refs._add(rootPath); rootRef.pathType = url.isFileSystemPath(rootPath) ? 'file' : 'http'; rootRef.value = merged; this.schema = merged; return merged as JSONSchema; } } export { sendRequest } from './resolvers/url'; export type { JSONSchema } from './types'; ================================================ FILE: packages/json-schema-ref-parser/src/options.ts ================================================ import { binaryParser } from './parsers/binary'; import { jsonParser } from './parsers/json'; import { textParser } from './parsers/text'; import { yamlParser } from './parsers/yaml'; import type { JSONSchemaObject, Plugin } from './types'; export interface DereferenceOptions { /** * Determines whether circular `$ref` pointers are handled. * * If set to `false`, then a `ReferenceError` will be thrown if the schema contains any circular references. * * If set to `"ignore"`, then circular references will simply be ignored. No error will be thrown, but the `$Refs.circular` property will still be set to `true`. */ circular?: boolean | 'ignore'; /** * A function, called for each path, which can return true to stop this path and all * subpaths from being dereferenced further. This is useful in schemas where some * subpaths contain literal $ref keys that should not be dereferenced. */ excludedPathMatcher?(path: string): boolean; /** * Callback invoked during dereferencing. * * @argument {string} path - The path being dereferenced (ie. the `$ref` string) * @argument {JSONSchemaObject} value - The JSON-Schema that the `$ref` resolved to * @argument {JSONSchemaObject} parent - The parent of the dereferenced object * @argument {string} parentPropName - The prop name of the parent object whose value was dereferenced */ onDereference?( path: string, value: JSONSchemaObject, parent?: JSONSchemaObject, parentPropName?: string, ): void; } /** * Options that determine how JSON schemas are parsed, resolved, and dereferenced. * * @param [options] - Overridden options * @class */ export interface $RefParserOptions { /** * The `dereference` options control how JSON Schema `$Ref` Parser will dereference `$ref` pointers within the JSON schema. */ dereference: DereferenceOptions; /** * The `parse` options determine how different types of files will be parsed. * * JSON Schema `$Ref` Parser comes with built-in JSON, YAML, plain-text, and binary parsers, any of which you can configure or disable. You can also add your own custom parsers if you want. */ parse: { binary: Plugin; json: Plugin; text: Plugin; yaml: Plugin; }; /** * The maximum amount of time (in milliseconds) that JSON Schema $Ref Parser will spend dereferencing a single schema. * It will throw a timeout error if the operation takes longer than this. */ timeoutMs?: number; } export const getJsonSchemaRefParserDefaultOptions = (): $RefParserOptions => ({ /** * Determines the types of JSON references that are allowed. */ dereference: { /** * Dereference circular (recursive) JSON references? * If false, then a {@link ReferenceError} will be thrown if a circular reference is found. * If "ignore", then circular references will not be dereferenced. * * @type {boolean|string} */ circular: true, /** * A function, called for each path, which can return true to stop this path and all * subpaths from being dereferenced further. This is useful in schemas where some * subpaths contain literal $ref keys that should not be dereferenced. * * @type {function} */ excludedPathMatcher: () => false, // @ts-expect-error referenceResolution: 'relative', }, /** * Determines how different types of files will be parsed. * * You can add additional parsers of your own, replace an existing one with * your own implementation, or disable any parser by setting it to false. */ parse: { binary: { ...binaryParser }, json: { ...jsonParser }, text: { ...textParser }, yaml: { ...yamlParser }, }, }); export type Options = $RefParserOptions; type DeepPartial = T extends object ? { [P in keyof T]?: DeepPartial; } : T; export type ParserOptions = DeepPartial<$RefParserOptions>; ================================================ FILE: packages/json-schema-ref-parser/src/parse.ts ================================================ import { ono } from '@jsdevtools/ono'; import type { $RefParserOptions } from './options'; import type { FileInfo } from './types'; import { ParserError } from './util/errors'; import type { PluginResult } from './util/plugins'; import * as plugins from './util/plugins'; import { getExtension } from './util/url'; /** * Prepares the file object so we can populate it with data and other values * when it's read and parsed. This "file object" will be passed to all * resolvers and parsers. */ export function newFile(path: string): FileInfo { let url = path; // Remove the URL fragment, if any const hashIndex = url.indexOf('#'); let hash = ''; if (hashIndex > -1) { hash = url.substring(hashIndex); url = url.substring(0, hashIndex); } return { extension: getExtension(url), hash, url, } as FileInfo; } /** * Parses the given file's contents, using the configured parser plugins. */ export async function parseFile( file: FileInfo, options: $RefParserOptions['parse'], ): Promise { try { // If none of the parsers are a match for this file, try all of them. This // handles situations where the file is a supported type, just with an // unknown extension. const parsers = [options.json, options.yaml, options.text, options.binary]; const filtered = parsers.filter((plugin) => plugin.canHandle(file)); return await plugins.run(filtered.length ? filtered : parsers, file); } catch (error: any) { if (error && error.message && error.message.startsWith('Error parsing')) { throw error; } if (!error || !('error' in error)) { throw ono.syntax(`Unable to parse ${file.url}`); } if (error.error instanceof ParserError) { throw error.error; } throw new ParserError(error.error.message, file.url); } } ================================================ FILE: packages/json-schema-ref-parser/src/parsers/binary.ts ================================================ import type { FileInfo, Plugin } from '../types'; const BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i; export const binaryParser: Plugin = { canHandle: (file: FileInfo) => Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url), handler: (file: FileInfo): Buffer => Buffer.isBuffer(file.data) ? file.data : // This will reject if data is anything other than a string or typed array Buffer.from(file.data), name: 'binary', }; ================================================ FILE: packages/json-schema-ref-parser/src/parsers/json.ts ================================================ import type { FileInfo, Plugin } from '../types'; import { ParserError } from '../util/errors'; export const jsonParser: Plugin = { canHandle: (file: FileInfo) => file.extension === '.json', async handler(file: FileInfo): Promise { let data = file.data; if (Buffer.isBuffer(data)) { data = data.toString(); } if (typeof data !== 'string') { // data is already a JavaScript value (object, array, number, null, NaN, etc.) return data as object; } if (!data.trim().length) { // this mirrors the YAML behavior return; } try { return JSON.parse(data); // eslint-disable-next-line @typescript-eslint/no-unused-vars } catch (error: any) { try { // find the first curly brace const firstCurlyBrace = data.indexOf('{'); // remove any characters before the first curly brace data = data.slice(firstCurlyBrace); return JSON.parse(data); } catch (error: any) { throw new ParserError(error.message, file.url); } } }, name: 'json', }; ================================================ FILE: packages/json-schema-ref-parser/src/parsers/text.ts ================================================ import type { FileInfo, Plugin } from '../types'; import { ParserError } from '../util/errors'; const TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i; export const textParser: Plugin = { canHandle: (file: FileInfo) => (typeof file.data === 'string' || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url), handler(file: FileInfo): string { if (typeof file.data === 'string') { return file.data; } if (!Buffer.isBuffer(file.data)) { throw new ParserError('data is not text', file.url); } return file.data.toString('utf-8'); }, name: 'text', }; ================================================ FILE: packages/json-schema-ref-parser/src/parsers/yaml.ts ================================================ import { parse } from 'yaml'; import type { FileInfo, JSONSchema, Plugin } from '../types'; import { ParserError } from '../util/errors'; export const yamlParser: Plugin = { // JSON is valid YAML canHandle: (file: FileInfo) => ['.yaml', '.yml', '.json'].includes(file.extension), handler: async (file: FileInfo): Promise => { const data = Buffer.isBuffer(file.data) ? file.data.toString() : file.data; if (typeof data !== 'string') { // data is already a JavaScript value (object, array, number, null, NaN, etc.) return data; } try { return parse(data) as JSONSchema; } catch (error: any) { throw new ParserError(error?.message || 'Parser Error', file.url); } }, name: 'yaml', }; ================================================ FILE: packages/json-schema-ref-parser/src/pointer.ts ================================================ import type { ParserOptions } from './options'; import $Ref from './ref'; import type { JSONSchema } from './types'; import { InvalidPointerError, isHandledError, JSONParserError, MissingPointerError, } from './util/errors'; import * as url from './util/url'; const slashes = /\//g; const tildes = /~/g; const escapedSlash = /~1/g; const escapedTilde = /~0/g; const safeDecodeURIComponent = (encodedURIComponent: string): string => { try { return decodeURIComponent(encodedURIComponent); } catch { return encodedURIComponent; } }; /** * This class represents a single JSON pointer and its resolved value. * * @param $ref * @param path * @param [friendlyPath] - The original user-specified path (used for error messages) * @class */ class Pointer { /** * The {@link $Ref} object that contains this {@link Pointer} object. */ $ref: $Ref; /** * The file path or URL, containing the JSON pointer in the hash. * This path is relative to the path of the main JSON schema file. */ path: string; /** * The original path or URL, used for error messages. */ originalPath: string; /** * The value of the JSON pointer. * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). */ value: any; /** * Indicates whether the pointer references itself. */ circular: boolean; /** * The number of indirect references that were traversed to resolve the value. * Resolving a single pointer may require resolving multiple $Refs. */ indirections: number; constructor($ref: $Ref, path: string, friendlyPath?: string) { this.$ref = $ref; this.path = path; this.originalPath = friendlyPath || path; this.value = undefined; this.circular = false; this.indirections = 0; } /** * Resolves the value of a nested property within the given object. * * @param obj - The object that will be crawled * @param options * @param pathFromRoot - the path of place that initiated resolving * * @returns * Returns a JSON pointer whose {@link Pointer#value} is the resolved value. * If resolving this value required resolving other JSON references, then * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path * of the resolved value. */ resolve(obj: S, options?: ParserOptions, pathFromRoot?: string) { const tokens = Pointer.parse(this.path, this.originalPath); // Crawl the object, one token at a time this.value = unwrapOrThrow(obj); const errors: MissingPointerError[] = []; for (let i = 0; i < tokens.length; i++) { if (resolveIf$Ref(this, options, pathFromRoot)) { // The $ref path has changed, so append the remaining tokens to the path this.path = Pointer.join(this.path, tokens.slice(i)); } if ( typeof this.value === 'object' && this.value !== null && !isRootPath(pathFromRoot) && '$ref' in this.value ) { return this; } const token = tokens[i]!; if ( this.value[token] === undefined || (this.value[token] === null && i === tokens.length - 1) ) { // one final case is if the entry itself includes slashes, and was parsed out as a token - we can join the remaining tokens and try again let didFindSubstringSlashMatch = false; for (let j = tokens.length - 1; j > i; j--) { const joinedToken = tokens.slice(i, j + 1).join('/'); if (this.value[joinedToken] !== undefined) { this.value = this.value[joinedToken]; i = j; didFindSubstringSlashMatch = true; break; } } if (didFindSubstringSlashMatch) { continue; } this.value = null; errors.push(new MissingPointerError(token, decodeURI(this.originalPath))); } else { this.value = this.value[token]; } } if (errors.length > 0) { throw errors.length === 1 ? errors[0] : new AggregateError(errors, 'Multiple missing pointer errors'); } // Resolve the final value if ( !this.value || (this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot) ) { resolveIf$Ref(this, options, pathFromRoot); } return this; } /** * Sets the value of a nested property within the given object. * * @param obj - The object that will be crawled * @param value - the value to assign * @param options * * @returns * Returns the modified object, or an entirely new object if the entire object is overwritten. */ set(obj: S, value: any, options?: ParserOptions) { const tokens = Pointer.parse(this.path); let token; if (tokens.length === 0) { // There are no tokens, replace the entire object with the new value this.value = value; return value; } // Crawl the object, one token at a time this.value = unwrapOrThrow(obj); for (let i = 0; i < tokens.length - 1; i++) { resolveIf$Ref(this, options); token = tokens[i]!; if (this.value && this.value[token] !== undefined) { // The token exists this.value = this.value[token]; } else { // The token doesn't exist, so create it this.value = setValue(this, token, {}); } } // Set the value of the final token resolveIf$Ref(this, options); token = tokens[tokens.length - 1]; setValue(this, token, value); // Return the updated object return obj; } /** * Parses a JSON pointer (or a path containing a JSON pointer in the hash) * and returns an array of the pointer's tokens. * (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"]) * * The pointer is parsed according to RFC 6901 * {@link https://tools.ietf.org/html/rfc6901#section-3} * * @param path * @param [originalPath] * @returns */ static parse(path: string, originalPath?: string): string[] { // Get the JSON pointer from the path's hash const pointer = url.getHash(path).substring(1); // If there's no pointer, then there are no tokens, // so return an empty array if (!pointer) { return []; } // Split into an array const split = pointer.split('/'); // Decode each part, according to RFC 6901 for (let i = 0; i < split.length; i++) { split[i] = safeDecodeURIComponent( split[i]!.replace(escapedSlash, '/').replace(escapedTilde, '~'), ); } if (split[0] !== '') { throw new InvalidPointerError(pointer, originalPath === undefined ? path : originalPath); } return split.slice(1); } /** * Creates a JSON pointer path, by joining one or more tokens to a base path. * * @param base - The base path (e.g. "schema.json#/definitions/person") * @param tokens - The token(s) to append (e.g. ["name", "first"]) * @returns */ static join(base: string, tokens: string | string[]) { // Ensure that the base path contains a hash if (base.indexOf('#') === -1) { base += '#'; } // Append each token to the base path tokens = Array.isArray(tokens) ? tokens : [tokens]; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]!; // Encode the token, according to RFC 6901 base += '/' + encodeURIComponent(token.replace(tildes, '~0').replace(slashes, '~1')); } return base; } } /** * If the given pointer's {@link Pointer#value} is a JSON reference, * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value. * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the * resolution path of the new value. * * @param pointer * @param options * @param [pathFromRoot] - the path of place that initiated resolving * @returns - Returns `true` if the resolution path changed */ function resolveIf$Ref(pointer: any, options: any, pathFromRoot?: any) { // Is the value a JSON reference? (and allowed?) if ($Ref.isAllowed$Ref(pointer.value)) { const $refPath = url.resolve(pointer.path, pointer.value.$ref); if ($refPath === pointer.path && !isRootPath(pathFromRoot)) { // The value is a reference to itself, so there's nothing to do. pointer.circular = true; } else { const resolved = pointer.$ref.$refs._resolve($refPath, pointer.path, options); if (resolved === null) { return false; } pointer.indirections += resolved.indirections + 1; if ($Ref.isExtended$Ref(pointer.value)) { // This JSON reference "extends" the resolved value, rather than simply pointing to it. // So the resolved path does NOT change. Just the value does. pointer.value = $Ref.dereference(pointer.value, resolved.value); return false; } else { // Resolve the reference pointer.$ref = resolved.$ref; pointer.path = resolved.path; pointer.value = resolved.value; } return true; } } return undefined; } export default Pointer; /** * Sets the specified token value of the {@link Pointer#value}. * * The token is evaluated according to RFC 6901. * {@link https://tools.ietf.org/html/rfc6901#section-4} * * @param pointer - The JSON Pointer whose value will be modified * @param token - A JSON Pointer token that indicates how to modify `obj` * @param value - The value to assign * @returns - Returns the assigned value */ function setValue(pointer: any, token: any, value: any) { if (pointer.value && typeof pointer.value === 'object') { if (token === '-' && Array.isArray(pointer.value)) { pointer.value.push(value); } else { pointer.value[token] = value; } } else { throw new JSONParserError( `Error assigning $ref pointer "${pointer.path}". \nCannot set "${token}" of a non-object.`, ); } return value; } function unwrapOrThrow(value: any) { if (isHandledError(value)) { throw value; } return value; } function isRootPath(pathFromRoot: any): boolean { return typeof pathFromRoot == 'string' && Pointer.parse(pathFromRoot).length == 0; } ================================================ FILE: packages/json-schema-ref-parser/src/ref.ts ================================================ import type { ParserOptions } from './options'; import Pointer from './pointer'; import type $Refs from './refs'; import type { JSONSchema } from './types'; import type { JSONParserError, MissingPointerError, ParserError, ResolverError, } from './util/errors'; import { normalizeError } from './util/errors'; export type $RefError = JSONParserError | ResolverError | ParserError | MissingPointerError; /** * This class represents a single JSON reference and its resolved value. * * @class */ class $Ref { /** * The file path or URL of the referenced file. * This path is relative to the path of the main JSON schema file. * * This path does NOT contain document fragments (JSON pointers). It always references an ENTIRE file. * Use methods such as {@link $Ref#get}, {@link $Ref#resolve}, and {@link $Ref#exists} to get * specific JSON pointers within the file. * * @type {string} */ path: undefined | string; /** * The resolved value of the JSON reference. * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). * * @type {?*} */ value: any; /** * The {@link $Refs} object that contains this {@link $Ref} object. * * @type {$Refs} */ $refs: $Refs; /** * Indicates the type of {@link $Ref#path} (e.g. "file", "http", etc.) */ pathType: string | unknown; /** * List of all errors. Undefined if no errors. */ errors: Array<$RefError> = []; constructor($refs: $Refs) { this.$refs = $refs; } /** * Pushes an error to errors array. * * @param err - The error to be pushed * @returns */ addError(err: $RefError) { if (this.errors === undefined) { this.errors = []; } const existingErrors = this.errors.map(({ footprint }: any) => footprint); // the path has been almost certainly set at this point, // but just in case something went wrong, normalizeError injects path if necessary // moreover, certain errors might point at the same spot, so filter them out to reduce noise if ('errors' in err && Array.isArray(err.errors)) { this.errors.push( ...err.errors .map(normalizeError) .filter(({ footprint }: any) => !existingErrors.includes(footprint)), ); } else if (!('footprint' in err) || !existingErrors.includes(err.footprint)) { this.errors.push(normalizeError(err)); } } /** * Determines whether the given JSON reference exists within this {@link $Ref#value}. * * @param path - The full path being resolved, optionally with a JSON pointer in the hash * @param options * @returns */ exists(path: string, options?: ParserOptions) { try { this.resolve(path, options); return true; } catch { return false; } } /** * Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value. * * @param path - The full path being resolved, optionally with a JSON pointer in the hash * @param options * @returns - Returns the resolved value */ get(path: string, options?: ParserOptions) { return this.resolve(path, options)?.value; } /** * Resolves the given JSON reference within this {@link $Ref#value}. * * @param path - The full path being resolved, optionally with a JSON pointer in the hash * @param options * @param friendlyPath - The original user-specified path (used for error messages) * @param pathFromRoot - The path of `obj` from the schema root * @returns */ resolve(path: string, options?: ParserOptions, friendlyPath?: string, pathFromRoot?: string) { const pointer = new Pointer(this, path, friendlyPath); return pointer.resolve(this.value, options, pathFromRoot); } /** * Sets the value of a nested property within this {@link $Ref#value}. * If the property, or any of its parents don't exist, they will be created. * * @param path - The full path of the property to set, optionally with a JSON pointer in the hash * @param value - The value to assign */ set(path: string, value: any) { const pointer = new Pointer(this, path); this.value = pointer.set(this.value, value); } /** * Determines whether the given value is a JSON reference. * * @param value - The value to inspect * @returns */ static is$Ref(value: unknown): value is { $ref: string; length?: number } { return ( Boolean(value) && typeof value === 'object' && value !== null && '$ref' in value && typeof value.$ref === 'string' && value.$ref.length > 0 ); } /** * Determines whether the given value is an external JSON reference. * * @param value - The value to inspect * @returns */ static isExternal$Ref(value: unknown): boolean { return $Ref.is$Ref(value) && value.$ref![0] !== '#'; } /** * Determines whether the given value is a JSON reference, and whether it is allowed by the options. * * @param value - The value to inspect * @param options * @returns */ static isAllowed$Ref(value: unknown) { if (this.is$Ref(value)) { if (value.$ref.substring(0, 2) === '#/' || value.$ref === '#') { // It's a JSON Pointer reference, which is always allowed return true; } else if (value.$ref[0] !== '#') { // It's an external reference, which is allowed by the options return true; } } return undefined; } /** * Determines whether the given value is a JSON reference that "extends" its resolved value. * That is, it has extra properties (in addition to "$ref"), so rather than simply pointing to * an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved * value, plus the extra properties. * * @example: { person: { properties: { firstName: { type: string } lastName: { type: string } } } employee: { properties: { $ref: #/person/properties salary: { type: number } } } } * In this example, "employee" is an extended $ref, since it extends "person" with an additional * property (salary). The result is a NEW value that looks like this: * * { * properties: { * firstName: { type: string } * lastName: { type: string } * salary: { type: number } * } * } * * @param value - The value to inspect * @returns */ static isExtended$Ref(value: unknown) { return $Ref.is$Ref(value) && Object.keys(value).length > 1; } /** * Returns the resolved value of a JSON Reference. * If necessary, the resolved value is merged with the JSON Reference to create a new object * * @example: { person: { properties: { firstName: { type: string } lastName: { type: string } } } employee: { properties: { $ref: #/person/properties salary: { type: number } } } } When "person" and "employee" are merged, you end up with the following object: * * { * properties: { * firstName: { type: string } * lastName: { type: string } * salary: { type: number } * } * } * * @param $ref - The JSON reference object (the one with the "$ref" property) * @param resolvedValue - The resolved value, which can be any type * @returns - Returns the dereferenced value */ static dereference($ref: $Ref, resolvedValue: S): S { if (resolvedValue && typeof resolvedValue === 'object' && $Ref.isExtended$Ref($ref)) { const merged = {}; for (const key of Object.keys($ref)) { if (key !== '$ref') { // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message merged[key] = $ref[key]; } } for (const key of Object.keys(resolvedValue)) { if (!(key in merged)) { // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message merged[key] = resolvedValue[key]; } } return merged as S; } else { // Completely replace the original reference with the resolved value return resolvedValue; } } } export default $Ref; ================================================ FILE: packages/json-schema-ref-parser/src/refs.ts ================================================ import { ono } from '@jsdevtools/ono'; import type { JSONSchema4Type, JSONSchema6Type, JSONSchema7Type } from 'json-schema'; import type { ParserOptions } from './options'; import $Ref from './ref'; import type { JSONSchema } from './types'; import convertPathToPosix from './util/convert-path-to-posix'; import * as url from './util/url'; interface $RefsMap { [url: string]: $Ref; } /** * When you call the resolve method, the value that gets passed to the callback function (or Promise) is a $Refs object. This same object is accessible via the parser.$refs property of $RefParser objects. * * This object is a map of JSON References and their resolved values. It also has several convenient helper methods that make it easy for you to navigate and manipulate the JSON References. * * See https://apitools.dev/json-schema-ref-parser/docs/refs.html */ export default class $Refs { /** * This property is true if the schema contains any circular references. You may want to check this property before serializing the dereferenced schema as JSON, since JSON.stringify() does not support circular references by default. * * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#circular */ public circular: boolean; /** * Returns the paths/URLs of all the files in your schema (including the main schema file). * * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#pathstypes * * @param types (optional) Optionally only return certain types of paths ("file", "http", etc.) */ paths(...types: (string | string[])[]): string[] { const paths = getPaths(this._$refs, types.flat()); return paths.map((path) => convertPathToPosix(path.decoded)); } /** * Returns a map of paths/URLs and their correspond values. * * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#valuestypes * * @param types (optional) Optionally only return values from certain locations ("file", "http", etc.) */ values(...types: (string | string[])[]): S { const $refs = this._$refs; const paths = getPaths($refs, types.flat()); return paths.reduce>((obj, path) => { obj[convertPathToPosix(path.decoded)] = $refs[path.encoded]!.value; return obj; }, {}) as S; } /** * Returns `true` if the given path exists in the schema; otherwise, returns `false` * * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#existsref * * @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash */ /** * Determines whether the given JSON reference exists. * * @param path - The path being resolved, optionally with a JSON pointer in the hash * @param [options] * @returns */ exists(path: string, options: any) { try { this._resolve(path, '', options); return true; } catch { return false; } } /** * Resolves the given JSON reference and returns the resolved value. * * @param path - The path being resolved, with a JSON pointer in the hash * @param [options] * @returns - Returns the resolved value */ get(path: string, options?: ParserOptions): JSONSchema4Type | JSONSchema6Type | JSONSchema7Type { return this._resolve(path, '', options)!.value; } /** * Sets the value at the given path in the schema. If the property, or any of its parents, don't exist, they will be created. * * @param path The JSON Reference path, optionally with a JSON Pointer in the hash * @param value The value to assign. Can be anything (object, string, number, etc.) */ set(path: string, value: JSONSchema4Type | JSONSchema6Type | JSONSchema7Type) { const absPath = url.resolve(this._root$Ref.path!, path); const withoutHash = url.stripHash(absPath); const $ref = this._$refs[withoutHash]; if (!$ref) { throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`); } $ref.set(absPath, value); } /** * Returns the specified {@link $Ref} object, or undefined. * * @param path - The path being resolved, optionally with a JSON pointer in the hash * @returns * @protected */ _get$Ref(path: string) { path = url.resolve(this._root$Ref.path!, path); const withoutHash = url.stripHash(path); return this._$refs[withoutHash]; } /** * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object. * * @param path - The file path or URL of the referenced file */ _add(path: string) { const withoutHash = url.stripHash(path); const $ref = new $Ref(this); $ref.path = withoutHash; this._$refs[withoutHash] = $ref; this._root$Ref = this._root$Ref || $ref; return $ref; } /** * Resolves the given JSON reference. * * @param path - The path being resolved, optionally with a JSON pointer in the hash * @param pathFromRoot - The path of `obj` from the schema root * @param [options] * @returns * @protected */ _resolve(path: string, pathFromRoot: string, options?: ParserOptions) { const absPath = url.resolve(this._root$Ref.path!, path); const withoutHash = url.stripHash(absPath); const $ref = this._$refs[withoutHash]; if (!$ref) { throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`); } if ($ref.value === undefined) { console.warn(`$ref entry exists but value is undefined: ${withoutHash}`); return null; // Treat as unresolved } return $ref.resolve(absPath, options, path, pathFromRoot); } /** * A map of paths/urls to {@link $Ref} objects * * @type {object} * @protected */ _$refs: $RefsMap = {}; /** * The {@link $Ref} object that is the root of the JSON schema. * * @type {$Ref} * @protected */ _root$Ref: $Ref; constructor() { /** * Indicates whether the schema contains any circular references. * * @type {boolean} */ this.circular = false; this._$refs = {}; // @ts-ignore this._root$Ref = null; } /** * Returns the paths of all the files/URLs that are referenced by the JSON schema, * including the schema itself. * * @param [types] - Only return paths of the given types ("file", "http", etc.) * @returns */ /** * Returns the map of JSON references and their resolved values. * * @param [types] - Only return references of the given types ("file", "http", etc.) * @returns */ /** * Returns a POJO (plain old JavaScript object) for serialization as JSON. * * @returns {object} */ toJSON = this.values; } /** * Returns the encoded and decoded paths keys of the given object. * * @param $refs - The object whose keys are URL-encoded paths * @param [types] - Only return paths of the given types ("file", "http", etc.) * @returns */ function getPaths($refs: $RefsMap, types: string[]) { let paths = Object.keys($refs); // Filter the paths by type types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types); if (types.length > 0 && types[0]) { paths = paths.filter((key) => types.includes($refs[key]!.pathType as string)); } // Decode local filesystem paths return paths.map((path) => ({ decoded: $refs[path]!.pathType === 'file' ? url.toFileSystemPath(path, true) : path, encoded: path, })); } ================================================ FILE: packages/json-schema-ref-parser/src/resolve-external.ts ================================================ import type { $RefParser } from '.'; import { getResolvedInput } from '.'; import type { $RefParserOptions } from './options'; import { newFile, parseFile } from './parse'; import Pointer from './pointer'; import $Ref from './ref'; import type $Refs from './refs'; import { fileResolver } from './resolvers/file'; import { urlResolver } from './resolvers/url'; import type { JSONSchema } from './types'; import { isHandledError } from './util/errors'; import * as url from './util/url'; /** * Crawls the JSON schema, finds all external JSON references, and resolves their values. * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}. * * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing. * * @returns * The promise resolves once all JSON references in the schema have been resolved, * including nested references that are contained in externally-referenced files. */ export async function resolveExternal(parser: $RefParser, options: $RefParserOptions) { const promises = crawl(parser.schema, { $refs: parser.$refs, options: options.parse, path: `${parser.$refs._root$Ref.path}#`, }); await Promise.all(promises); } /** * Recursively crawls the given value, and resolves any external JSON references. * * @param obj - The value to crawl. If it's not an object or array, it will be ignored. * @returns An array of promises. There will be one promise for each JSON reference in `obj`. * If `obj` does not contain any JSON references, then the array will be empty. * If any of the JSON references point to files that contain additional JSON references, * then the corresponding promise will internally reference an array of promises. */ function crawl( obj: string | Buffer | S | undefined | null, { $refs, external = false, options, path, seen = new Set(), }: { $refs: $Refs; /** Whether `obj` was found in an external document. */ external?: boolean; options: $RefParserOptions['parse']; /** The full path of `obj`, possibly with a JSON Pointer in the hash. */ path: string; seen?: Set; }, ): ReadonlyArray> { let promises: Array> = []; if (obj && typeof obj === 'object' && !ArrayBuffer.isView(obj) && !seen.has(obj)) { seen.add(obj); if ($Ref.isExternal$Ref(obj)) { promises.push( resolve$Ref(obj, { $refs, options, path, seen, }), ); } for (const [key, value] of Object.entries(obj)) { promises = promises.concat( crawl(value, { $refs, external, options, path: Pointer.join(path, key), seen, }), ); } } return promises; } /** * Resolves the given JSON Reference, and then crawls the resulting value. * * @param $ref - The JSON Reference to resolve * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash * @param $refs * @param options * * @returns * The promise resolves once all JSON references in the object have been resolved, * including nested references that are contained in externally-referenced files. */ async function resolve$Ref( $ref: S, { $refs, options, path, seen, }: { $refs: $Refs; options: $RefParserOptions['parse']; path: string; seen: Set; }, ): Promise { const resolvedPath = url.resolve(path, ($ref as JSONSchema).$ref!); const withoutHash = url.stripHash(resolvedPath); // If this ref points back to an input source we've already merged, avoid re-importing // by checking if the path (without hash) matches a known source in parser and we can serve it internally later. // We keep normal flow but ensure cache hit if already added. // Do we already have this $ref? const ref = $refs._$refs[withoutHash]; if (ref) { // We've already parsed this $ref, so crawl it to resolve its own externals const promises = crawl(ref.value as S, { $refs, external: true, options, path: `${withoutHash}#`, seen, }); return Promise.all(promises); } // Parse the $referenced file/url const file = newFile(resolvedPath); // Add a new $Ref for this file, even though we don't have the value yet. // This ensures that we don't simultaneously read & parse the same file multiple times const $refAdded = $refs._add(file.url); try { const resolvedInput = getResolvedInput({ pathOrUrlOrSchema: resolvedPath }); $refAdded.pathType = resolvedInput.type; let promises: ReadonlyArray> = []; if (resolvedInput.type !== 'json') { const resolver = resolvedInput.type === 'file' ? fileResolver : urlResolver; await resolver.handler({ file }); const parseResult = await parseFile(file, options); $refAdded.value = parseResult.result; promises = crawl(parseResult.result, { $refs, external: true, options, path: `${withoutHash}#`, seen, }); } return Promise.all(promises); } catch (error) { if (isHandledError(error)) { $refAdded.value = error; } throw error; } } ================================================ FILE: packages/json-schema-ref-parser/src/resolvers/file.ts ================================================ import { ono } from '@jsdevtools/ono'; import fs from 'fs'; import type { FileInfo } from '../types'; import { ResolverError } from '../util/errors'; import * as url from '../util/url'; export const fileResolver = { handler: async ({ file }: { file: FileInfo }): Promise => { let path: string | undefined; try { path = url.toFileSystemPath(file.url); } catch (error: any) { throw new ResolverError(ono.uri(error, `Malformed URI: ${file.url}`), file.url); } try { const data = await fs.promises.readFile(path); file.data = data; } catch (error: any) { throw new ResolverError(ono(error, `Error opening file "${path}"`), path); } }, }; ================================================ FILE: packages/json-schema-ref-parser/src/resolvers/url.ts ================================================ import { ono } from '@jsdevtools/ono'; import type { FileInfo } from '../types'; import { ResolverError } from '../util/errors'; import { resolve } from '../util/url'; export const sendRequest = async ({ fetchOptions, redirects = [], timeout = 60_000, url, }: { fetchOptions?: RequestInit; redirects?: string[]; timeout?: number; url: URL | string; }): Promise<{ fetchOptions?: RequestInit; response: Response; }> => { url = new URL(url); redirects.push(url.href); const controller = new AbortController(); const timeoutId = setTimeout(() => { controller.abort(); }, timeout); const response = await fetch(url, { signal: controller.signal, ...fetchOptions, }); clearTimeout(timeoutId); if (response.status >= 300 && response.status <= 399) { if (redirects.length > 5) { throw new ResolverError( ono( { status: response.status }, `Error requesting ${redirects[0]}. \nToo many redirects: \n ${redirects.join(' \n ')}`, ), ); } if (!('location' in response.headers) || !response.headers.location) { throw ono( { status: response.status }, `HTTP ${response.status} redirect with no location header`, ); } return sendRequest({ fetchOptions, redirects, timeout, url: resolve(url.href, response.headers.location as string), }); } return { fetchOptions, response }; }; export const urlResolver = { handler: async ({ arrayBuffer, fetch: _fetch, file, }: { arrayBuffer?: ArrayBuffer; fetch?: RequestInit; file: FileInfo; }): Promise => { let data = arrayBuffer; if (!data) { try { const { fetchOptions, response } = await sendRequest({ fetchOptions: { method: 'GET', ..._fetch, }, url: file.url, }); if (response.status >= 400) { // gracefully handle HEAD method not allowed if (response.status !== 405 || fetchOptions?.method !== 'HEAD') { throw ono({ status: response.status }, `HTTP ERROR ${response.status}`); } } data = response.body ? await response.arrayBuffer() : new ArrayBuffer(0); } catch (error: any) { throw new ResolverError(ono(error, `Error requesting ${file.url}`), file.url); } } file.data = Buffer.from(data!); }, }; ================================================ FILE: packages/json-schema-ref-parser/src/types/index.ts ================================================ import type { JSONSchema4, JSONSchema4Object, JSONSchema6, JSONSchema6Object, JSONSchema7, JSONSchema7Object, } from 'json-schema'; export type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7; export type JSONSchemaObject = JSONSchema4Object | JSONSchema6Object | JSONSchema7Object; export interface Plugin { /** * Can this parser be used to process this file? */ canHandle: (file: FileInfo) => boolean; /** * This is where the real work of a parser happens. The `parse` method accepts the same file info object as the `canHandle` function, but rather than returning a boolean value, the `parse` method should return a JavaScript representation of the file contents. For our CSV parser, that is a two-dimensional array of lines and values. For your parser, it might be an object, a string, a custom class, or anything else. * * Unlike the `canHandle` function, the `parse` method can also be asynchronous. This might be important if your parser needs to retrieve data from a database or if it relies on an external HTTP service to return the parsed value. You can return your asynchronous value via a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a Node.js-style error-first callback. Here are examples of both approaches: */ handler: ( file: FileInfo, ) => | string | Buffer | JSONSchema | Promise<{ data: Buffer }> | Promise; name: 'binary' | 'file' | 'http' | 'json' | 'text' | 'yaml'; } /** * JSON Schema `$Ref` Parser supports plug-ins, such as resolvers and parsers. These plug-ins can have methods such as `canHandle()`, `read()`, `canHandle()`, and `parse()`. All of these methods accept the same object as their parameter: an object containing information about the file being read or parsed. * * The file info object currently only consists of a few properties, but it may grow in the future if plug-ins end up needing more information. * * See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html */ export interface FileInfo { /** * The raw file contents, in whatever form they were returned by the resolver that read the file. */ data: string | Buffer; /** * The lowercase file extension, such as ".json", ".yaml", ".txt", etc. */ extension: string; /** * The hash (URL fragment) of the file URL, including the # symbol. If the URL doesn't have a hash, then this will be an empty string. */ hash: string; /** * The full URL of the file. This could be any type of URL, including "http://", "https://", "file://", "ftp://", "mongodb://", or even a local filesystem path (when running in Node.js). */ url: string; } ================================================ FILE: packages/json-schema-ref-parser/src/util/convert-path-to-posix.ts ================================================ export default function convertPathToPosix(filePath: string): string { // Extended-length paths on Windows should not be converted if (filePath.startsWith('\\\\?\\')) { return filePath; } return filePath.replaceAll('\\', '/'); } ================================================ FILE: packages/json-schema-ref-parser/src/util/errors.ts ================================================ import { Ono } from '@jsdevtools/ono'; import type { $RefParser } from '..'; import type $Ref from '../ref'; import type { JSONSchema } from '../types'; import { getHash, stripHash, toFileSystemPath } from './url'; export type JSONParserErrorType = | 'EUNKNOWN' | 'EPARSER' | 'EUNMATCHEDPARSER' | 'ETIMEOUT' | 'ERESOLVER' | 'EUNMATCHEDRESOLVER' | 'EMISSINGPOINTER' | 'EINVALIDPOINTER'; export class JSONParserError extends Error { public readonly name: string; public readonly message: string; public source: string | undefined; public path: Array | null; public readonly code: JSONParserErrorType; public constructor(message: string, source?: string) { super(); this.code = 'EUNKNOWN'; this.name = 'JSONParserError'; this.message = message; this.source = source; this.path = null; Ono.extend(this); } get footprint() { return `${this.path}+${this.source}+${this.code}+${this.message}`; } } export class JSONParserErrorGroup extends Error { files: $RefParser; constructor(parser: $RefParser) { super(); this.files = parser; this.name = 'JSONParserErrorGroup'; this.message = `${this.errors.length} error${ this.errors.length > 1 ? 's' : '' } occurred while reading '${toFileSystemPath(parser.$refs._root$Ref!.path)}'`; Ono.extend(this); } static getParserErrors(parser: $RefParser) { const errors = []; for (const $ref of Object.values(parser.$refs._$refs) as $Ref[]) { if ($ref.errors) { errors.push(...$ref.errors); } } return errors; } get errors(): Array< | JSONParserError | InvalidPointerError | ResolverError | ParserError | MissingPointerError | UnmatchedParserError | UnmatchedResolverError > { return JSONParserErrorGroup.getParserErrors(this.files); } } export class ParserError extends JSONParserError { code = 'EPARSER' as JSONParserErrorType; name = 'ParserError'; constructor(message: any, source: any) { super(`Error parsing ${source}: ${message}`, source); } } export class UnmatchedParserError extends JSONParserError { code = 'EUNMATCHEDPARSER' as JSONParserErrorType; name = 'UnmatchedParserError'; constructor(source: string) { super(`Could not find parser for "${source}"`, source); } } export class ResolverError extends JSONParserError { code = 'ERESOLVER' as JSONParserErrorType; name = 'ResolverError'; ioErrorCode?: string; constructor(ex: Error | any, source?: string) { super(ex.message || `Error reading file "${source}"`, source); if ('code' in ex) { this.ioErrorCode = String(ex.code); } } } export class UnmatchedResolverError extends JSONParserError { code = 'EUNMATCHEDRESOLVER' as JSONParserErrorType; name = 'UnmatchedResolverError'; constructor(source: any) { super(`Could not find resolver for "${source}"`, source); } } export class MissingPointerError extends JSONParserError { code = 'EMISSINGPOINTER' as JSONParserErrorType; name = 'MissingPointerError'; constructor(token: string, path: string) { super( `Missing $ref pointer "${getHash(path)}". Token "${token}" does not exist.`, stripHash(path), ); } } export class TimeoutError extends JSONParserError { code = 'ETIMEOUT' as JSONParserErrorType; name = 'TimeoutError'; constructor(timeout: number) { super(`Dereferencing timeout reached: ${timeout}ms`); } } export class InvalidPointerError extends JSONParserError { code = 'EUNMATCHEDRESOLVER' as JSONParserErrorType; name = 'InvalidPointerError'; constructor(pointer: string, path: string) { super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, stripHash(path)); } } export function isHandledError(err: any): err is JSONParserError { return err instanceof JSONParserError || err instanceof JSONParserErrorGroup; } export function normalizeError(err: any) { if (err.path === null) { err.path = []; } return err; } ================================================ FILE: packages/json-schema-ref-parser/src/util/is-windows.ts ================================================ const isWindowsConst = /^win/.test(globalThis.process ? globalThis.process.platform : ''); export const isWindows = () => isWindowsConst; ================================================ FILE: packages/json-schema-ref-parser/src/util/plugins.ts ================================================ import type { FileInfo, JSONSchema, Plugin } from '../types'; export interface PluginResult { error?: any; plugin: Pick; result?: string | Buffer | JSONSchema; } /** * Runs the specified method of the given plugins, in order, until one of them returns a successful result. * Each method can return a synchronous value, a Promise, or call an error-first callback. * If the promise resolves successfully, or the callback is called without an error, then the result * is immediately returned and no further plugins are called. * If the promise rejects, or the callback is called with an error, then the next plugin is called. * If ALL plugins fail, then the last error is thrown. */ export async function run(plugins: Pick[], file: FileInfo) { let index = 0; let lastError: PluginResult; let plugin: Pick; return new Promise((resolve, reject) => { const runNextPlugin = async () => { plugin = plugins[index++]!; if (!plugin) { // there are no more functions, re-throw the last error return reject(lastError); } try { const result = await plugin.handler(file); if (result !== undefined) { return resolve({ plugin, result, }); } if (index === plugins.length) { throw new Error('No promise has been returned.'); } } catch (error) { lastError = { error, plugin, }; runNextPlugin(); } }; runNextPlugin(); }); } ================================================ FILE: packages/json-schema-ref-parser/src/util/url.ts ================================================ import path, { join, win32 } from 'node:path'; import convertPathToPosix from './convert-path-to-posix'; import { isWindows } from './is-windows'; const forwardSlashPattern = /\//g; const protocolPattern = /^(\w{2,}):\/\//i; // RegExp patterns to URL-encode special characters in local filesystem paths const urlEncodePatterns = [ [/\?/g, '%3F'], [/#/g, '%23'], ] as [RegExp, string][]; // RegExp patterns to URL-decode special characters for local filesystem paths const urlDecodePatterns = [/%23/g, '#', /%24/g, '$', /%26/g, '&', /%2C/g, ',', /%40/g, '@']; /** * Returns resolved target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF. * * @returns */ export function resolve(from: string, to: string) { const fromUrl = new URL(convertPathToPosix(from), 'resolve://'); const resolvedUrl = new URL(convertPathToPosix(to), fromUrl); const endSpaces = to.match(/(\s*)$/)?.[1] || ''; if (resolvedUrl.protocol === 'resolve:') { // `from` is a relative URL. const { hash, pathname, search } = resolvedUrl; return pathname + search + hash + endSpaces; } return resolvedUrl.toString() + endSpaces; } /** * Returns the current working directory (in Node) or the current page URL (in browsers). * * @returns */ export function cwd() { if (typeof window !== 'undefined') { return location.href; } const path = process.cwd(); const lastChar = path.slice(-1); if (lastChar === '/' || lastChar === '\\') { return path; } else { return path + '/'; } } /** * Returns the protocol of the given URL, or `undefined` if it has no protocol. * * @param path * @returns */ export function getProtocol(path: string | undefined) { const match = protocolPattern.exec(path || ''); if (match) { return match[1]!.toLowerCase(); } return undefined; } /** * Returns the lowercased file extension of the given URL, * or an empty string if it has no extension. * * @param path * @returns */ export function getExtension(path: any) { const lastDot = path.lastIndexOf('.'); if (lastDot > -1) { return stripQuery(path.substr(lastDot).toLowerCase()); } return ''; } /** * Removes the query, if any, from the given path. * * @param path * @returns */ export function stripQuery(path: any) { const queryIndex = path.indexOf('?'); if (queryIndex > -1) { path = path.substr(0, queryIndex); } return path; } /** * Returns the hash (URL fragment), of the given path. * If there is no hash, then the root hash ("#") is returned. * * @param path * @returns */ export function getHash(path: undefined | string) { if (!path) { return '#'; } const hashIndex = path.indexOf('#'); if (hashIndex > -1) { return path.substring(hashIndex); } return '#'; } /** * Removes the hash (URL fragment), if any, from the given path. * * @param path * @returns */ export function stripHash(path?: string | undefined) { if (!path) { return ''; } const hashIndex = path.indexOf('#'); if (hashIndex > -1) { path = path.substring(0, hashIndex); } return path; } /** * Determines whether the given path is a filesystem path. * This includes "file://" URLs. * * @param path * @returns */ export function isFileSystemPath(path: string | undefined) { // @ts-ignore if (typeof window !== 'undefined' || (typeof process !== 'undefined' && process.browser)) { // We're running in a browser, so assume that all paths are URLs. // This way, even relative paths will be treated as URLs rather than as filesystem paths return false; } const protocol = getProtocol(path); return protocol === undefined || protocol === 'file'; } /** * Converts a filesystem path to a properly-encoded URL. * * This is intended to handle situations where JSON Schema $Ref Parser is called * with a filesystem path that contains characters which are not allowed in URLs. * * @example * The following filesystem paths would be converted to the following URLs: * * <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json * C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json * file://Project #42/file.json ==> file://Project%20%2342/file.json * * @param path * @returns */ export function fromFileSystemPath(path: string) { // Step 1: On Windows, replace backslashes with forward slashes, // rather than encoding them as "%5C" if (isWindows()) { const projectDir = cwd(); const upperPath = path.toUpperCase(); const projectDirPosixPath = convertPathToPosix(projectDir); const posixUpper = projectDirPosixPath.toUpperCase(); const hasProjectDir = upperPath.includes(posixUpper); const hasProjectUri = upperPath.includes(posixUpper); const isAbsolutePath = win32.isAbsolute(path) || path.startsWith('http://') || path.startsWith('https://') || path.startsWith('file://'); if (!(hasProjectDir || hasProjectUri || isAbsolutePath) && !projectDir.startsWith('http')) { path = join(projectDir, path); } path = convertPathToPosix(path); } // Step 2: `encodeURI` will take care of MOST characters path = encodeURI(path); // Step 3: Manually encode characters that are not encoded by `encodeURI`. // This includes characters such as "#" and "?", which have special meaning in URLs, // but are just normal characters in a filesystem path. for (const pattern of urlEncodePatterns) { path = path.replace(pattern[0], pattern[1]); } return path; } /** * Converts a URL to a local filesystem path. */ export function toFileSystemPath(path: string | undefined, keepFileProtocol?: boolean): string { // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc. path = decodeURI(path!); // Step 2: Manually decode characters that are not decoded by `decodeURI`. // This includes characters such as "#" and "?", which have special meaning in URLs, // but are just normal characters in a filesystem path. for (let i = 0; i < urlDecodePatterns.length; i += 2) { path = path.replace(urlDecodePatterns[i]!, urlDecodePatterns[i + 1] as string); } // Step 3: If it's a "file://" URL, then format it consistently // or convert it to a local filesystem path let isFileUrl = path.substr(0, 7).toLowerCase() === 'file://'; if (isFileUrl) { // Strip-off the protocol, and the initial "/", if there is one path = path[7] === '/' ? path.substr(8) : path.substr(7); // insert a colon (":") after the drive letter on Windows if (isWindows() && path[1] === '/') { path = path[0] + ':' + path.substr(1); } if (keepFileProtocol) { // Return the consistently-formatted "file://" URL path = 'file:///' + path; } else { // Convert the "file://" URL to a local filesystem path. // On Windows, it will start with something like "C:/". // On Posix, it will start with "/" isFileUrl = false; path = isWindows() ? path : '/' + path; } } // Step 4: Normalize Windows paths (unless it's a "file://" URL) if (isWindows() && !isFileUrl) { // Replace forward slashes with backslashes path = path.replace(forwardSlashPattern, '\\'); // Capitalize the drive letter if (path.substr(1, 2) === ':\\') { path = path[0]!.toUpperCase() + path.substr(1); } } return path; } export function relative(from: string, to: string) { if (!isFileSystemPath(from) || !isFileSystemPath(to)) { return resolve(from, to); } const fromDir = path.dirname(stripHash(from)); const toPath = stripHash(to); const result = path.relative(fromDir, toPath); return result + getHash(to); } ================================================ FILE: packages/json-schema-ref-parser/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "composite": true, "outDir": "dist", "rootDir": "src", "types": ["vitest/globals"] }, "include": ["src"] } ================================================ FILE: packages/json-schema-ref-parser/tsdown.config.ts ================================================ import { defineConfig } from 'tsdown'; export default defineConfig({ clean: true, dts: true, entry: ['src/index.ts'], format: ['esm'], minify: false, sourcemap: true, treeshake: true, }); ================================================ FILE: packages/nuxt/CHANGELOG.md ================================================ # @hey-api/nuxt ## 0.2.1 ### Patch Changes - fix: update peer dependencies to be more permissible ([#2574](https://github.com/hey-api/openapi-ts/pull/2574)) ([`996021e`](https://github.com/hey-api/openapi-ts/commit/996021e4ce306ce762dfd55f2a7ec8099be4f24c)) by [@mrlubos](https://github.com/mrlubos) ## 0.2.0 ### Minor Changes - [#2175](https://github.com/hey-api/openapi-ts/pull/2175) [`6d56fa8`](https://github.com/hey-api/openapi-ts/commit/6d56fa8d80fd02c67746324b8edd6d008f788d67) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: remove `@hey-api/client-nuxt` dependency ## 0.1.7 ### Patch Changes - Updated dependencies [[`96cd12c`](https://github.com/hey-api/openapi-ts/commit/96cd12c87ca11a396e0df47771ceb1f9f20860d7)]: - @hey-api/client-nuxt@0.4.2 ## 0.1.6 ### Patch Changes - Updated dependencies [[`565e0b8`](https://github.com/hey-api/openapi-ts/commit/565e0b89fbab4556ecdc63dfe08250942681140e)]: - @hey-api/client-nuxt@0.4.1 ## 0.1.5 ### Patch Changes - [#1939](https://github.com/hey-api/openapi-ts/pull/1939) [`09bce36`](https://github.com/hey-api/openapi-ts/commit/09bce3644680a68ea91c9a1396d506b13709ae93) Thanks [@a1mersnow](https://github.com/a1mersnow)! - fix: avoid duplicate definition of `@hey-api/client-nuxt` plugin - [#1939](https://github.com/hey-api/openapi-ts/pull/1939) [`f46e241`](https://github.com/hey-api/openapi-ts/commit/f46e2419d8eaefea4eaff232f00ec770509afcb1) Thanks [@a1mersnow](https://github.com/a1mersnow)! - fix: skip watch mode in prepare step - Updated dependencies []: - @hey-api/client-nuxt@0.4.0 ## 0.1.4 ### Patch Changes - Updated dependencies [[`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248)]: - @hey-api/client-nuxt@0.4.0 ## 0.1.3 ### Patch Changes - Updated dependencies [[`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1)]: - @hey-api/client-nuxt@0.3.1 ## 0.1.2 ### Patch Changes - [#1825](https://github.com/hey-api/openapi-ts/pull/1825) [`0670a38`](https://github.com/hey-api/openapi-ts/commit/0670a38c66dffc1431a7d4b48ec06b72d4f6868f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: move @hey-api/openapi-ts to peerDependencies - Updated dependencies [[`c73b0d4`](https://github.com/hey-api/openapi-ts/commit/c73b0d401c2bfa6f0b0d89d844a6aa09f2685a69), [`90886c1`](https://github.com/hey-api/openapi-ts/commit/90886c1372a999e8cb59d5da218762f6ee6cd459)]: - @hey-api/openapi-ts@0.64.13 ## 0.1.1 ### Patch Changes - Updated dependencies [[`b9e1b4b`](https://github.com/hey-api/openapi-ts/commit/b9e1b4bec5e1c5d1f2b5b9cfc7fa145274ae604d)]: - @hey-api/openapi-ts@0.64.12 ## 0.1.0 ### Minor Changes - [#1800](https://github.com/hey-api/openapi-ts/pull/1800) [`d80f835`](https://github.com/hey-api/openapi-ts/commit/d80f835b46775a01451f02f832ceb288c2b561d2) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: initial release ### Patch Changes - Updated dependencies [[`a4811bd`](https://github.com/hey-api/openapi-ts/commit/a4811bdf178ec1a7f1602e0483a32fe7303f4eac), [`d80f835`](https://github.com/hey-api/openapi-ts/commit/d80f835b46775a01451f02f832ceb288c2b561d2), [`a4811bd`](https://github.com/hey-api/openapi-ts/commit/a4811bdf178ec1a7f1602e0483a32fe7303f4eac)]: - @hey-api/openapi-ts@0.64.11 - @hey-api/client-nuxt@0.3.0 ================================================ FILE: packages/nuxt/LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/nuxt/README.md ================================================
    Hey API logo

    Nuxt Module

    🚀 Nuxt module for @hey-api/openapi-ts codegen.

    ## Features - seamless integration with `@hey-api/openapi-ts` ecosystem - type-safe response data and errors - response data validation and transformation - access to the original request and response - granular request and response customization options - minimal learning curve thanks to extending the underlying technology - support bundling inside the generated output - [platform](https://heyapi.dev/openapi-ts/integrations) for automating codegen builds ## Dashboard Access your projects and OpenAPI specifications in the [Hey API Platform](https://app.heyapi.dev/). ## Contributing Want to see your code in products used by millions? Start with our [Contributing](https://heyapi.dev/openapi-ts/community/contributing) guide and release your first feature. ## Documentation Please visit our [website](https://heyapi.dev) for documentation, guides, migrating, and more. ## Sponsors Help Hey API stay around for the long haul by becoming a [sponsor](https://github.com/sponsors/hey-api).

    Gold

    Stainless logo
    Best-in-class developer interfaces for your API.
    stainless.com

    Opencode logo
    The open source coding agent.
    opencode.ai

    Mintlify logo
    The intelligent knowledge platform.
    mintlify.com

    Silver

    Scalar logo
    scalar.com
    FastAPI logo
    fastapi.tiangolo.com

    Bronze

    Kinde logo Cella logo
    ## Migrating You can learn more on the [Migrating](https://heyapi.dev/openapi-ts/migrating) page. ## License Released under the [MIT License](https://github.com/hey-api/openapi-ts/blob/main/LICENSE.md). ================================================ FILE: packages/nuxt/package.json ================================================ { "name": "@hey-api/nuxt", "version": "0.2.1", "description": "🚀 Nuxt module for `@hey-api/openapi-ts` codegen.", "keywords": [ "client", "codegen", "fetch", "http", "javascript", "nuxt", "openapi", "rest", "swagger", "typescript", "vue" ], "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "files": [ "dist", "LICENSE.md", "README.md" ], "type": "module", "sideEffects": false, "main": "./dist/module.cjs", "types": "./dist/types.d.ts", "exports": { ".": { "types": "./dist/types.d.ts", "import": "./dist/module.mjs", "require": "./dist/module.cjs" } }, "scripts": { "build": "nuxt-module-build build", "dev": "tsdown --watch", "prepack": "pnpm build", "prepublishOnly": "pnpm build" }, "dependencies": { "@nuxt/kit": "4.3.1", "defu": "6.1.4", "mlly": "1.8.0" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@nuxt/module-builder": "0.8.4", "@nuxt/schema": "3.16.2", "@nuxt/test-utils": "4.0.0", "vite": "7.3.1" }, "peerDependencies": { "@hey-api/openapi-ts": "<2", "nuxt": ">=3.0.0", "vue": ">=3.5.13" } } ================================================ FILE: packages/nuxt/src/module.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import type { UserConfig } from '@hey-api/openapi-ts'; import { createClient } from '@hey-api/openapi-ts'; import { addImportsSources, defineNuxtModule, useNuxt } from '@nuxt/kit'; import type {} from '@nuxt/schema'; import { defu } from 'defu'; import { findExports, findTypeExports } from 'mlly'; import { findPath } from 'nuxt/kit'; interface ModuleOptions { /** * Module alias. * * @default '#hey-api' */ alias?: string; /** * Automatically import all re-exported identifiers from the index file? * You may want to disable this option if the imported identifier names * clash with identifier names from other modules. * * @default true */ autoImport?: boolean; /** * `@hey-api/openapi-ts` configuration options. */ config: Omit & Partial>; } export default defineNuxtModule({ defaults: { alias: '#hey-api', autoImport: true, }, meta: { configKey: 'heyApi', name: '@hey-api/nuxt', }, async setup(options) { const nuxt = useNuxt(); const config = defu(options.config, { output: { path: path.join(nuxt.options.buildDir, 'client'), }, plugins: (options.config.plugins || []).some( (plugin: Required['plugins'][number]) => { const pluginName = typeof plugin === 'string' ? plugin : plugin.name; return pluginName === '@hey-api/client-nuxt'; }, ) ? [] : ['@hey-api/client-nuxt'], } satisfies Partial) as UserConfig; if (nuxt.options._prepare) { config.watch = false; } const output = config.output instanceof Array ? config.output[0] : config.output; const folder = path.resolve( nuxt.options.rootDir, typeof output === 'string' ? output : (output?.path ?? ''), ); nuxt.options.alias[options.alias!] = folder; nuxt.hooks.hookOnce('app:templates', async () => { await createClient(config); }); // auto-import enabled if (options.autoImport) { await createClient(config); const typeImports = new Set(); const valueImports = new Set(); const files = findExports(fs.readFileSync(path.join(folder, 'index.ts'), 'utf-8')); for (const file of files) { if (!file.specifier || !/^\.{1,2}\//.test(file.specifier)) { continue; } const filePath = await findPath(path.resolve(folder, file.specifier)); if (!filePath) { continue; } const blob = fs.readFileSync(filePath, 'utf-8'); for (const { names } of findTypeExports(blob)) { for (const name of names) { typeImports.add(name); } } for (const { names } of findExports(blob)) { for (const name of names) { valueImports.add(name); } } } const imports = [...[...typeImports].map((name) => ({ name, type: true })), ...valueImports]; if (imports.length && options.alias) { addImportsSources({ from: options.alias, imports, }); } } }, }) as any; ================================================ FILE: packages/nuxt/tsconfig.base.json ================================================ { "compilerOptions": { "declaration": true, "esModuleInterop": true, "module": "ESNext", "moduleResolution": "Bundler", "noImplicitOverride": true, "noUncheckedIndexedAccess": true, "noUnusedLocals": true, "strict": true, "target": "ES2022", "useUnknownInCatchVariables": false } } ================================================ FILE: packages/nuxt/tsconfig.json ================================================ { "extends": "./tsconfig.base.json", "compilerOptions": { "declaration": false, "esModuleInterop": true } } ================================================ FILE: packages/nuxt/vitest.config.ts ================================================ import { defineVitestProject } from '@nuxt/test-utils/config'; export default defineVitestProject({ test: { environment: 'nuxt', environmentOptions: { nuxt: { domEnvironment: 'jsdom', }, }, }, }); ================================================ FILE: packages/openapi-python/.gitignore ================================================ .DS_Store .idea .tsdown .tmp junit.xml logs node_modules npm-debug.log* temp *.iml dist coverage .env ================================================ FILE: packages/openapi-python/CHANGELOG.md ================================================ # @hey-api/openapi-python ## 0.0.12 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.2.5 - @hey-api/codegen-core@0.7.4 ## 0.0.11 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.2.4 - @hey-api/codegen-core@0.7.3 - @hey-api/types@0.1.4 ## 0.0.10 ### Patch Changes - **cli**: show environment value in development ([#3546](https://github.com/hey-api/openapi-ts/pull/3546)) ([`571bc8a`](https://github.com/hey-api/openapi-ts/commit/571bc8a32b55647083bb506d4a5b575c4736cb94)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.7.2 - @hey-api/shared@0.2.3 ## 0.0.9 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.2.2 - @hey-api/codegen-core@0.7.1 ## 0.0.8 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.2.1 - @hey-api/json-schema-ref-parser@1.3.1 ## 0.0.7 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.2.0 - @hey-api/json-schema-ref-parser@1.3.0 ## 0.0.6 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.1.2 - @hey-api/codegen-core@0.7.0 ## 0.0.5 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.1.2 - @hey-api/codegen-core@0.7.0 ## 0.0.4 ### Patch Changes ### Updated Dependencies: - @hey-api/codegen-core@0.6.1 - @hey-api/shared@0.1.1 ## 0.0.3 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.1.0 - @hey-api/codegen-core@0.6.0 - @hey-api/types@0.1.3 ## 0.0.2 ### Patch Changes ### Updated Dependencies: - @hey-api/types@0.1.2 - @hey-api/codegen-core@0.5.5 ================================================ FILE: packages/openapi-python/LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/openapi-python/README.md ================================================

    OpenAPI Python

    Coming soon. ================================================ FILE: packages/openapi-python/bin/run.cmd ================================================ @echo off node "%~dp0\run.js" %* ================================================ FILE: packages/openapi-python/bin/run.js ================================================ #!/usr/bin/env node import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const target = path.join(__dirname, '..', 'dist', 'run.mjs'); if (!fs.existsSync(target)) { console.error('openapi-python not built (expect dist/run.mjs)'); process.exit(1); } const res = spawnSync(process.execPath, [target, ...process.argv.slice(2)], { stdio: 'inherit', }); process.exit(res.status ?? 0); ================================================ FILE: packages/openapi-python/package.json ================================================ { "name": "@hey-api/openapi-python", "version": "0.0.12", "private": true, "description": "🐍 OpenAPI to Python codegen.", "keywords": [ "codegen", "generator", "http", "javascript", "json", "node", "openapi", "python", "rest", "swagger", "typescript", "yaml" ], "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "bin": { "openapi-python": "./bin/run.js" }, "files": [ "bin", "dist", "LICENSE.md", "README.md" ], "type": "module", "main": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "types": "./dist/index.d.mts", "import": "./dist/index.mjs" }, "./package.json": "./package.json" }, "scripts": { "build": "tsdown && pnpm check-exports", "check-exports": "attw --pack . --profile esm-only --ignore-rules cjs-resolves-to-esm", "dev": "tsdown --watch", "prepublishOnly": "pnpm build", "typecheck": "tsgo --noEmit", "typecheck:next": "tsc --noEmit && uv run mypy src/py-compiler/__snapshots__" }, "dependencies": { "@hey-api/codegen-core": "workspace:*", "@hey-api/json-schema-ref-parser": "workspace:*", "@hey-api/shared": "workspace:*", "@hey-api/types": "workspace:*", "ansi-colors": "4.1.3", "color-support": "1.1.3", "commander": "14.0.3" }, "devDependencies": { "eslint": "9.39.1", "typescript": "5.9.3", "yaml": "2.8.2" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-python/src/__tests__/index.test.ts ================================================ // import { createClient } from './index'; // type Config = Parameters[0]; describe('createClient', () => { it('works', () => { expect(true).toBe(true); }); // it('1 config, 1 input, 1 output', async () => { // const config: Config = { // dryRun: true, // input: { // info: { title: 'foo', version: '1.0.0' }, // openapi: '3.0.0', // }, // logs: { // level: 'silent', // }, // output: 'output', // plugins: ['@hey-api/sdk'], // }; // const results = await createClient(config); // expect(results).toHaveLength(1); // }); // it('1 config, 2 inputs, 1 output', async () => { // const config: Config = { // dryRun: true, // input: [ // { // info: { title: 'foo', version: '1.0.0' }, // openapi: '3.0.0', // }, // { // info: { title: 'bar', version: '1.0.0' }, // openapi: '3.0.0', // paths: {}, // }, // ], // logs: { // level: 'silent', // }, // output: 'output', // plugins: ['@hey-api/sdk'], // }; // const results = await createClient(config); // expect(results).toHaveLength(1); // }); // it('1 config, 2 inputs, 2 outputs', async () => { // const config: Config = { // dryRun: true, // input: [ // { // info: { title: 'foo', version: '1.0.0' }, // openapi: '3.0.0', // }, // { // info: { title: 'bar', version: '1.0.0' }, // openapi: '3.0.0', // paths: {}, // }, // ], // logs: { // level: 'silent', // }, // output: ['output', 'output2'], // plugins: ['@hey-api/sdk'], // }; // const results = await createClient(config); // expect(results).toHaveLength(2); // }); // it('2 configs, 1 input, 1 output', async () => { // const config: Config = [ // { // dryRun: true, // input: { // info: { title: 'foo', version: '1.0.0' }, // openapi: '3.0.0', // }, // logs: { // level: 'silent', // }, // output: 'output', // plugins: ['@hey-api/sdk'], // }, // { // dryRun: true, // input: { // info: { title: 'bar', version: '1.0.0' }, // openapi: '3.0.0', // }, // logs: { // level: 'silent', // }, // output: 'output2', // plugins: ['@hey-api/sdk'], // }, // ]; // const results = await createClient(config); // expect(results).toHaveLength(2); // }); // it('2 configs, 2 inputs, 2 outputs', async () => { // const config: Config = [ // { // dryRun: true, // input: [ // { // info: { title: 'foo', version: '1.0.0' }, // openapi: '3.0.0', // }, // { // info: { title: 'bar', version: '1.0.0' }, // openapi: '3.0.0', // paths: {}, // }, // ], // logs: { // level: 'silent', // }, // output: ['output', 'output2'], // plugins: ['@hey-api/sdk'], // }, // { // dryRun: true, // input: [ // { // info: { title: 'baz', version: '1.0.0' }, // openapi: '3.0.0', // }, // { // info: { title: 'qux', version: '1.0.0' }, // openapi: '3.0.0', // paths: {}, // }, // ], // logs: { // level: 'silent', // }, // output: ['output3', 'output4'], // plugins: ['@hey-api/sdk'], // }, // ]; // const results = await createClient(config); // expect(results).toHaveLength(4); // }); }); ================================================ FILE: packages/openapi-python/src/cli/adapter.ts ================================================ import type { ToArray } from '@hey-api/types'; import type { UserConfig } from '../config/types'; import type { CliOptions } from './schema'; export const cliToConfig = (cli: CliOptions): Partial => { const config: Partial = {}; if (cli.input) config.input = cli.input; if (cli.output) config.output = cli.output; if (cli.file) config.configFile = cli.file; if (cli.dryRun !== undefined) config.dryRun = cli.dryRun; const plugins: ToArray = []; if (cli.plugins instanceof Array && cli.plugins.length > 0) { plugins.push(...cli.plugins); } // if (cli.client) plugins.push(cli.client); if (plugins.length > 0) config.plugins = plugins; if (cli.debug || cli.silent || cli.logs || cli.logFile !== undefined) { config.logs = { ...(cli.logs && { path: cli.logs }), ...(cli.debug && { level: 'debug' as const }), ...(cli.silent && { level: 'silent' as const }), ...(cli.logFile !== undefined && { file: cli.logFile }), }; } if (cli.watch !== undefined) { if (typeof cli.watch === 'string') { config.watch = Number.parseInt(cli.watch, 10); } else { config.watch = cli.watch; } } return config; }; ================================================ FILE: packages/openapi-python/src/cli/index.ts ================================================ import { isEnvironment } from '@hey-api/shared'; import { Command, CommanderError } from 'commander'; import pkg from '../../package.json'; import { createClient } from '../index'; import { cliToConfig } from './adapter'; const binName = Object.keys(pkg.bin)[0]!; const program = new Command() .name(binName) .description('Generate Python code from OpenAPI specifications') .version(isEnvironment('development') ? '[DEVELOPMENT]' : pkg.version); program .option('-i, --input ', 'OpenAPI specification (path, URL, or string)') .option('-o, --output ', 'Output folder(s)') .option('-c, --client ', 'HTTP client to generate') .option('-p, --plugins [names...]', 'Plugins to use') .option('-f, --file ', 'Path to config file') .option('-d, --debug', 'Enable debug logging') .option('-s, --silent', 'Suppress all output') .option('-l, --logs ', 'Logs folder path') .option('--no-log-file', 'Disable log file output') .option('--dry-run', 'Skip writing files') .option('-w, --watch [interval]', 'Watch for changes') .action(async (options) => { const config = cliToConfig(options); const context = await createClient(config as Parameters[0]); const hasActiveWatch = context[0]?.config.input.some((input) => input.watch?.enabled); if (!hasActiveWatch) { process.exit(0); } }); export async function runCli(): Promise { try { await program.parseAsync(process.argv); } catch (error) { if (error instanceof CommanderError && 'code' in error) { if (error.code === 'commander.optionMissingArgument') { console.error(`\nMissing required argument. Run '${binName} --help' for usage.\n`); } else if (error.code === 'commander.unknownOption') { console.error(`\nUnknown option. Run '${binName} --help' for available options.\n`); } process.exit(error.exitCode); } console.error('Unexpected error:', error); process.exit(1); } } ================================================ FILE: packages/openapi-python/src/cli/schema.ts ================================================ import type { PluginNames } from '@hey-api/shared'; import type { MaybeArray } from '@hey-api/types'; import type { PluginClientNames } from '../plugins/types'; export interface CliOptions { client?: PluginClientNames; debug?: boolean; dryRun?: boolean; file?: string; input?: MaybeArray; logFile?: boolean; logs?: string; output?: MaybeArray; plugins?: ReadonlyArray; silent?: boolean; watch?: boolean | string; } ================================================ FILE: packages/openapi-python/src/config/expand.ts ================================================ import { getInput } from '@hey-api/shared'; import colors from 'ansi-colors'; import type { UserConfig } from './types'; export interface Job { config: UserConfig; index: number; } export function expandToJobs(configs: ReadonlyArray): ReadonlyArray { const jobs: Array = []; let jobIndex = 0; for (const config of configs) { const inputs = getInput(config); const outputs = config.output instanceof Array ? config.output : [config.output]; if (outputs.length === 1) { jobs.push({ config: { ...config, input: inputs, output: outputs[0]!, // output array with single item }, index: jobIndex++, }); } else if (outputs.length > 1 && inputs.length !== outputs.length) { // Warn and create job per output (all with same inputs) console.warn( `⚙️ ${colors.yellow('Warning:')} You provided ${colors.cyan(String(inputs.length))} ${colors.cyan(inputs.length === 1 ? 'input' : 'inputs')} and ${colors.yellow(String(outputs.length))} ${colors.yellow('outputs')}. This will produce identical output in multiple locations. You likely want to provide a single output or the same number of outputs as inputs.`, ); for (const output of outputs) { jobs.push({ config: { ...config, input: inputs, output }, index: jobIndex++, }); } } else if (outputs.length > 1) { // Pair inputs with outputs by index outputs.forEach((output, index) => { jobs.push({ config: { ...config, input: inputs[index]!, output }, index: jobIndex++, }); }); } } return jobs; } ================================================ FILE: packages/openapi-python/src/config/init.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { loadConfigFile } from '@hey-api/codegen-core'; import { expandToJobs } from './expand'; // import { getProjectDependencies } from './packages'; import type { ResolvedJob } from './resolve'; import { resolveConfig } from './resolve'; import type { UserConfig } from './types'; import { validateJobs } from './validate'; export type Configs = { dependencies: Record; jobs: ReadonlyArray; }; /** * @internal */ export async function resolveJobs({ logger, userConfigs, }: { logger: Logger; userConfigs: ReadonlyArray; }): Promise { const configs: Array = []; const dependencies: Record = {}; // let dependencies: Record = {}; const eventLoad = logger.timeEvent('load'); for (const userConfig of userConfigs) { let configFile: string | undefined; if (userConfig.configFile) { const parts = userConfig.configFile.split('.'); configFile = parts.slice(0, parts.length - 1).join('.'); } const loaded = await loadConfigFile({ configFile, logger, name: 'openapi-python', userConfig, }); if (!Object.keys(dependencies).length) { // TODO: handle dependencies for multiple configs properly? // TODO: collect Python dependencies // dependencies = getProjectDependencies( // loaded.foundConfig ? loaded.configFile : undefined, // ); } configs.push(...loaded.configs); } eventLoad.timeEnd(); const eventBuild = logger.timeEvent('build'); const jobs = validateJobs(expandToJobs(configs)); const resolvedJobs = jobs.map((validated) => resolveConfig(validated, dependencies)); eventBuild.timeEnd(); return { dependencies, jobs: resolvedJobs, }; } ================================================ FILE: packages/openapi-python/src/config/output/config.ts ================================================ import type { PostProcessor } from '@hey-api/shared'; import { resolveSource, valueToObject } from '@hey-api/shared'; import type { MaybeArray } from '@hey-api/types'; import { postProcessors } from './postprocess'; import type { Output, UserOutput } from './types'; export function getOutput(userConfig: { output: MaybeArray }): Output { if (userConfig.output instanceof Array) { throw new Error( 'Unexpected array of outputs in user configuration. This should have been expanded already.', ); } const userOutput = typeof userConfig.output === 'string' ? { path: userConfig.output } : (userConfig.output ?? {}); const output = valueToObject({ defaultValue: { clean: true, entryFile: true, fileName: { case: 'preserve', name: '{{name}}', suffix: '_gen', }, module: {}, path: '', postProcess: [], preferExportAll: false, }, mappers: { object: (fields, defaultValue) => ({ ...fields, fileName: valueToObject({ defaultValue: { ...(defaultValue.fileName as Extract< typeof defaultValue.fileName, Record >), }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: fields.fileName, }), }), }, value: userOutput, }) as Output; if (output.module.extension && !output.module.extension.startsWith('.')) { output.module.extension = `.${output.module.extension}`; } output.postProcess = normalizePostProcess(userOutput.postProcess); output.source = resolveSource(output); return output; } function normalizePostProcess(input: UserOutput['postProcess']): ReadonlyArray { if (!input) return []; return input.map((item) => { if (typeof item === 'string') { const preset = postProcessors[item]; if (!preset) { throw new Error(`Unknown post-processor preset: "${item}"`); } return preset; } return { name: item.name ?? item.command, ...item, }; }); } ================================================ FILE: packages/openapi-python/src/config/output/postprocess.ts ================================================ import type { PostProcessor } from '@hey-api/shared'; export const postProcessors = { autopep8: { args: ['--in-place', '{{path}}'], command: 'autopep8', name: 'autopep8', }, black: { args: ['{{path}}'], command: 'black', name: 'Black', }, isort: { args: ['{{path}}'], command: 'isort', name: 'isort', }, 'ruff:format': { args: ['format', '{{path}}'], command: 'ruff', name: 'Ruff (Format)', }, 'ruff:lint': { args: ['check', '--fix', '{{path}}'], command: 'ruff', name: 'Ruff (Lint)', }, yapf: { args: ['-i', '{{path}}'], command: 'yapf', name: 'YAPF', }, } as const satisfies Record; export type PostProcessorPreset = keyof typeof postProcessors; ================================================ FILE: packages/openapi-python/src/config/output/types.ts ================================================ import type { BaseOutput, BaseUserOutput, UserPostProcessor } from '@hey-api/shared'; import type { PostProcessorPreset } from './postprocess'; export type UserOutput = BaseUserOutput<'.py'> & { /** * Post-processing commands to run on the output folder, executed in order. * * Use preset strings for common tools, or provide custom configurations. * * @example ['ruff:lint', 'ruff:format'] * @example [{ command: 'flake8', args: ['{{path}}'] }] * * @default [] */ postProcess?: ReadonlyArray; /** * Whether `export * from 'module'` should be used when possible * instead of named exports. * * @default false */ preferExportAll?: boolean; }; export type Output = BaseOutput<'.py'> & { /** * Whether `export * from 'module'` should be used when possible * instead of named exports. */ preferExportAll: boolean; }; ================================================ FILE: packages/openapi-python/src/config/plugins.ts ================================================ import type { AnyPluginName, PluginContext, PluginNames } from '@hey-api/shared'; import { dependencyFactory, valueToObject } from '@hey-api/shared'; import { defaultPluginConfigs } from '../plugins/config'; import type { Config, UserConfig } from './types'; /** * Default plugins used to generate artifacts if plugins aren't specified. */ export const defaultPlugins = ['@hey-api/python-sdk'] as const satisfies ReadonlyArray; function getPluginsConfig({ dependencies, userPlugins, userPluginsConfig, }: { dependencies: Record; userPlugins: ReadonlyArray; userPluginsConfig: Config['plugins']; }): Pick { const circularReferenceTracker = new Set(); const pluginOrder = new Set(); const plugins: Config['plugins'] = {}; const dfs = (name: AnyPluginName) => { if (circularReferenceTracker.has(name)) { throw new Error(`Circular reference detected at '${name}'`); } if (pluginOrder.has(name)) { return; } circularReferenceTracker.add(name); const defaultPlugin = defaultPluginConfigs[name as PluginNames]; const userPlugin = userPluginsConfig[name as PluginNames]; if (!defaultPlugin && !userPlugin) { throw new Error( `unknown plugin dependency "${name}" - do you need to register a custom plugin with this name?`, ); } const plugin = { ...defaultPlugin, ...userPlugin, config: { ...defaultPlugin?.config, ...userPlugin?.config, }, dependencies: new Set([ ...(defaultPlugin?.dependencies || []), ...(userPlugin?.dependencies || []), ]), }; if (plugin.resolveConfig) { const context: PluginContext = { package: dependencyFactory(dependencies), pluginByTag: (tag, props = {}) => { const { defaultPlugin, errorMessage } = props; for (const userPlugin of userPlugins) { const defaultConfig = defaultPluginConfigs[userPlugin as PluginNames] || userPluginsConfig[userPlugin as PluginNames]; if (defaultConfig && defaultConfig.tags?.includes(tag) && userPlugin !== name) { return userPlugin as any; } } if (defaultPlugin) { const defaultConfig = defaultPluginConfigs[defaultPlugin as PluginNames] || userPluginsConfig[defaultPlugin as PluginNames]; if (defaultConfig && defaultConfig.tags?.includes(tag) && defaultPlugin !== name) { return defaultPlugin; } } throw new Error(errorMessage || `missing plugin - no plugin with tag "${tag}" found`); }, valueToObject, }; // @ts-expect-error plugin.resolveConfig(plugin, context); } for (const dependency of plugin.dependencies) { dfs(dependency); } circularReferenceTracker.delete(name); pluginOrder.add(name); // @ts-expect-error plugins[name] = plugin; }; for (const name of userPlugins) { dfs(name); } return { pluginOrder: Array.from(pluginOrder) as ReadonlyArray, plugins, }; } function isPluginClient(plugin: Required['plugins'][number]): boolean { if (typeof plugin === 'string') { return plugin.startsWith('@hey-api/client'); } return ( plugin.name.startsWith('@hey-api/client') || // @ts-expect-error (plugin.tags && plugin.tags.includes('client')) ); } export function getPlugins({ dependencies, userConfig, }: { dependencies: Record; userConfig: UserConfig; }): Pick { const userPluginsConfig: Config['plugins'] = {}; let definedPlugins: UserConfig['plugins'] = defaultPlugins; if (userConfig.plugins) { userConfig.plugins = userConfig.plugins.filter( (plugin) => (typeof plugin === 'string' && plugin) || (typeof plugin !== 'string' && plugin.name), ); if (userConfig.plugins.length === 1 && isPluginClient(userConfig.plugins[0]!)) { definedPlugins = [...defaultPlugins, ...userConfig.plugins]; } else { definedPlugins = userConfig.plugins; } } const userPlugins = definedPlugins .map((plugin) => { if (typeof plugin === 'string') { return plugin; } const pluginName = plugin.name; if (pluginName) { // @ts-expect-error if (plugin.handler) { // @ts-expect-error userPluginsConfig[pluginName] = plugin; } else { // @ts-expect-error userPluginsConfig[pluginName] = { config: { ...plugin }, }; // @ts-expect-error delete userPluginsConfig[pluginName]!.config.name; } } return pluginName; }) .filter(Boolean); return getPluginsConfig({ dependencies, userPlugins, userPluginsConfig }); } ================================================ FILE: packages/openapi-python/src/config/resolve.ts ================================================ import path from 'node:path'; import { detectInteractiveSession } from '@hey-api/codegen-core'; import { ConfigError, getInput, getLogs, getParser } from '@hey-api/shared'; import colors from 'ansi-colors'; import { getOutput } from './output/config'; import { getPlugins } from './plugins'; import type { Config } from './types'; import type { ValidationResult } from './validate'; export type ResolvedJob = { config: Config; errors: Array; index: number; }; export function resolveConfig( validated: ValidationResult, dependencies: Record, ): ResolvedJob { const logs = getLogs(validated.job.config.logs); const input = getInput(validated.job.config); const output = getOutput(validated.job.config); const parser = getParser(validated.job.config); output.path = path.resolve(process.cwd(), output.path); let plugins: Pick; try { plugins = getPlugins({ dependencies, userConfig: validated.job.config }); } catch (error) { if (error instanceof ConfigError) { validated.errors.push(error); } plugins = { pluginOrder: [], plugins: {}, }; } const config: Config = { configFile: validated.job.config.configFile ?? '', dryRun: validated.job.config.dryRun ?? false, input, interactive: validated.job.config.interactive ?? detectInteractiveSession(), logs, output, parser, pluginOrder: plugins.pluginOrder, plugins: plugins.plugins, }; if (logs.level === 'debug') { const jobPrefix = colors.gray(`[Job ${validated.job.index}] `); console.warn(`${jobPrefix}${colors.cyan('config:')}`, config); } return { config, errors: validated.errors, index: validated.job.index, }; } ================================================ FILE: packages/openapi-python/src/config/types.ts ================================================ import type { BaseConfig, BaseUserConfig, Plugin, PluginConfigMap, PluginNames, } from '@hey-api/shared'; import type { Output, UserOutput } from './output/types'; export type UserConfig = BaseUserConfig & { /** * Plugins generate artifacts from `input`. By default, we generate SDK * functions and TypeScript interfaces. If you manually define `plugins`, * you need to include the default plugins if you wish to use them. * * @default ['@hey-api/python-sdk'] */ plugins?: ReadonlyArray< | PluginNames | { [K in PluginNames]: PluginConfigMap[K]['config'] & { name: K; }; }[PluginNames] >; }; export type Config = BaseConfig & { pluginOrder: ReadonlyArray; plugins: { [K in PluginNames]?: Plugin.Config; }; }; ================================================ FILE: packages/openapi-python/src/config/utils.ts ================================================ import type { Context, PluginInstance } from '@hey-api/shared'; import type { Config } from './types'; export function getTypedConfig( plugin: Pick | Pick, ): Config { if ('context' in plugin) { return plugin.context.config as Config; } return plugin.config as Config; } ================================================ FILE: packages/openapi-python/src/config/validate.ts ================================================ import { ConfigError, getInput } from '@hey-api/shared'; import type { Job } from './expand'; import { getOutput } from './output/config'; export type ValidationResult = { errors: Array; job: Job; }; export function validateJobs(jobs: ReadonlyArray): ReadonlyArray { return jobs.map((job) => { const errors: Array = []; const { config } = job; const inputs = getInput(config); if (!inputs.length) { errors.push( new ConfigError( 'missing input - which OpenAPI specification should we use to generate your output?', ), ); } const output = getOutput(config); if (!output.path) { errors.push(new ConfigError('missing output - where should we generate your output?')); } return { errors, job }; }); } ================================================ FILE: packages/openapi-python/src/createClient.ts ================================================ import path from 'node:path'; import { type Logger, Project } from '@hey-api/codegen-core'; import { $RefParser } from '@hey-api/json-schema-ref-parser'; import { applyNaming, buildGraph, compileInputPath, Context, getSpec, type Input, logInputPaths, type OpenApi, parseOpenApiSpec, patchOpenApiSpec, postprocessOutput, type WatchValues, } from '@hey-api/shared'; import colors from 'ansi-colors'; import { postProcessors } from './config/output/postprocess'; import type { Config } from './config/types'; import { generateOutput } from './generate/output'; import { PythonRenderer } from './py-dsl'; export async function createClient({ config, dependencies, jobIndex, logger, watches: _watches, }: { config: Config; dependencies: Record; jobIndex: number; logger: Logger; /** * Always undefined on the first run, defined on subsequent runs. */ watches?: ReadonlyArray; }): Promise { const watches: ReadonlyArray = _watches || Array.from({ length: config.input.length }, () => ({ headers: new Headers(), })); const inputPaths = config.input.map((input) => compileInputPath(input)); // on first run, print the message as soon as possible if (config.logs.level !== 'silent' && !_watches) { logInputPaths(inputPaths, jobIndex); } const getSpecData = async (input: Input, index: number) => { const eventSpec = logger.timeEvent('spec'); const { arrayBuffer, error, resolvedInput, response } = await getSpec({ fetchOptions: input.fetch, inputPath: inputPaths[index]!.path, timeout: input.watch.timeout, watch: watches[index]!, }); eventSpec.timeEnd(); // throw on first run if there's an error to preserve user experience // if in watch mode, subsequent errors won't throw to gracefully handle // cases where server might be reloading if (error && !_watches) { const text = await response.text().catch(() => ''); throw new Error( `Request failed with status ${response.status}: ${text || response.statusText}`, ); } return { arrayBuffer, resolvedInput }; }; const specData = ( await Promise.all(config.input.map((input, index) => getSpecData(input, index))) ).filter((data) => data.arrayBuffer || data.resolvedInput); let context: Context | undefined; if (specData.length) { const refParser = new $RefParser(); const data = specData.length > 1 ? await refParser.bundleMany({ arrayBuffer: specData.map((data) => data.arrayBuffer!), pathOrUrlOrSchemas: [], resolvedInputs: specData.map((data) => data.resolvedInput!), }) : await refParser.bundle({ arrayBuffer: specData[0]!.arrayBuffer, pathOrUrlOrSchema: undefined, resolvedInput: specData[0]!.resolvedInput!, }); // on subsequent runs in watch mode, print the message only if we know we're // generating the output if (config.logs.level !== 'silent' && _watches) { console.clear(); logInputPaths(inputPaths, jobIndex); } const eventInputPatch = logger.timeEvent('input.patch'); await patchOpenApiSpec({ patchOptions: config.parser.patch, spec: data }); eventInputPatch.timeEnd(); const eventParser = logger.timeEvent('parser'); const header = config.output.header; // TODO: allow overriding via config const project = new Project({ defaultFileName: '__init__', fileName: (base) => { const name = applyNaming(base, config.output.fileName); const { suffix } = config.output.fileName; if (!suffix) { return name; } return name === '__init__' || name.endsWith(suffix) ? name : `${name}${suffix}`; }, nameConflictResolvers: config.output.nameConflictResolver ? { python: config.output.nameConflictResolver, } : undefined, renderers: [ new PythonRenderer({ header: (ctx) => { const defaultValue = ['# This file is auto-generated by @hey-api/openapi-python']; const result = typeof header === 'function' ? header({ ...ctx, defaultValue }) : header; return result === undefined ? defaultValue : result; }, module: config.output.module, preferExportAll: config.output.preferExportAll, }), ], root: config.output.path, }); context = new Context({ config, dependencies, logger, project, spec: data as OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X, }); parseOpenApiSpec(context); context.graph = buildGraph(context.ir, logger).graph; eventParser.timeEnd(); const eventGenerator = logger.timeEvent('generator'); await generateOutput(context); eventGenerator.timeEnd(); const eventPostprocess = logger.timeEvent('postprocess'); if (!config.dryRun) { const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `); postprocessOutput(config.output, postProcessors, jobPrefix); if (config.logs.level !== 'silent') { const outputPath = process.env.INIT_CWD ? `./${path.relative(process.env.INIT_CWD, config.output.path)}` : config.output.path; console.log( `${jobPrefix}${colors.green('✅ Done!')} Your output is in ${colors.cyanBright(outputPath)}`, ); } } eventPostprocess.timeEnd(); } const watchedInput = config.input.find( (input, index) => input.watch.enabled && typeof inputPaths[index]!.path === 'string', ); if (watchedInput) { setTimeout(() => { createClient({ config, dependencies, jobIndex, logger, watches, }); }, watchedInput.watch.interval); } return context; } ================================================ FILE: packages/openapi-python/src/generate/client.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { IProject } from '@hey-api/codegen-core'; import type { DefinePlugin, OutputHeader } from '@hey-api/shared'; import { ensureDirSync, isEnvironment, outputHeaderToPrefix } from '@hey-api/shared'; import type { Config } from '../config/types'; import type { Client } from '../plugins/@hey-api/client-core/types'; import { getClientPlugin } from '../plugins/@hey-api/client-core/utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); /** * Returns paths to client bundle files based on execution context */ function getClientBundlePaths(pluginName: string): { clientPath: string; corePath: string; } { const clientName = pluginName.slice('@hey-api/client-'.length); if (isEnvironment('development')) { // Dev: source bundle folders at src/plugins/@hey-api/{client}/bundle const pluginsDir = path.resolve(__dirname, '..', 'plugins', '@hey-api'); return { clientPath: path.resolve(pluginsDir, `client-${clientName}`, 'bundle'), corePath: path.resolve(pluginsDir, 'client-core', 'bundle'), }; } // Prod: copied to dist/clients/{clientName} return { clientPath: path.resolve(__dirname, 'clients', clientName), corePath: path.resolve(__dirname, 'clients', 'core'), }; } /** * Returns absolute path to the client folder. This is hard-coded for now. */ export function clientFolderAbsolutePath(config: Config): string { const client = getClientPlugin(config); if ('bundle' in client.config && client.config.bundle) { // not proud of this one const renamed: Map | undefined = // @ts-expect-error config._FRAGILE_CLIENT_BUNDLE_RENAMED; return path.resolve(config.output.path, 'client', `${renamed?.get('index') ?? 'index'}.py`); } return client.name; } /** * Recursively copies files and directories. * This is a PnP-compatible alternative to fs.cpSync that works with Yarn PnP's * virtualized filesystem. */ function copyRecursivePnP(src: string, dest: string): void { const stat = fs.statSync(src); if (stat.isDirectory()) { if (!fs.existsSync(dest)) { fs.mkdirSync(dest, { recursive: true }); } const files = fs.readdirSync(src); for (const file of files) { copyRecursivePnP(path.join(src, file), path.join(dest, file)); } } else { const content = fs.readFileSync(src); fs.writeFileSync(dest, content); } } function renameFile({ filePath, project, renamed, }: { filePath: string; project: IProject; renamed: Map; }): void { const extension = path.extname(filePath); const name = path.basename(filePath, extension); const renamedName = project.fileName?.(name) || name; if (renamedName !== name) { const outputPath = path.dirname(filePath); fs.renameSync(filePath, path.resolve(outputPath, `${renamedName}${extension}`)); renamed.set(name, renamedName); } } function replaceImports({ filePath, header, renamed, }: { filePath: string; header?: string; renamed: Map; }): void { let content = fs.readFileSync(filePath, 'utf8'); // Dev mode: rewrite source bundle imports to match output structure if (isEnvironment('development')) { // ...client_core.bundle.foo -> ..core.foo content = content.replace( /from\s+(\.{3,})\.?client_core\.bundle\./g, (match, dots) => `from ${dots === '...' ? '..' : dots.slice(0, -1)}core.`, ); // ...client_core.bundle (index import) -> ..core content = content.replace( /from\s+(\.{3,})\.?client_core\.bundle['"]?/g, (match, dots) => `from ${dots === '...' ? '..' : dots.slice(0, -1)}core`, ); } content = content.replace(/from\s+(.+?)\s+import/g, (match, importPath) => { const cleanPath = importPath.replace(/^['"]|['"]$/g, ''); if (!cleanPath.startsWith('.')) return match; const leadingDots = cleanPath.match(/^\.+/)?.[0] || ''; const moduleName = cleanPath.replace(/^\.+/, ''); if (!moduleName) return match; const replacedName = renamed.get(moduleName) ?? moduleName; return `from ${leadingDots}${replacedName} import`; }); const fileHeader = header ?? ''; content = `${fileHeader}${content}`; fs.writeFileSync(filePath, content, 'utf8'); } /** * Creates a `client` folder containing the same modules as the client package. */ export function generateClientBundle({ header, outputPath, plugin, project, }: { header?: OutputHeader; outputPath: string; plugin: DefinePlugin['Config']; project: IProject; }): Map | undefined { const renamed = new Map(); const headerPrefix = outputHeaderToPrefix({ defaultValue: ['# This file is auto-generated by @hey-api/openapi-python'], header, project, }); // copy Hey API clients to output const isHeyApiClientPlugin = plugin.name.startsWith('@hey-api/client-'); if (isHeyApiClientPlugin) { const { clientPath } = getClientBundlePaths(plugin.name); // const { clientPath, corePath } = getClientBundlePaths(plugin.name); // copy client core // const coreOutputPath = path.resolve(outputPath, 'core'); // ensureDirSync(coreOutputPath); // copyRecursivePnP(corePath, coreOutputPath); // copy client bundle const clientOutputPath = path.resolve(outputPath, 'client'); ensureDirSync(clientOutputPath); copyRecursivePnP(clientPath, clientOutputPath); if (project) { // const copiedCoreFiles = fs.readdirSync(coreOutputPath); // for (const file of copiedCoreFiles) { // renameFile({ // filePath: path.resolve(coreOutputPath, file), // project, // renamed, // }); // } const copiedClientFiles = fs.readdirSync(clientOutputPath); for (const file of copiedClientFiles) { renameFile({ filePath: path.resolve(clientOutputPath, file), project, renamed, }); } } // const coreFiles = fs.readdirSync(coreOutputPath); // for (const file of coreFiles) { // replaceImports({ // filePath: path.resolve(coreOutputPath, file), // renamed, // }); // } const clientFiles = fs.readdirSync(clientOutputPath); for (const file of clientFiles) { replaceImports({ filePath: path.resolve(clientOutputPath, file), header: headerPrefix, renamed, }); } return renamed; } const clientSrcPath = path.isAbsolute(plugin.name) ? path.dirname(plugin.name) : undefined; // copy custom local client to output if (clientSrcPath) { const dirPath = path.resolve(outputPath, 'client'); ensureDirSync(dirPath); copyRecursivePnP(clientSrcPath, dirPath); return; } // copy third-party client to output const clientModulePath = path.normalize(require.resolve(plugin.name)); const clientModulePathComponents = clientModulePath.split(path.sep); const clientDistPath = clientModulePathComponents .slice(0, clientModulePathComponents.indexOf('dist') + 1) .join(path.sep); const indexJsFile = clientModulePathComponents[clientModulePathComponents.length - 1]; const distFiles = [indexJsFile!, 'index.d.mts', 'index.d.cts']; const dirPath = path.resolve(outputPath, 'client'); ensureDirSync(dirPath); for (const file of distFiles) { fs.copyFileSync(path.resolve(clientDistPath, file), path.resolve(dirPath, file)); } return; } ================================================ FILE: packages/openapi-python/src/generate/output.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import type { Context } from '@hey-api/shared'; import { IntentContext } from '@hey-api/shared'; import { getTypedConfig } from '../config/utils'; import { getClientPlugin } from '../plugins/@hey-api/client-core/utils'; import { generateClientBundle } from './client'; export async function generateOutput(context: Context): Promise { const outputPath = path.resolve(context.config.output.path); if (context.config.output.clean) { if (fs.existsSync(outputPath)) { fs.rmSync(outputPath, { force: true, recursive: true }); } } const config = getTypedConfig(context); const client = getClientPlugin(config); if ('bundle' in client.config && client.config.bundle && !config.dryRun) { // not proud of this one // @ts-expect-error config._FRAGILE_CLIENT_BUNDLE_RENAMED = generateClientBundle({ header: config.output.header, outputPath, // @ts-expect-error plugin: client, project: context.gen, }); } for (const plugin of context.registerPlugins()) { await plugin.run(); } context.gen.plan(); const ctx = new IntentContext(context.spec); for (const intent of context.intents) { await intent.run(ctx); } for (const file of context.gen.render()) { const filePath = path.resolve(outputPath, file.path); const dir = path.dirname(filePath); if (!context.config.dryRun) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(filePath, file.content, { encoding: 'utf8' }); } } const { source } = context.config.output; if (source.enabled) { const sourcePath = source.path === null ? undefined : path.resolve(outputPath, source.path); if (!context.config.dryRun && sourcePath && sourcePath !== outputPath) { fs.mkdirSync(sourcePath, { recursive: true }); } const serialized = await source.serialize(context.spec); // TODO: handle yaml (convert before writing) if (!context.config.dryRun && sourcePath) { fs.writeFileSync( path.resolve(sourcePath, `${source.fileName}.${source.extension}`), serialized, { encoding: 'utf8' }, ); } if (source.callback) { await source.callback(serialized); } } } ================================================ FILE: packages/openapi-python/src/generate.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { Logger } from '@hey-api/codegen-core'; import type { Context } from '@hey-api/shared'; import { checkNodeVersion, ConfigValidationError, getLogs, JobError, logCrashReport, openGitHubIssueWithCrashReport, printCliIntro, printCrashReport, shouldReportCrash, } from '@hey-api/shared'; import type { LazyOrAsync, MaybeArray } from '@hey-api/types'; import type { Configs } from './config/init'; import { resolveJobs } from './config/init'; import type { UserConfig } from './config/types'; import { createClient as pCreateClient } from './createClient'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); /** * Generate a client from the provided configuration. * * @param userConfig User provided {@link UserConfig} configuration(s). */ export async function createClient( userConfig?: LazyOrAsync>, logger = new Logger(), ): Promise> { const resolvedConfig = typeof userConfig === 'function' ? await userConfig() : userConfig; const userConfigs = resolvedConfig ? resolvedConfig instanceof Array ? resolvedConfig : [resolvedConfig] : []; let rawLogs = userConfigs.find((config) => getLogs(config.logs).level !== 'silent')?.logs; if (typeof rawLogs === 'string') { rawLogs = getLogs(rawLogs); } let jobs: Configs['jobs'] = []; try { checkNodeVersion(); const eventCreateClient = logger.timeEvent('createClient'); const eventConfig = logger.timeEvent('config'); const resolved = await resolveJobs({ logger, userConfigs }); const dependencies = resolved.dependencies; jobs = resolved.jobs; const printIntro = jobs.some((job) => job.config.logs.level !== 'silent'); if (printIntro) printCliIntro(__dirname); eventConfig.timeEnd(); const configErrors = jobs.flatMap((job) => job.errors.map((error) => ({ error, jobIndex: job.index })), ); if (configErrors.length > 0) { throw new ConfigValidationError(configErrors); } const outputs = await Promise.all( jobs.map(async (job) => { try { return await pCreateClient({ config: job.config, dependencies, jobIndex: job.index, logger, }); } catch (error) { if (error instanceof Error) { throw new JobError('', { error, jobIndex: job.index, }); } } }), ); const contexts = outputs.filter((ctx): ctx is Context => ctx !== undefined); eventCreateClient.timeEnd(); logger.report(jobs.some((job) => job.config.logs.level === 'debug')); return contexts; } catch (error) { const logs = jobs.find((job) => job.config.logs.level !== 'silent')?.config.logs ?? jobs[0]?.config.logs ?? rawLogs; const dryRun = jobs.some((job) => job.config.dryRun) ?? userConfigs.some((config) => config.dryRun) ?? false; const logPath = logs?.file && !dryRun ? logCrashReport(error, logs.path ?? '') : undefined; if (!logs || logs.level !== 'silent') { printCrashReport({ error, logPath }); const isInteractive = jobs.some((job) => job.config.interactive) ?? userConfigs.some((config) => config.interactive) ?? false; if (await shouldReportCrash({ error, isInteractive })) { await openGitHubIssueWithCrashReport(error, __dirname); } } throw error; } } ================================================ FILE: packages/openapi-python/src/index.ts ================================================ /* eslint-disable @typescript-eslint/no-namespace */ // OVERRIDES // hard-coded here because build process doesn't pick up overrides from separate files import '@hey-api/codegen-core'; import '@hey-api/shared'; declare module '@hey-api/codegen-core' { interface ProjectRenderMeta { /** * If specified, this will be the file extension used when importing * other modules. By default, we don't add a file extension and let the * runtime resolve it. * * @default null */ importFileExtension?: AnyString | null; } interface SymbolMeta { category?: | 'client' | 'external' | 'hook' | 'schema' | 'sdk' | 'transform' | 'type' | 'utility' | AnyString; /** * Path to the resource this symbol represents. */ path?: ReadonlyArray; /** * Name of the plugin that registered this symbol. */ pluginName?: string; resource?: 'client' | 'definition' | 'operation' | 'webhook' | AnyString; resourceId?: string; role?: 'data' | 'error' | 'errors' | 'options' | 'response' | 'responses' | AnyString; /** * Tags associated with this symbol. */ tags?: ReadonlyArray; tool?: 'pydantic' | 'sdk' | AnyString; variant?: 'container' | AnyString; } } declare module '@hey-api/shared' { interface PluginConfigMap { '@hey-api/client-httpx': Plugins.HeyApiClientHttpx.Types['Types']; '@hey-api/python-sdk': Plugins.HeyApiSdk.Types['Types']; pydantic: Plugins.Pydantic.Types['Types']; } } // END OVERRIDES import type { AnyString, LazyOrAsync, MaybeArray } from '@hey-api/types'; import colors from 'ansi-colors'; // @ts-expect-error import colorSupport from 'color-support'; import type { UserConfig } from './config/types'; import type { HeyApiClientHttpxPlugin } from './plugins/@hey-api/client-httpx'; import type { HeyApiSdkPlugin } from './plugins/@hey-api/sdk'; import type { PydanticPlugin, PydanticResolvers } from './plugins/pydantic'; colors.enabled = colorSupport().hasBasic; export { createClient } from './generate'; /** * Type helper for configuration object, returns {@link MaybeArray} object(s) */ export function defineConfig( config: LazyOrAsync>, ): Promise>; export function defineConfig(config: LazyOrAsync): Promise; export async function defineConfig>( config: LazyOrAsync, ): Promise { return typeof config === 'function' ? await config() : config; } export { defaultPlugins } from './config/plugins'; export type { UserConfig } from './config/types'; export { Logger } from '@hey-api/codegen-core'; export type { DefinePlugin, IR, OpenApi, OpenApiMetaObject, OpenApiOperationObject, OpenApiParameterObject, OpenApiRequestBodyObject, OpenApiResponseObject, OpenApiSchemaObject, Plugin, } from '@hey-api/shared'; export { defaultPaginationKeywords, definePluginConfig, OperationPath, OperationStrategy, utils, } from '@hey-api/shared'; export namespace Plugins { export namespace HeyApiClientHttpx { export type Types = HeyApiClientHttpxPlugin; } export namespace HeyApiSdk { export type Types = HeyApiSdkPlugin; } export namespace Pydantic { export type Resolvers = Required['~resolvers']; export type Types = PydanticPlugin; } } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-core/config.ts ================================================ export const clientDefaultConfig = { baseUrl: true, bundle: true, includeInEntry: false, } as const; export const clientDefaultMeta = { tags: ['client'], } as const; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-core/types.ts ================================================ /* eslint-disable @typescript-eslint/no-namespace */ import type { Plugin } from '@hey-api/shared'; import type { HeyApiClientHttpxPlugin } from '../../../plugins/@hey-api/client-httpx'; export interface PluginHandler { (...args: Parameters): void; } /** * Public Client API. */ export namespace Client { export type Config = Plugin.Hooks & Plugin.UserExports & { /** * Set a default base URL when creating the client? You can set `baseUrl` * to a string which will be used as the base URL. If your input defines * server(s), you can set `baseUrl` to a number to pick a specific server * to use as the base URL. You can disable setting the base URL by setting * `baseUrl` to `false`. By default, `baseUrl` is `true` and it will try to * use the first defined server value. If there's none, we won't set a * base URL. * * If the matched URL contains template literals, it will be ignored. * * @default true */ baseUrl?: string | number | boolean; /** * Bundle the client module? When `true`, the client module will be copied * from the client plugin and bundled with the generated output. * * @default true */ bundle?: boolean; /** * Relative path to the runtime configuration file. This file must export * a `createClientConfig()` function. The `createClientConfig()` function * will be called on client initialization and the returned object will * become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ runtimeConfigPath?: string; /** * Should the type helper for base URL allow only values matching the * server(s) defined in the input? By default, `strictBaseUrl` is `false` * which will provide type hints and allow you to pass any string. * * Note that setting `strictBaseUrl` to `true` can produce an invalid * build if you specify `baseUrl` which doesn't conform to the type helper. * * @default false */ strictBaseUrl?: boolean; }; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-core/utils.ts ================================================ import type { Config } from '../../../config/types'; import type { PluginClientNames } from '../../types'; export function getClientPlugin( config: Config, ): Config['plugins'][PluginClientNames] & { name: PluginClientNames } { for (const name of config.pluginOrder) { const plugin = config.plugins[name]; if (plugin?.tags?.includes('client')) { return plugin as Config['plugins'][PluginClientNames] & { name: PluginClientNames; }; } } return { config: { // @ts-expect-error name: '', }, // @ts-expect-error name: '', }; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-httpx/bundle/__init__.py ================================================ from .client import Client, build_client_params, create_client __all__ = ["Client", "build_client_params", "create_client"] ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-httpx/bundle/client.py ================================================ from typing import Any, Optional import httpx EXTRA_PREFIXES_MAP = { "$body_": "json", "$headers_": "headers", "$path_": "path", "$query_": "params", } def build_client_params(fields: list[dict[str, Any]], **kwargs) -> dict[str, Any]: """Build client parameters from flat keyword arguments. Args: fields: List of field configurations with 'in', 'key', and optional 'map'. **kwargs: Flat parameters passed to the SDK method. Returns: Dict suitable for httpx client methods: {params: {...}, headers: {...}, json: Any} """ result: dict[str, Any] = {} key_map = {} for field in fields: key = field.get("key") if key: key_map[key] = { "in": field.get("in"), "map": field.get("map", key), } for key, value in kwargs.items(): if value is None: continue field = key_map.get(key) if field: in_slot = field["in"] map_key = field["map"] slot = "json" if in_slot == "body" else in_slot if in_slot == "body": result[slot] = value else: if slot not in result: result[slot] = {} result[slot][map_key] = value else: for prefix, slot in EXTRA_PREFIXES_MAP.items(): if key.startswith(prefix): actual_key = key[len(prefix) :] if slot not in result: result[slot] = {} result[slot][actual_key] = value break else: if "params" not in result: result["params"] = {} result["params"][key] = value for slot in list(result.keys()): if not result[slot]: del result[slot] return result class BaseClient: """Base HTTP client using httpx that SDK classes extend.""" def __init__(self, client: Optional[httpx.Client] = None, base_url: Optional[str] = None, **kwargs): if client is not None: self._client = client else: self._client = httpx.Client(base_url=base_url or "", **kwargs) @property def client(self) -> httpx.Client: """Get the httpx client instance.""" return self._client def request(self, method: str, url: str, **kwargs) -> httpx.Response: """Make an HTTP request.""" return self._client.request(method, url, **kwargs) def get(self, url: str, **kwargs) -> httpx.Response: """Make a GET request.""" return self._client.get(url, **kwargs) def post(self, url: str, **kwargs) -> httpx.Response: """Make a POST request.""" return self._client.post(url, **kwargs) def put(self, url: str, **kwargs) -> httpx.Response: """Make a PUT request.""" return self._client.put(url, **kwargs) def patch(self, url: str, **kwargs) -> httpx.Response: """Make a PATCH request.""" return self._client.patch(url, **kwargs) def delete(self, url: str, **kwargs) -> httpx.Response: """Make a DELETE request.""" return self._client.delete(url, **kwargs) def close(self): """Close the client.""" self._client.close() def __enter__(self): return self def __exit__(self, *args): self.close() class Client(BaseClient): """HTTP client using httpx (alias for BaseClient).""" pass def create_client(base_url: Optional[str] = None, **kwargs) -> Client: """Create a new HTTP client instance.""" return Client(base_url=base_url, **kwargs) ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-httpx/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta } from '../client-core/config'; import type { HeyApiClientHttpxPlugin } from './types'; export const defaultConfig: HeyApiClientHttpxPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler() { // TODO: handler }, name: '@hey-api/client-httpx', }; /** * Type helper for `@hey-api/client-httpx` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-httpx/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientHttpxPlugin } from './types'; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/client-httpx/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@hey-api/client-httpx'> & { /** * Set a default base URL when creating the client? You can set `baseUrl` * to a string which will be used as the base URL. If your input defines * server(s), you can set `baseUrl` to a number to pick a specific server * to use as the base URL. You can disable setting the base URL by setting * `baseUrl` to `false`. By default, `baseUrl` is `true` and it will try to * use the first defined server value. If there's none, we won't set a * base URL. * * If the matched URL contains template literals, it will be ignored. * * @default true */ baseUrl?: string | number | boolean; }; export type Config = Plugin.Name<'@hey-api/client-httpx'> & { baseUrl: string | number | boolean; }; export type HeyApiClientHttpxPlugin = DefinePlugin; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { resolveOperations } from './operations'; import { handler } from './plugin'; import type { HeyApiSdkPlugin } from './types'; export const defaultConfig: HeyApiSdkPlugin['Config'] = { config: { // auth: true, client: true, comments: true, includeInEntry: true, paramsStructure: 'grouped', // responseStyle: 'fields', // transformer: false, // validator: false, }, dependencies: ['pydantic'], handler, name: '@hey-api/python-sdk', resolveConfig: (plugin, context) => { if (plugin.config.client) { if (typeof plugin.config.client === 'boolean') { plugin.config.client = context.pluginByTag('client', { defaultPlugin: '@hey-api/client-httpx', }); } plugin.dependencies.add(plugin.config.client!); } else { plugin.config.client = false; } // if (plugin.config.transformer) { // if (typeof plugin.config.transformer === 'boolean') { // plugin.config.transformer = context.pluginByTag('transformer'); // } // plugin.dependencies.add(plugin.config.transformer!); // } else { // plugin.config.transformer = false; // } // if (typeof plugin.config.validator !== 'object') { // plugin.config.validator = { // request: plugin.config.validator, // response: plugin.config.validator, // }; // } // if (plugin.config.validator.request) { // if (typeof plugin.config.validator.request === 'boolean') { // plugin.config.validator.request = context.pluginByTag('validator'); // } // plugin.dependencies.add(plugin.config.validator.request!); // } else { // plugin.config.validator.request = false; // } // if (plugin.config.validator.response) { // if (typeof plugin.config.validator.response === 'boolean') { // plugin.config.validator.response = context.pluginByTag('validator'); // } // plugin.dependencies.add(plugin.config.validator.response!); // } else { // plugin.config.validator.response = false; // } // plugin.config.examples = resolveExamples(plugin.config, context); plugin.config.operations = resolveOperations(plugin.config, context); }, }; /** * Type helper for `@hey-api/python-sdk` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/examples/config.ts ================================================ import type { PluginContext } from '@hey-api/shared'; import type { UserConfig } from '../types'; import type { ExamplesConfig } from './types'; type Config = Omit; export function resolveExamples(config: Config, context: PluginContext): ExamplesConfig { return context.valueToObject({ defaultValue: { enabled: Boolean(config.examples), language: 'Python', }, mappers: { boolean: (enabled) => ({ enabled }), }, value: config.examples, }) as ExamplesConfig; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/examples/index.ts ================================================ export { resolveExamples } from './config'; export type { ExamplesConfig, UserExamplesConfig } from './types'; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/examples/types.ts ================================================ import type { FeatureToggle, IR, LinguistLanguages } from '@hey-api/shared'; import type { MaybeFunc } from '@hey-api/types'; import type { CallArgs, DollarPyDsl, ExampleOptions } from '../../../../py-dsl'; export type UserExamplesConfig = Omit & { /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * The programming language for the generated examples. * * This is used to display the language label in code blocks in * documentation UIs. * * @default 'Python' */ language?: LinguistLanguages; /** * Example request payload. */ payload?: MaybeFunc< (operation: IR.OperationObject, ctx: DollarPyDsl) => CallArgs | CallArgs[number] >; /** * Transform the generated example string. * * @param example The generated example string. * @param operation The operation the example was generated for. * @returns The final example string. */ transform?: (example: string, operation: IR.OperationObject) => string; }; export type ExamplesConfig = Omit & FeatureToggle & { /** * The programming language for the generated examples. * * This is used to display the language label in code blocks in * documentation UIs. */ language: LinguistLanguages; /** * Example request payload. */ payload?: MaybeFunc< (operation: IR.OperationObject, ctx: DollarPyDsl) => CallArgs | CallArgs[number] >; /** * Transform the generated example string. * * @param example The generated example string. * @param operation The operation the example was generated for. * @returns The final example string. */ transform?: (example: string, operation: IR.OperationObject) => string; }; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { HeyApiSdkPlugin } from './types'; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/operations/config.ts ================================================ import type { OperationsStrategy, PluginContext } from '@hey-api/shared'; import type { UserConfig } from '../types'; import type { OperationsConfig, UserOperationsConfig } from './types'; type Config = Omit; export function resolveOperations(config: Config, context: PluginContext): OperationsConfig { return normalizeConfig(config.operations, context); } function normalizeConfig( input: Exclude | UserOperationsConfig | undefined, context: PluginContext, ): OperationsConfig { if (!input || typeof input === 'string' || typeof input === 'function') { input = { strategy: input }; } const strategy = input.strategy ?? 'single'; return context.valueToObject({ defaultValue: { container: 'class', methods: 'instance', nesting: 'operationId', nestingDelimiters: /[./]/, strategy, strategyDefaultTag: 'default', }, mappers: { object(value) { value.containerName = context.valueToObject({ defaultValue: strategy === 'single' ? { casing: 'PascalCase', name: 'Sdk' } : { casing: 'PascalCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.containerName, }); value.methodName = context.valueToObject({ defaultValue: { casing: 'snake_case' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.methodName, }); value.segmentName = context.valueToObject({ defaultValue: { casing: 'PascalCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.segmentName, }); return value; }, }, value: { ...input, } as UserOperationsConfig, }) as OperationsConfig; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/operations/index.ts ================================================ export { resolveOperations } from './config'; export { resolveStrategy } from './resolve'; export type { OperationsConfig, UserOperationsConfig } from './types'; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/operations/resolve.ts ================================================ import type { OperationPathStrategy, OperationStructureStrategy } from '@hey-api/shared'; import { OperationPath, OperationStrategy } from '@hey-api/shared'; import type { HeyApiSdkPlugin } from '../types'; function resolvePath(plugin: HeyApiSdkPlugin['Instance']): OperationPathStrategy { if (plugin.config.operations.nesting === 'id') { return OperationPath.id(); } if (plugin.config.operations.nesting === 'operationId') { return OperationPath.fromOperationId({ delimiters: plugin.config.operations.nestingDelimiters, fallback: OperationPath.id(), }); } return plugin.config.operations.nesting; } export function resolveStrategy(plugin: HeyApiSdkPlugin['Instance']): OperationStructureStrategy { // if (plugin.config.operations.strategy === 'flat') { // return OperationStrategy.flat({ // path: (operation) => [resolvePath(plugin)(operation).join('.')], // }); // } if (plugin.config.operations.strategy === 'single') { const root = plugin.config.operations.containerName; return OperationStrategy.single({ path: resolvePath(plugin), root: typeof root.name === 'string' ? root.name : (root.name?.('') ?? ''), }); } if (plugin.config.operations.strategy === 'byTags') { return OperationStrategy.byTags({ fallback: plugin.config.operations.strategyDefaultTag, path: resolvePath(plugin), }); } return plugin.config.operations.strategy; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/operations/types.ts ================================================ import type { NamingConfig, NamingRule, OperationPathStrategy, OperationsStrategy, } from '@hey-api/shared'; export interface UserOperationsConfig { /** * Type of container for grouped operations. * * Ignored when `strategy` is `'flat'`. * * - `'class'` - Class with methods * * @default 'class' */ container?: 'class'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'Sdk' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'MyApi' * * @example * // Transform tag names with suffix * containerName: '{{name}}Service' * * @example * // With casing * containerName: { name: '{{name}}Service', casing: 'PascalCase' } */ containerName?: NamingRule; /** * Customize method/function names. * * Applied to the final segment of the path (the method name). */ methodName?: NamingRule; /** * How methods are attached to class containers. * * Only applies when `container` is `'class'`. * * - `'instance'` - Instance methods, requires `new ClassName(config)` * * @default 'instance' */ methods?: 'instance'; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control * * @default 'operationId' */ nesting?: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. * * @default /[./]/ */ nestingDelimiters?: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the method name). */ segmentName?: NamingRule; /** * Grouping strategy. * * - `'byTags'` - One container per operation tag * - `'single'` - All operations in one container * - Custom function for full control * * @default 'single' */ strategy?: Exclude; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. * * @default 'default' */ strategyDefaultTag?: string; } export interface OperationsConfig { /** * Type of container for grouped operations. * * Ignored when `strategy` is `'flat'`. * * - `'class'` - Class with methods */ container: 'class'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'Sdk' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'MyApi' * * @example * // Transform tag names with suffix * containerName: '{{name}}Service' * * @example * // With casing * containerName: { name: '{{name}}Service', case: 'PascalCase' } */ containerName: NamingConfig; /** * Customize method/function names. * * Applied to the final segment of the path (the method name). */ methodName: NamingConfig; /** * How methods are attached to class containers. * * Only applies when `container` is `'class'`. * * - `'instance'` - Instance methods, requires `new ClassName(config)` */ methods: 'instance'; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control */ nesting: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. */ nestingDelimiters: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the method name). */ segmentName: NamingConfig; /** * Grouping strategy. * * - `'byTags'` - One container per operation tag * - `'single'` - All operations in one container * - Custom function for full control */ strategy: Exclude; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. */ strategyDefaultTag: string; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/plugin.ts ================================================ import type { HeyApiSdkPlugin } from './types'; import { handlerV1 } from './v1/plugin'; export const handler: HeyApiSdkPlugin['Handler'] = (args) => handlerV1(args); ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/shared/class.ts ================================================ export const createRegistryClass = () => {}; export const createClientClass = () => {}; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/shared/operation.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { HeyApiSdkPlugin } from '../types'; import { getSignatureParameters } from './signature'; type OperationParameters = { bodyRef?: string; fields: Array<{ in: string; key: string; map?: string; }>; parameters: Array>; }; const PYTHON_BUILTIN_TYPES: Record = { array: 'list', boolean: 'bool', integer: 'int', number: 'float', object: 'dict', string: 'str', }; function schemaToPythonType( schema: IR.SchemaObject, plugin: HeyApiSdkPlugin['Instance'], ): ReturnType | Symbol { if (schema.$ref) { return plugin.referenceSymbol({ category: 'schema', resourceId: schema.$ref, }); } if (schema.type === 'array') { const itemsSchema = schema.items?.[0]; const itemType = itemsSchema ? schemaToPythonType(itemsSchema, plugin) : plugin.external('typing.Any'); return $('list').slice(itemType); } if (schema.type === 'object' || schema.additionalProperties) { if (schema.additionalProperties && typeof schema.additionalProperties === 'object') { const valueType = schemaToPythonType(schema.additionalProperties, plugin); return $('dict').slice('str', valueType); } return $('dict').slice('str', plugin.external('typing.Any')); } if (schema.type === 'tuple') { const itemsSchema = schema.items; const itemTypes = itemsSchema ? itemsSchema.map((item) => schemaToPythonType(item, plugin)) : []; return $('tuple').slice(...itemTypes); } const builtinType = schema.type ? PYTHON_BUILTIN_TYPES[schema.type] : undefined; return $(builtinType ?? plugin.external('typing.Any')); } export function operationParameters({ operation, plugin, }: { operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): OperationParameters { const result: OperationParameters = { fields: [], parameters: [], }; if (plugin.config.paramsStructure === 'flat') { const signature = getSignatureParameters({ operation }); if (!signature) return result; result.bodyRef = signature.bodyRef; result.fields = signature.fields; const paramEntries = Object.entries(signature.parameters).sort(([, valueA], [, valueB]) => valueA.isRequired === valueB.isRequired ? 0 : valueA.isRequired ? -1 : 1, ); for (const [paramName, param] of paramEntries) { const type = schemaToPythonType(param.schema, plugin); if (param.isRequired) { result.parameters.push($.param(paramName).type(type)); } else { result.parameters.push( $.param(paramName) .type($(plugin.external('typing.Union')).slice(type, 'None')) .default('None'), ); } } } return result; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/shared/signature.ts ================================================ import type { IR } from '@hey-api/shared'; import { refToName, toCase } from '@hey-api/shared'; type Location = keyof IR.ParametersObject | 'body'; type SignatureParameter = { in: Location; isRequired: boolean; name: string; originalName?: string; schema: IR.SchemaObject; }; type SignatureParameters = Record; type Field = { in: Location | 'headers'; key: string; map?: string; }; type Signature = { bodyRef?: string; fields: Field[]; parameters: SignatureParameters; }; export function getSignatureParameters({ operation, }: { operation: IR.OperationObject; }): Signature | undefined { const locations = ['header', 'path', 'query'] as const satisfies ReadonlyArray; const nameToLocations: Record> = {}; const addParameter = (name: string, location: Location): void => { if (!nameToLocations[name]) { nameToLocations[name] = new Set(); } nameToLocations[name]!.add(location); }; for (const location of locations) { const parameters = operation.parameters?.[location]; if (parameters) { for (const key in parameters) { const parameter = parameters[key]!; addParameter(parameter.name, location); } } } if (operation.body) { if ( !operation.body.schema.logicalOperator && operation.body.schema.type === 'object' && operation.body.schema.properties ) { const properties = operation.body.schema.properties; for (const key in properties) { addParameter(key, 'body'); } } else if (operation.body.schema.$ref) { const name = refToName(operation.body.schema.$ref); const key = toCase(name, 'snake_case'); addParameter(key, 'body'); } else { addParameter('body', 'body'); } } const conflicts = new Set(); for (const name in nameToLocations) { if (nameToLocations[name]!.size > 1) { conflicts.add(name); } } const signatureParameters: SignatureParameters = {}; const fields: Field[] = []; for (const location of locations) { const parameters = operation.parameters?.[location]; if (parameters) { for (const key in parameters) { const parameter = parameters[key]!; const originalName = parameter.name; const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; const signatureParameter: SignatureParameter = { in: location, isRequired: parameter.required ?? false, name, schema: parameter.schema, }; if (name !== originalName) { signatureParameter.originalName = originalName; } signatureParameters[name] = signatureParameter; fields.push({ in: location === 'header' ? 'headers' : location, key: name, ...(name !== originalName ? { map: originalName } : {}), }); } } } let bodyRef: string | undefined; if (operation.body) { const location = 'body'; if ( !operation.body.schema.logicalOperator && operation.body.schema.type === 'object' && operation.body.schema.properties ) { const properties = operation.body.schema.properties; for (const originalName in properties) { const property = properties[originalName]!; const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; const signatureParameter: SignatureParameter = { in: location, isRequired: operation.body.schema.required?.includes(originalName) ?? false, name, schema: property, }; if (name !== originalName) { signatureParameter.originalName = originalName; } signatureParameters[name] = signatureParameter; fields.push({ in: location, key: name, ...(name !== originalName ? { map: originalName } : {}), }); } } else if (operation.body.schema.$ref) { const value = refToName(operation.body.schema.$ref); const originalName = toCase(value, 'snake_case'); const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; bodyRef = toCase(value, 'PascalCase'); const signatureParameter: SignatureParameter = { in: location, isRequired: operation.body.required ?? false, name, schema: operation.body.schema, }; if (name !== originalName) { signatureParameter.originalName = originalName; } signatureParameters[name] = signatureParameter; fields.push({ in: location, key: name, map: 'body', }); } else { signatureParameters.body = { in: location, isRequired: operation.body.required ?? false, name: 'body', schema: operation.body.schema, }; fields.push({ in: location, key: 'body', map: 'body', }); } } if (!Object.keys(signatureParameters).length) { return; } return { bodyRef, fields, parameters: signatureParameters }; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/types.ts ================================================ import type { DefinePlugin, OperationsStrategy, Plugin } from '@hey-api/shared'; import type { PluginClientNames } from '../../types'; // import type { PluginClientNames, PluginValidatorNames } from '../../types'; import type { ExamplesConfig, UserExamplesConfig } from './examples'; import type { OperationsConfig, UserOperationsConfig } from './operations'; export type UserConfig = Plugin.Name<'@hey-api/python-sdk'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Should the generated functions contain auth mechanisms? You may want to * disable this option if you're handling auth yourself or defining it * globally on the client and want to reduce the size of generated code. * * @default true */ // auth?: boolean; /** * Use an internal client instance to send HTTP requests? This is useful if * you don't want to manually pass the client to each SDK function. * * You can customize the selected client output through its plugin. You can * also set `client` to `true` to automatically choose the client from your * defined plugins. If we can't detect a client plugin when using `true`, we * will default to `@hey-api/client-httpx`. * * @default true */ client?: PluginClientNames | boolean; /** * Generate code examples for SDK operations and attach them to the * input source (e.g. via `x-codeSamples`). * * Set to `false` to disable example generation entirely, or provide an * object for fine-grained control over the output and post-processing. * * @default false */ examples?: boolean | UserExamplesConfig; /** * Define the structure of generated SDK operations. * * String shorthand: * - `'byTags'` – one container per operation tag * - `'single'` – all operations in a single container * - custom function for full control * * Use the object form for advanced configuration. * * @default 'single' */ operations?: Exclude | UserOperationsConfig; /** * Define how request parameters are structured in generated SDK methods. * * - `'flat'` merges parameters into a single object. * - `'grouped'` separates parameters by transport layer. * * Use `'flat'` for simpler calls or `'grouped'` for stricter typing and code clarity. * * @default 'grouped' */ paramsStructure?: 'flat' | 'grouped'; /** * **This feature works only with the Fetch client** * * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ // responseStyle?: 'data' | 'fields'; /** * Transform response data before returning. This is useful if you want to * convert for example ISO strings into Date objects. However, transformation * adds runtime overhead, so it's not recommended to use unless necessary. * * You can customize the selected transformer output through its plugin. You * can also set `transformer` to `true` to automatically choose the * transformer from your defined plugins. * * @default false */ // transformer?: PluginTransformerNames | boolean; /** * Validate request and/or response data against schema before returning. * This is useful if you want to ensure the request and/or response conforms * to a desired shape. However, validation adds runtime overhead, so it's * not recommended to use unless absolutely necessary. * * You can customize the validator output through its plugin. You can also * set `validator` to `true` to automatically choose the validator from your * defined plugins. * * You can enable/disable validation for requests and responses separately * by setting `validator` to an object `{ request, response }`. * * Ensure you have declared the selected library as a dependency to avoid * errors. * * @default false */ // validator?: // | PluginValidatorNames // | boolean // | { // /** // * Validate request data against schema before sending. // * // * Can be a validator plugin name or boolean (true to auto-select, false // * to disable). // * // * @default false // */ // request?: PluginValidatorNames | boolean; // /** // * Validate response data against schema before returning. // * // * Can be a validator plugin name or boolean (true to auto-select, false // * to disable). // * // * @default false // */ // response?: PluginValidatorNames | boolean; // }; }; export type Config = Plugin.Name<'@hey-api/python-sdk'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Should the generated functions contain auth mechanisms? You may want to * disable this option if you're handling auth yourself or defining it * globally on the client and want to reduce the size of generated code. * * @default true */ // auth: boolean; /** * Use an internal client instance to send HTTP requests? This is useful if * you don't want to manually pass the client to each SDK function. * * You can customize the selected client output through its plugin. You can * also set `client` to `true` to automatically choose the client from your * defined plugins. If we can't detect a client plugin when using `true`, we * will default to `@hey-api/client-httpx`. * * @default true */ client: PluginClientNames | false; /** * Configuration for generating SDK code examples. */ examples: ExamplesConfig; /** * Define the structure of generated SDK operations. */ operations: OperationsConfig; /** * Define how request parameters are structured in generated SDK methods. * * - `'flat'` merges parameters into a single object. * - `'grouped'` separates parameters by transport layer. * * Use `'flat'` for simpler calls or `'grouped'` for stricter typing and code clarity. * * @default 'grouped' */ paramsStructure: 'flat' | 'grouped'; /** * **This feature works only with the Fetch client** * * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ // responseStyle: 'data' | 'fields'; /** * Transform response data before returning. This is useful if you want to * convert for example ISO strings into Date objects. However, transformation * adds runtime overhead, so it's not recommended to use unless necessary. * * You can customize the selected transformer output through its plugin. You * can also set `transformer` to `true` to automatically choose the * transformer from your defined plugins. * * @default false */ // transformer: PluginTransformerNames | false; /** * Validate request and/or response data against schema before returning. * This is useful if you want to ensure the request and/or response conforms * to a desired shape. However, validation adds runtime overhead, so it's * not recommended to use unless absolutely necessary. */ // validator: { // /** // * The validator plugin to use for request validation, or false to disable. // * // * @default false // */ // request: PluginValidatorNames | false; // /** // * The validator plugin to use for response validation, or false to disable. // * // * @default false // */ // response: PluginValidatorNames | false; // }; }; export type HeyApiSdkPlugin = DefinePlugin; ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/v1/node.ts ================================================ import type { StructureItem, StructureNode, StructureShell, Symbol, SymbolMeta, } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { applyNaming, toCase } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import { createOperationComment } from '../../../shared/utils/operation'; import { operationParameters } from '../shared/operation'; import type { HeyApiSdkPlugin } from '../types'; export interface OperationItem { operation: IR.OperationObject; path: ReadonlyArray; tags: ReadonlyArray | undefined; } export const source = globalThis.Symbol('@hey-api/python-sdk'); function attachComment>(args: { node: T; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): T { const { node, operation, plugin } = args; return node.$if(plugin.config.comments && createOperationComment(operation), (n, v) => n.doc(v), ) as T; } function createShellMeta(node: StructureNode): SymbolMeta { return { category: 'utility', resource: 'class', resourceId: node.getPath().join('.'), tool: 'sdk', }; } function createFnSymbol( plugin: HeyApiSdkPlugin['Instance'], item: StructureItem & { data: OperationItem }, ): Symbol { const { operation, path, tags } = item.data; const name = item.location[item.location.length - 1]!; return plugin.symbol(applyNaming(name, plugin.config.operations.methodName), { meta: { category: 'sdk', path, resource: 'operation', resourceId: operation.id, tags, tool: 'sdk', }, }); } function childToNode( resource: StructureNode, plugin: HeyApiSdkPlugin['Instance'], ): ReadonlyArray> { const refChild = plugin.referenceSymbol(createShellMeta(resource)); const memberNameStr = toCase( refChild.name, plugin.config.operations.methodName.casing ?? 'camelCase', ); const memberName = plugin.symbol(memberNameStr); const cachedProp = plugin.external('functools.cached_property'); return [ $.method(memberName) .decorator(cachedProp) .param('self') .returns(refChild) .do( $(refChild) .call($.kwarg('client', $('self').attr('client'))) .return(), ), ]; } export function createShell(plugin: HeyApiSdkPlugin['Instance']): StructureShell { return { define: (node) => { const symbol = plugin.symbol( applyNaming( node.name, node.isRoot ? plugin.config.operations.containerName : plugin.config.operations.segmentName, ), { meta: createShellMeta(node), }, ); const symbolClient = plugin.external('client.Client'); const c = $.class(symbol).export().extends(symbolClient); const dependencies: Array> = []; return { dependencies, node: c }; }, }; } function implementFn>(args: { node: T; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): T { const { node, operation, plugin } = args; const method = operation.method.toLowerCase(); const opParameters = operationParameters({ operation, plugin }); if (plugin.config.paramsStructure === 'flat' && opParameters.fields.length > 0) { const paramNames = opParameters.parameters.map((parameter) => parameter.name.toString()); const fieldsList = $.list(); for (const field of opParameters.fields) { const fieldDict = $.dict(); fieldDict.entry($.literal('in'), $.literal(field.in)); fieldDict.entry($.literal('key'), $.literal(field.key)); if (field.map) { fieldDict.entry($.literal('map'), $.literal(field.map)); } fieldsList.element(fieldDict); } return ( node .params(...opParameters.parameters) // TODO: extract operation statements into a separate function .do( $.var('params').assign( $(plugin.external('client.build_client_params')).call( fieldsList, ...paramNames.map((name) => $.kwarg(name, name)), ), ), ) .do( $('self') .attr('client') .attr(method) .call($.literal(operation.path), $.kwarg('params', $('params') as never)) .return(), ) as T ); } return node .params(...opParameters.parameters) .do($('self').attr('client').attr(method).call($.literal(operation.path)).return()) as T; } export function toNode( model: StructureNode, plugin: HeyApiSdkPlugin['Instance'], ): { dependencies?: Array>; nodes: ReadonlyArray>; } { if (model.virtual) { const nodes: Array> = []; for (const item of model.itemsFrom(source)) { const fnName = applyNaming( String(item.location[item.location.length - 1]), plugin.config.operations.methodName, ); const node = $.func(fnName).export().do($('None').return()); nodes.push(node); } return { nodes }; } if (!model.shell) { return { nodes: [] }; } const nodes: Array> = []; const shell = model.shell.define(model); const node = shell.node as ReturnType; let index = 0; for (const item of model.itemsFrom(source)) { const { operation } = item.data; if (node['~dsl'] === 'FuncPyDsl') { // TODO: function? } else { if (index > 0 || node.hasBody) node.newline(); const method = implementFn({ node: $.method(createFnSymbol(plugin, item), (m) => attachComment({ node: m, operation, plugin, }), ).param('self'), operation, plugin, }); node.do(method); // exampleIntent(method, operation, plugin); } index += 1; } for (const child of model.children.values()) { if (node['~dsl'] === 'FuncPyDsl') { // TODO: function? } else { if (node.hasBody) node.newline(); node.do(...childToNode(child, plugin)); } } nodes.push(node); return { dependencies: shell.dependencies as Array>, nodes, }; } ================================================ FILE: packages/openapi-python/src/plugins/@hey-api/sdk/v1/plugin.ts ================================================ import { StructureModel } from '@hey-api/codegen-core'; import { getTypedConfig } from '../../../../config/utils'; import { clientFolderAbsolutePath } from '../../../../generate/client'; import type { $ } from '../../../../py-dsl'; import { getClientPlugin } from '../../client-core/utils'; import { resolveStrategy } from '../operations'; import type { HeyApiSdkPlugin } from '../types'; import { createShell, type OperationItem, source, toNode } from './node'; export const handlerV1: HeyApiSdkPlugin['Handler'] = ({ plugin }) => { const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin)); const client = getClientPlugin(getTypedConfig(plugin)); // client plugin.symbol('build_client_params', { external: clientModule, meta: { category: 'external', resource: 'client.build_client_params', tool: client.name, }, }); plugin.symbol('Client', { external: clientModule, meta: { category: 'external', resource: 'client.Client', tool: client.name, }, }); // functools plugin.symbol('cached_property', { external: 'functools', meta: { category: 'external', resource: 'functools.cached_property', }, }); // typing plugin.symbol('Any', { external: 'typing', meta: { category: 'external', resource: 'typing.Any', }, }); plugin.symbol('Union', { external: 'typing', meta: { category: 'external', resource: 'typing.Union', }, }); const structure = new StructureModel(); const shell = createShell(plugin); const strategy = resolveStrategy(plugin); plugin.forEach( 'operation', (event) => { structure.insert({ data: { operation: event.operation, path: event._path, tags: event.tags, } satisfies OperationItem, locations: strategy(event.operation).map((path) => ({ path, shell })), source, }); }, { order: 'declarations' }, ); const allDependencies: Array> = []; const allNodes: Array> = []; for (const node of structure.walk()) { const { dependencies, nodes } = toNode(node, plugin); allDependencies.push(...(dependencies ?? [])); allNodes.push(...nodes); } for (const dep of allDependencies) { plugin.node(dep); } for (const node of allNodes) { plugin.node(node); } }; ================================================ FILE: packages/openapi-python/src/plugins/config.ts ================================================ import type { Plugin, PluginConfigMap, PluginNames } from '@hey-api/shared'; import { defaultConfig as heyApiClientHttpx } from '../plugins/@hey-api/client-httpx'; import { defaultConfig as heyApiSdk } from '../plugins/@hey-api/sdk'; import { defaultConfig as pydantic } from '../plugins/pydantic'; export const defaultPluginConfigs: { [K in PluginNames]: Plugin.Config; } = { '@hey-api/client-httpx': heyApiClientHttpx, '@hey-api/python-sdk': heyApiSdk, pydantic, }; ================================================ FILE: packages/openapi-python/src/plugins/pydantic/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from './plugin'; import type { PydanticPlugin } from './types'; export const defaultConfig: PydanticPlugin['Config'] = { config: { case: 'PascalCase', comments: true, enums: 'enum', includeInEntry: false, strict: false, }, handler, name: 'pydantic', resolveConfig: (plugin, context) => { plugin.config.definitions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}', }, mappers, value: plugin.config.definitions, }); plugin.config.requests = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}Request', }, mappers, value: plugin.config.requests, }); plugin.config.responses = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}Response', }, mappers, value: plugin.config.responses, }); plugin.config.webhooks = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}Webhook', }, mappers, value: plugin.config.webhooks, }); }, tags: ['validator'], }; /** * Type helper for Pydantic plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-python/src/plugins/pydantic/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { PydanticResolvers } from './resolvers'; export type { PydanticPlugin } from './types'; ================================================ FILE: packages/openapi-python/src/plugins/pydantic/plugin.ts ================================================ import type { PydanticPlugin } from './types'; import { handlerV2 } from './v2/plugin'; export const handler: PydanticPlugin['Handler'] = (args) => handlerV2(args); ================================================ FILE: packages/openapi-python/src/plugins/pydantic/resolvers.ts ================================================ import type { IR, Plugin, SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import type { DollarPyDsl } from '../../py-dsl'; import type { PydanticField, PydanticFinal, PydanticResult, PydanticType } from './shared/types'; import type { PydanticPlugin } from './types'; export type PydanticResolvers = Plugin.Resolvers<{ /** * Resolver for array schemas. * * Allows customization of how array types are rendered. * * Returning `undefined` will execute the default resolver logic. */ array?: (ctx: ArrayResolverContext) => PydanticType | undefined; /** * Resolver for boolean schemas. * * Allows customization of how boolean types are rendered. * * Returning `undefined` will execute the default resolver logic. */ boolean?: (ctx: BooleanResolverContext) => PydanticType | undefined; /** * Resolver for enum schemas. * * Allows customization of how enum types are rendered. * * Returning `undefined` will execute the default resolver logic. */ enum?: (ctx: EnumResolverContext) => PydanticType | undefined; /** * Resolver for intersection schemas. * * Allows customization of how intersection types are rendered. * * Returning `undefined` will execute the default resolver logic. */ intersection?: (ctx: IntersectionResolverContext) => PydanticType | undefined; /** * Resolver for never schemas. * * Allows customization of how never types are rendered. * * Returning `undefined` will execute the default resolver logic. */ never?: (ctx: NeverResolverContext) => PydanticType | undefined; /** * Resolver for null schemas. * * Allows customization of how null types are rendered. * * Returning `undefined` will execute the default resolver logic. */ null?: (ctx: NullResolverContext) => PydanticType | undefined; /** * Resolver for number schemas. * * Allows customization of how number types are rendered. * * Returning `undefined` will execute the default resolver logic. */ number?: (ctx: NumberResolverContext) => PydanticType | undefined; /** * Resolver for object schemas. * * Allows customization of how object types are rendered. * * Returning `undefined` will execute the default resolver logic. */ object?: ( ctx: ObjectResolverContext, ) => (PydanticType & { fields?: Array }) | undefined; /** * Resolver for string schemas. * * Allows customization of how string types are rendered. * * Returning `undefined` will execute the default resolver logic. */ string?: (ctx: StringResolverContext) => PydanticType | undefined; /** * Resolver for tuple schemas. * * Allows customization of how tuple types are rendered. * * Returning `undefined` will execute the default resolver logic. */ tuple?: (ctx: TupleResolverContext) => PydanticType | undefined; /** * Resolver for undefined schemas. * * Allows customization of how undefined types are rendered. * * Returning `undefined` will execute the default resolver logic. */ undefined?: (ctx: UndefinedResolverContext) => PydanticType | undefined; /** * Resolver for union schemas. * * Allows customization of how union types are rendered. * * Returning `undefined` will execute the default resolver logic. */ union?: (ctx: UnionResolverContext) => PydanticType | undefined; /** * Resolver for unknown schemas. * * Allows customization of how unknown types are rendered. * * Returning `undefined` will execute the default resolver logic. */ unknown?: (ctx: UnknownResolverContext) => PydanticType | undefined; /** * Resolver for void schemas. * * Allows customization of how void types are rendered. * * Returning `undefined` will execute the default resolver logic. */ void?: (ctx: VoidResolverContext) => PydanticType | undefined; }>; interface BaseContext extends DollarPyDsl { /** The plugin instance. */ plugin: PydanticPlugin['Instance']; } export interface ArrayResolverContext extends BaseContext { applyModifiers: (result: PydanticResult, opts?: { optional?: boolean }) => PydanticFinal; childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: ArrayResolverContext) => PydanticType; maxLength: (ctx: ArrayResolverContext) => PydanticType | undefined; minLength: (ctx: ArrayResolverContext) => PydanticType | undefined; }; schema: SchemaWithType<'array'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface BooleanResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: BooleanResolverContext) => PydanticType; const: (ctx: BooleanResolverContext) => PydanticType | undefined; }; schema: SchemaWithType<'boolean'>; } export interface EnumResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: EnumResolverContext) => PydanticType; items: (ctx: EnumResolverContext) => { enumMembers: Required['enumMembers']; isNullable: boolean; }; }; schema: SchemaWithType<'enum'>; } export interface IntersectionResolverContext extends BaseContext { applyModifiers: (result: PydanticResult, opts?: { optional?: boolean }) => PydanticFinal; childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: IntersectionResolverContext) => PydanticType; }; parentSchema: IR.SchemaObject; schema: IR.SchemaObject; } export interface NeverResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: NeverResolverContext) => PydanticType; }; schema: SchemaWithType<'never'>; } export interface NullResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: NullResolverContext) => PydanticType; }; schema: SchemaWithType<'null'>; } export interface NumberResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: NumberResolverContext) => PydanticType; const: (ctx: NumberResolverContext) => PydanticType | undefined; }; schema: SchemaWithType<'integer' | 'number'>; } export interface ObjectResolverContext extends BaseContext { _childResults: Array; applyModifiers: (result: PydanticResult, opts: { optional?: boolean }) => PydanticFinal; /** * Nodes used to build different parts of the result. */ nodes: { additionalProperties: (ctx: ObjectResolverContext) => PydanticType | null | undefined; base: (ctx: ObjectResolverContext) => PydanticType & { fields?: Array }; fields: (ctx: ObjectResolverContext) => Array; }; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface StringResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: StringResolverContext) => PydanticType; const: (ctx: StringResolverContext) => PydanticType | undefined; }; schema: SchemaWithType<'string'>; } export interface TupleResolverContext extends BaseContext { applyModifiers: (result: PydanticResult, opts?: { optional?: boolean }) => PydanticFinal; childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: TupleResolverContext) => PydanticType; const: (ctx: TupleResolverContext) => PydanticType | undefined; }; schema: SchemaWithType<'tuple'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface UndefinedResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: UndefinedResolverContext) => PydanticType; }; schema: SchemaWithType<'undefined'>; } export interface UnionResolverContext extends BaseContext { applyModifiers: (result: PydanticResult, opts?: { optional?: boolean }) => PydanticFinal; childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: UnionResolverContext) => PydanticType; }; parentSchema: IR.SchemaObject; schema: IR.SchemaObject; schemas: ReadonlyArray; } export interface UnknownResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: UnknownResolverContext) => PydanticType; }; schema: SchemaWithType<'unknown'>; } export interface VoidResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: VoidResolverContext) => PydanticType; }; schema: SchemaWithType<'void'>; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/shared/export.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import { buildSymbolIn, pathToName } from '@hey-api/shared'; import { $ } from '../../../py-dsl'; import type { PydanticPlugin } from '../types'; import { identifiers } from '../v2/constants'; import { createFieldCall } from './field'; import type { ProcessorContext } from './processor'; import type { PydanticField, PydanticFinal } from './types'; export function exportAst({ final, meta, naming, namingAnchor, path, plugin, schema, tags, }: ProcessorContext & { final: PydanticFinal; }): void { const name = pathToName(path, { anchor: namingAnchor }); const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'schema', path, tags, tool: 'pydantic', ...meta, }, name, naming, plugin, schema, }), ); if (final.enumMembers) { exportEnumClass({ final, plugin, symbol }); } else if (final.fields) { exportClass({ final, plugin, symbol }); } else { exportTypeAlias({ final, plugin, symbol }); } } function exportClass({ final, plugin, symbol, }: { final: PydanticFinal; plugin: PydanticPlugin['Instance']; symbol: Symbol; }): void { const baseModel = plugin.external('pydantic.BaseModel'); const classDef = $.class(symbol).extends(baseModel); if (plugin.config.strict) { const configDict = plugin.external('pydantic.ConfigDict'); classDef.do( $.var(identifiers.model_config).assign($(configDict).call($.kwarg('extra', 'forbid'))), ); } for (const field of final.fields!) { const fieldStatement = createFieldStatement(field, plugin); classDef.do(fieldStatement); } plugin.node(classDef); } function exportEnumClass({ final, plugin, symbol, }: { final: PydanticFinal; plugin: PydanticPlugin['Instance']; symbol: Symbol; }): void { const members = final.enumMembers ?? []; const hasStrings = members.some((m) => typeof m.value === 'string'); const hasNumbers = members.some((m) => typeof m.value === 'number'); const enumSymbol = plugin.external('enum.Enum'); const classDef = $.class(symbol).extends(enumSymbol); if (hasStrings && !hasNumbers) { classDef.extends('str'); } else if (!hasStrings && hasNumbers) { classDef.extends('int'); } for (const member of final.enumMembers ?? []) { classDef.do($.var(member.name).assign($.literal(member.value))); } plugin.node(classDef); } function createFieldStatement( field: PydanticField, plugin: PydanticPlugin['Instance'], ): ReturnType { const fieldSymbol = field.name; const varStatement = $.var(fieldSymbol).$if(field.type, (v, a) => v.type(a)); const originalName = field.originalName ?? fieldSymbol.name; const needsAlias = field.originalName !== undefined && fieldSymbol.name !== originalName; const constraints = { ...field.fieldConstraints, ...(needsAlias && !field.fieldConstraints?.alias && { alias: originalName }), }; if (Object.keys(constraints).length > 0) { const fieldCall = createFieldCall(constraints, plugin, { required: !field.isOptional, }); return varStatement.assign(fieldCall); } if (field.isOptional) { return varStatement.assign('None'); } return varStatement; } function exportTypeAlias({ final, plugin, symbol, }: { final: PydanticFinal; plugin: PydanticPlugin['Instance']; symbol: Symbol; }): void { const typeAlias = plugin.external('typing.TypeAlias'); const statement = $.var(symbol) .type(typeAlias) .assign(final.type ?? plugin.external('typing.Any')); plugin.node(statement); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/shared/field.ts ================================================ import { $ } from '../../../py-dsl'; import type { PydanticPlugin } from '../types'; import type { FieldConstraints } from '../v2/constants'; type FieldArg = ReturnType; export function createFieldCall( constraints: FieldConstraints, plugin: PydanticPlugin['Instance'], options?: { /** If true, the field is required. */ required?: boolean; }, ): ReturnType { const field = plugin.external('pydantic.Field'); const args: Array = []; const isRequired = options?.required !== false && constraints.default === undefined; // For required fields with no default, use ... as first arg if (isRequired && constraints.default === undefined) { args.push($('...')); } // TODO: move to DSL // Add constraint arguments in a consistent order const orderedKeys: Array = [ 'default', 'default_factory', 'alias', 'title', 'description', 'gt', 'ge', 'lt', 'le', 'multiple_of', 'min_length', 'max_length', 'pattern', ]; for (const key of orderedKeys) { const value = constraints[key]; if (value === undefined) continue; // Skip default if we already added ... for required fields if (key === 'default' && isRequired) continue; args.push($.kwarg(key, toKwargValue(value))); } return $(field).call(...(args as Array[1]>)); } /** * Converts a constraint value to a kwarg-compatible value. */ function toKwargValue(value: unknown): string | number | boolean | null { if ( value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) { return value; } // For complex types, stringify return String(value); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/shared/meta.ts ================================================ import type { IR } from '@hey-api/shared'; import type { PydanticMeta, PydanticResult } from './types'; /** * Creates default metadata from a schema. */ export function defaultMeta(schema: IR.SchemaObject): PydanticMeta { return { default: schema.default, hasForwardReference: false, nullable: false, readonly: schema.accessScope === 'read', }; } /** * Composes metadata from child results. * * @param children - Results from walking child schemas * @param overrides - Explicit overrides (e.g., from parent schema) */ export function composeMeta( children: ReadonlyArray, overrides?: Partial, ): PydanticMeta { return { default: overrides?.default, hasForwardReference: overrides?.hasForwardReference ?? children.some((c) => c.meta.hasForwardReference), nullable: overrides?.nullable ?? children.some((c) => c.meta.nullable), readonly: overrides?.readonly ?? children.some((c) => c.meta.readonly), }; } /** * Merges parent schema metadata with composed child metadata. * * @param parent - The parent schema * @param children - Results from walking child schemas */ export function inheritMeta( parent: IR.SchemaObject, children: ReadonlyArray, ): PydanticMeta { return composeMeta(children, { default: parent.default, nullable: false, readonly: parent.accessScope === 'read', }); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/shared/processor.ts ================================================ import type { IR, NamingConfig, SchemaProcessorContext } from '@hey-api/shared'; import type { PydanticPlugin } from '../types'; import type { PydanticFinal } from './types'; export type ProcessorContext = SchemaProcessorContext & { /** Whether to export the result (default: true) */ export?: boolean; naming: NamingConfig; /** The plugin instance. */ plugin: PydanticPlugin['Instance']; schema: IR.SchemaObject; }; export type ProcessorResult = { process: (ctx: ProcessorContext) => PydanticFinal | void; }; ================================================ FILE: packages/openapi-python/src/plugins/pydantic/shared/types.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { VarType } from '../../../py-dsl'; import type { FieldConstraints } from '../v2/constants'; /** * Return type for toType converters. */ export interface PydanticType { fieldConstraints?: FieldConstraints; type?: VarType; } /** * Metadata that flows through schema walking. */ export interface PydanticMeta { /** Default value from schema. */ default?: unknown; /** Whether this or any child contains a forward reference. */ hasForwardReference: boolean; /** Does this schema explicitly allow null? */ nullable: boolean; /** Is this schema read-only? */ readonly: boolean; } /** * Result from walking a schema node. */ export interface PydanticResult extends PydanticType { enumMembers?: Array<{ name: Symbol; value: string | number }>; fields?: Array; // present = emit class, absent = emit type alias meta: PydanticMeta; } export interface PydanticField extends PydanticType { isOptional: boolean; name: Symbol; originalName?: string; } /** * Finalized result after applyModifiers. */ export interface PydanticFinal extends PydanticType, Pick {} ================================================ FILE: packages/openapi-python/src/plugins/pydantic/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; import type { PydanticResolvers } from './resolvers'; export type UserConfig = Plugin.Name<'pydantic'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & PydanticResolvers & { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Configuration for reusable schema definitions. * * Controls generation of shared Pydantic models that can be referenced * across requests and responses. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ definitions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}' */ name?: NameTransformer; }; /** * How to generate enum types. * * - `'enum'`: Generate Python Enum classes (e.g., `class Status(str, Enum): ...`) * - `'literal'`: Generate Literal type hints (e.g., `Literal["pending", "active"]`) * * @default 'enum' */ enums?: 'enum' | 'literal'; /** * Configuration for request-specific Pydantic models. * * Controls generation of Pydantic models for request bodies, * query parameters, path parameters, and headers. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ requests?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}Request' */ name?: NameTransformer; }; /** * Configuration for response-specific Pydantic models. * * Controls generation of Pydantic models for response bodies, * error responses, and status codes. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ responses?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}Response' */ name?: NameTransformer; }; /** * Enable strict mode for Pydantic models? * * When enabled, extra fields not defined in the schema will be rejected. * * This adds `model_config = ConfigDict(extra='forbid')` * to generated models. * * @default false */ strict?: boolean; /** * Configuration for webhook-specific Pydantic models. * * Controls generation of Pydantic models for webhook payloads. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ webhooks?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}Webhook' */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'pydantic'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & PydanticResolvers & { /** Casing convention for generated names. */ case: Casing; /** Configuration for reusable schema definitions. */ definitions: NamingOptions & FeatureToggle; /** How to generate enum types. */ enums: 'enum' | 'literal'; /** Configuration for request-specific Pydantic models. */ requests: NamingOptions & FeatureToggle; /** Configuration for response-specific Pydantic models. */ responses: NamingOptions & FeatureToggle; /** Enable strict mode for Pydantic models? */ strict: boolean; /** Configuration for webhook-specific Pydantic models. */ webhooks: NamingOptions & FeatureToggle; }; export type PydanticPlugin = DefinePlugin; ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/constants.ts ================================================ export const identifiers = { model_config: 'model_config', }; export interface FieldConstraints { /** Alias for the field name in serialization. */ alias?: string; /** Default value for the field. */ default?: unknown; /** Default factory function (for mutable defaults). */ default_factory?: string; /** Description of the field. */ description?: string; /** Greater than or equal constraint for numbers. */ ge?: number; /** Greater than constraint for numbers. */ gt?: number; /** Less than or equal constraint for numbers. */ le?: number; /** Less than constraint for numbers. */ lt?: number; /** Maximum length constraint for strings/arrays. */ max_length?: number; /** Minimum length constraint for strings/arrays. */ min_length?: number; /** Multiple of constraint for numbers. */ multiple_of?: number; /** Regex pattern constraint for strings. */ pattern?: string; /** Title for the field. */ title?: string; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/plugin.ts ================================================ import { pathToJsonPointer } from '@hey-api/shared'; import type { PydanticPlugin } from '../types'; import { createProcessor } from './processor'; export const handlerV2: PydanticPlugin['Handler'] = ({ plugin }) => { // enum plugin.symbol('Enum', { external: 'enum', meta: { category: 'external', resource: 'enum.Enum', }, }); // typing plugin.symbol('Any', { external: 'typing', meta: { category: 'external', resource: 'typing.Any', }, }); plugin.symbol('Literal', { external: 'typing', meta: { category: 'external', resource: 'typing.Literal', }, }); plugin.symbol('NoReturn', { external: 'typing', meta: { category: 'external', resource: 'typing.NoReturn', }, }); plugin.symbol('Optional', { external: 'typing', meta: { category: 'external', resource: 'typing.Optional', }, }); plugin.symbol('TypeAlias', { external: 'typing', meta: { category: 'external', resource: 'typing.TypeAlias', }, }); plugin.symbol('Union', { external: 'typing', meta: { category: 'external', resource: 'typing.Union', }, }); // Pydantic plugin.symbol('BaseModel', { external: 'pydantic', meta: { category: 'external', resource: 'pydantic.BaseModel', }, }); plugin.symbol('ConfigDict', { external: 'pydantic', meta: { category: 'external', resource: 'pydantic.ConfigDict', }, }); plugin.symbol('Field', { external: 'pydantic', meta: { category: 'external', resource: 'pydantic.Field', }, }); const processor = createProcessor(plugin); plugin.forEach('operation', 'parameter', 'requestBody', 'schema', 'webhook', (event) => { switch (event.type) { case 'parameter': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.parameter.schema, tags: event.tags, }); break; case 'requestBody': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.requestBody.schema, tags: event.tags, }); break; case 'schema': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.schema, tags: event.tags, }); break; } }); }; ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/processor.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { Hooks, IR } from '@hey-api/shared'; import { createSchemaProcessor, createSchemaWalker, pathToJsonPointer } from '@hey-api/shared'; import { exportAst } from '../shared/export'; import type { ProcessorContext, ProcessorResult } from '../shared/processor'; import type { PydanticFinal } from '../shared/types'; import type { PydanticPlugin } from '../types'; import { createVisitor } from './walker'; export function createProcessor(plugin: PydanticPlugin['Instance']): ProcessorResult { const processor = createSchemaProcessor(); const extractorHooks: ReadonlyArray['shouldExtract']> = [ (ctx) => ctx.schema.type === 'object' && ctx.schema.properties !== undefined && Object.keys(ctx.schema.properties).length > 0, (ctx) => ctx.schema.type === 'enum' && ctx.schema.items !== undefined && ctx.schema.items.length > 0, plugin.config['~hooks']?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract, ]; function extractor(ctx: ProcessorContext): IR.SchemaObject { if (processor.hasEmitted(ctx.path)) { return ctx.schema; } for (const hook of extractorHooks) { const result = hook?.(ctx); if (result) { process({ namingAnchor: processor.context.anchor, tags: processor.context.tags, ...ctx, }); return { $ref: pathToJsonPointer(ctx.path) }; } } return ctx.schema; } function process(ctx: ProcessorContext): PydanticFinal | void { if (!processor.markEmitted(ctx.path)) return; const shouldExport = ctx.export !== false; return processor.withContext({ anchor: ctx.namingAnchor, tags: ctx.tags }, () => { const visitor = createVisitor({ schemaExtractor: extractor }); const walk = createSchemaWalker(visitor); const result = walk(ctx.schema, { path: ref(ctx.path), plugin, }); const final = visitor.applyModifiers(result, { path: ref(ctx.path), plugin, }) as PydanticFinal; if (shouldExport) { exportAst({ ...ctx, final, plugin }); return; } return final; }); } return { process }; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/array.ts ================================================ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext, deduplicateSchema } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { ArrayResolverContext } from '../../resolvers'; import type { PydanticFinal, PydanticResult, PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; import type { FieldConstraints } from '../constants'; function baseNode(ctx: ArrayResolverContext): PydanticType { const { applyModifiers, childResults, plugin } = ctx; const any = plugin.external('typing.Any'); if (childResults.length === 0) { return { type: $('list').slice(any), }; } if (childResults.length === 1) { const itemResult = applyModifiers(childResults[0]!); return { type: $('list').slice(itemResult.type ?? any), }; } if (childResults.length > 1) { const union = plugin.external('typing.Union'); const itemTypes = childResults.map((r) => applyModifiers(r).type ?? any); return { type: $('list').slice($(union).slice(...itemTypes)), }; } return { type: $('list').slice(any), }; } function minLengthNode(ctx: ArrayResolverContext): PydanticType | undefined { const { schema } = ctx; if (schema.minItems === undefined) return; return { fieldConstraints: { min_length: schema.minItems }, }; } function maxLengthNode(ctx: ArrayResolverContext): PydanticType | undefined { const { schema } = ctx; if (schema.maxItems === undefined) return; return { fieldConstraints: { max_length: schema.maxItems }, }; } function arrayResolver(ctx: ArrayResolverContext): PydanticType { const baseResult = ctx.nodes.base(ctx); const minLengthResult = ctx.nodes.minLength(ctx); const maxLengthResult = ctx.nodes.maxLength(ctx); const fieldConstraints: FieldConstraints = { ...(baseResult.fieldConstraints ?? {}), ...(minLengthResult?.fieldConstraints ?? {}), ...(maxLengthResult?.fieldConstraints ?? {}), }; if (ctx.schema.description !== undefined) { fieldConstraints.description = ctx.schema.description; } return { ...baseResult, fieldConstraints: Object.keys(fieldConstraints).length > 0 ? fieldConstraints : undefined, }; } export interface ArrayToTypeResult extends PydanticType { childResults: Array; } export function arrayToType(ctx: { applyModifiers: (result: PydanticResult, options?: { optional?: boolean }) => PydanticFinal; plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'array'>; walk: Walker; walkerCtx: SchemaVisitorContext; }): ArrayToTypeResult { const { applyModifiers, plugin, schema, walk, walkerCtx } = ctx; const any = plugin.external('typing.Any'); const childResults: Array = []; if (schema.items) { const normalizedSchema = deduplicateSchema({ schema }); for (let i = 0; i < normalizedSchema.items!.length; i++) { const item = normalizedSchema.items![i]!; const result = walk(item, childContext(walkerCtx, 'items', i)); childResults.push(result); } } const resolverCtx: ArrayResolverContext = { $, applyModifiers, childResults, nodes: { base: baseNode, maxLength: maxLengthNode, minLength: minLengthNode, }, plugin, schema, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.array; const resolved = resolver?.(resolverCtx) ?? arrayResolver(resolverCtx); if (!resolved.type) { resolved.type = $('list').slice(any); } return { ...resolved, childResults, }; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/boolean.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { BooleanResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; function constNode(ctx: BooleanResolverContext): PydanticType | undefined { const { plugin, schema } = ctx; if (typeof schema.const === 'boolean') { const literal = plugin.external('typing.Literal'); return { type: $(literal).slice($.literal(schema.const)), }; } } // eslint-disable-next-line @typescript-eslint/no-unused-vars function baseNode(_ctx: BooleanResolverContext): PydanticType { return { type: 'bool', }; } function booleanResolver(ctx: BooleanResolverContext): PydanticType { const constResult = ctx.nodes.const(ctx); if (constResult) return constResult; return ctx.nodes.base(ctx); } export function booleanToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'boolean'>; }): PydanticType { const ctx: BooleanResolverContext = { $, nodes: { base: baseNode, const: constNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.boolean; return resolver?.(ctx) ?? booleanResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/enum.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { toCase } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { EnumResolverContext } from '../../resolvers'; import type { PydanticFinal, PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; export interface EnumToTypeResult extends PydanticType { enumMembers: Required['enumMembers']; isNullable: boolean; } // TODO: replace with casing utils function toEnumMemberName(value: string | number): string { if (typeof value === 'number') { // For numbers, prefix with underscore if starts with digit return `VALUE_${value}`.replace(/-/g, '_NEG_').replace(/\./g, '_DOT_'); } return toCase(value, 'SCREAMING_SNAKE_CASE'); } function itemsNode(ctx: EnumResolverContext) { const { plugin, schema } = ctx; const enumMembers: Required['enumMembers'] = []; let isNullable = false; for (const item of schema.items ?? []) { if (item.type === 'null' || item.const === null) { isNullable = true; continue; } if ( (item.type === 'string' && typeof item.const === 'string') || ((item.type === 'integer' || item.type === 'number') && typeof item.const === 'number') ) { enumMembers.push({ name: plugin.symbol(toEnumMemberName(item.const)), value: item.const, }); } } return { enumMembers, isNullable }; } function baseNode(ctx: EnumResolverContext): PydanticType { const { plugin } = ctx; const { enumMembers } = ctx.nodes.items(ctx); if (enumMembers.length === 0) { return { type: plugin.external('typing.Any'), }; } const mode = plugin.config.enums ?? 'enum'; if (mode === 'literal') { if (enumMembers.length === 0) { return { type: plugin.external('typing.Any'), }; } const literal = plugin.external('typing.Literal'); const values = enumMembers.map((m) => // TODO: replace typeof m.value === 'string' ? `"<<<<${m.value}"` : `<<<${m.value}`, ); return { type: $(literal).slice(...values), }; } return {}; } function enumResolver(ctx: EnumResolverContext): PydanticType { return ctx.nodes.base(ctx); } export function enumToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'enum'>; }): EnumToTypeResult { const ctx: EnumResolverContext = { $, nodes: { base: baseNode, items: itemsNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.enum; const resolved = resolver?.(ctx) ?? enumResolver(ctx); const { enumMembers, isNullable } = ctx.nodes.items(ctx); return { ...resolved, enumMembers, isNullable, }; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/intersection.ts ================================================ import type { IR } from '@hey-api/shared'; import { $, type VarType } from '../../../../py-dsl'; import type { IntersectionResolverContext } from '../../resolvers'; import type { PydanticField, PydanticFinal, PydanticResult, PydanticType, } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; import type { FieldConstraints } from '../constants'; function baseNode(ctx: IntersectionResolverContext): PydanticType { const { applyModifiers, childResults, plugin } = ctx; if (childResults.length === 0) { return { type: plugin.external('typing.Any'), }; } if (childResults.length === 1) { const finalResult = applyModifiers(childResults[0]!); return finalResult; } const baseClasses: Array = []; const mergedFields: Array = []; const seenFieldIds = new Set(); for (const result of childResults) { const finalResult = applyModifiers(result); // TODO: replace const typeStr = String(finalResult.type); const isReference = !finalResult.fields && typeStr !== '' && !typeStr.startsWith('dict[') && !typeStr.startsWith('Dict[') && typeStr !== String(plugin.external('typing.Any')); if (isReference) { const baseName = typeStr.replace(/^'|'$/g, ''); if (baseName && !baseClasses.includes(baseName)) { baseClasses.push(baseName); } } if (finalResult.fields) { for (const field of finalResult.fields) { if (!seenFieldIds.has(field.name.id)) { seenFieldIds.add(field.name.id); mergedFields.push(field); } } } } let type: VarType; if (baseClasses.length > 0 && mergedFields.length === 0) { type = baseClasses[0]!; } else if (mergedFields.length > 0) { // TODO: replace type = '__INTERSECTION_PLACEHOLDER__'; } else { type = plugin.external('typing.Any'); } return { type, }; } function intersectionResolver(ctx: IntersectionResolverContext): PydanticType { return ctx.nodes.base(ctx); } export interface IntersectionToTypeResult extends PydanticType { baseClasses?: Array; childResults: Array; mergedFields?: Array; } export function intersectionToType({ applyModifiers, childResults, parentSchema, plugin, }: { applyModifiers: (result: PydanticResult, options?: { optional?: boolean }) => PydanticFinal; childResults: Array; parentSchema: IR.SchemaObject; plugin: PydanticPlugin['Instance']; }): IntersectionToTypeResult { const constraints: FieldConstraints = {}; if (parentSchema.description !== undefined) { constraints.description = parentSchema.description; } const resolverCtx: IntersectionResolverContext = { $, applyModifiers, childResults, nodes: { base: baseNode, }, parentSchema, plugin, schema: parentSchema, }; const resolver = plugin.config['~resolvers']?.intersection; const resolved = resolver?.(resolverCtx) ?? intersectionResolver(resolverCtx); const baseClasses: Array = []; const mergedFields: Array = []; const seenFieldIds = new Set(); for (const result of childResults) { const finalResult = applyModifiers(result); // TODO: replace const typeStr = String(finalResult.type); const isReference = !finalResult.fields && typeStr !== '' && !typeStr.startsWith('dict[') && !typeStr.startsWith('Dict[') && typeStr !== String(plugin.external('typing.Any')); if (isReference) { const baseName = typeStr.replace(/^'|'$/g, ''); if (baseName && !baseClasses.includes(baseName)) { baseClasses.push(baseName); } } if (finalResult.fields) { for (const field of finalResult.fields) { if (!seenFieldIds.has(field.name.id)) { seenFieldIds.add(field.name.id); mergedFields.push(field); } } } } return { ...resolved, baseClasses: baseClasses.length > 0 ? baseClasses : undefined, childResults, fieldConstraints: Object.keys(constraints).length > 0 ? { ...constraints, ...resolved.fieldConstraints } : resolved.fieldConstraints, mergedFields: mergedFields.length > 0 ? mergedFields : undefined, }; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/never.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { NeverResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; function baseNode(ctx: NeverResolverContext): PydanticType { const { plugin } = ctx; return { type: plugin.external('typing.NoReturn'), }; } function neverResolver(ctx: NeverResolverContext): PydanticType { return ctx.nodes.base(ctx); } export function neverToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'never'>; }): PydanticType { const ctx: NeverResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.never; return resolver?.(ctx) ?? neverResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/null.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { NullResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; // eslint-disable-next-line @typescript-eslint/no-unused-vars function baseNode(_ctx: NullResolverContext): PydanticType { return { type: 'None', }; } function nullResolver(ctx: NullResolverContext): PydanticType { return ctx.nodes.base(ctx); } export function nullToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'null'>; }): PydanticType { const ctx: NullResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.null; return resolver?.(ctx) ?? nullResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/number.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { NumberResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; import type { FieldConstraints } from '../constants'; function constNode(ctx: NumberResolverContext): PydanticType | undefined { const { plugin, schema } = ctx; if (typeof schema.const === 'number') { const literal = plugin.external('typing.Literal'); return { type: $(literal).slice($.literal(schema.const)), }; } } function baseNode(ctx: NumberResolverContext): PydanticType { const { schema } = ctx; const constraints: FieldConstraints = {}; if (schema.minimum !== undefined) { constraints.ge = schema.minimum; } if (schema.exclusiveMinimum !== undefined) { constraints.gt = schema.exclusiveMinimum; } if (schema.maximum !== undefined) { constraints.le = schema.maximum; } if (schema.exclusiveMaximum !== undefined) { constraints.lt = schema.exclusiveMaximum; } if (schema.description !== undefined) { constraints.description = schema.description; } return { fieldConstraints: constraints, type: schema.type === 'integer' ? 'int' : 'float', }; } function numberResolver(ctx: NumberResolverContext): PydanticType { const constResult = ctx.nodes.const(ctx); if (constResult) return constResult; return ctx.nodes.base(ctx); } export function numberToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'integer' | 'number'>; }): PydanticType { const ctx: NumberResolverContext = { $, nodes: { base: baseNode, const: constNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.number; return resolver?.(ctx) ?? numberResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/object.ts ================================================ import { childContext, toCase } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import { safeRuntimeName } from '../../../../py-dsl/utils/name'; import type { ObjectResolverContext } from '../../resolvers'; import type { PydanticField, PydanticResult, PydanticType } from '../../shared/types'; export interface ObjectToFieldsResult extends Pick { childResults: Array; } function additionalPropertiesNode(ctx: ObjectResolverContext): PydanticType | null | undefined { const { schema } = ctx; if (!schema.additionalProperties || !schema.additionalProperties.type) return; if (schema.additionalProperties.type === 'never') return null; const result = ctx.walk( schema.additionalProperties, childContext(ctx.walkerCtx, 'additionalProperties'), ); ctx._childResults.push(result); return { type: result.type, }; } function fieldsNode(ctx: ObjectResolverContext): Array { const { schema } = ctx; const fields: Array = []; for (const name in schema.properties) { const property = schema.properties[name]!; const isOptional = !schema.required?.includes(name); const propertyResult = ctx.walk(property, childContext(ctx.walkerCtx, 'properties', name)); ctx._childResults.push(propertyResult); const final = ctx.applyModifiers(propertyResult, { optional: isOptional }); const snakeCaseName = safeRuntimeName(toCase(name, 'snake_case')); fields.push({ fieldConstraints: final.fieldConstraints, isOptional, name: ctx.plugin.symbol(snakeCaseName), originalName: name, type: final.type, }); } return fields; } function baseNode(ctx: ObjectResolverContext): PydanticType & { fields?: Array } { const additional = additionalPropertiesNode(ctx); if (additional === null) { const fields = fieldsNode(ctx); return { fields }; } if (additional) { const any = ctx.plugin.external('typing.Any'); if (!ctx.schema.properties) { return { type: $('dict').slice('str', any) }; } return { type: $('dict').slice('str', any) }; } // TODO: consider model_config = ConfigDict(extra='allow') if (ctx.schema.properties) { const fields = fieldsNode(ctx); return { fields }; } const any = ctx.plugin.external('typing.Any'); return { type: $('dict').slice('str', any) }; } function objectResolver(ctx: ObjectResolverContext): PydanticType { return ctx.nodes.base(ctx); } export function objectToFields( ctx: Pick, ): ObjectToFieldsResult { const { applyModifiers, plugin, schema, walk, walkerCtx } = ctx; const childResults: Array = []; const extendedCtx: ObjectResolverContext = { $, _childResults: childResults, applyModifiers, nodes: { additionalProperties: additionalPropertiesNode, base: baseNode, fields: fieldsNode, }, plugin, schema, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.object; const resolved = resolver?.(extendedCtx) ?? objectResolver(extendedCtx); const childResultsFinal = extendedCtx._childResults; return { childResults: childResultsFinal, ...resolved }; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/string.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { StringResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; import type { FieldConstraints } from '../constants'; function constNode(ctx: StringResolverContext): PydanticType | undefined { const { plugin, schema } = ctx; if (typeof schema.const === 'string') { const literal = plugin.external('typing.Literal'); return { type: $(literal).slice($.literal(schema.const)), }; } } function baseNode(ctx: StringResolverContext): PydanticType { const { schema } = ctx; const constraints: FieldConstraints = {}; if (schema.minLength !== undefined) { constraints.min_length = schema.minLength; } if (schema.maxLength !== undefined) { constraints.max_length = schema.maxLength; } if (schema.pattern !== undefined) { constraints.pattern = schema.pattern; } if (schema.description !== undefined) { constraints.description = schema.description; } return { fieldConstraints: constraints, type: 'str', }; } function stringResolver(ctx: StringResolverContext): PydanticType { const constResult = ctx.nodes.const(ctx); if (constResult) return constResult; return ctx.nodes.base(ctx); } export function stringToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'string'>; }): PydanticType { const ctx: StringResolverContext = { $, nodes: { base: baseNode, const: constNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.string; return resolver?.(ctx) ?? stringResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/tuple.ts ================================================ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext } from '@hey-api/shared'; import { $, type VarType } from '../../../../py-dsl'; import type { TupleResolverContext } from '../../resolvers'; import type { PydanticFinal, PydanticResult, PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; import type { FieldConstraints } from '../constants'; function baseNode(ctx: TupleResolverContext): PydanticType { const { applyModifiers, childResults, plugin } = ctx; const tuple = plugin.external('typing.Tuple'); const any = plugin.external('typing.Any'); if (childResults.length === 0) { return { type: $(tuple).slice(), }; } const itemTypes: Array = []; for (const result of childResults) { const finalResult = applyModifiers(result); if (finalResult.type !== undefined) { itemTypes.push(finalResult.type); } } if (itemTypes.length === 0) { return { type: $(tuple).slice(any, '...'), }; } return { type: $(tuple).slice(...itemTypes), }; } // eslint-disable-next-line @typescript-eslint/no-unused-vars function constNode(_ctx: TupleResolverContext): PydanticType | undefined { return; } function tupleResolver(ctx: TupleResolverContext): PydanticType { const baseResult = ctx.nodes.base(ctx); const fieldConstraints: FieldConstraints = { ...(baseResult.fieldConstraints ?? {}), }; if (ctx.schema.description !== undefined) { fieldConstraints.description = ctx.schema.description; } return { ...baseResult, fieldConstraints: Object.keys(fieldConstraints).length > 0 ? fieldConstraints : undefined, }; } export interface TupleToTypeResult extends PydanticType { childResults: Array; } export function tupleToType(ctx: { applyModifiers: (result: PydanticResult, options?: { optional?: boolean }) => PydanticFinal; plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'tuple'>; walk: Walker; walkerCtx: SchemaVisitorContext; }): TupleToTypeResult { const { applyModifiers, plugin, schema, walk, walkerCtx } = ctx; const childResults: Array = []; if (schema.items && schema.items.length > 0) { for (let i = 0; i < schema.items.length; i++) { const item = schema.items[i]!; const result = walk(item, childContext(walkerCtx, 'items', i)); childResults.push(result); } } const resolverCtx: TupleResolverContext = { $, applyModifiers, childResults, nodes: { base: baseNode, const: constNode, }, plugin, schema, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.tuple; const resolved = resolver?.(resolverCtx) ?? tupleResolver(resolverCtx); return { ...resolved, childResults, }; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/undefined.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { UndefinedResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; // eslint-disable-next-line @typescript-eslint/no-unused-vars function baseNode(_ctx: UndefinedResolverContext): PydanticType { return { type: 'None', }; } function undefinedResolver(ctx: UndefinedResolverContext): PydanticType { return ctx.nodes.base(ctx); } export function undefinedToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'undefined'>; }): PydanticType { const ctx: UndefinedResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.undefined; return resolver?.(ctx) ?? undefinedResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/union.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { UnionResolverContext } from '../../resolvers'; import type { PydanticFinal, PydanticResult, PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; import type { FieldConstraints } from '../constants'; function baseNode(ctx: UnionResolverContext): PydanticType { const { applyModifiers, childResults, plugin } = ctx; const nonNullResults: Array = []; let isNullable = false; for (const result of childResults) { if (result.type === 'None') { isNullable = true; } else { nonNullResults.push(result); } } isNullable = isNullable || childResults.some((r) => r.meta.nullable); if (nonNullResults.length === 0) { return { type: 'None', }; } if (nonNullResults.length === 1) { const finalResult = applyModifiers(nonNullResults[0]!); return finalResult; } const union = plugin.external('typing.Union'); const itemTypes = nonNullResults.map( (r) => applyModifiers(r).type ?? plugin.external('typing.Any'), ); if (isNullable) { itemTypes.push('None'); } return { type: $(union).slice(...itemTypes), }; } function unionResolver(ctx: UnionResolverContext): PydanticType { return ctx.nodes.base(ctx); } export interface UnionToTypeResult extends PydanticType { childResults: Array; isNullable: boolean; } export function unionToType({ applyModifiers, childResults, parentSchema, plugin, schemas, }: { applyModifiers: (result: PydanticResult, options?: { optional?: boolean }) => PydanticFinal; childResults: Array; parentSchema: IR.SchemaObject; plugin: PydanticPlugin['Instance']; schemas: ReadonlyArray; }): UnionToTypeResult { const constraints: FieldConstraints = {}; if (parentSchema.description !== undefined) { constraints.description = parentSchema.description; } let isNullable = false; for (const result of childResults) { if (result.type === 'None') { isNullable = true; break; } } isNullable = isNullable || childResults.some((r) => r.meta.nullable); const resolverCtx: UnionResolverContext = { $, applyModifiers, childResults, nodes: { base: baseNode, }, parentSchema, plugin, schema: parentSchema, schemas, }; const resolver = plugin.config['~resolvers']?.union; const resolved = resolver?.(resolverCtx) ?? unionResolver(resolverCtx); return { ...resolved, childResults, fieldConstraints: Object.keys(constraints).length > 0 ? { ...constraints, ...resolved.fieldConstraints } : resolved.fieldConstraints, isNullable, }; } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/unknown.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { UnknownResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; function baseNode(ctx: UnknownResolverContext): PydanticType { const { plugin } = ctx; return { type: plugin.external('typing.Any'), }; } function unknownResolver(ctx: UnknownResolverContext): PydanticType { return ctx.nodes.base(ctx); } export function unknownToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'unknown'>; }): PydanticType { const ctx: UnknownResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.unknown; return resolver?.(ctx) ?? unknownResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/toAst/void.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import type { VoidResolverContext } from '../../resolvers'; import type { PydanticType } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; // eslint-disable-next-line @typescript-eslint/no-unused-vars function baseNode(_ctx: VoidResolverContext): PydanticType { return { type: 'None', }; } function voidResolver(ctx: VoidResolverContext): PydanticType { return ctx.nodes.base(ctx); } export function voidToType({ plugin, schema, }: { plugin: PydanticPlugin['Instance']; schema: SchemaWithType<'void'>; }): PydanticType { const ctx: VoidResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.void; return resolver?.(ctx) ?? voidResolver(ctx); } ================================================ FILE: packages/openapi-python/src/plugins/pydantic/v2/walker.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import { fromRef } from '@hey-api/codegen-core'; import type { SchemaExtractor, SchemaVisitor } from '@hey-api/shared'; import { pathToJsonPointer } from '@hey-api/shared'; import { $ } from '../../../py-dsl'; import { composeMeta, defaultMeta, inheritMeta } from '../shared/meta'; import type { ProcessorContext } from '../shared/processor'; import type { PydanticFinal, PydanticResult } from '../shared/types'; import type { PydanticPlugin } from '../types'; import { arrayToType } from './toAst/array'; import { booleanToType } from './toAst/boolean'; import { enumToType } from './toAst/enum'; import { intersectionToType } from './toAst/intersection'; import { neverToType } from './toAst/never'; import { nullToType } from './toAst/null'; import { numberToType } from './toAst/number'; import { objectToFields } from './toAst/object'; import { stringToType } from './toAst/string'; import { tupleToType } from './toAst/tuple'; import { undefinedToType } from './toAst/undefined'; import { unionToType } from './toAst/union'; import { unknownToType } from './toAst/unknown'; import { voidToType } from './toAst/void'; export interface VisitorConfig { /** Optional schema extractor function. */ schemaExtractor?: SchemaExtractor; } export function createVisitor( config: VisitorConfig, ): SchemaVisitor { const { schemaExtractor } = config; return { applyModifiers(result, ctx, options = {}): PydanticFinal { const { optional } = options; const hasDefault = result.meta.default !== undefined; const needsOptional = optional || hasDefault; const needsNullable = result.meta.nullable; let type = result.type; const fieldConstraints = { ...result.fieldConstraints }; if (needsOptional || needsNullable) { const optionalType = ctx.plugin.external('typing.Optional'); type = $(optionalType).slice(type ?? ctx.plugin.external('typing.Any')); if (needsOptional) { fieldConstraints.default = hasDefault ? result.meta.default : null; } } return { enumMembers: result.enumMembers, fieldConstraints, fields: result.fields, type, }; }, array(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as PydanticFinal; const { childResults, fieldConstraints, type } = arrayToType({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { fieldConstraints, meta: composeMeta(childResults, { ...defaultMeta(schema) }), type, }; }, boolean(schema, ctx) { const result = booleanToType({ plugin: ctx.plugin, schema }); return { ...result, meta: defaultMeta(schema), }; }, enum(schema, ctx) { const result = enumToType({ plugin: ctx.plugin, schema }); return { ...result, meta: defaultMeta(schema), }; }, integer(schema, ctx) { const result = numberToType({ plugin: ctx.plugin, schema }); return { ...result, meta: defaultMeta(schema), }; }, intercept(schema, ctx, walk) { if (schemaExtractor && !schema.$ref) { const extracted = schemaExtractor({ meta: { resource: 'definition', resourceId: pathToJsonPointer(fromRef(ctx.path)) }, naming: ctx.plugin.config.definitions, path: fromRef(ctx.path), plugin: ctx.plugin, schema, }); if (extracted !== schema) return walk(extracted, ctx); } }, intersection(items, schemas, parentSchema, ctx) { const applyModifiers: Parameters[0]['applyModifiers'] = ( result, opts, ) => this.applyModifiers(result, ctx, opts) as PydanticFinal; const result = intersectionToType({ applyModifiers, childResults: items, parentSchema, plugin: ctx.plugin, }); return { ...result, meta: composeMeta(items, { default: parentSchema.default }), }; }, never(schema, ctx) { const result = neverToType({ plugin: ctx.plugin, schema }); return { ...result, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, null(schema, ctx) { const result = nullToType({ plugin: ctx.plugin, schema }); return { ...result, meta: { ...defaultMeta(schema), nullable: true, readonly: false, }, }; }, number(schema, ctx) { const result = numberToType({ plugin: ctx.plugin, schema }); return { ...result, meta: defaultMeta(schema), }; }, object(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = ( result, opts, ) => this.applyModifiers(result, ctx, opts) as PydanticFinal; const { childResults, fields, type } = objectToFields({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { fields, meta: inheritMeta(schema, childResults), type: type ?? '', }; }, postProcess(result) { return result; }, reference($ref, schema, ctx) { const query: SymbolMeta = { category: 'schema', resource: 'definition', resourceId: $ref, tool: 'pydantic', }; const refSymbol = ctx.plugin.referenceSymbol(query); const isRegistered = ctx.plugin.isSymbolRegistered(query); return { meta: { ...defaultMeta(schema), hasForwardReference: !isRegistered, }, type: refSymbol, }; }, string(schema, ctx) { const result = stringToType({ plugin: ctx.plugin, schema }); return { ...result, meta: defaultMeta(schema), }; }, tuple(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as PydanticFinal; const { childResults, fieldConstraints, type } = tupleToType({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { fieldConstraints, meta: composeMeta(childResults, { ...defaultMeta(schema) }), type, }; }, undefined(schema, ctx) { const result = undefinedToType({ plugin: ctx.plugin, schema }); return { ...result, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, union(items, schemas, parentSchema, ctx) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as PydanticFinal; const result = unionToType({ applyModifiers, childResults: items, parentSchema, plugin: ctx.plugin, schemas, }); return { ...result, meta: composeMeta(items, { default: parentSchema.default }), }; }, unknown(schema, ctx) { const result = unknownToType({ plugin: ctx.plugin, schema }); return { ...result, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, void(schema, ctx) { const result = voidToType({ plugin: ctx.plugin, schema }); return { ...result, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, }; } ================================================ FILE: packages/openapi-python/src/plugins/shared/utils/operation.ts ================================================ import type { IR } from '@hey-api/shared'; import { escapeComment } from '@hey-api/shared'; export function createOperationComment( operation: IR.OperationObject, ): ReadonlyArray | undefined { const comments: Array = []; if (operation.summary) { comments.push(escapeComment(operation.summary)); } if (operation.description) { if (comments.length) { comments.push(''); // Add an empty line between summary and description } comments.push(escapeComment(operation.description)); } if (operation.deprecated) { if (comments.length) { comments.push(''); // Add an empty line before deprecated } // TODO: smarter deprecation message comments.push('Deprecated.'); } return comments.length ? comments : undefined; } ================================================ FILE: packages/openapi-python/src/plugins/types.ts ================================================ export type PluginClientNames = | '@hey-api/client-aiohttp' | '@hey-api/client-httpx' | '@hey-api/client-requests' | '@hey-api/client-urllib3'; export type PluginMockNames = 'factory_boy' | 'faker' | 'mimesis'; export type PluginTransformerNames = never; export type PluginValidatorNames = 'attrs' | 'dataclasses' | 'marshmallow' | 'pydantic'; ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/class/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/class/default.py ================================================ class MyClass: pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/class/with-decorators.py ================================================ def my_decorator(func): return func def another_decorator(func): return func @my_decorator @another_decorator class MyClass: pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/class/with-docstring.py ================================================ class MyClass: """This is a class docstring""" pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/class/with-extends.py ================================================ class BaseClass: pass class MyClass(BaseClass): pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/class/with-method-docstring.py ================================================ class MyClass: def greet(): """Greets the user.""" pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/class/with-method.py ================================================ class MyClass: def foo(): return 42 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/function/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/function/default.py ================================================ def greet(): pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/function/with-annotations-defaults-return.py ================================================ def greet(name: str = "World", times: int = 1) -> None: for i in range(times): print("Hello, " + name) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/function/with-body.py ================================================ def greet(name): print(name) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/function/with-decorators.py ================================================ def my_decorator(func): return func def another_decorator(func): return func @my_decorator @another_decorator def greet(): pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/declarations/function/with-docstring.py ================================================ def greet(): """This function prints a greeting.""" print("Hello") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/await/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/await/inside-function.py ================================================ def fetchData(): pass async def main(): await fetchData() ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/binary/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/binary/add.py ================================================ a = 42 b = 84 z = a + b ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/binary/subtract.py ================================================ a = 42 b = 84 z = a - b ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/call/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/call/call.py ================================================ print("hi") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/dict/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/dict/dict.py ================================================ async def foo(): items = {"key1": "value1", "key2": "value2"} {k: v async for (k, v) in items.items() if k % 2} ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/list/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/list/list.py ================================================ async def foo(): items = [1, 2, 3] evens = [x async for x in items if x % 2 == 0] ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/nested/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/nested/dict-list.py ================================================ data = {"numbers": [1, 2, 3], "nestedDict": {"foo": "bar"}} ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/set/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/comprehensions/set/dict.py ================================================ async def foo(): items = [1, 2, 3] unique_evens = {x for x in items if x % 2} ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/dict/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/dict/dict.py ================================================ person = {"name": "Alice", "age": 30} ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/fString/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/fString/multiple-expressions.py ================================================ a = 1 b = 2 print(f"Sum: {a + b}") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/fString/simple-interpolation.py ================================================ name = "Joe" print(f"Hello, {name}!") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/generator/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/generator/async.py ================================================ x_iter = [1, 2, 3] (x async for x in x_iter) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/generator/simple.py ================================================ x_iter = [1, 2, 3] (x for x in x_iter) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/generator/with-filter.py ================================================ x_iter = [1, 2, 3] (x for x in x_iter if x > 10) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/identifier/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/identifier/identifier.py ================================================ y = 42 x = y ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/kwarg/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/kwarg/multiple.py ================================================ result = Field(..., min_length=1, max_length=100, description="A field") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/kwarg/number.py ================================================ result = func(count=42) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/kwarg/string.py ================================================ result = func(name="test") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/lambda/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/lambda/simple.py ================================================ x = 5 lambda : x + 1 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/lambda/with-params-and-default.py ================================================ lambda x, y = 10: x * y ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/list/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/list/list.py ================================================ nums = [1, 2, 3] ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/literal/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/literal/primitive.py ================================================ s = "hello" n = 123 b = True c = False none = None ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/set/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/set/set.py ================================================ foo = "bar" emptySet = set() numberSet = {1, 2, 3} mixedSet = {"a", True, foo} ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/subscript/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/subscript/index-access.py ================================================ items = (1, 2, 3) first = items[0] ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/subscript/multiple.py ================================================ data = dict[str, int] ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/subscript/nested.py ================================================ matrix = list[list[int]] ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/subscript/single.py ================================================ numbers = list[int] ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/tuple/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/tuple/tuple.py ================================================ t = (1, 2, 3) single = (42,) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/yield/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/yield/default.py ================================================ def gen(): yield ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/yield/from-iterable.py ================================================ iterable = [1, 2, 3] def gen(): yield from iterable ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/expressions/yield/with-value.py ================================================ def gen(): yield 42 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/assignment/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/assignment/annotation-only.py ================================================ name: str ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/assignment/annotation-with-value.py ================================================ name: str = "default" ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/assignment/complex-annotation.py ================================================ items: List[str] = Field(..., min_length=1) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/assignment/optional-annotation.py ================================================ name: Optional[str] = None ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/assignment/primitive.py ================================================ foo = 42 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/augmentedAssignment/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/augmentedAssignment/arithmetic.py ================================================ x = 0 y = 0 z = 0 a = 0 b = 0 c = 0 x += 1 y -= 2 z *= 3 a /= 4 b //= 5 c %= 6 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/augmentedAssignment/bitwise.py ================================================ x = 1 y = 1 z = 1 a = 1 b = 1 c = 1 x **= 2 y &= 1 z |= 1 a ^= 1 b >>= 1 c <<= 1 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/block/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/block/function.py ================================================ def main(): print("inside") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/break/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/break/while.py ================================================ while True: break ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/continue/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/continue/while.py ================================================ while True: continue ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/expression/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/expression/simple.py ================================================ print("hello") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/for/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/for/for-else.py ================================================ items = [1, 2, 3] for x in items: pass else: print("done") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/for/for.py ================================================ for i in range(3): print(i) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/if/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/if/if-else.py ================================================ x = 0 if x > 0: print("positive") else: print("non-positive") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/if/if.py ================================================ if True: print("positive") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/import/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/import/from-with-alias.py ================================================ from os import environ as env ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/import/from-with-asterisk.py ================================================ from collections import * ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/import/from-with-name-alias.py ================================================ from os import path, environ as env ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/import/from-with-name.py ================================================ from sys import argv ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/import/module-with-alias.py ================================================ import json as js ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/import/module.py ================================================ import math import loads ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/raise/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/raise/reraise.py ================================================ raise ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/raise/with-exception.py ================================================ raise ValueError("Invalid input") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/return/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/return/function.py ================================================ def get_message(): return "hi" ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/try/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/try/with-except-else-finally.py ================================================ def dangerous_func(): pass try: dangerous_func() except Exception as e: print(e) else: pass finally: pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/try/with-except-else.py ================================================ def dangerous_func(): pass try: dangerous_func() except: pass else: pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/try/with-except-finally.py ================================================ def dangerous_func(): pass try: dangerous_func() except Exception: pass finally: pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/try/with-except.py ================================================ def dangerous_func(): pass try: dangerous_func() except ValueError as e: print(e) ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/try/with-finally.py ================================================ def dangerous_func(): pass try: dangerous_func() finally: pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/while/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/while/while-else.py ================================================ def should_continue(): return False while should_continue(): pass else: print("done") ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/while/while.py ================================================ x = 3 while x > 0: print(x) x = x - 1 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/with/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/with/with-alias.py ================================================ class context_manager: def __enter__(self): return self def __exit__( self, exc_type, exc_val, exc_tb, ): return False with context_manager() as alias: pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/with/with-async.py ================================================ class context_manager: def __enter__(self): return self def __exit__( self, exc_type, exc_val, exc_tb, ): return False async def foo(): async with context_manager(): pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/with/with-many-items.py ================================================ class context_manager: def __enter__(self): return self def __exit__( self, exc_type, exc_val, exc_tb, ): return False class context_manager2: def __enter__(self): return self def __exit__( self, exc_type, exc_val, exc_tb, ): return False class context_manager3: def __enter__(self): return self def __exit__( self, exc_type, exc_val, exc_tb, ): return False with context_manager() as alias, context_manager2() as (a, b), context_manager3(): pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/with/with-tuple-alias.py ================================================ class context_manager: def __enter__(self): return self def __exit__( self, exc_type, exc_val, exc_tb, ): return False with context_manager() as (a, b): pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/statements/with/with.py ================================================ class context_manager: def __enter__(self): return self def __exit__( self, exc_type, exc_val, exc_tb, ): return False with context_manager(): pass ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/structure/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/structure/comment/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/structure/comment/simple.py ================================================ # This is a comment ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/structure/sourceFile/__init__.py ================================================ ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/structure/sourceFile/simple.py ================================================ a = 1 b = 2 ================================================ FILE: packages/openapi-python/src/py-compiler/__snapshots__/nodes/structure/sourceFile/with-docstring.py ================================================ """This is a module-level docstring.""" foo = 1 ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/constants.ts ================================================ import path from 'node:path'; export const snapshotsDir = path.join(__dirname, '..', '__snapshots__'); export const tmpDir = path.join(__dirname, '..', '.tmp'); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/globalTeardown.ts ================================================ import fs from 'node:fs'; import { tmpDir } from './constants'; export function teardown() { fs.rmSync(tmpDir, { force: true, recursive: true }); } ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/declarations/class.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('class declaration', () => { it('default', async () => { const file = py.factory.createSourceFile([py.factory.createClassDeclaration('MyClass', [])]); await assertPrintedMatchesSnapshot(file, 'default.py'); }); it('with docstring', async () => { const node = py.factory.createSourceFile([ py.factory.createClassDeclaration( 'MyClass', [], undefined, undefined, 'This is a class docstring', ), ]); await assertPrintedMatchesSnapshot(node, 'with-docstring.py'); }); it('with base class', async () => { const node = py.factory.createSourceFile([ py.factory.createClassDeclaration('BaseClass', []), py.factory.createEmptyStatement(), py.factory.createClassDeclaration('MyClass', [], undefined, [ py.factory.createIdentifier('BaseClass'), ]), ]); await assertPrintedMatchesSnapshot(node, 'with-extends.py'); }); it('with method', async () => { const node = py.factory.createSourceFile([ py.factory.createClassDeclaration('MyClass', [ py.factory.createFunctionDeclaration('foo', [], undefined, [ py.factory.createReturnStatement(py.factory.createLiteral(42)), ]), ]), ]); await assertPrintedMatchesSnapshot(node, 'with-method.py'); }); it('with decorators', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'my_decorator', [py.factory.createFunctionParameter('func')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('func'))], ), py.factory.createEmptyStatement(), py.factory.createFunctionDeclaration( 'another_decorator', [py.factory.createFunctionParameter('func')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('func'))], ), py.factory.createEmptyStatement(), py.factory.createClassDeclaration( 'MyClass', [], [ py.factory.createIdentifier('my_decorator'), py.factory.createIdentifier('another_decorator'), ], ), ]); await assertPrintedMatchesSnapshot(file, 'with-decorators.py'); }); it('with method docstring', async () => { const file = py.factory.createSourceFile([ py.factory.createClassDeclaration('MyClass', [ py.factory.createFunctionDeclaration( 'greet', [], undefined, [], undefined, 'Greets the user.', ), ]), ]); await assertPrintedMatchesSnapshot(file, 'with-method-docstring.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/declarations/function.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('function declaration', () => { it('default', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('greet', [], undefined, []), ]); await assertPrintedMatchesSnapshot(file, 'default.py'); }); it('with docstring', async () => { const node = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'greet', [], undefined, [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('Hello'), ]), ), ], undefined, 'This function prints a greeting.', ), ]); await assertPrintedMatchesSnapshot(node, 'with-docstring.py'); }); it('with body', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'greet', [py.factory.createFunctionParameter('name')], undefined, [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createIdentifier('name'), ]), ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'with-body.py'); }); it('with decorators', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'my_decorator', [py.factory.createFunctionParameter('func')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('func'))], ), py.factory.createEmptyStatement(), py.factory.createFunctionDeclaration( 'another_decorator', [py.factory.createFunctionParameter('func')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('func'))], ), py.factory.createEmptyStatement(), py.factory.createFunctionDeclaration( 'greet', [], undefined, [], [ py.factory.createIdentifier('my_decorator'), py.factory.createIdentifier('another_decorator'), ], ), ]); await assertPrintedMatchesSnapshot(file, 'with-decorators.py'); }); it('with parameter annotations, defaults, and return type', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'greet', [ py.factory.createFunctionParameter( 'name', py.factory.createIdentifier('str'), py.factory.createLiteral('World'), ), py.factory.createFunctionParameter( 'times', py.factory.createIdentifier('int'), py.factory.createLiteral(1), ), ], py.factory.createIdentifier('None'), // returnType [ py.factory.createForStatement( py.factory.createIdentifier('i'), py.factory.createCallExpression(py.factory.createIdentifier('range'), [ py.factory.createIdentifier('times'), ]), [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createBinaryExpression( py.factory.createLiteral('Hello, '), '+', py.factory.createIdentifier('name'), ), ]), ), ], ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'with-annotations-defaults-return.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/await.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('await expression', () => { it('inside async function', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('fetchData', [], undefined, []), py.factory.createEmptyStatement(), py.factory.createFunctionDeclaration( 'main', [], undefined, [ py.factory.createExpressionStatement( py.factory.createAwaitExpression( py.factory.createCallExpression(py.factory.createIdentifier('fetchData'), []), ), ), ], undefined, undefined, [py.factory.createIdentifier('async')], ), ]); await assertPrintedMatchesSnapshot(file, 'inside-function.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/binary.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('binary expression', () => { it('add', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('a'), undefined, py.factory.createLiteral(42), ), py.factory.createAssignment( py.factory.createIdentifier('b'), undefined, py.factory.createLiteral(84), ), py.factory.createAssignment( py.factory.createIdentifier('z'), undefined, py.factory.createBinaryExpression( py.factory.createIdentifier('a'), '+', py.factory.createIdentifier('b'), ), ), ]); await assertPrintedMatchesSnapshot(file, 'add.py'); }); it('subtract', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('a'), undefined, py.factory.createLiteral(42), ), py.factory.createAssignment( py.factory.createIdentifier('b'), undefined, py.factory.createLiteral(84), ), py.factory.createAssignment( py.factory.createIdentifier('z'), undefined, py.factory.createBinaryExpression( py.factory.createIdentifier('a'), '-', py.factory.createIdentifier('b'), ), ), ]); await assertPrintedMatchesSnapshot(file, 'subtract.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/call.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('call expression', () => { it('print', async () => { const file = py.factory.createSourceFile([ py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('hi'), ]), ]); await assertPrintedMatchesSnapshot(file, 'call.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/comprehensions/dict.test.ts ================================================ import { py } from '../../../../index'; import { assertPrintedMatchesSnapshot } from '../../utils'; describe('dict comprehension', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'foo', [], undefined, [ py.factory.createAssignment( py.factory.createIdentifier('items'), undefined, py.factory.createDictExpression([ { key: py.factory.createLiteral('key1'), value: py.factory.createLiteral('value1'), }, { key: py.factory.createLiteral('key2'), value: py.factory.createLiteral('value2'), }, ]), ), py.factory.createExpressionStatement( py.factory.createDictComprehension( py.factory.createIdentifier('k'), py.factory.createIdentifier('v'), py.factory.createTupleExpression([ py.factory.createIdentifier('k'), py.factory.createIdentifier('v'), ]), py.factory.createCallExpression( py.factory.createMemberExpression( py.factory.createIdentifier('items'), py.factory.createIdentifier('items'), ), [], ), [ py.factory.createBinaryExpression( py.factory.createIdentifier('k'), '%', py.factory.createLiteral(2), ), ], true, ), ), ], undefined, undefined, [py.factory.createIdentifier('async')], ), ]); await assertPrintedMatchesSnapshot(file, 'dict.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/comprehensions/list.test.ts ================================================ import { py } from '../../../../index'; import { assertPrintedMatchesSnapshot } from '../../utils'; describe('list comprehension', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'foo', [], undefined, [ py.factory.createAssignment( py.factory.createIdentifier('items'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createAssignment( py.factory.createIdentifier('evens'), undefined, py.factory.createListComprehension( py.factory.createIdentifier('x'), py.factory.createIdentifier('x'), py.factory.createIdentifier('items'), [ py.factory.createBinaryExpression( py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '%', py.factory.createLiteral(2), ), '==', py.factory.createLiteral(0), ), ], true, ), ), ], undefined, undefined, [py.factory.createIdentifier('async')], ), ]); await assertPrintedMatchesSnapshot(file, 'list.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/comprehensions/nested.test.ts ================================================ import { py } from '../../../../index'; import { assertPrintedMatchesSnapshot } from '../../utils'; describe('nested comprehension', () => { it('dict and list', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('data'), undefined, py.factory.createDictExpression([ { key: py.factory.createLiteral('numbers'), value: py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), }, { key: py.factory.createLiteral('nestedDict'), value: py.factory.createDictExpression([ { key: py.factory.createLiteral('foo'), value: py.factory.createLiteral('bar'), }, ]), }, ]), ), ]); await assertPrintedMatchesSnapshot(file, 'dict-list.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/comprehensions/set.test.ts ================================================ import { py } from '../../../../index'; import { assertPrintedMatchesSnapshot } from '../../utils'; describe('set comprehension', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration( 'foo', [], undefined, [ py.factory.createAssignment( py.factory.createIdentifier('items'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createAssignment( py.factory.createIdentifier('unique_evens'), undefined, py.factory.createSetComprehension( py.factory.createIdentifier('x'), py.factory.createIdentifier('x'), py.factory.createIdentifier('items'), [ py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '%', py.factory.createLiteral(2), ), ], ), ), ], undefined, undefined, [py.factory.createIdentifier('async')], ), ]); await assertPrintedMatchesSnapshot(file, 'dict.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/dict.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('dict expression', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('person'), undefined, py.factory.createDictExpression([ { key: py.factory.createLiteral('name'), value: py.factory.createLiteral('Alice'), }, { key: py.factory.createLiteral('age'), value: py.factory.createLiteral(30), }, ]), ), ]); await assertPrintedMatchesSnapshot(file, 'dict.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/fString.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('f-string expression', () => { it('simple interpolation', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('name'), undefined, py.factory.createLiteral('Joe'), ), py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createFStringExpression(['Hello, ', py.factory.createIdentifier('name'), '!']), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'simple-interpolation.py'); }); it('with multiple expressions', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('a'), undefined, py.factory.createLiteral(1), ), py.factory.createAssignment( py.factory.createIdentifier('b'), undefined, py.factory.createLiteral(2), ), py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createFStringExpression([ 'Sum: ', py.factory.createBinaryExpression( py.factory.createIdentifier('a'), '+', py.factory.createIdentifier('b'), ), ]), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'multiple-expressions.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/generator.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('generator expression', () => { it('simple', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x_iter'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createExpressionStatement( py.factory.createGeneratorExpression( py.factory.createIdentifier('x'), py.factory.createIdentifier('x'), py.factory.createIdentifier('x_iter'), ), ), ]); await assertPrintedMatchesSnapshot(file, 'simple.py'); }); it('with filters', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x_iter'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createExpressionStatement( py.factory.createGeneratorExpression( py.factory.createIdentifier('x'), py.factory.createIdentifier('x'), py.factory.createIdentifier('x_iter'), [ py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '>', py.factory.createLiteral(10), ), ], ), ), ]); await assertPrintedMatchesSnapshot(file, 'with-filter.py'); }); it('async', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x_iter'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createExpressionStatement( py.factory.createGeneratorExpression( py.factory.createIdentifier('x'), py.factory.createIdentifier('x'), py.factory.createIdentifier('x_iter'), undefined, true, ), ), ]); await assertPrintedMatchesSnapshot(file, 'async.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/identifier.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('identifier expression', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('y'), undefined, py.factory.createLiteral(42), ), py.factory.createAssignment( py.factory.createIdentifier('x'), undefined, py.factory.createIdentifier('y'), ), ]); await assertPrintedMatchesSnapshot(file, 'identifier.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/kwarg.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('keyword argument expression', () => { it('string value', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('result'), undefined, py.factory.createCallExpression(py.factory.createIdentifier('func'), [ py.factory.createKeywordArgument('name', py.factory.createLiteral('test')), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'string.py'); }); it('number value', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('result'), undefined, py.factory.createCallExpression(py.factory.createIdentifier('func'), [ py.factory.createKeywordArgument('count', py.factory.createLiteral(42)), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'number.py'); }); it('multiple keyword arguments', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('result'), undefined, py.factory.createCallExpression(py.factory.createIdentifier('Field'), [ py.factory.createIdentifier('...'), py.factory.createKeywordArgument('min_length', py.factory.createLiteral(1)), py.factory.createKeywordArgument('max_length', py.factory.createLiteral(100)), py.factory.createKeywordArgument('description', py.factory.createLiteral('A field')), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'multiple.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/lambda.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('lambda expression', () => { it('simple', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x'), undefined, py.factory.createLiteral(5), ), py.factory.createExpressionStatement( py.factory.createLambdaExpression( [], py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '+', py.factory.createLiteral(1), ), ), ), ]); await assertPrintedMatchesSnapshot(file, 'simple.py'); }); it('with parameters and default', async () => { const file = py.factory.createSourceFile([ py.factory.createExpressionStatement( py.factory.createLambdaExpression( [ py.factory.createFunctionParameter('x'), py.factory.createFunctionParameter('y', undefined, py.factory.createLiteral(10)), ], py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '*', py.factory.createIdentifier('y'), ), ), ), ]); await assertPrintedMatchesSnapshot(file, 'with-params-and-default.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/list.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('list expression', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('nums'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'list.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/literal.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('literal expression', () => { it('primitive variables', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('s'), undefined, py.factory.createLiteral('hello'), ), py.factory.createAssignment( py.factory.createIdentifier('n'), undefined, py.factory.createLiteral(123), ), py.factory.createAssignment( py.factory.createIdentifier('b'), undefined, py.factory.createLiteral(true), ), py.factory.createAssignment( py.factory.createIdentifier('c'), undefined, py.factory.createLiteral(false), ), py.factory.createAssignment( py.factory.createIdentifier('none'), undefined, py.factory.createLiteral(null), ), ]); await assertPrintedMatchesSnapshot(file, 'primitive.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/set.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('set expression', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('foo'), undefined, py.factory.createLiteral('bar'), ), py.factory.createAssignment( py.factory.createIdentifier('emptySet'), undefined, py.factory.createSetExpression([]), ), py.factory.createAssignment( py.factory.createIdentifier('numberSet'), undefined, py.factory.createSetExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createAssignment( py.factory.createIdentifier('mixedSet'), undefined, py.factory.createSetExpression([ py.factory.createLiteral('a'), py.factory.createLiteral(true), py.factory.createIdentifier('foo'), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'set.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/subscript.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('subscript expression', () => { it('type annotation with single type parameter', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('numbers'), undefined, py.factory.createSubscriptExpression( py.factory.createIdentifier('list'), py.factory.createIdentifier('int'), ), ), ]); await assertPrintedMatchesSnapshot(file, 'single.py'); }); it('type annotation with multiple type parameters', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('data'), undefined, py.factory.createSubscriptExpression( py.factory.createIdentifier('dict'), py.factory.createSubscriptSlice([ py.factory.createIdentifier('str'), py.factory.createIdentifier('int'), ]), ), ), ]); await assertPrintedMatchesSnapshot(file, 'multiple.py'); }); it('index access', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('items'), undefined, py.factory.createTupleExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createAssignment( py.factory.createIdentifier('first'), undefined, py.factory.createSubscriptExpression( py.factory.createIdentifier('items'), py.factory.createLiteral(0), ), ), ]); await assertPrintedMatchesSnapshot(file, 'index-access.py'); }); it('nested type annotation', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('matrix'), undefined, py.factory.createSubscriptExpression( py.factory.createIdentifier('list'), py.factory.createSubscriptExpression( py.factory.createIdentifier('list'), py.factory.createIdentifier('int'), ), ), ), ]); await assertPrintedMatchesSnapshot(file, 'nested.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/tuple.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('tuple expression', () => { it('assignment', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('t'), undefined, py.factory.createTupleExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createAssignment( py.factory.createIdentifier('single'), undefined, py.factory.createTupleExpression([py.factory.createLiteral(42)]), ), ]); await assertPrintedMatchesSnapshot(file, 'tuple.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/expressions/yield.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('yield expression', () => { it('without value', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('gen', [], undefined, [ py.factory.createExpressionStatement(py.factory.createYieldExpression(undefined)), ]), ]); await assertPrintedMatchesSnapshot(file, 'default.py'); }); it('with value', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('gen', [], undefined, [ py.factory.createExpressionStatement( py.factory.createYieldExpression(py.factory.createLiteral(42)), ), ]), ]); await assertPrintedMatchesSnapshot(file, 'with-value.py'); }); it('from expression', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('iterable'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createEmptyStatement(), py.factory.createFunctionDeclaration('gen', [], undefined, [ py.factory.createExpressionStatement( py.factory.createYieldFromExpression(py.factory.createIdentifier('iterable')), ), ]), ]); await assertPrintedMatchesSnapshot(file, 'from-iterable.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/assignment.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('assignment statement', () => { it('primitive variables', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('foo'), undefined, py.factory.createLiteral(42), ), ]); await assertPrintedMatchesSnapshot(file, 'primitive.py'); }); it('annotation only', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('name'), py.factory.createIdentifier('str'), ), ]); await assertPrintedMatchesSnapshot(file, 'annotation-only.py'); }); it('annotation with value', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('name'), py.factory.createIdentifier('str'), py.factory.createLiteral('default'), ), ]); await assertPrintedMatchesSnapshot(file, 'annotation-with-value.py'); }); it('optional annotation', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('name'), py.factory.createSubscriptExpression( py.factory.createIdentifier('Optional'), py.factory.createIdentifier('str'), ), py.factory.createIdentifier('None'), ), ]); await assertPrintedMatchesSnapshot(file, 'optional-annotation.py'); }); it('complex type annotation', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('items'), py.factory.createSubscriptExpression( py.factory.createIdentifier('List'), py.factory.createIdentifier('str'), ), py.factory.createCallExpression(py.factory.createIdentifier('Field'), [ py.factory.createIdentifier('...'), py.factory.createKeywordArgument('min_length', py.factory.createLiteral(1)), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'complex-annotation.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/augmentedAssignment.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('augmented assignment statement', () => { it('arithmetic operators', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x'), undefined, py.factory.createLiteral(0), ), py.factory.createAssignment( py.factory.createIdentifier('y'), undefined, py.factory.createLiteral(0), ), py.factory.createAssignment( py.factory.createIdentifier('z'), undefined, py.factory.createLiteral(0), ), py.factory.createAssignment( py.factory.createIdentifier('a'), undefined, py.factory.createLiteral(0.0), ), py.factory.createAssignment( py.factory.createIdentifier('b'), undefined, py.factory.createLiteral(0), ), py.factory.createAssignment( py.factory.createIdentifier('c'), undefined, py.factory.createLiteral(0), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('x'), '+=', py.factory.createLiteral(1), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('y'), '-=', py.factory.createLiteral(2), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('z'), '*=', py.factory.createLiteral(3), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('a'), '/=', py.factory.createLiteral(4), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('b'), '//=', py.factory.createLiteral(5), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('c'), '%=', py.factory.createLiteral(6), ), ]); await assertPrintedMatchesSnapshot(file, 'arithmetic.py'); }); it('power and bitwise operators', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x'), undefined, py.factory.createLiteral(1), ), py.factory.createAssignment( py.factory.createIdentifier('y'), undefined, py.factory.createLiteral(1), ), py.factory.createAssignment( py.factory.createIdentifier('z'), undefined, py.factory.createLiteral(1), ), py.factory.createAssignment( py.factory.createIdentifier('a'), undefined, py.factory.createLiteral(1), ), py.factory.createAssignment( py.factory.createIdentifier('b'), undefined, py.factory.createLiteral(1), ), py.factory.createAssignment( py.factory.createIdentifier('c'), undefined, py.factory.createLiteral(1), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('x'), '**=', py.factory.createLiteral(2), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('y'), '&=', py.factory.createLiteral(1), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('z'), '|=', py.factory.createLiteral(1), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('a'), '^=', py.factory.createLiteral(1), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('b'), '>>=', py.factory.createLiteral(1), ), py.factory.createAugmentedAssignment( py.factory.createIdentifier('c'), '<<=', py.factory.createLiteral(1), ), ]); await assertPrintedMatchesSnapshot(file, 'bitwise.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/block.test.ts ================================================ import { py } from '../../..'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('block statement', () => { it('inside function', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('main', [], undefined, [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('inside'), ]), ), ]), ]); await assertPrintedMatchesSnapshot(file, 'function.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/break.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('break statement', () => { it('inside a while loop', async () => { const file = py.factory.createSourceFile([ py.factory.createWhileStatement(py.factory.createLiteral(true), [ py.factory.createBreakStatement(), ]), ]); await assertPrintedMatchesSnapshot(file, 'while.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/continue.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('continue statement', () => { it('inside a while loop', async () => { const file = py.factory.createSourceFile([ py.factory.createWhileStatement(py.factory.createLiteral(true), [ py.factory.createContinueStatement(), ]), ]); await assertPrintedMatchesSnapshot(file, 'while.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/expression.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('expression statement', () => { it('simple', async () => { const file = py.factory.createSourceFile([ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('hello'), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'simple.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/for.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('for statement', () => { it('simple', async () => { const file = py.factory.createSourceFile([ py.factory.createForStatement( py.factory.createIdentifier('i'), py.factory.createCallExpression(py.factory.createIdentifier('range'), [ py.factory.createLiteral(3), ]), [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createIdentifier('i'), ]), ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'for.py'); }); it('with else', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('items'), undefined, py.factory.createListExpression([ py.factory.createLiteral(1), py.factory.createLiteral(2), py.factory.createLiteral(3), ]), ), py.factory.createForStatement( py.factory.createIdentifier('x'), py.factory.createIdentifier('items'), [], [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('done'), ]), ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'for-else.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/if.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('if statement', () => { it('simple', async () => { const file = py.factory.createSourceFile([ py.factory.createIfStatement(py.factory.createLiteral(true), [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('positive'), ]), ), ]), ]); await assertPrintedMatchesSnapshot(file, 'if.py'); }); it('with else', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x'), undefined, py.factory.createLiteral(0), ), py.factory.createIfStatement( py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '>', py.factory.createLiteral(0), ), [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('positive'), ]), ), ], [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('non-positive'), ]), ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'if-else.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/import.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('import statement', () => { it('module', async () => { const file = py.factory.createSourceFile([ py.factory.createImportStatement('math'), py.factory.createImportStatement('json', [{ name: 'loads' }], false), ]); await assertPrintedMatchesSnapshot(file, 'module.py'); }); it('module with alias', async () => { const file = py.factory.createSourceFile([ py.factory.createImportStatement('json', [{ alias: 'js', name: 'json' }], false), ]); await assertPrintedMatchesSnapshot(file, 'module-with-alias.py'); }); it('from with name and alias', async () => { const file = py.factory.createSourceFile([ py.factory.createImportStatement( 'os', [{ name: 'path' }, { alias: 'env', name: 'environ' }], true, ), ]); await assertPrintedMatchesSnapshot(file, 'from-with-name-alias.py'); }); it('from with alias', async () => { const file = py.factory.createSourceFile([ py.factory.createImportStatement('os', [{ alias: 'env', name: 'environ' }], true), ]); await assertPrintedMatchesSnapshot(file, 'from-with-alias.py'); }); it('from with name', async () => { const file = py.factory.createSourceFile([ py.factory.createImportStatement('sys', [{ name: 'argv' }], true), ]); await assertPrintedMatchesSnapshot(file, 'from-with-name.py'); }); it('from with asterisk', async () => { const file = py.factory.createSourceFile([ py.factory.createImportStatement('collections', [], true), ]); await assertPrintedMatchesSnapshot(file, 'from-with-asterisk.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/raise.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('raise statement', () => { it('with exception', async () => { const file = py.factory.createSourceFile([ py.factory.createRaiseStatement( py.factory.createCallExpression(py.factory.createIdentifier('ValueError'), [ py.factory.createLiteral('Invalid input'), ]), ), ]); await assertPrintedMatchesSnapshot(file, 'with-exception.py'); }); it('re-raise', async () => { const file = py.factory.createSourceFile([py.factory.createRaiseStatement()]); await assertPrintedMatchesSnapshot(file, 'reraise.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/return.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('return statement', () => { it('inside function', async () => { const node = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('get_message', [], undefined, [ py.factory.createReturnStatement(py.factory.createLiteral('hi')), ]), ]); await assertPrintedMatchesSnapshot(node, 'function.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/try.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('try statement', () => { it('with except', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('dangerous_func', [], undefined, []), py.factory.createEmptyStatement(), py.factory.createTryStatement( [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('dangerous_func'), []), ), ], [ py.factory.createExceptClause( [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createIdentifier('e'), ]), ), ], py.factory.createIdentifier('ValueError'), py.factory.createIdentifier('e'), ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'with-except.py'); }); it('with except and else', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('dangerous_func', [], undefined, []), py.factory.createEmptyStatement(), py.factory.createTryStatement( [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('dangerous_func'), []), ), ], [py.factory.createExceptClause([])], [], ), ]); await assertPrintedMatchesSnapshot(file, 'with-except-else.py'); }); it('with finally', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('dangerous_func', [], undefined, []), py.factory.createEmptyStatement(), py.factory.createTryStatement( [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('dangerous_func'), []), ), ], undefined, undefined, [], ), ]); await assertPrintedMatchesSnapshot(file, 'with-finally.py'); }); it('with except and finally', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('dangerous_func', [], undefined, []), py.factory.createEmptyStatement(), py.factory.createTryStatement( [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('dangerous_func'), []), ), ], [py.factory.createExceptClause([], py.factory.createIdentifier('Exception'))], undefined, [], ), ]); await assertPrintedMatchesSnapshot(file, 'with-except-finally.py'); }); it('with except, else, and finally', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('dangerous_func', [], undefined, []), py.factory.createEmptyStatement(), py.factory.createTryStatement( [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('dangerous_func'), []), ), ], [ py.factory.createExceptClause( [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createIdentifier('e'), ]), ), ], py.factory.createIdentifier('Exception'), py.factory.createIdentifier('e'), ), ], [], [], ), ]); await assertPrintedMatchesSnapshot(file, 'with-except-else-finally.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/while.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('while statement', () => { it('simple', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('x'), undefined, py.factory.createLiteral(3), ), py.factory.createWhileStatement( py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '>', py.factory.createLiteral(0), ), [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createIdentifier('x'), ]), ), py.factory.createAssignment( py.factory.createIdentifier('x'), undefined, py.factory.createBinaryExpression( py.factory.createIdentifier('x'), '-', py.factory.createLiteral(1), ), ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'while.py'); }); it('with else', async () => { const file = py.factory.createSourceFile([ py.factory.createFunctionDeclaration('should_continue', [], undefined, [ py.factory.createReturnStatement(py.factory.createLiteral(false)), ]), py.factory.createWhileStatement( py.factory.createCallExpression(py.factory.createIdentifier('should_continue'), []), [], [ py.factory.createExpressionStatement( py.factory.createCallExpression(py.factory.createIdentifier('print'), [ py.factory.createLiteral('done'), ]), ), ], ), ]); await assertPrintedMatchesSnapshot(file, 'while-else.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/statements/with.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('with statement', () => { it('with alias', async () => { const file = py.factory.createSourceFile([ py.factory.createClassDeclaration('context_manager', [ py.factory.createFunctionDeclaration( '__enter__', [py.factory.createFunctionParameter('self')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('self'))], ), py.factory.createFunctionDeclaration( '__exit__', [ py.factory.createFunctionParameter('self'), py.factory.createFunctionParameter('exc_type'), py.factory.createFunctionParameter('exc_val'), py.factory.createFunctionParameter('exc_tb'), ], undefined, [py.factory.createReturnStatement(py.factory.createLiteral(false))], ), ]), py.factory.createEmptyStatement(), py.factory.createWithStatement( [ py.factory.createWithItem( py.factory.createCallExpression(py.factory.createIdentifier('context_manager'), []), py.factory.createIdentifier('alias'), ), ], [], ), ]); await assertPrintedMatchesSnapshot(file, 'with-alias.py'); }); it('with tuple alias', async () => { const file = py.factory.createSourceFile([ py.factory.createClassDeclaration('context_manager', [ py.factory.createFunctionDeclaration( '__enter__', [py.factory.createFunctionParameter('self')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('self'))], ), py.factory.createFunctionDeclaration( '__exit__', [ py.factory.createFunctionParameter('self'), py.factory.createFunctionParameter('exc_type'), py.factory.createFunctionParameter('exc_val'), py.factory.createFunctionParameter('exc_tb'), ], undefined, [py.factory.createReturnStatement(py.factory.createLiteral(false))], ), ]), py.factory.createEmptyStatement(), py.factory.createWithStatement( [ py.factory.createWithItem( py.factory.createCallExpression(py.factory.createIdentifier('context_manager'), []), py.factory.createTupleExpression([ py.factory.createIdentifier('a'), py.factory.createIdentifier('b'), ]), ), ], [], ), ]); await assertPrintedMatchesSnapshot(file, 'with-tuple-alias.py'); }); it('without alias', async () => { const file = py.factory.createSourceFile([ py.factory.createClassDeclaration('context_manager', [ py.factory.createFunctionDeclaration( '__enter__', [py.factory.createFunctionParameter('self')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('self'))], ), py.factory.createFunctionDeclaration( '__exit__', [ py.factory.createFunctionParameter('self'), py.factory.createFunctionParameter('exc_type'), py.factory.createFunctionParameter('exc_val'), py.factory.createFunctionParameter('exc_tb'), ], undefined, [py.factory.createReturnStatement(py.factory.createLiteral(false))], ), ]), py.factory.createEmptyStatement(), py.factory.createWithStatement( [ py.factory.createWithItem( py.factory.createCallExpression(py.factory.createIdentifier('context_manager'), []), ), ], [], ), ]); await assertPrintedMatchesSnapshot(file, 'with.py'); }); it('many with items', async () => { const file = py.factory.createSourceFile([ py.factory.createClassDeclaration('context_manager', [ py.factory.createFunctionDeclaration( '__enter__', [py.factory.createFunctionParameter('self')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('self'))], ), py.factory.createFunctionDeclaration( '__exit__', [ py.factory.createFunctionParameter('self'), py.factory.createFunctionParameter('exc_type'), py.factory.createFunctionParameter('exc_val'), py.factory.createFunctionParameter('exc_tb'), ], undefined, [py.factory.createReturnStatement(py.factory.createLiteral(false))], ), ]), py.factory.createEmptyStatement(), py.factory.createClassDeclaration('context_manager2', [ py.factory.createFunctionDeclaration( '__enter__', [py.factory.createFunctionParameter('self')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('self'))], ), py.factory.createFunctionDeclaration( '__exit__', [ py.factory.createFunctionParameter('self'), py.factory.createFunctionParameter('exc_type'), py.factory.createFunctionParameter('exc_val'), py.factory.createFunctionParameter('exc_tb'), ], undefined, [py.factory.createReturnStatement(py.factory.createLiteral(false))], ), ]), py.factory.createEmptyStatement(), py.factory.createClassDeclaration('context_manager3', [ py.factory.createFunctionDeclaration( '__enter__', [py.factory.createFunctionParameter('self')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('self'))], ), py.factory.createFunctionDeclaration( '__exit__', [ py.factory.createFunctionParameter('self'), py.factory.createFunctionParameter('exc_type'), py.factory.createFunctionParameter('exc_val'), py.factory.createFunctionParameter('exc_tb'), ], undefined, [py.factory.createReturnStatement(py.factory.createLiteral(false))], ), ]), py.factory.createEmptyStatement(), py.factory.createWithStatement( [ py.factory.createWithItem( py.factory.createCallExpression(py.factory.createIdentifier('context_manager'), []), py.factory.createIdentifier('alias'), ), py.factory.createWithItem( py.factory.createCallExpression(py.factory.createIdentifier('context_manager2'), []), py.factory.createTupleExpression([ py.factory.createIdentifier('a'), py.factory.createIdentifier('b'), ]), ), py.factory.createWithItem( py.factory.createCallExpression(py.factory.createIdentifier('context_manager3'), []), ), ], [], ), ]); await assertPrintedMatchesSnapshot(file, 'with-many-items.py'); }); it('with async', async () => { const file = py.factory.createSourceFile([ py.factory.createClassDeclaration('context_manager', [ py.factory.createFunctionDeclaration( '__enter__', [py.factory.createFunctionParameter('self')], undefined, [py.factory.createReturnStatement(py.factory.createIdentifier('self'))], ), py.factory.createFunctionDeclaration( '__exit__', [ py.factory.createFunctionParameter('self'), py.factory.createFunctionParameter('exc_type'), py.factory.createFunctionParameter('exc_val'), py.factory.createFunctionParameter('exc_tb'), ], undefined, [py.factory.createReturnStatement(py.factory.createLiteral(false))], ), ]), py.factory.createEmptyStatement(), py.factory.createFunctionDeclaration( 'foo', [], undefined, [ py.factory.createWithStatement( [ py.factory.createWithItem( py.factory.createCallExpression(py.factory.createIdentifier('context_manager'), []), ), ], [], [py.factory.createIdentifier('async')], ), ], undefined, undefined, [py.factory.createIdentifier('async')], ), ]); await assertPrintedMatchesSnapshot(file, 'with-async.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/structure/comment.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('comment', () => { it('simple', async () => { const file = py.factory.createSourceFile([py.factory.createComment('This is a comment')]); await assertPrintedMatchesSnapshot(file, 'simple.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/structure/sourceFile.test.ts ================================================ import { py } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('source file', () => { it('simple', async () => { const file = py.factory.createSourceFile([ py.factory.createAssignment( py.factory.createIdentifier('a'), undefined, py.factory.createLiteral(1), ), py.factory.createAssignment( py.factory.createIdentifier('b'), undefined, py.factory.createLiteral(2), ), ]); await assertPrintedMatchesSnapshot(file, 'simple.py'); }); it('with docstring', async () => { const file = py.factory.createSourceFile( [ py.factory.createAssignment( py.factory.createIdentifier('foo'), undefined, py.factory.createLiteral(1), ), ], 'This is a module-level docstring.', ); await assertPrintedMatchesSnapshot(file, 'with-docstring.py'); }); }); ================================================ FILE: packages/openapi-python/src/py-compiler/__tests__/nodes/utils.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { py } from '../../index'; import { snapshotsDir, tmpDir } from '../constants'; function getCallerFile(): string { const error = new Error(); const stack = (error.stack ?? '').split('\n'); const callerLine = stack.find((line) => line.includes('.test.ts')); if (!callerLine) { throw new Error('Could not find test file in stack trace'); } const match = callerLine.match(/\(([^)]+)\)/) || callerLine.match(/at (.+):\d+:\d+/); if (!match?.[1]) { throw new Error('Could not extract file path'); } return match[1]; } function ensureInitFiles(dir: string, rootDir: string): void { let current = dir; while (current.startsWith(rootDir) && current !== rootDir) { const initPath = path.join(current, '__init__.py'); if (!fs.existsSync(initPath)) { fs.writeFileSync(initPath, ''); } current = path.dirname(current); } const rootInit = path.join(rootDir, '__init__.py'); if (!fs.existsSync(rootInit)) { fs.writeFileSync(rootInit, ''); } } export async function assertPrintedMatchesSnapshot( file: py.SourceFile, filename: string, ): Promise { const result = py.createPrinter().printFile(file); const caller = getCallerFile(); const relPath = path .relative(path.join(process.cwd(), 'src', 'py-compiler', '__tests__'), caller) .replace(/\.test\.ts$/, ''); const outputPath = path.join(tmpDir, relPath, filename); const outputDir = path.dirname(outputPath); fs.mkdirSync(outputDir, { recursive: true }); fs.writeFileSync(outputPath, result); ensureInitFiles(outputDir, tmpDir); const snapshotPath = path.join(snapshotsDir, relPath, filename); const snapshotDir = path.dirname(snapshotPath); fs.mkdirSync(snapshotDir, { recursive: true }); ensureInitFiles(snapshotDir, snapshotsDir); await expect(result).toMatchFileSnapshot(snapshotPath); } ================================================ FILE: packages/openapi-python/src/py-compiler/index.ts ================================================ import type { PyNode as _PyNode, PyNodeBase as _PyNodeBase } from './nodes/base'; import type { PyComprehension as _PyComprehension, PyComprehensionNode as _PyComprehensionNode, } from './nodes/comprehension'; import type { PyClassDeclaration as _PyClassDeclaration } from './nodes/declarations/class'; import type { PyFunctionDeclaration as _PyFunctionDeclaration } from './nodes/declarations/function'; import type { PyFunctionParameter as _PyFunctionParameter } from './nodes/declarations/functionParameter'; import type { PyExpression as _PyExpression } from './nodes/expression'; import type { PyAsyncExpression as _PyAsyncExpression } from './nodes/expressions/async'; import type { PyAwaitExpression as _PyAwaitExpression } from './nodes/expressions/await'; import type { PyBinaryExpression as _PyBinaryExpression, PyBinaryOperator as _PyBinaryOperator, } from './nodes/expressions/binary'; import type { PyCallExpression as _PyCallExpression } from './nodes/expressions/call'; import type { PyDictComprehension as _PyDictComprehension } from './nodes/expressions/comprehensions/dict'; import type { PyListComprehension as _PyListComprehension } from './nodes/expressions/comprehensions/list'; import type { PySetComprehension as _PySetComprehension } from './nodes/expressions/comprehensions/set'; import type { PyDictExpression as _PyDictExpression } from './nodes/expressions/dict'; import type { PyFStringExpression as _PyFStringExpression } from './nodes/expressions/fString'; import type { PyGeneratorExpression as _PyGeneratorExpression } from './nodes/expressions/generator'; import type { PyIdentifier as _PyIdentifier } from './nodes/expressions/identifier'; import type { PyKeywordArgument as _PyKeywordArgument } from './nodes/expressions/keywordArg'; import type { PyLambdaExpression as _PyLambdaExpression } from './nodes/expressions/lambda'; import type { PyListExpression as _PyListExpression } from './nodes/expressions/list'; import type { PyLiteral as _PyLiteral, PyLiteralValue as _PyLiteralValue, } from './nodes/expressions/literal'; import type { PyMemberExpression as _PyMemberExpression } from './nodes/expressions/member'; import type { PySetExpression as _PySetExpression } from './nodes/expressions/set'; import type { PySubscriptExpression as _PySubscriptExpression } from './nodes/expressions/subscript'; import type { PySubscriptSlice as _PySubscriptSlice } from './nodes/expressions/subscript-slice'; import type { PyTupleExpression as _PyTupleExpression } from './nodes/expressions/tuple'; import type { PyYieldExpression as _PyYieldExpression } from './nodes/expressions/yield'; import type { PyYieldFromExpression as _PyYieldFromExpression } from './nodes/expressions/yieldFrom'; import { factory } from './nodes/factory'; import { PyNodeKind } from './nodes/kinds'; import type { PyStatement as _PyStatement } from './nodes/statement'; import type { PyAssignment as _PyAssignment } from './nodes/statements/assignment'; import type { PyAugmentedAssignment as _PyAugmentedAssignment, PyAugmentedOperator as _PyAugmentedOperator, } from './nodes/statements/augmentedAssignment'; import type { PyBlock as _PyBlock } from './nodes/statements/block'; import type { PyBreakStatement as _PyBreakStatement } from './nodes/statements/break'; import type { PyContinueStatement as _PyContinueStatement } from './nodes/statements/continue'; import type { PyEmptyStatement as _PyEmptyStatement } from './nodes/statements/empty'; import type { PyExceptClause as _PyExceptClause } from './nodes/statements/except'; import type { PyExpressionStatement as _PyExpressionStatement } from './nodes/statements/expression'; import type { PyForStatement as _PyForStatement } from './nodes/statements/for'; import type { PyIfStatement as _PyIfStatement } from './nodes/statements/if'; import type { PyImportStatement as _PyImportStatement } from './nodes/statements/import'; import type { PyRaiseStatement as _PyRaiseStatement } from './nodes/statements/raise'; import type { PyReturnStatement as _PyReturnStatement } from './nodes/statements/return'; import type { PyTryStatement as _PyTryStatement } from './nodes/statements/try'; import type { PyWhileStatement as _PyWhileStatement } from './nodes/statements/while'; import type { PyWithStatement as _PyWithStatement } from './nodes/statements/with'; import type { PyWithItem as _PyWithItem } from './nodes/statements/withItem'; import type { PyComment as _PyComment } from './nodes/structure/comment'; import type { PySourceFile as _PySourceFile } from './nodes/structure/sourceFile'; import type { PyPrinterOptions as _PyPrinterOptions } from './printer'; import { createPrinter, printAst } from './printer'; // eslint-disable-next-line @typescript-eslint/no-namespace export namespace py { // Base / Core export type Node = _PyNode; export type NodeBase = _PyNodeBase; export type NodeKind = PyNodeKind; export type Expression = _PyExpression; export type Statement = _PyStatement; // Structure export type SourceFile = _PySourceFile; export type Comment = _PyComment; // Declarations export type ClassDeclaration = _PyClassDeclaration; export type FunctionDeclaration = _PyFunctionDeclaration; export type FunctionParameter = _PyFunctionParameter; // Statements export type Assignment = _PyAssignment; export type AugmentedAssignment = _PyAugmentedAssignment; export type AugmentedOperator = _PyAugmentedOperator; export type Block = _PyBlock; export type BreakStatement = _PyBreakStatement; export type ContinueStatement = _PyContinueStatement; export type EmptyStatement = _PyEmptyStatement; export type ExceptClause = _PyExceptClause; export type ExpressionStatement = _PyExpressionStatement; export type ForStatement = _PyForStatement; export type IfStatement = _PyIfStatement; export type ImportStatement = _PyImportStatement; export type RaiseStatement = _PyRaiseStatement; export type ReturnStatement = _PyReturnStatement; export type TryStatement = _PyTryStatement; export type WhileStatement = _PyWhileStatement; export type WithItem = _PyWithItem; export type WithStatement = _PyWithStatement; // Expressions export type AsyncExpression = _PyAsyncExpression; export type AwaitExpression = _PyAwaitExpression; export type BinaryExpression = _PyBinaryExpression; export type BinaryOperator = _PyBinaryOperator; export type CallExpression = _PyCallExpression; export type DictExpression = _PyDictExpression; export type FStringExpression = _PyFStringExpression; export type GeneratorExpression = _PyGeneratorExpression; export type Identifier = _PyIdentifier; export type KeywordArgument = _PyKeywordArgument; export type LambdaExpression = _PyLambdaExpression; export type ListExpression = _PyListExpression; export type Literal = _PyLiteral; export type MemberExpression = _PyMemberExpression; export type SetExpression = _PySetExpression; export type SubscriptExpression = _PySubscriptExpression; export type SubscriptSlice = _PySubscriptSlice; export type TupleExpression = _PyTupleExpression; export type YieldExpression = _PyYieldExpression; export type YieldFromExpression = _PyYieldFromExpression; // Comprehensions export type Comprehension = _PyComprehension; export type ComprehensionNode = _PyComprehensionNode; export type DictComprehension = _PyDictComprehension; export type ListComprehension = _PyListComprehension; export type SetComprehension = _PySetComprehension; // Printer export type PrinterOptions = _PyPrinterOptions; // Miscellaneous export type LiteralValue = _PyLiteralValue; } export const py = { PyNodeKind, createPrinter, factory, printAst, } as const; ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/base.ts ================================================ import type { PyExpression } from './expression'; import type { PyNodeKind } from './kinds'; import type { PyStatement } from './statement'; import type { PyBlock } from './statements/block'; import type { PySourceFile } from './structure/sourceFile'; export interface PyNodeBase { kind: PyNodeKind; leadingComments?: ReadonlyArray; trailingComments?: ReadonlyArray; } export type PyNode = PyBlock | PyExpression | PySourceFile | PyStatement; ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/comprehension.ts ================================================ import type { PyNodeBase } from './base'; import type { PyExpression } from './expression'; import type { PyDictComprehension } from './expressions/comprehensions/dict'; import type { PyListComprehension } from './expressions/comprehensions/list'; import type { PySetComprehension } from './expressions/comprehensions/set'; export type PyComprehension = PyDictComprehension | PyListComprehension | PySetComprehension; export interface PyComprehensionNode extends PyNodeBase { ifs?: ReadonlyArray; isAsync?: boolean; iterable: PyExpression; target: PyExpression; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/declarations/class.ts ================================================ import type { PyNode, PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import type { PyBlock } from '../statements/block'; import { createBlock } from '../statements/block'; export interface PyClassDeclaration extends PyNodeBase { baseClasses?: ReadonlyArray; body: PyBlock; decorators?: ReadonlyArray; docstring?: string; kind: PyNodeKind.ClassDeclaration; name: string; } export function createClassDeclaration( name: string, body: ReadonlyArray, decorators?: ReadonlyArray, baseClasses?: ReadonlyArray, docstring?: string, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyClassDeclaration { return { baseClasses, body: createBlock(body), decorators, docstring, kind: PyNodeKind.ClassDeclaration, leadingComments, name, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/declarations/function.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import type { PyBlock } from '../statements/block'; import { createBlock } from '../statements/block'; import type { PyFunctionParameter } from './functionParameter'; export interface PyFunctionDeclaration extends PyNodeBase { body: PyBlock; decorators?: ReadonlyArray; docstring?: string; kind: PyNodeKind.FunctionDeclaration; modifiers?: ReadonlyArray; name: string; parameters: ReadonlyArray; returnType?: PyExpression; } export function createFunctionDeclaration( name: string, parameters: ReadonlyArray, returnType: PyExpression | undefined, body: ReadonlyArray, decorators?: ReadonlyArray, docstring?: string, modifiers?: ReadonlyArray, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyFunctionDeclaration { return { body: createBlock(body), decorators, docstring, kind: PyNodeKind.FunctionDeclaration, leadingComments, modifiers, name, parameters, returnType, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/declarations/functionParameter.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyFunctionParameter extends PyNodeBase { defaultValue?: PyExpression; kind: PyNodeKind.FunctionParameter; name: string; type?: PyExpression; } export function createFunctionParameter( name: string, type?: PyExpression, defaultValue?: PyExpression, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyFunctionParameter { return { defaultValue, kind: PyNodeKind.FunctionParameter, leadingComments, name, trailingComments, type, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expression.ts ================================================ import type { PyComprehension } from './comprehension'; import type { PyAsyncExpression } from './expressions/async'; import type { PyAwaitExpression } from './expressions/await'; import type { PyBinaryExpression } from './expressions/binary'; import type { PyCallExpression } from './expressions/call'; import type { PyDictExpression } from './expressions/dict'; import type { PyFStringExpression } from './expressions/fString'; import type { PyGeneratorExpression } from './expressions/generator'; import type { PyIdentifier } from './expressions/identifier'; import type { PyKeywordArgument } from './expressions/keywordArg'; import type { PyLambdaExpression } from './expressions/lambda'; import type { PyListExpression } from './expressions/list'; import type { PyLiteral } from './expressions/literal'; import type { PyMemberExpression } from './expressions/member'; import type { PySetExpression } from './expressions/set'; import type { PySubscriptExpression } from './expressions/subscript'; import type { PySubscriptSlice } from './expressions/subscript-slice'; import type { PyTupleExpression } from './expressions/tuple'; import type { PyYieldExpression } from './expressions/yield'; import type { PyYieldFromExpression } from './expressions/yieldFrom'; export type PyExpression = | PyAsyncExpression | PyAwaitExpression | PyBinaryExpression | PyCallExpression | PyComprehension | PyDictExpression | PyFStringExpression | PyGeneratorExpression | PyIdentifier | PyKeywordArgument | PyLambdaExpression | PyListExpression | PyLiteral | PyMemberExpression | PySetExpression | PySubscriptExpression | PySubscriptSlice | PyTupleExpression | PyYieldExpression | PyYieldFromExpression; ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/async.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyAsyncExpression extends PyNodeBase { expression: PyExpression; kind: PyNodeKind.AsyncExpression; } export function createAsyncExpression(expression: PyExpression): PyAsyncExpression { return { expression, kind: PyNodeKind.AsyncExpression, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/await.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyAwaitExpression extends PyNodeBase { expression: PyExpression; kind: PyNodeKind.AwaitExpression; } export function createAwaitExpression(expression: PyExpression): PyAwaitExpression { return { expression, kind: PyNodeKind.AwaitExpression, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/binary.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export type PyBinaryOperator = | '+' | '-' | '*' | '/' | '//' | '%' | '**' | '==' | '!=' | '>' | '>=' | '<' | '<=' | 'is' | 'is not' | 'in' | 'not in' | 'and' | 'or'; export interface PyBinaryExpression extends PyNodeBase { kind: PyNodeKind.BinaryExpression; left: PyExpression; operator: PyBinaryOperator; right: PyExpression; } export function createBinaryExpression( left: PyExpression, operator: PyBinaryOperator, right: PyExpression, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyBinaryExpression { return { kind: PyNodeKind.BinaryExpression, leadingComments, left, operator, right, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/call.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyCallExpression extends PyNodeBase { args: ReadonlyArray; callee: PyExpression; kind: PyNodeKind.CallExpression; } export function createCallExpression( callee: PyExpression, args: ReadonlyArray, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyCallExpression { return { args, callee, kind: PyNodeKind.CallExpression, leadingComments, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/comprehensions/dict.ts ================================================ import type { PyComprehensionNode } from '../../comprehension'; import type { PyExpression } from '../../expression'; import { PyNodeKind } from '../../kinds'; export interface PyDictComprehension extends PyComprehensionNode { key: PyExpression; kind: PyNodeKind.DictComprehension; value: PyExpression; } export function createDictComprehension( key: PyExpression, value: PyExpression, target: PyExpression, iterable: PyExpression, ifs?: ReadonlyArray, isAsync?: boolean, ): PyDictComprehension { return { ifs, isAsync, iterable, key, kind: PyNodeKind.DictComprehension, target, value, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/comprehensions/list.ts ================================================ import type { PyComprehensionNode } from '../../comprehension'; import type { PyExpression } from '../../expression'; import { PyNodeKind } from '../../kinds'; export interface PyListComprehension extends PyComprehensionNode { element: PyExpression; kind: PyNodeKind.ListComprehension; } export function createListComprehension( element: PyExpression, target: PyExpression, iterable: PyExpression, ifs?: ReadonlyArray, isAsync?: boolean, ): PyListComprehension { return { element, ifs, isAsync, iterable, kind: PyNodeKind.ListComprehension, target, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/comprehensions/set.ts ================================================ import type { PyComprehensionNode } from '../../comprehension'; import type { PyExpression } from '../../expression'; import { PyNodeKind } from '../../kinds'; export interface PySetComprehension extends PyComprehensionNode { element: PyExpression; kind: PyNodeKind.SetComprehension; } export function createSetComprehension( element: PyExpression, target: PyExpression, iterable: PyExpression, ifs?: ReadonlyArray, isAsync?: boolean, ): PySetComprehension { return { element, ifs, isAsync, iterable, kind: PyNodeKind.SetComprehension, target, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/dict.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyDictExpression extends PyNodeBase { entries: ReadonlyArray<{ key: PyExpression; value: PyExpression; }>; kind: PyNodeKind.DictExpression; } export function createDictExpression( entries: ReadonlyArray<{ key: PyExpression; value: PyExpression }>, ): PyDictExpression { return { entries, kind: PyNodeKind.DictExpression, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/fString.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyFStringExpression extends PyNodeBase { kind: PyNodeKind.FStringExpression; parts: Array; } export function createFStringExpression( parts: Array, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyFStringExpression { return { kind: PyNodeKind.FStringExpression, leadingComments, parts, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/generator.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyGeneratorExpression extends PyNodeBase { element: PyExpression; ifs?: ReadonlyArray; isAsync?: boolean; iterable: PyExpression; kind: PyNodeKind.GeneratorExpression; target: PyExpression; } export function createGeneratorExpression( element: PyExpression, target: PyExpression, iterable: PyExpression, ifs?: ReadonlyArray, isAsync?: boolean, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyGeneratorExpression { return { element, ifs, isAsync, iterable, kind: PyNodeKind.GeneratorExpression, leadingComments, target, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/identifier.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PyIdentifier extends PyNodeBase { kind: PyNodeKind.Identifier; name: string; } export function createIdentifier( name: string, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyIdentifier { return { kind: PyNodeKind.Identifier, leadingComments, name, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/keywordArg.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyKeywordArgument extends PyNodeBase { kind: PyNodeKind.KeywordArgument; name: string; value: PyExpression; } export function createKeywordArgument( name: string, value: PyExpression, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyKeywordArgument { return { kind: PyNodeKind.KeywordArgument, leadingComments, name, trailingComments, value, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/lambda.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyFunctionParameter } from '../declarations/functionParameter'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyLambdaExpression extends PyNodeBase { expression: PyExpression; kind: PyNodeKind.LambdaExpression; parameters: ReadonlyArray; } export function createLambdaExpression( parameters: ReadonlyArray, expression: PyExpression, ): PyLambdaExpression { return { expression, kind: PyNodeKind.LambdaExpression, parameters, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/list.ts ================================================ import type { PyNode, PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PyListExpression extends PyNodeBase { elements: ReadonlyArray; kind: PyNodeKind.ListExpression; } export function createListExpression(elements: ReadonlyArray): PyListExpression { return { elements, kind: PyNodeKind.ListExpression, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/literal.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export type PyLiteralValue = string | number | boolean | null; export interface PyLiteral extends PyNodeBase { kind: PyNodeKind.Literal; value: PyLiteralValue; } export function createLiteral( value: PyLiteralValue, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyLiteral { return { kind: PyNodeKind.Literal, leadingComments, trailingComments, value, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/member.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; import type { PyIdentifier } from './identifier'; export interface PyMemberExpression extends PyNodeBase { kind: PyNodeKind.MemberExpression; member: PyIdentifier; object: PyExpression; } export function createMemberExpression( object: PyExpression, member: PyIdentifier, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyMemberExpression { return { kind: PyNodeKind.MemberExpression, leadingComments, member, object, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/set.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PySetExpression extends PyNodeBase { elements: ReadonlyArray; kind: PyNodeKind.SetExpression; } export function createSetExpression(elements: ReadonlyArray): PySetExpression { return { elements, kind: PyNodeKind.SetExpression, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/subscript-slice.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PySubscriptSlice extends PyNodeBase { elements: ReadonlyArray; kind: PyNodeKind.SubscriptSlice; } export function createSubscriptSlice(elements: ReadonlyArray): PySubscriptSlice { return { elements, kind: PyNodeKind.SubscriptSlice, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/subscript.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PySubscriptExpression extends PyNodeBase { kind: PyNodeKind.SubscriptExpression; slice: PyExpression; value: PyExpression; } export function createSubscriptExpression( value: PyExpression, slice: PyExpression, ): PySubscriptExpression { return { kind: PyNodeKind.SubscriptExpression, slice, value, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/tuple.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyTupleExpression extends PyNodeBase { elements: ReadonlyArray; kind: PyNodeKind.TupleExpression; } export function createTupleExpression(elements: ReadonlyArray): PyTupleExpression { return { elements, kind: PyNodeKind.TupleExpression, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/yield.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyYieldExpression extends PyNodeBase { kind: PyNodeKind.YieldExpression; value?: PyExpression; } export function createYieldExpression(value?: PyExpression): PyYieldExpression { return { kind: PyNodeKind.YieldExpression, value, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/expressions/yieldFrom.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyYieldFromExpression extends PyNodeBase { expression: PyExpression; kind: PyNodeKind.YieldFromExpression; } export function createYieldFromExpression(expression: PyExpression): PyYieldFromExpression { return { expression, kind: PyNodeKind.YieldFromExpression, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/factory.ts ================================================ import { createClassDeclaration } from './declarations/class'; import { createFunctionDeclaration } from './declarations/function'; import { createFunctionParameter } from './declarations/functionParameter'; import { createAsyncExpression } from './expressions/async'; import { createAwaitExpression } from './expressions/await'; import { createBinaryExpression } from './expressions/binary'; import { createCallExpression } from './expressions/call'; import { createDictComprehension } from './expressions/comprehensions/dict'; import { createListComprehension } from './expressions/comprehensions/list'; import { createSetComprehension } from './expressions/comprehensions/set'; import { createDictExpression } from './expressions/dict'; import { createFStringExpression } from './expressions/fString'; import { createGeneratorExpression } from './expressions/generator'; import { createIdentifier } from './expressions/identifier'; import { createKeywordArgument } from './expressions/keywordArg'; import { createLambdaExpression } from './expressions/lambda'; import { createListExpression } from './expressions/list'; import { createLiteral } from './expressions/literal'; import { createMemberExpression } from './expressions/member'; import { createSetExpression } from './expressions/set'; import { createSubscriptExpression } from './expressions/subscript'; import { createSubscriptSlice } from './expressions/subscript-slice'; import { createTupleExpression } from './expressions/tuple'; import { createYieldExpression } from './expressions/yield'; import { createYieldFromExpression } from './expressions/yieldFrom'; import { createAssignment } from './statements/assignment'; import { createAugmentedAssignment } from './statements/augmentedAssignment'; import { createBlock } from './statements/block'; import { createBreakStatement } from './statements/break'; import { createContinueStatement } from './statements/continue'; import { createEmptyStatement } from './statements/empty'; import { createExceptClause } from './statements/except'; import { createExpressionStatement } from './statements/expression'; import { createForStatement } from './statements/for'; import { createIfStatement } from './statements/if'; import { createImportStatement } from './statements/import'; import { createRaiseStatement } from './statements/raise'; import { createReturnStatement } from './statements/return'; import { createTryStatement } from './statements/try'; import { createWhileStatement } from './statements/while'; import { createWithStatement } from './statements/with'; import { createWithItem } from './statements/withItem'; import { createComment } from './structure/comment'; import { createSourceFile } from './structure/sourceFile'; export const factory = { createAssignment, createAsyncExpression, createAugmentedAssignment, createAwaitExpression, createBinaryExpression, createBlock, createBreakStatement, createCallExpression, createClassDeclaration, createComment, createContinueStatement, createDictComprehension, createDictExpression, createEmptyStatement, createExceptClause, createExpressionStatement, createFStringExpression, createForStatement, createFunctionDeclaration, createFunctionParameter, createGeneratorExpression, createIdentifier, createIfStatement, createImportStatement, createKeywordArgument, createLambdaExpression, createListComprehension, createListExpression, createLiteral, createMemberExpression, createRaiseStatement, createReturnStatement, createSetComprehension, createSetExpression, createSourceFile, createSubscriptExpression, createSubscriptSlice, createTryStatement, createTupleExpression, createWhileStatement, createWithItem, createWithStatement, createYieldExpression, createYieldFromExpression, }; ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/kinds.ts ================================================ export enum PyNodeKind { Assignment = 'Assignment', AsyncExpression = 'AsyncExpression', AugmentedAssignment = 'AugmentedAssignment', AwaitExpression = 'AwaitExpression', BinaryExpression = 'BinaryExpression', Block = 'Block', BreakStatement = 'BreakStatement', CallExpression = 'CallExpression', ClassDeclaration = 'ClassDeclaration', Comment = 'Comment', ContinueStatement = 'ContinueStatement', DictComprehension = 'DictComprehension', DictExpression = 'DictExpression', EmptyStatement = 'EmptyStatement', ExceptClause = 'ExceptClause', ExpressionStatement = 'ExpressionStatement', FStringExpression = 'FStringExpression', ForStatement = 'ForStatement', FunctionDeclaration = 'FunctionDeclaration', FunctionParameter = 'FunctionParameter', GeneratorExpression = 'GeneratorExpression', Identifier = 'Identifier', IfStatement = 'IfStatement', ImportStatement = 'ImportStatement', KeywordArgument = 'KeywordArgument', LambdaExpression = 'LambdaExpression', ListComprehension = 'ListComprehension', ListExpression = 'ListExpression', Literal = 'Literal', MemberExpression = 'MemberExpression', RaiseStatement = 'RaiseStatement', ReturnStatement = 'ReturnStatement', SetComprehension = 'SetComprehension', SetExpression = 'SetExpression', SourceFile = 'SourceFile', SubscriptExpression = 'SubscriptExpression', SubscriptSlice = 'SubscriptSlice', TryStatement = 'TryStatement', TupleExpression = 'TupleExpression', WhileStatement = 'WhileStatement', WithItem = 'WithItem', WithStatement = 'WithStatement', YieldExpression = 'YieldExpression', YieldFromExpression = 'YieldFromExpression', } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statement.ts ================================================ import type { PyClassDeclaration } from './declarations/class'; import type { PyFunctionDeclaration } from './declarations/function'; import type { PyFunctionParameter } from './declarations/functionParameter'; import type { PyAssignment } from './statements/assignment'; import type { PyAugmentedAssignment } from './statements/augmentedAssignment'; import type { PyBreakStatement } from './statements/break'; import type { PyContinueStatement } from './statements/continue'; import type { PyEmptyStatement } from './statements/empty'; import type { PyExpressionStatement } from './statements/expression'; import type { PyForStatement } from './statements/for'; import type { PyIfStatement } from './statements/if'; import type { PyImportStatement } from './statements/import'; import type { PyRaiseStatement } from './statements/raise'; import type { PyReturnStatement } from './statements/return'; import type { PyTryStatement } from './statements/try'; import type { PyWhileStatement } from './statements/while'; import type { PyWithStatement } from './statements/with'; import type { PyComment } from './structure/comment'; export type PyStatement = | PyAssignment | PyAugmentedAssignment | PyBreakStatement | PyClassDeclaration | PyComment | PyContinueStatement | PyEmptyStatement | PyExpressionStatement | PyForStatement | PyFunctionDeclaration | PyFunctionParameter | PyIfStatement | PyImportStatement | PyRaiseStatement | PyReturnStatement | PyTryStatement | PyWhileStatement | PyWithStatement; ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/assignment.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyAssignment extends PyNodeBase { kind: PyNodeKind.Assignment; target: PyExpression; type?: PyExpression; value?: PyExpression; } export function createAssignment( target: PyExpression, type?: PyExpression, value?: PyExpression, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyAssignment { if (!type && !value) { throw new Error('Assignment requires at least type or value'); } return { kind: PyNodeKind.Assignment, leadingComments, target, trailingComments, type, value, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/augmentedAssignment.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export type PyAugmentedOperator = | '+=' | '-=' | '*=' | '/=' | '//=' | '%=' | '**=' | '&=' | '|=' | '^=' | '>>=' | '<<='; export interface PyAugmentedAssignment extends PyNodeBase { kind: PyNodeKind.AugmentedAssignment; operator: PyAugmentedOperator; target: PyExpression; value: PyExpression; } export function createAugmentedAssignment( target: PyExpression, operator: PyAugmentedOperator, value: PyExpression, ): PyAugmentedAssignment { return { kind: PyNodeKind.AugmentedAssignment, operator, target, value, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/block.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; export interface PyBlock extends PyNodeBase { kind: PyNodeKind.Block; statements: ReadonlyArray; } export function createBlock( statements: ReadonlyArray, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyBlock { return { kind: PyNodeKind.Block, leadingComments, statements, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/break.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PyBreakStatement extends PyNodeBase { kind: PyNodeKind.BreakStatement; } export function createBreakStatement(): PyBreakStatement { return { kind: PyNodeKind.BreakStatement, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/continue.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PyContinueStatement extends PyNodeBase { kind: PyNodeKind.ContinueStatement; } export function createContinueStatement(): PyContinueStatement { return { kind: PyNodeKind.ContinueStatement, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/empty.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PyEmptyStatement extends PyNodeBase { kind: PyNodeKind.EmptyStatement; } export function createEmptyStatement(): PyEmptyStatement { return { kind: PyNodeKind.EmptyStatement, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/except.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import type { PyIdentifier } from '../expressions/identifier'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import { createBlock, type PyBlock } from './block'; export interface PyExceptClause extends PyNodeBase { block: PyBlock; exceptionName?: PyIdentifier; exceptionType?: PyExpression; kind: PyNodeKind.ExceptClause; } export function createExceptClause( block: ReadonlyArray, exceptionType?: PyExpression, exceptionName?: PyIdentifier, ): PyExceptClause { return { block: createBlock(block), exceptionName, exceptionType, kind: PyNodeKind.ExceptClause, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/expression.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyExpressionStatement extends PyNodeBase { expression: PyExpression; kind: PyNodeKind.ExpressionStatement; } export function createExpressionStatement(expression: PyExpression): PyExpressionStatement { return { expression, kind: PyNodeKind.ExpressionStatement, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/for.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import type { PyBlock } from './block'; import { createBlock } from './block'; export interface PyForStatement extends PyNodeBase { body: PyBlock; elseBlock?: PyBlock; iterable: PyExpression; kind: PyNodeKind.ForStatement; target: PyExpression; } export function createForStatement( target: PyExpression, iterable: PyExpression, body: ReadonlyArray, elseBlock?: ReadonlyArray, ): PyForStatement { return { body: createBlock(body), elseBlock: elseBlock ? createBlock(elseBlock) : undefined, iterable, kind: PyNodeKind.ForStatement, target, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/if.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import { createBlock, type PyBlock } from './block'; export interface PyIfStatement extends PyNodeBase { condition: PyExpression; elseBlock?: PyBlock | PyIfStatement; kind: PyNodeKind.IfStatement; thenBlock: PyBlock; } export function createIfStatement( condition: PyExpression, thenBlock: ReadonlyArray, elseBlock?: ReadonlyArray | PyIfStatement, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyIfStatement { return { condition, elseBlock: elseBlock instanceof Array ? createBlock(elseBlock) : elseBlock, kind: PyNodeKind.IfStatement, leadingComments, thenBlock: createBlock(thenBlock), trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/import.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PyImportStatement extends PyNodeBase { isFrom: boolean; kind: PyNodeKind.ImportStatement; module: string; names?: ReadonlyArray<{ alias?: string; name: string }>; } export function createImportStatement( module: string, names?: ReadonlyArray<{ alias?: string; name: string }>, isFrom: boolean = false, ): PyImportStatement { return { isFrom, kind: PyNodeKind.ImportStatement, module, names, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/raise.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyRaiseStatement extends PyNodeBase { expression?: PyExpression; kind: PyNodeKind.RaiseStatement; } export function createRaiseStatement(expression?: PyExpression): PyRaiseStatement { return { expression, kind: PyNodeKind.RaiseStatement, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/return.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyReturnStatement extends PyNodeBase { expression?: PyExpression; kind: PyNodeKind.ReturnStatement; } export function createReturnStatement(expression?: PyExpression): PyReturnStatement { return { expression, kind: PyNodeKind.ReturnStatement, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/try.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import { createBlock, type PyBlock } from './block'; import type { PyExceptClause } from './except'; export interface PyTryStatement extends PyNodeBase { elseBlock?: PyBlock; exceptClauses?: ReadonlyArray; finallyBlock?: PyBlock; kind: PyNodeKind.TryStatement; tryBlock: PyBlock; } export function createTryStatement( tryBlock: ReadonlyArray, exceptClauses?: ReadonlyArray, elseBlock?: ReadonlyArray, finallyBlock?: ReadonlyArray, ): PyTryStatement { return { elseBlock: elseBlock ? createBlock(elseBlock) : undefined, exceptClauses, finallyBlock: finallyBlock ? createBlock(finallyBlock) : undefined, kind: PyNodeKind.TryStatement, tryBlock: createBlock(tryBlock), }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/while.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import type { PyBlock } from './block'; import { createBlock } from './block'; export interface PyWhileStatement extends PyNodeBase { body: PyBlock; condition: PyExpression; elseBlock?: PyBlock; kind: PyNodeKind.WhileStatement; } export function createWhileStatement( condition: PyExpression, body: ReadonlyArray, elseBlock?: ReadonlyArray, ): PyWhileStatement { return { body: createBlock(body), condition, elseBlock: elseBlock ? createBlock(elseBlock) : undefined, kind: PyNodeKind.WhileStatement, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/with.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; import type { PyStatement } from '../statement'; import { createBlock, type PyBlock } from './block'; import type { PyWithItem } from './withItem'; export interface PyWithStatement extends PyNodeBase { body: PyBlock; items: ReadonlyArray; kind: PyNodeKind.WithStatement; modifiers?: ReadonlyArray; } export function createWithStatement( items: ReadonlyArray, body: ReadonlyArray, modifiers?: ReadonlyArray, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyWithStatement { return { body: createBlock(body), items, kind: PyNodeKind.WithStatement, leadingComments, modifiers, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/statements/withItem.ts ================================================ import type { PyNodeBase } from '../base'; import type { PyExpression } from '../expression'; import { PyNodeKind } from '../kinds'; export interface PyWithItem extends PyNodeBase { alias?: PyExpression; contextExpr: PyExpression; kind: PyNodeKind.WithItem; } export function createWithItem( contextExpr: PyExpression, alias?: PyExpression, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PyWithItem { return { alias, contextExpr, kind: PyNodeKind.WithItem, leadingComments, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/structure/comment.ts ================================================ import type { PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PyComment extends PyNodeBase { kind: PyNodeKind.Comment; text: string; } export function createComment(text: string): PyComment { return { kind: PyNodeKind.Comment, text, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/nodes/structure/sourceFile.ts ================================================ import type { PyNode, PyNodeBase } from '../base'; import { PyNodeKind } from '../kinds'; export interface PySourceFile extends PyNodeBase { docstring?: string; kind: PyNodeKind.SourceFile; statements: ReadonlyArray; } export function createSourceFile( statements: ReadonlyArray, docstring?: string, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): PySourceFile { return { docstring, kind: PyNodeKind.SourceFile, leadingComments, statements, trailingComments, }; } ================================================ FILE: packages/openapi-python/src/py-compiler/printer.ts ================================================ import type { PyNode } from './nodes/base'; import { PyNodeKind } from './nodes/kinds'; export interface PyPrinterOptions { indentSize?: number; } const DEFAULT_INDENT_SIZE = 4; const PARAMS_MULTILINE_THRESHOLD = 3; export function createPrinter(options?: PyPrinterOptions) { const indentSize = options?.indentSize ?? DEFAULT_INDENT_SIZE; let indentLevel = 0; function printComments( parts: Array, lines: ReadonlyArray, indent?: boolean, ): void { if (indent) indentLevel += 1; parts.push(...lines.map((line) => printLine(`# ${line}`))); if (indent) indentLevel -= 1; } function printDocstring(docstring: string): Array { const lines = docstring.split('\n'); const parts: Array = []; if (lines.length === 1) { parts.push(printLine(`"""${lines[0]}"""`), ''); } else { parts.push(printLine(`"""`)); parts.push(...lines.map((line) => printLine(line))); parts.push(printLine(`"""`), ''); } return parts; } function printLine(line: string): string { if (line === '') return ''; return ' '.repeat(indentLevel * indentSize) + line; } function printNode(node: PyNode): string { const parts: Array = []; if (node.leadingComments) { printComments(parts, node.leadingComments); } let indentTrailingComments = false; switch (node.kind) { case PyNodeKind.Assignment: { const target = printNode(node.target); if (node.type) { const type = printNode(node.type); if (node.value) { parts.push(printLine(`${target}: ${type} = ${printNode(node.value)}`)); } else { parts.push(printLine(`${target}: ${type}`)); } } else { parts.push(printLine(`${target} = ${printNode(node.value!)}`)); } break; } case PyNodeKind.AsyncExpression: parts.push(`async ${printNode(node.expression)}`); break; case PyNodeKind.AugmentedAssignment: parts.push( printLine(`${printNode(node.target)} ${node.operator} ${printNode(node.value)}`), ); break; case PyNodeKind.AwaitExpression: parts.push(`await ${printNode(node.expression)}`); break; case PyNodeKind.BinaryExpression: parts.push(`${printNode(node.left)} ${node.operator} ${printNode(node.right)}`); break; case PyNodeKind.Block: indentLevel += 1; if (node.statements.length) { parts.push(...node.statements.map(printNode)); } else { parts.push(printLine('pass')); } indentLevel -= 1; break; case PyNodeKind.BreakStatement: parts.push(printLine('break')); break; case PyNodeKind.CallExpression: parts.push(`${printNode(node.callee)}(${node.args.map(printNode).join(', ')})`); break; case PyNodeKind.ClassDeclaration: { indentTrailingComments = true; if (node.decorators) { parts.push(...node.decorators.map((decorator) => printLine(`@${printNode(decorator)}`))); } const bases = node.baseClasses?.length ? `(${node.baseClasses.map(printNode).join(', ')})` : ''; parts.push(printLine(`class ${node.name}${bases}:`)); if (node.docstring) { indentLevel += 1; parts.push(...printDocstring(node.docstring)); indentLevel -= 1; } parts.push(printNode(node.body)); break; } case PyNodeKind.Comment: parts.push(printLine(`# ${node.text}`)); break; case PyNodeKind.ContinueStatement: parts.push(printLine('continue')); break; case PyNodeKind.DictComprehension: { const asyncPrefix = node.isAsync ? 'async ' : ''; const children: Array = [ `${printNode(node.key)}: ${printNode(node.value)} ${asyncPrefix}for ${printNode(node.target)} in ${printNode(node.iterable)}`, ]; if (node.ifs) { for (const condition of node.ifs) { children.push(`if ${printNode(condition)}`); } } parts.push(`{${children.join(' ')}}`); break; } case PyNodeKind.DictExpression: { const entries = node.entries .map(({ key, value }) => `${printNode(key)}: ${printNode(value)}`) .join(', '); parts.push(`{${entries}}`); break; } case PyNodeKind.EmptyStatement: parts.push(''); break; case PyNodeKind.ExpressionStatement: parts.push(printLine(printNode(node.expression))); break; case PyNodeKind.ForStatement: parts.push(printLine(`for ${printNode(node.target)} in ${printNode(node.iterable)}:`)); parts.push(printNode(node.body)); if (node.elseBlock) { parts.push(`${printLine('else:')}`); parts.push(`${printNode(node.elseBlock)}`); } break; case PyNodeKind.FStringExpression: { const children = node.parts.map((part) => typeof part === 'string' ? part : `{${printNode(part)}}`, ); parts.push(`f"${children.join('')}"`); break; } case PyNodeKind.FunctionDeclaration: { if (node.decorators) { parts.push(...node.decorators.map((decorator) => printLine(`@${printNode(decorator)}`))); } const modifiers = node.modifiers?.map(printNode).join(' ') ?? ''; const defPrefix = modifiers ? `${modifiers} def` : 'def'; const formatParameter = (parameter: (typeof node.parameters)[number]): string => { const children: Array = [parameter.name]; if (parameter.type) children.push(`: ${printNode(parameter.type)}`); if (parameter.defaultValue) children.push(` = ${printNode(parameter.defaultValue)}`); return children.join(''); }; const returnAnnotation = node.returnType ? ` -> ${printNode(node.returnType)}` : ''; const preParams = `${defPrefix} ${node.name}(`; const postParams = `)${returnAnnotation}:`; if (node.parameters.length > PARAMS_MULTILINE_THRESHOLD) { parts.push(printLine(preParams)); indentLevel += 1; const params = node.parameters.map((parameter) => printLine(`${formatParameter(parameter)},`), ); parts.push(...params); indentLevel -= 1; parts.push(printLine(postParams)); } else { const parameters = node.parameters.map((parameter) => formatParameter(parameter)); const params = parameters.join(', '); parts.push(printLine(`${preParams}${params}${postParams}`)); } if (node.docstring) { indentLevel += 1; parts.push(...printDocstring(node.docstring)); indentLevel -= 1; } parts.push(printNode(node.body)); break; } case PyNodeKind.GeneratorExpression: { const asyncPrefix = node.isAsync ? 'async ' : ''; const children: Array = [ `${printNode(node.element)} ${asyncPrefix}for ${printNode(node.target)} in ${printNode(node.iterable)}`, ]; if (node.ifs) { for (const condition of node.ifs) { children.push(`if ${printNode(condition)}`); } } parts.push(`(${children.join(' ')})`); break; } case PyNodeKind.Identifier: parts.push(node.name); break; case PyNodeKind.IfStatement: parts.push(printLine(`if ${printNode(node.condition)}:`)); parts.push(`${printNode(node.thenBlock)}`); if (node.elseBlock) { parts.push(`${printLine('else:')}`); parts.push(`${printNode(node.elseBlock)}`); } break; case PyNodeKind.KeywordArgument: parts.push(`${node.name}=${printNode(node.value)}`); break; case PyNodeKind.ImportStatement: { const fromPrefix = node.isFrom ? `from ${node.module} ` : ''; if (fromPrefix) { if (node.names && node.names.length > 0) { const imports = node.names .map(({ alias, name }) => (alias ? `${name} as ${alias}` : name)) .join(', '); parts.push(printLine(`${fromPrefix}import ${imports}`)); } else { parts.push(printLine(`${fromPrefix}import *`)); } } else { if (node.names && node.names.length > 0) { const imports = node.names .map(({ alias, name }) => (alias ? `${name} as ${alias}` : name)) .join(', '); parts.push(printLine(`import ${imports}`)); } else { parts.push(printLine(`import ${node.module}`)); } } break; } case PyNodeKind.LambdaExpression: { const parameters = node.parameters.map((parameter) => { const children: Array = [parameter.name]; if (parameter.type) children.push(`: ${printNode(parameter.type)}`); if (parameter.defaultValue) children.push(` = ${printNode(parameter.defaultValue)}`); return children.join(''); }); parts.push(`lambda ${parameters.join(', ')}: ${printNode(node.expression)}`); break; } case PyNodeKind.ListComprehension: { const asyncPrefix = node.isAsync ? 'async ' : ''; const children: Array = [ `${printNode(node.element)} ${asyncPrefix}for ${printNode(node.target)} in ${printNode(node.iterable)}`, ]; if (node.ifs) { for (const condition of node.ifs) { children.push(`if ${printNode(condition)}`); } } parts.push(`[${children.join(' ')}]`); break; } case PyNodeKind.ListExpression: parts.push(`[${node.elements.map(printNode).join(', ')}]`); break; case PyNodeKind.Literal: if (typeof node.value === 'string') { parts.push(`"${node.value}"`); } else if (typeof node.value === 'boolean') { parts.push(node.value ? 'True' : 'False'); } else if (node.value === null) { parts.push('None'); } else { parts.push(String(node.value)); } break; case PyNodeKind.MemberExpression: parts.push(`${printNode(node.object)}.${printNode(node.member)}`); break; case PyNodeKind.RaiseStatement: if (node.expression) { parts.push(printLine(`raise ${printNode(node.expression)}`)); } else { parts.push(printLine('raise')); } break; case PyNodeKind.ReturnStatement: if (node.expression) { parts.push(printLine(`return ${printNode(node.expression)}`)); } else { parts.push(printLine('return')); } break; case PyNodeKind.SetComprehension: { const asyncPrefix = node.isAsync ? 'async ' : ''; const children: Array = [ `${printNode(node.element)} ${asyncPrefix}for ${printNode(node.target)} in ${printNode(node.iterable)}`, ]; if (node.ifs) { for (const condition of node.ifs) { children.push(`if ${printNode(condition)}`); } } parts.push(`{${children.join(' ')}}`); break; } case PyNodeKind.SetExpression: { if (!node.elements.length) { parts.push('set()'); } else { parts.push(`{${node.elements.map(printNode).join(', ')}}`); } break; } case PyNodeKind.SourceFile: if (node.docstring) { parts.push(...printDocstring(node.docstring)); } parts.push(...node.statements.map(printNode)); break; case PyNodeKind.SubscriptExpression: parts.push(`${printNode(node.value)}[${printNode(node.slice)}]`); break; case PyNodeKind.SubscriptSlice: parts.push(node.elements.map(printNode).join(', ')); break; case PyNodeKind.TryStatement: { parts.push(printLine('try:'), printNode(node.tryBlock)); if (node.exceptClauses) { for (const clause of node.exceptClauses) { const type = clause.exceptionType ? ` ${printNode(clause.exceptionType)}` : ''; const name = clause.exceptionName ? ` as ${printNode(clause.exceptionName)}` : ''; parts.push(printLine(`except${type}${name}:`), printNode(clause.block)); } } if (node.elseBlock) { parts.push(printLine(`else:`), printNode(node.elseBlock)); } if (node.finallyBlock) { parts.push(printLine(`finally:`), printNode(node.finallyBlock)); } break; } case PyNodeKind.TupleExpression: { // Single-element tuple needs trailing comma const trailingComma = node.elements.length === 1 ? ',' : ''; parts.push(`(${node.elements.map(printNode).join(', ')}${trailingComma})`); break; } case PyNodeKind.WhileStatement: { parts.push(printLine(`while ${printNode(node.condition)}:`)); parts.push(printNode(node.body)); if (node.elseBlock) { parts.push(`${printLine('else:')}`); parts.push(`${printNode(node.elseBlock)}`); } break; } case PyNodeKind.WithStatement: { const modifiers = node.modifiers?.map(printNode).join(' ') ?? ''; const withPrefix = modifiers ? `${modifiers} with` : 'with'; const items = node.items .map((item) => item.alias ? `${printNode(item.contextExpr)} as ${printNode(item.alias)}` : printNode(item.contextExpr), ) .join(', '); parts.push(printLine(`${withPrefix} ${items}:`)); parts.push(printNode(node.body)); break; } case PyNodeKind.YieldExpression: if (node.value) { parts.push(`yield ${printNode(node.value)}`); } else { parts.push('yield'); } break; case PyNodeKind.YieldFromExpression: parts.push(`yield from ${printNode(node.expression)}`); break; default: throw new Error(`Unsupported node kind: ${(node as { kind: string }).kind}`); } if (node.trailingComments) { printComments(parts, node.trailingComments, indentTrailingComments); } return parts.join('\n'); } function printFile(node: PyNode): string { const parts: Array = [printNode(node), '']; return parts.join('\n'); } return { printFile, }; } export function printAst(node: PyNode): string { return JSON.stringify(node, null, 2); } ================================================ FILE: packages/openapi-python/src/py-dsl/base.ts ================================================ // TODO: symbol should be protected, but needs to be public to satisfy types import type { AnalysisContext, File, FromRef, Language, Node, NodeName, NodeNameSanitizer, NodeRelationship, NodeScope, Ref, Symbol, } from '@hey-api/codegen-core'; import { fromRef, isNode, isRef, isSymbol, nodeBrand, ref } from '@hey-api/codegen-core'; import type { AnyString } from '@hey-api/types'; import { py } from '../py-compiler'; import type { AccessOptions } from './utils/context'; export abstract class PyDsl implements Node { // eslint-disable-next-line @typescript-eslint/no-unused-vars analyze(_: AnalysisContext): void {} clone(): this { const cloned = Object.create(Object.getPrototypeOf(this)); Object.assign(cloned, this); return cloned; } exported?: boolean; file?: File; get name(): Node['name'] { return { ...this._name, set: (value) => { this._name = ref(value); if (isSymbol(value)) { value.setNode(this); } }, toString: () => (this._name ? this.$name(this._name) : ''), } as Node['name']; } readonly nameSanitizer?: NodeNameSanitizer; language: Language = 'python'; parent?: Node; root: boolean = false; scope?: NodeScope = 'value'; structuralChildren?: Map; structuralParents?: Map; symbol?: Symbol; toAst(): T { return undefined as unknown as T; } readonly '~brand' = nodeBrand; /** Branding property to identify the DSL class at runtime. */ abstract readonly '~dsl': AnyString; /** Conditionally applies a callback to this builder. */ $if( this: T, value: V, ifTrue: (self: T, v: Exclude) => R | void, ifFalse?: (self: T, v: Extract) => R | void, ): R | T; $if( this: T, value: V, ifTrue: (v: Exclude) => R | void, ifFalse?: (v: Extract) => R | void, ): R | T; $if( this: T, value: V, ifTrue: () => R | void, ifFalse?: () => R | void, ): R | T; $if( this: T, value: V, ifTrue: any, ifFalse?: any, ): R | T { if (value) { // Try calling with (self, value), then (value), then () let result: R | void | undefined; try { result = ifTrue?.(this, value as Exclude); } catch { // ignore and try other signatures } if (result === undefined) { try { result = ifTrue?.(value as Exclude); } catch { // ignore and try zero-arg } } if (result === undefined) { try { result = ifTrue?.(); } catch { // swallow } } return (result ?? this) as R | T; } if (ifFalse) { let result: R | void | undefined; try { result = ifFalse?.(this, value as Extract); } catch { // ignore } if (result === undefined) { try { result = ifFalse?.(value as Extract); } catch { // ignore } } if (result === undefined) { try { result = ifFalse?.(); } catch { // ignore } } return (result ?? this) as R | T; } return this; } /** Access patterns for this node. */ toAccessNode?( node: this, options: AccessOptions, ctx: { /** The full chain. */ chain: ReadonlyArray; /** Position in the chain (0 = root). */ index: number; /** Is this the leaf node? */ isLeaf: boolean; /** Is this the root node? */ isRoot: boolean; /** Total length of the chain. */ length: number; }, ): PyDsl | undefined; protected $maybeId( expr: T, ): T extends string ? py.Identifier : T { return (typeof expr === 'string' ? py.factory.createIdentifier(expr) : expr) as T extends string ? py.Identifier : T; } protected $name(name: Ref): string { const value = fromRef(name); if (isSymbol(value)) { try { return value.finalName; } catch { return value.name; } } return String(value); } protected $node(value: I): NodeOfMaybe { if (value === undefined) { return undefined as NodeOfMaybe; } // @ts-expect-error if (isRef(value)) value = fromRef(value); if (isSymbol(value)) { return this.$maybeId(value.finalName) as NodeOfMaybe; } if (typeof value === 'string') { return this.$maybeId(value) as NodeOfMaybe; } if (value instanceof Array) { return value.map((item) => { if (isRef(item)) item = fromRef(item); return this.unwrap(item); }) as NodeOfMaybe; } return this.unwrap(value as any) as NodeOfMaybe; } // protected $type(value: I, args?: ReadonlyArray): TypeOfMaybe { // if (value === undefined) { // return undefined as TypeOfMaybe; // } // // @ts-expect-error // if (isRef(value)) value = fromRef(value); // if (isSymbol(value)) { // return ts.factory.createTypeReferenceNode(value.finalName, args) as TypeOfMaybe; // } // if (typeof value === 'string') { // return ts.factory.createTypeReferenceNode(value, args) as TypeOfMaybe; // } // if (typeof value === 'boolean') { // const literal = value ? ts.factory.createTrue() : ts.factory.createFalse(); // return ts.factory.createLiteralTypeNode(literal) as TypeOfMaybe; // } // if (typeof value === 'number') { // return ts.factory.createLiteralTypeNode( // ts.factory.createNumericLiteral(value), // ) as TypeOfMaybe; // } // if (value instanceof Array) { // return value.map((item) => this.$type(item, args)) as TypeOfMaybe; // } // return this.unwrap(value as any) as TypeOfMaybe; // } private _name?: Ref; /** Unwraps nested nodes into raw Python AST. */ private unwrap(value: I): I extends PyDsl ? N : I { return (isNode(value) ? value.toAst() : value) as I extends PyDsl ? N : I; } } type NodeOfMaybe = undefined extends I ? NodeOf>> | undefined : NodeOf>; type NodeOf = I extends ReadonlyArray ? ReadonlyArray ? N : U> : I extends string ? py.Expression : I extends PyDsl ? N : I extends py.Node ? I : never; export type MaybePyDsl = T extends PyDsl ? U | PyDsl : T extends py.Node ? T | PyDsl : never; // export abstract class TypePyDsl< // T extends // | ts.LiteralTypeNode // | ts.QualifiedName // | ts.TypeElement // | ts.TypeNode // | ts.TypeParameterDeclaration = ts.TypeNode, // > extends PyDsl {} // type TypeOfMaybe = undefined extends I // ? TypeOf>> | undefined // : TypeOf>; // type TypeOf = // I extends ReadonlyArray // ? ReadonlyArray> // : I extends string // ? ts.TypeNode // : I extends boolean // ? ts.LiteralTypeNode // : I extends PyDsl // ? N // : I extends ts.TypeNode // ? I // : never; ================================================ FILE: packages/openapi-python/src/py-dsl/decl/class.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { isSymbol, ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { type MaybePyDsl, PyDsl } from '../base'; import { NewlinePyDsl } from '../layout/newline'; import { DecoratorMixin } from '../mixins/decorator'; import { DocMixin } from '../mixins/doc'; import { LayoutMixin } from '../mixins/layout'; import { ExportMixin } from '../mixins/modifiers'; import { safeRuntimeName } from '../utils/name'; type Body = Array>; const Mixed = DecoratorMixin(DocMixin(ExportMixin(LayoutMixin(PyDsl)))); export class ClassPyDsl extends Mixed { readonly '~dsl' = 'ClassPyDsl'; override readonly nameSanitizer = safeRuntimeName; protected baseClasses: Array> = []; protected body: Body = []; constructor(name: NodeName) { super(); this.name.set(name); if (isSymbol(name)) { name.setKind('class'); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const baseClass of this.baseClasses) { ctx.analyze(baseClass); } ctx.analyze(this.name); ctx.pushScope(); try { for (const item of this.body) { ctx.analyze(item); } } finally { ctx.popScope(); } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Returns true if the class has any members. */ get hasBody(): boolean { return this.body.length > 0; } /** Adds one or more class members (fields, methods, etc.). */ do(...items: Body): this { this.body.push(...items); return this; } /** Records base classes to extend from. */ extends(...baseClass: ReadonlyArray): this { this.baseClasses.push(...baseClass.map((item) => ref(item))); return this; } /** Inserts an empty line between members for formatting. */ newline(): this { this.body.push(new NewlinePyDsl()); return this; } override toAst() { this.$validate(); // const uniqueClasses: Array = []; // for (const base of baseClass) { // let expr: py.Expression; // if (typeof base === 'string' || base instanceof PyDsl) { // expr = this.$node(base) as py.Expression; // } else if (isSymbol(base)) { // expr = py.factory.createIdentifier(base.finalName); // } // // Avoid duplicates by checking if already added // const exists = uniqueClasses.some((existing) => { // const existingExpr = this.$node(existing) as py.Expression; // return existingExpr === expr; // }); // if (!exists) { // uniqueClasses.push(expr); // } // } return py.factory.createClassDeclaration( this.name.toString(), this.$node(this.body), this.$decorators(), this.baseClasses.map((c) => this.$node(c)), this.$docs(), ); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Class declaration missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.name.toString()) missing.push('name'); return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/decl/func.ts ================================================ import type { AnalysisContext, NodeName, NodeNameSanitizer } from '@hey-api/codegen-core'; import { isSymbol } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; import { DecoratorMixin } from '../mixins/decorator'; import { DoMixin } from '../mixins/do'; import { DocMixin } from '../mixins/doc'; import { LayoutMixin } from '../mixins/layout'; import { AsyncMixin, ExportMixin } from '../mixins/modifiers'; import { ParamMixin } from '../mixins/param'; import { ReturnsMixin } from '../mixins/returns'; import { safeRuntimeName } from '../utils/name'; const Mixed = AsyncMixin( DecoratorMixin( DocMixin( DoMixin(ExportMixin(LayoutMixin(ParamMixin(ReturnsMixin(PyDsl))))), ), ), ); export class FuncPyDsl extends Mixed { readonly '~dsl' = 'FuncPyDsl'; override readonly nameSanitizer: NodeNameSanitizer; constructor( name: NodeName, fn?: (f: FuncPyDsl) => void, options?: { nameSanitizer?: NodeNameSanitizer }, ) { super(); this.nameSanitizer = options?.nameSanitizer ?? safeRuntimeName; this.name.set(name); if (isSymbol(name)) { name.setKind('function'); } fn?.(this); } override analyze(ctx: AnalysisContext): void { ctx.pushScope(); try { super.analyze(ctx); ctx.analyze(this.name); } finally { ctx.popScope(); } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } override toAst() { this.$validate(); return py.factory.createFunctionDeclaration( this.name.toString(), this.$params(), this.$returns(), this.$do(), this.$decorators(), this.$docs(), this.modifiers, ); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Function declaration missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.name.toString()) missing.push('name'); return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/decl/param.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; export type ParamDefaultValue = NodeName | py.Expression | undefined; export type ParamFn = (p: ParamPyDsl) => void; export type ParamName = NodeName | ParamFn; export type ParamType = NodeName | PyDsl | undefined; export type ParamCtor = (name: ParamName, fn?: ParamFn) => ParamPyDsl; export class ParamPyDsl extends PyDsl { readonly '~dsl' = 'ParamPyDsl'; protected _defaultValue?: Ref; protected _type?: Ref; constructor(name: ParamName, fn?: ParamFn) { super(); if (typeof name === 'function') { name(this); } else { this.name.set(name); fn?.(this); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.analyze(this._type); ctx.analyze(this._defaultValue); } /** Sets the parameter default value. */ default(value: ParamDefaultValue): this { this._defaultValue = ref(value); return this; } get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the parameter type. */ type(type: ParamType): this { this._type = ref(type); return this; } override toAst() { this.$validate(); return py.factory.createFunctionParameter( this.name.toString(), this.$node(this._type), this.$node(this._defaultValue), ); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Parameter missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.name.toString()) missing.push('name'); return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/attr.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { fromRef, isSymbol, ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { ExprMixin } from '../mixins/expr'; import { f } from '../utils/factories'; export type AttrLeft = NodeName | MaybePyDsl; export type AttrCtor = (left: AttrLeft, right: NodeName) => AttrPyDsl; const Mixed = ExprMixin(PyDsl); export class AttrPyDsl extends Mixed { readonly '~dsl' = 'AttrPyDsl'; protected left: Ref; constructor(left: AttrLeft, right: NodeName) { super(); this.left = ref(left); this.name.set(right); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.left); ctx.analyze(this.name); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } override toAst() { this.$validate(); const leftNode = this.$node(this.left); const right = fromRef(this.name); const value = isSymbol(right) ? right.finalName : right; return py.factory.createMemberExpression( leftNode, py.factory.createIdentifier(value as string), ); } $validate(): asserts this is this & { left: MaybePyDsl; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Attribute access missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.name.toString()) missing.push('property name'); return missing; } } f.attr.set((...args) => new AttrPyDsl(...args)); ================================================ FILE: packages/openapi-python/src/py-dsl/expr/binary.ts ================================================ import type { AnalysisContext, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; export type PyBinaryOperator = | '+' | '-' | '*' | '/' | '//' | '%' | '**' | '==' | '!=' | '>' | '>=' | '<' | '<=' | 'is' | 'is not' | 'in' | 'not in' | 'and' | 'or'; const Mixed = PyDsl; export class BinaryPyDsl extends Mixed { readonly '~dsl' = 'BinaryPyDsl'; protected _left?: Ref>; protected _op?: PyBinaryOperator; protected _right?: Ref>; constructor( left: MaybePyDsl, op: PyBinaryOperator, right: MaybePyDsl, ) { super(); this._left = ref(left); this._op = op; this._right = ref(right); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._left); ctx.analyze(this._right); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } and(right: MaybePyDsl): this { return this.opAndExpr('and', right); } div(right: MaybePyDsl): this { return this.opAndExpr('/', right); } eq(right: MaybePyDsl): this { return this.opAndExpr('==', right); } floordiv(right: MaybePyDsl): this { return this.opAndExpr('//', right); } gt(right: MaybePyDsl): this { return this.opAndExpr('>', right); } gte(right: MaybePyDsl): this { return this.opAndExpr('>=', right); } in_(right: MaybePyDsl): this { return this.opAndExpr('in', right); } is(right: MaybePyDsl): this { return this.opAndExpr('is', right); } isNot(right: MaybePyDsl): this { return this.opAndExpr('is not', right); } lt(right: MaybePyDsl): this { return this.opAndExpr('<', right); } lte(right: MaybePyDsl): this { return this.opAndExpr('<=', right); } minus(right: MaybePyDsl): this { return this.opAndExpr('-', right); } mod(right: MaybePyDsl): this { return this.opAndExpr('%', right); } neq(right: MaybePyDsl): this { return this.opAndExpr('!=', right); } notIn(right: MaybePyDsl): this { return this.opAndExpr('not in', right); } or(right: MaybePyDsl): this { return this.opAndExpr('or', right); } plus(right: MaybePyDsl): this { return this.opAndExpr('+', right); } pow(right: MaybePyDsl): this { return this.opAndExpr('**', right); } times(right: MaybePyDsl): this { return this.opAndExpr('*', right); } override toAst() { this.$validate(); return py.factory.createBinaryExpression( this.$node(this._left!), this._op!, this.$node(this._right!), ); } $validate(): asserts this is this & { _left: MaybePyDsl; _op: PyBinaryOperator; _right: MaybePyDsl; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Binary expression missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._left) missing.push('left operand'); if (!this._op) missing.push('operator'); if (!this._right) missing.push('right operand'); return missing; } private opAndExpr(op: PyBinaryOperator, right: MaybePyDsl): this { this._right = ref(right); this._op = op; return this; } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/call.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { ArgsMixin } from '../mixins/args'; import { ExprMixin } from '../mixins/expr'; import { f } from '../utils/factories'; export type CallArgs = ReadonlyArray; export type CallCallee = NodeName | MaybePyDsl; export type CallCtor = (callee: CallCallee, ...args: CallArgs) => CallPyDsl; const Mixed = ArgsMixin(ExprMixin(PyDsl)); export class CallPyDsl extends Mixed { readonly '~dsl' = 'CallPyDsl'; protected _callee: Ref; constructor(callee: CallCallee, ...args: CallArgs) { super(); this._callee = ref(callee); this.args(...args); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._callee); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } override toAst() { this.$validate(); return py.factory.createCallExpression(this.$node(this._callee!), this.$args()); } $validate(): asserts this is this & { _callee: MaybePyDsl; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Call expression missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._callee) missing.push('callee'); return missing; } } f.call.set((...args) => new CallPyDsl(...args)); ================================================ FILE: packages/openapi-python/src/py-dsl/expr/dict.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { LayoutMixin } from '../mixins/layout'; const Mixed = LayoutMixin(PyDsl); export class DictPyDsl extends Mixed { readonly '~dsl' = 'DictPyDsl'; protected _entries: Array<{ key: MaybePyDsl; value: MaybePyDsl; }> = []; constructor( ...entries: Array<{ key: MaybePyDsl; value: MaybePyDsl }> ) { super(); this._entries = entries; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const entry of this._entries) { ctx.analyze(entry.key); ctx.analyze(entry.value); } } entry(key: MaybePyDsl, value: MaybePyDsl): this { this._entries.push({ key, value }); return this; } entries( ...entries: ReadonlyArray<{ key: MaybePyDsl; value: MaybePyDsl }> ): this { this._entries.push(...entries); return this; } override toAst() { const astEntries = this._entries.map((entry) => ({ key: this.$node(entry.key), value: this.$node(entry.value), })); return py.factory.createDictExpression(astEntries); } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/expr.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { isNode, isSymbol, ref } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { ExprMixin } from '../mixins/expr'; type Id = NodeName | MaybePyDsl; const Mixed = ExprMixin(PyDsl); export class ExprPyDsl extends Mixed { readonly '~dsl' = 'ExprPyDsl'; protected _exprInput: Ref; constructor(id: Id) { super(); this._exprInput = ref(id); if (typeof id === 'string' || isSymbol(id)) { this.name.set(id); } else if (isNode(id)) { this.name.set(id.name); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._exprInput); } override toAst() { return this.$node(this._exprInput); } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/identifier.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; const Mixed = PyDsl; export class IdPyDsl extends Mixed { readonly '~dsl' = 'IdPyDsl'; constructor(name: NodeName) { super(); this.name.set(name); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); } override toAst() { return py.factory.createIdentifier(this.name.toString()); } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/kwarg.ts ================================================ import type { NodeName } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; export type KwargValue = string | number | boolean | null | MaybePyDsl; export class KwargPyDsl extends PyDsl { readonly '~dsl' = 'KwargPyDsl'; protected _value: KwargValue; constructor(name: NodeName, value: KwargValue) { super(); this.name.set(name); this._value = value; } override toAst() { const name = this.name.toString(); return py.factory.createKeywordArgument(name, this.$valueToNode(this._value)); } private $valueToNode(value: KwargValue) { if ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value === null ) { return py.factory.createLiteral(value); } return this.$node(value); } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/list.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { LayoutMixin } from '../mixins/layout'; const Mixed = LayoutMixin(PyDsl); export class ListPyDsl extends Mixed { readonly '~dsl' = 'ListPyDsl'; protected _elements: Array> = []; constructor(...elements: Array>) { super(); this._elements = elements; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const el of this._elements) { ctx.analyze(el); } } element(expr: MaybePyDsl): this { this._elements.push(expr); return this; } elements(...exprs: ReadonlyArray>): this { this._elements.push(...exprs); return this; } override toAst() { const astElements = this._elements.map((el) => this.$node(el)); return py.factory.createListExpression(astElements); } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/literal.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; const Mixed = PyDsl; export class LiteralPyDsl extends Mixed { readonly '~dsl' = 'LiteralPyDsl'; protected value: py.LiteralValue; constructor(value: py.LiteralValue) { super(); this.value = value; } override analyze(_ctx: AnalysisContext): void { super.analyze(_ctx); } override toAst() { return py.factory.createLiteral(this.value); } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/set.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { LayoutMixin } from '../mixins/layout'; const Mixed = LayoutMixin(PyDsl); export class SetPyDsl extends Mixed { readonly '~dsl' = 'SetPyDsl'; protected _elements: Array> = []; constructor(...elements: Array>) { super(); this._elements = elements; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const el of this._elements) { ctx.analyze(el); } } element(expr: MaybePyDsl): this { this._elements.push(expr); return this; } elements(...exprs: ReadonlyArray>): this { this._elements.push(...exprs); return this; } override toAst() { const astElements = this._elements.map((el) => this.$node(el)); return py.factory.createSetExpression(astElements); } } ================================================ FILE: packages/openapi-python/src/py-dsl/expr/subscript.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; import { LayoutMixin } from '../mixins/layout'; import { f } from '../utils/factories'; export type SubscriptExpr = NodeName | PyDsl; export type SubscriptCtor = ( value: SubscriptExpr, ...slices: Array ) => SubscriptPyDsl; const Mixed = LayoutMixin(PyDsl); export class SubscriptPyDsl extends Mixed { readonly '~dsl' = 'SubscriptPyDsl'; protected _slices: Array>; protected _value: Ref; constructor(value: SubscriptExpr, ...slices: Array) { super(); this._slices = slices.map((slice) => ref(slice)); this._value = ref(value); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._value); for (const slice of this._slices) { ctx.analyze(slice); } } override toAst() { const slice = this._slices.length === 1 ? this.$node(this._slices[0]!) : py.factory.createSubscriptSlice(this._slices.map((s) => this.$node(s))); return py.factory.createSubscriptExpression(this.$node(this._value), slice); } } f.slice.set((...args) => new SubscriptPyDsl(...args)); ================================================ FILE: packages/openapi-python/src/py-dsl/expr/tuple.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { LayoutMixin } from '../mixins/layout'; export type TupleElement = NodeName | MaybePyDsl; const Mixed = LayoutMixin(PyDsl); export class TuplePyDsl extends Mixed { readonly '~dsl' = 'TuplePyDsl'; protected _elements: Array> = []; constructor(...elements: Array) { super(); this._elements = elements.map((element) => ref(element)); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const el of this._elements) { ctx.analyze(el); } } element(expr: TupleElement): this { this._elements.push(ref(expr)); return this; } elements(...exprs: ReadonlyArray): this { this._elements.push(...exprs.map((expr) => ref(expr))); return this; } override toAst() { const astElements = this._elements.map((el) => this.$node(el)); return py.factory.createTupleExpression(astElements); } } ================================================ FILE: packages/openapi-python/src/py-dsl/index.ts ================================================ import type { NodeName } from '@hey-api/codegen-core'; import type { py } from '../py-compiler'; import { ClassPyDsl } from './decl/class'; // import { DecoratorPyDsl } from './decl/decorator'; // import { EnumPyDsl } from './decl/enum'; // import { FieldPyDsl } from './decl/field'; import { FuncPyDsl } from './decl/func'; import { ParamPyDsl } from './decl/param'; // import { GetterPyDsl } from './decl/getter'; // import { InitPyDsl } from './decl/init'; // import { EnumMemberPyDsl } from './decl/member'; // import { MethodPyDsl } from './decl/method'; // import { PatternPyDsl } from './decl/pattern'; // import { SetterPyDsl } from './decl/setter'; // import { ArrayPyDsl } from './expr/array'; // import { AsPyDsl } from './expr/as'; import { AttrPyDsl } from './expr/attr'; // import { AwaitPyDsl } from './expr/await'; import { BinaryPyDsl } from './expr/binary'; import { CallPyDsl } from './expr/call'; import { DictPyDsl } from './expr/dict'; import { ExprPyDsl } from './expr/expr'; // import { fromValue as exprValue } from './expr/fromValue'; import { IdPyDsl } from './expr/identifier'; import { KwargPyDsl } from './expr/kwarg'; import { ListPyDsl } from './expr/list'; import { LiteralPyDsl } from './expr/literal'; // import { NewPyDsl } from './expr/new'; // import { ObjectPyDsl } from './expr/object'; // import { PrefixPyDsl } from './expr/prefix'; // import { ObjectPropPyDsl } from './expr/prop'; // import { RegExpPyDsl } from './expr/regexp'; import { SetPyDsl } from './expr/set'; import { SubscriptPyDsl } from './expr/subscript'; // import { TemplatePyDsl } from './expr/template'; // import { TernaryPyDsl } from './expr/ternary'; import { TuplePyDsl } from './expr/tuple'; // import { TypeOfExprPyDsl } from './expr/typeof'; import { DocPyDsl } from './layout/doc'; import { HintPyDsl } from './layout/hint'; import { NewlinePyDsl } from './layout/newline'; import { BlockPyDsl } from './stmt/block'; import { BreakPyDsl } from './stmt/break'; import { ContinuePyDsl } from './stmt/continue'; import { ForPyDsl } from './stmt/for'; import { IfPyDsl } from './stmt/if'; import { ImportPyDsl } from './stmt/import'; import { RaisePyDsl } from './stmt/raise'; import { ReturnPyDsl } from './stmt/return'; import { StmtPyDsl } from './stmt/stmt'; import { TryPyDsl } from './stmt/try'; import { VarPyDsl } from './stmt/var'; import { WhilePyDsl } from './stmt/while'; import { WithPyDsl } from './stmt/with'; // import { TokenPyDsl } from './token'; // import { TypeAliasPyDsl } from './type/alias'; // import { TypeAndPyDsl } from './type/and'; // import { TypeAttrPyDsl } from './type/attr'; // import { TypeExprPyDsl } from './type/expr'; // import { fromValue as typeValue } from './type/fromValue'; // import { TypeFuncPyDsl } from './type/func'; // import { TypeIdxPyDsl } from './type/idx'; // import { TypeLiteralPyDsl } from './type/literal'; // import { TypeMappedPyDsl } from './type/mapped'; // import { TypeObjectPyDsl } from './type/object'; // import { TypeOperatorPyDsl } from './type/operator'; // import { TypeOrPyDsl } from './type/or'; // import { TypeParamPyDsl } from './type/param'; // import { TypeQueryPyDsl } from './type/query'; // import { TypeTemplatePyDsl } from './type/template'; // import { TypeTuplePyDsl } from './type/tuple'; import { LazyPyDsl } from './utils/lazy'; import { safeKeywordName } from './utils/name'; const pyDsl = { /** Creates an array literal expression (e.g. `[1, 2, 3]`). */ // array: (...args: ConstructorParameters) => new ArrayTsDsl(...args), /** Creates an `as` type assertion expression (e.g. `value as Type`). */ // as: (...args: ConstructorParameters) => new AsTsDsl(...args), /** Creates a property access expression (e.g. `obj.foo`). */ attr: (...args: ConstructorParameters) => new AttrPyDsl(...args), /** Creates an await expression (e.g. `await promise`). */ // await: (...args: ConstructorParameters) => new AwaitTsDsl(...args), /** Creates a binary expression (e.g. `a + b`). */ binary: (...args: ConstructorParameters) => new BinaryPyDsl(...args), /** Creates a statement block. */ block: (...args: ConstructorParameters) => new BlockPyDsl(...args), /** Creates a break statement. */ break: (...args: ConstructorParameters) => new BreakPyDsl(...args), /** Creates a function or method call expression (e.g. `fn(arg)`). */ call: (...args: ConstructorParameters) => new CallPyDsl(...args), /** Creates a class declaration or expression. */ class: (...args: ConstructorParameters) => new ClassPyDsl(...args), /** Creates a continue statement. */ continue: (...args: ConstructorParameters) => new ContinuePyDsl(...args), /** Creates a decorator expression (e.g. `@decorator`). */ // decorator: (...args: ConstructorParameters) => new DecoratorTsDsl(...args), /** Creates a dictionary expression (e.g. `{ 'a': 1 }`). */ dict: (...args: ConstructorParameters) => new DictPyDsl(...args), /** Creates a Python docstring (`"""..."""`). */ doc: (...args: ConstructorParameters) => new DocPyDsl(...args), /** Creates an enum declaration. */ // enum: (...args: ConstructorParameters) => new EnumTsDsl(...args), /** Creates a general expression node. */ expr: (...args: ConstructorParameters) => new ExprPyDsl(...args), /** Creates a field declaration in a class or object. */ // field: (...args: ConstructorParameters) => new FieldTsDsl(...args), /** Creates a for statement (e.g. `for x in items:`). */ for: (...args: ConstructorParameters) => new ForPyDsl(...args), /** Converts a runtime value into a corresponding expression node. */ // fromValue: (...args: Parameters) => exprValue(...args), /** Creates a function declaration. */ func: ((name: NodeName, fn?: (f: FuncPyDsl) => void) => new FuncPyDsl(name, fn)) as { (name: NodeName): FuncPyDsl; (name: NodeName, fn: (f: FuncPyDsl) => void): FuncPyDsl; }, /** Creates a getter method declaration. */ // getter: (...args: ConstructorParameters) => new GetterTsDsl(...args), /** Creates a Python comment (`# ...`). */ hint: (...args: ConstructorParameters) => new HintPyDsl(...args), /** Creates an identifier (e.g. `foo`). */ id: (...args: ConstructorParameters) => new IdPyDsl(...args), /** Creates an if statement. */ if: (...args: ConstructorParameters) => new IfPyDsl(...args), /** Creates an import statement. */ import: (...args: ConstructorParameters) => new ImportPyDsl(...args), /** Creates an initialization block or statement. */ // init: (...args: ConstructorParameters) => new InitTsDsl(...args), /** Creates a keyword argument expression (e.g. `name=value`). */ kwarg: (...args: ConstructorParameters) => new KwargPyDsl(...args), /** Creates a lazy, context-aware node with deferred evaluation. */ lazy: (...args: ConstructorParameters>) => new LazyPyDsl(...args), /** Creates a list expression (e.g. `[1, 2, 3]`). */ list: (...args: ConstructorParameters) => new ListPyDsl(...args), /** Creates a literal value (e.g. string, number, boolean). */ literal: (...args: ConstructorParameters) => new LiteralPyDsl(...args), /** Creates an enum member declaration. */ // member: (...args: ConstructorParameters) => new EnumMemberTsDsl(...args), /** Creates a class method declaration. */ method: ((name: NodeName, fn?: (f: FuncPyDsl) => void) => new FuncPyDsl(name, fn, { nameSanitizer: safeKeywordName })) as { (name: NodeName): FuncPyDsl; (name: NodeName, fn: (f: FuncPyDsl) => void): FuncPyDsl; }, /** Creates a negation expression (`-x`). */ // neg: (...args: ConstructorParameters) => new PrefixTsDsl(...args).neg(), /** Creates a new expression (e.g. `new ClassName()`). */ // new: (...args: ConstructorParameters) => new NewTsDsl(...args), /** Creates a newline (for formatting purposes). */ newline: (...args: ConstructorParameters) => new NewlinePyDsl(...args), /** Creates a logical NOT expression (`!x`). */ // not: (...args: ConstructorParameters) => new PrefixTsDsl(...args).not(), /** Creates an object literal expression. */ // object: (...args: ConstructorParameters) => new ObjectTsDsl(...args), /** Creates a parameter declaration for functions or methods. */ param: (...args: ConstructorParameters) => new ParamPyDsl(...args), /** Creates a pattern for destructuring or matching. */ // pattern: (...args: ConstructorParameters) => new PatternTsDsl(...args), /** Creates a prefix unary expression (e.g. `-x`, `!x`, `~x`). */ // prefix: (...args: ConstructorParameters) => new PrefixTsDsl(...args), /** Creates an object literal property (e.g. `{ foo: bar }`). */ // prop: (...args: ConstructorParameters) => new ObjectPropTsDsl(...args), /** Creates a raise statement. */ raise: (...args: ConstructorParameters) => new RaisePyDsl(...args), /** Creates a regular expression literal (e.g. `/foo/gi`). */ // regexp: (...args: ConstructorParameters) => new RegExpTsDsl(...args), /** Creates a return statement. */ return: (...args: ConstructorParameters) => new ReturnPyDsl(...args), /** Creates a set expression (e.g. `{1, 2, 3}`). */ set: (...args: ConstructorParameters) => new SetPyDsl(...args), /** Creates a setter method declaration. */ // setter: (...args: ConstructorParameters) => new SetterTsDsl(...args), /** Wraps an expression or statement-like value into a `StmtPyDsl`. */ stmt: (...args: ConstructorParameters) => new StmtPyDsl(...args), /** Creates a subscript expression (e.g. `obj[index]` or `Type[Param]`). */ subscript: (...args: ConstructorParameters) => new SubscriptPyDsl(...args), /** Creates a template literal expression. */ // template: (...args: ConstructorParameters) => new TemplateTsDsl(...args), /** Creates a ternary conditional expression (if ? then : else). */ // ternary: (...args: ConstructorParameters) => new TernaryTsDsl(...args), // /** Creates a throw statement. */ // throw: (...args: ConstructorParameters) => new ThrowTsDsl(...args), /** Creates a syntax token (e.g. `?`, `readonly`, `+`, `-`). */ // token: (...args: ConstructorParameters) => new TokenTsDsl(...args), /** Creates a try/except/finally statement. */ try: (...args: ConstructorParameters) => new TryPyDsl(...args), /** Creates a tuple expression (e.g. `(1, 2, 3)`). */ tuple: (...args: ConstructorParameters) => new TuplePyDsl(...args), /** Creates a basic type reference or type expression (e.g. Foo or Foo). */ // type: Object.assign( // (...args: ConstructorParameters) => new TypeExprTsDsl(...args), // { /** Creates a type alias declaration (e.g. `type Foo = Bar`). */ // alias: (...args: ConstructorParameters) => new TypeAliasTsDsl(...args), /** Creates an intersection type (e.g. `A & B`). */ // and: (...args: ConstructorParameters) => new TypeAndTsDsl(...args), /** Creates a qualified type reference (e.g. Foo.Bar). */ // attr: (...args: ConstructorParameters) => new TypeAttrTsDsl(...args), /** Creates a basic type reference or type expression (e.g. Foo or Foo). */ // expr: (...args: ConstructorParameters) => new TypeExprTsDsl(...args), /** Converts a runtime value into a corresponding type expression node. */ // fromValue: (...args: Parameters) => typeValue(...args), /** Creates a function type node (e.g. `(a: string) => number`). */ // func: (...args: ConstructorParameters) => new TypeFuncTsDsl(...args), /** Creates an indexed-access type (e.g. `Foo[K]`). */ // idx: (...args: ConstructorParameters) => new TypeIdxTsDsl(...args), /** Creates a literal type node (e.g. 'foo', 42, or true). */ // literal: (...args: ConstructorParameters) => // new TypeLiteralTsDsl(...args), /** Creates a mapped type (e.g. `{ [K in keyof T]: U }`). */ // mapped: (...args: ConstructorParameters) => // new TypeMappedTsDsl(...args), /** Creates a type literal node (e.g. { foo: string }). */ // object: (...args: ConstructorParameters) => // new TypeObjectTsDsl(...args), /** Creates a type operator node (e.g. `readonly T`, `keyof T`, `unique T`). */ // operator: (...args: ConstructorParameters) => // new TypeOperatorTsDsl(...args), /** Represents a union type (e.g. `A | B | C`). */ // or: (...args: ConstructorParameters) => new TypeOrTsDsl(...args), /** Creates a type parameter (e.g. ``). */ // param: (...args: ConstructorParameters) => new TypeParamTsDsl(...args), /** Creates a type query node (e.g. `typeof Foo`). */ // query: (...args: ConstructorParameters) => new TypeQueryTsDsl(...args), /** Builds a TypeScript template literal *type* (e.g. `${Foo}-${Bar}` as a type). */ // template: (...args: ConstructorParameters) => // new TypeTemplateTsDsl(...args), /** Creates a tuple type (e.g. [A, B, C]). */ // tuple: (...args: ConstructorParameters) => new TypeTupleTsDsl(...args), // }, // ), /** Creates a `typeof` expression (e.g. `typeof value`). */ // typeofExpr: (...args: ConstructorParameters) => // new TypeOfExprTsDsl(...args), /** Creates a variable assignment. */ var: (...args: ConstructorParameters) => new VarPyDsl(...args), /** Creates a while statement (e.g. `while x:`). */ while: (...args: ConstructorParameters) => new WhilePyDsl(...args), /** Creates a with statement (e.g. `with open(f) as file:`). */ with: (...args: ConstructorParameters) => new WithPyDsl(...args), }; export const $ = Object.assign( (...args: ConstructorParameters) => new ExprPyDsl(...args), pyDsl, ); export type DollarPyDsl = { /** * Entry point to the Python DSL. * * `$` creates a general expression node by default, but also exposes * builders for all other constructs. * * Example: * ```ts * const node = $('console').attr('log').call($.literal('Hello')); * ``` * * Returns: * - A new `ExprPyDsl` instance when called directly. * - The `pyDsl` object for constructing more specific nodes. */ $: typeof $; }; export type { MaybePyDsl } from './base'; // export type { MaybePyDsl, TypePyDsl } from './base'; export { PyDsl } from './base'; export type { CallArgs } from './expr/call'; export type { VarType } from './stmt/var'; export type { ExampleOptions } from './utils/context'; export { ctx, PyDslContext } from './utils/context'; export { keywords } from './utils/keywords'; export { regexp } from './utils/regexp'; export { PythonRenderer } from './utils/render'; export { reserved } from './utils/reserved'; ================================================ FILE: packages/openapi-python/src/py-dsl/layout/doc.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; import type { PyDslContext } from '../utils/context'; import { ctx } from '../utils/context'; type DocMaybeLazy = ((ctx: PyDslContext) => T) | T; export type DocFn = (d: DocPyDsl) => void; export type DocLines = DocMaybeLazy>; export class DocPyDsl extends PyDsl { readonly '~dsl' = 'DocPyDsl'; protected _lines: Array = []; constructor(lines?: DocLines, fn?: DocFn) { super(); if (lines) this.add(lines); fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } add(lines: DocLines): this { this._lines.push(lines); return this; } resolve(): string | undefined { const lines = this._lines.reduce((lines: Array, line: DocLines) => { if (typeof line === 'function') line = line(ctx); for (const l of typeof line === 'string' ? [line] : line) { if (l || l === '') lines.push(l); } return lines; }, []); if (!lines.length) return; return lines.join('\n'); } override toAst() { // Return a dummy comment node for compliance. return py.factory.createComment(this.resolve() ?? ''); // return this.$node(new IdTsDsl('')); } } ================================================ FILE: packages/openapi-python/src/py-dsl/layout/hint.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; import type { PyDslContext } from '../utils/context'; import { ctx } from '../utils/context'; type HintMaybeLazy = ((ctx: PyDslContext) => T) | T; export type HintFn = (d: HintPyDsl) => void; export type HintLines = HintMaybeLazy>; export class HintPyDsl extends PyDsl { readonly '~dsl' = 'HintPyDsl'; protected _lines: Array = []; constructor(lines?: HintLines, fn?: HintFn) { super(); if (lines) this.add(lines); fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } add(lines: HintLines): this { this._lines.push(lines); return this; } apply(node: T): T { const lines = this._resolveLines(); if (!lines.length) return node; const existing = node.leadingComments ? [...node.leadingComments] : []; existing.push(...lines); node.leadingComments = existing; return node; } override toAst() { // Return a dummy comment node for compliance. const lines = this._resolveLines(); return py.factory.createComment(lines.join('\n')); } private _resolveLines(): Array { return this._lines.reduce((lines: Array, line: HintLines) => { if (typeof line === 'function') line = line(ctx); for (const l of typeof line === 'string' ? [line] : line) { if (l || l === '') lines.push(l); } return lines; }, []); } } ================================================ FILE: packages/openapi-python/src/py-dsl/layout/newline.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; export class NewlinePyDsl extends PyDsl { readonly '~dsl' = 'NewlinePyDsl'; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } override toAst() { return py.factory.createEmptyStatement(); } } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/args.ts ================================================ import type { AnalysisContext, Node, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import type { BaseCtor, MixinCtor } from './types'; type Arg = NodeName | MaybePyDsl; export interface ArgsMethods extends Node { /** Renders the arguments into an array of `Expression`s. */ $args(): ReadonlyArray; /** Adds a single expression argument. */ arg(arg: Arg | undefined): this; /** Adds one or more expression arguments. */ args(...args: ReadonlyArray): this; } /** * Adds `.arg()` and `.args()` for managing expression arguments in call-like nodes. */ export function ArgsMixin>(Base: TBase) { abstract class Args extends Base { protected _args: Array> = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const arg of this._args) { ctx.analyze(arg); } } protected arg(arg: Arg | undefined): this { if (arg !== undefined) this._args.push(ref(arg)); return this; } protected args(...args: ReadonlyArray): this { this._args.push( ...args.filter((a): a is NonNullable => a !== undefined).map((a) => ref(a)), ); return this; } protected $args(): ReadonlyArray { return this.$node(this._args).map((arg) => this.$node(arg)); } } return Args as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/decorator.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import type { BaseCtor, MixinCtor } from './types'; type DecoratorArg = MaybePyDsl; type DecoratorName = NodeName | MaybePyDsl; export interface DecoratorMethods extends Node { $decorators(): ReadonlyArray; decorator(name: DecoratorName, ...args: ReadonlyArray): this; } export function DecoratorMixin>(Base: TBase) { abstract class Decorator extends Base { protected _decorators: Array<{ args: ReadonlyArray>; name: Ref; }> = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const decorator of this._decorators) { ctx.analyze(decorator.name); for (const arg of decorator.args) { ctx.analyze(arg); } } } protected decorator(name: DecoratorName, ...args: ReadonlyArray): this { this._decorators.push({ args: args.map((arg) => ref(arg)), name: ref(name), }); return this; } protected $decorators(): ReadonlyArray { return this._decorators.map((decorator) => decorator.args.length > 0 ? py.factory.createCallExpression( this.$node(decorator.name), decorator.args.map((arg) => this.$node(arg)), ) : this.$node(decorator.name), ); } } return Decorator as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/do.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { StmtPyDsl } from '../stmt/stmt'; import type { BaseCtor, MixinCtor } from './types'; export type DoExpr = MaybePyDsl; export interface DoMethods extends Node { /** Renders the collected `.do()` calls into an array of `py.Statement` nodes. */ $do(): ReadonlyArray; _do: Array; /** Adds one or more expressions/statements to the body. */ do(...items: ReadonlyArray): this; } export function DoMixin>(Base: TBase) { abstract class Do extends Base { protected _do: Array = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.pushScope(); try { for (const item of this._do) { ctx.analyze(item); } } finally { ctx.popScope(); } } protected do(...items: ReadonlyArray): this { this._do.push(...items); return this; } protected $do(): ReadonlyArray { return this.$node(this._do.map((item) => new StmtPyDsl(item))); } } return Do as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/doc.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { DocFn, DocLines } from '../layout/doc'; import { DocPyDsl } from '../layout/doc'; import type { BaseCtor, MixinCtor } from './types'; export interface DocMethods extends Node { $docs(): string | undefined; doc(lines?: DocLines, fn?: DocFn): this; } export function DocMixin>(Base: TBase) { abstract class Doc extends Base { private _doc?: DocPyDsl; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected doc(lines?: DocLines, fn?: DocFn): this { this._doc = new DocPyDsl(lines, fn); return this; } protected $docs(): string | undefined { return this._doc ? this._doc.resolve() : undefined; } } return Doc as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/expr.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import { f } from '../utils/factories'; import type { BaseCtor, DropFirst, MixinCtor } from './types'; export interface ExprMethods extends Node { /** Accesses a property on the current expression (e.g. `this.foo`). */ attr(...args: DropFirst>): ReturnType; /** Calls the current expression (e.g. `fn(arg1, arg2)`). */ call(...args: DropFirst>): ReturnType; /** Produces a `return` statement returning the current expression. */ return(): ReturnType; /** Produces a subscript/slice expression (e.g. `expr[args]`). */ slice(...args: DropFirst>): ReturnType; } export function ExprMixin>(Base: TBase) { abstract class Expr extends Base { override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected attr(...args: DropFirst>): ReturnType { // @ts-expect-error - fix this type return f.attr(this, ...args); } protected call(...args: DropFirst>): ReturnType { // @ts-expect-error - fix this type return f.call(this, ...args); } protected return(): ReturnType { // @ts-expect-error - fix this type return f.return(this); } protected slice(...args: DropFirst>): ReturnType { return f.slice(this, ...args); } } return Expr as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/hint.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { HintFn, HintLines } from '../layout/hint'; import { HintPyDsl } from '../layout/hint'; import type { BaseCtor, MixinCtor } from './types'; export interface HintMethods extends Node { $hint(node: T): T; hint(lines?: HintLines, fn?: HintFn): this; } export function HintMixin>(Base: TBase) { abstract class Hint extends Base { private _hint?: HintPyDsl; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected hint(lines?: HintLines, fn?: HintFn): this { this._hint = new HintPyDsl(lines, fn); return this; } protected $hint(node: T): T { return this._hint ? this._hint.apply(node) : node; } } return Hint as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/layout.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { BaseCtor, MixinCtor } from './types'; export interface LayoutMethods extends Node { /** Computes whether output should be multiline based on layout setting and element count. */ $multiline(count: number): boolean; /** Sets automatic line output with optional threshold (default: 3). */ auto(threshold?: number): this; /** Sets single line output. */ inline(): this; /** Sets multi line output. */ pretty(): this; } export function LayoutMixin>(Base: TBase) { abstract class Layout extends Base { protected static readonly DEFAULT_THRESHOLD = 3; protected layout: boolean | number | undefined; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected auto(threshold: number = Layout.DEFAULT_THRESHOLD): this { this.layout = threshold; return this; } protected inline(): this { this.layout = false; return this; } protected pretty(): this { this.layout = true; return this; } protected $multiline(count: number): boolean { if (this.layout === undefined) { this.layout = Layout.DEFAULT_THRESHOLD; } if (count === 0) return false; return typeof this.layout === 'number' ? count >= this.layout : this.layout; } } return Layout as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/modifiers.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { BaseCtor, MixinCtor } from './types'; export type Modifiers = { /** * Checks if specified modifier is present. * * @param modifier - The modifier to check. * @returns True if modifier is present, false otherwise. */ hasModifier(modifier: Modifier): boolean; modifiers: Array; }; type Modifier = 'async'; export interface ModifierMethods extends Modifiers { /** * Adds a modifier of specified kind to modifiers list if condition is true. * * @param modifier - The modifier to add. * @param condition - Whether to add modifier. * @returns The parent node for chaining. */ _m(modifier: Modifier, condition: boolean): this; } function modifierToKind(modifier: Modifier): py.Expression { switch (modifier) { case 'async': return py.factory.createIdentifier('async'); } } function ModifiersMixin>(Base: TBase) { abstract class Modifiers extends Base { protected modifiers: Array = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected hasModifier(modifier: Modifier): boolean { const kind = modifierToKind(modifier); return Boolean(this.modifiers.find((mod) => mod === kind)); } protected _m(modifier: Modifier, condition: boolean): this { if (condition) { const kind = modifierToKind(modifier); this.modifiers.push(kind); } return this; } } return Modifiers as unknown as MixinCtor; } export interface AsyncMethods extends Modifiers { /** * Adds an `async` keyword modifier if condition is true. * * @param condition - Whether to add modifier (default: true). * @returns The target object for chaining. */ async(condition?: boolean): this; } /** * Mixin that adds an `async` modifier to a node. */ export function AsyncMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Async extends Mixed { protected async(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('async', cond); } } return Async as unknown as MixinCtor; } export interface ExportMethods extends Modifiers { /** * Adds the `export` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ export(condition?: boolean): this; } /** * Mixin that adds an `export` modifier to a node. */ export function ExportMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Export extends Mixed { /** * Adds the `export` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ protected export(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); this.exported = cond; // TODO: remove this side-effect once planner handles exported flag if (this.symbol) this.symbol.setExported(cond); return this; } } return Export as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/operator.ts ================================================ import type { AnalysisContext, Node, NodeName } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { BinaryPyDsl } from '../expr/binary'; import type { BaseCtor, MixinCtor } from './types'; type Expr = NodeName | MaybePyDsl; export interface OperatorMethods extends Node { and(expr: Expr): BinaryPyDsl; div(expr: Expr): BinaryPyDsl; eq(expr: Expr): BinaryPyDsl; floordiv(expr: Expr): BinaryPyDsl; gt(expr: Expr): BinaryPyDsl; gte(expr: Expr): BinaryPyDsl; in_(expr: Expr): BinaryPyDsl; is(expr: Expr): BinaryPyDsl; isNot(expr: Expr): BinaryPyDsl; lt(expr: Expr): BinaryPyDsl; lte(expr: Expr): BinaryPyDsl; minus(expr: Expr): BinaryPyDsl; mod(expr: Expr): BinaryPyDsl; neq(expr: Expr): BinaryPyDsl; notIn(expr: Expr): BinaryPyDsl; or(expr: Expr): BinaryPyDsl; plus(expr: Expr): BinaryPyDsl; pow(expr: Expr): BinaryPyDsl; times(expr: Expr): BinaryPyDsl; } export function OperatorMixin>(Base: TBase) { abstract class Operator extends Base { override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected and(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, 'and', expr as MaybePyDsl, ); } protected div(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '/', expr as MaybePyDsl, ); } protected eq(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '==', expr as MaybePyDsl, ); } protected floordiv(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '//', expr as MaybePyDsl, ); } protected gt(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '>', expr as MaybePyDsl, ); } protected gte(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '>=', expr as MaybePyDsl, ); } protected in_(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, 'in', expr as MaybePyDsl, ); } protected is(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, 'is', expr as MaybePyDsl, ); } protected isNot(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, 'is not', expr as MaybePyDsl, ); } protected lt(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '<', expr as MaybePyDsl, ); } protected lte(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '<=', expr as MaybePyDsl, ); } protected minus(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '-', expr as MaybePyDsl, ); } protected mod(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '%', expr as MaybePyDsl, ); } protected neq(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '!=', expr as MaybePyDsl, ); } protected notIn(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, 'not in', expr as MaybePyDsl, ); } protected or(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, 'or', expr as MaybePyDsl, ); } protected plus(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '+', expr as MaybePyDsl, ); } protected pow(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '**', expr as MaybePyDsl, ); } protected times(expr: Expr): BinaryPyDsl { return new BinaryPyDsl( this as unknown as MaybePyDsl, '*', expr as MaybePyDsl, ); } } return Operator as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/param.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import type { ParamCtor, ParamFn, ParamName } from '../decl/param'; import { ParamPyDsl } from '../decl/param'; import type { BaseCtor, MixinCtor } from './types'; export interface ParamMethods extends Node { /** Renders the parameters into an array of `FunctionParameter`s. */ $params(): ReadonlyArray; /** Adds a parameter. */ param(...args: Parameters): this; /** Adds multiple parameters. */ params(...params: ReadonlyArray>): this; } export function ParamMixin>(Base: TBase) { abstract class Param extends Base { protected _params: Array> = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const param of this._params) { ctx.analyze(param); } } protected param(name: ParamName, fn?: ParamFn): this { const p = typeof name === 'function' ? new ParamPyDsl(name) : new ParamPyDsl(name, fn); this._params.push(p); return this; } protected params(...params: ReadonlyArray>): this { this._params.push(...params); return this; } protected $params(): ReadonlyArray { return this.$node(this._params); } } return Param as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/returns.ts ================================================ import type { AnalysisContext, Node, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { BaseCtor, MixinCtor } from './types'; export interface ReturnsMethods extends Node { $returns(): py.Expression | undefined; returns(type: NodeName | py.Expression): this; } export function ReturnsMixin>(Base: TBase) { abstract class Returns extends Base { protected _returns?: Ref; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._returns); } returns(type: NodeName | py.Expression): this { this._returns = ref(type); return this; } protected $returns(): py.Expression | undefined { return this.$node(this._returns); } } return Returns as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/types.ts ================================================ import type { py } from '../../py-compiler'; import type { PyDsl } from '../base'; export type BaseCtor = abstract new (...args: Array) => PyDsl; export type DropFirst> = T extends [any, ...infer Rest] ? Rest : never; export type MixinCtor, K> = abstract new ( ...args: Array ) => InstanceType & K; ================================================ FILE: packages/openapi-python/src/py-dsl/mixins/value.ts ================================================ import type { AnalysisContext, Node, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import type { PyDsl } from '../base'; import type { BaseCtor, MixinCtor } from './types'; export type ValueExpr = NodeName | PyDsl; export interface ValueMethods extends Node { $value(): py.Expression | undefined; /** Sets the initializer expression (e.g. `= expr`). */ assign(expr: ValueExpr): this; } export function ValueMixin>(Base: TBase) { abstract class Value extends Base { protected value?: Ref; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.value); } protected assign(expr: ValueExpr): this { this.value = ref(expr); return this; } protected $value(): py.Expression | undefined { return this.$node(this.value); } } return Value as unknown as MixinCtor; } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/block.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { DoMixin } from '../mixins/do'; import { LayoutMixin } from '../mixins/layout'; const Mixed = DoMixin(LayoutMixin(PyDsl)); export class BlockPyDsl extends Mixed { readonly '~dsl' = 'BlockPyDsl'; constructor(...items: Array) { super(); this.do(...items); } override analyze(ctx: AnalysisContext) { super.analyze(ctx); } override toAst() { const statements = this.$do(); return py.factory.createBlock(statements); } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/break.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; const Mixed = PyDsl; export class BreakPyDsl extends Mixed { readonly '~dsl' = 'BreakPyDsl'; override analyze(_ctx: AnalysisContext): void { super.analyze(_ctx); } override toAst() { return py.factory.createBreakStatement(); } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/continue.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; const Mixed = PyDsl; export class ContinuePyDsl extends Mixed { readonly '~dsl' = 'ContinuePyDsl'; override analyze(_ctx: AnalysisContext): void { super.analyze(_ctx); } override toAst() { return py.factory.createContinueStatement(); } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/for.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { BlockPyDsl } from './block'; const Mixed = PyDsl; export class ForPyDsl extends Mixed { readonly '~dsl' = 'ForPyDsl'; protected _body?: Array; protected _else?: Array; protected _iterable?: MaybePyDsl; protected _target?: MaybePyDsl; constructor( target: MaybePyDsl, iterable: MaybePyDsl, ...body: Array ) { super(); this._target = target; this._iterable = iterable; this._body = body; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); if (this._target) ctx.analyze(this._target); if (this._iterable) ctx.analyze(this._iterable); if (this._body) { ctx.pushScope(); try { for (const stmt of this._body) ctx.analyze(stmt); } finally { ctx.popScope(); } } if (this._else) { ctx.pushScope(); try { for (const stmt of this._else) ctx.analyze(stmt); } finally { ctx.popScope(); } } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } body(...items: Array): this { this._body = items; return this; } else(...items: Array): this { this._else = items; return this; } override toAst() { this.$validate(); const body = new BlockPyDsl(...this._body!).$do(); const elseBlock = this._else ? new BlockPyDsl(...this._else).$do() : undefined; return py.factory.createForStatement( this.$node(this._target!), this.$node(this._iterable!), [...body], elseBlock ? [...elseBlock] : undefined, ); } $validate(): asserts this is this & { _body: Array; _iterable: MaybePyDsl; _target: MaybePyDsl; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`For statement missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._target) missing.push('target'); if (!this._iterable) missing.push('iterable'); if (!this._body || this._body.length === 0) missing.push('body'); return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/if.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { DoMixin } from '../mixins/do'; import { BlockPyDsl } from './block'; export type IfCondition = string | MaybePyDsl; const Mixed = DoMixin(PyDsl); export class IfPyDsl extends Mixed { readonly '~dsl' = 'IfPyDsl'; protected _condition?: IfCondition; protected _else?: Array; constructor(condition?: IfCondition) { super(); if (condition) this.condition(condition); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._condition); if (this._else) { ctx.pushScope(); try { for (const stmt of this._else) { ctx.analyze(stmt); } } finally { ctx.popScope(); } } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } condition(condition: IfCondition): this { this._condition = condition; return this; } otherwise(...items: Array): this { this._else = items; return this; } override toAst() { this.$validate(); const thenStatements = this.$do(); const elseStatements = this._else ? new BlockPyDsl(...this._else).$do() : undefined; return py.factory.createIfStatement( this.$node(this._condition!), [...thenStatements], elseStatements ? [...elseStatements] : undefined, ); } $validate(): asserts this is this & { _condition: IfCondition; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`If statement missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._condition) missing.push('.condition()'); if (this._do.length === 0) missing.push('.do()'); return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/import.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; type ImportName = { alias?: string; name: string }; const Mixed = PyDsl; export class ImportPyDsl extends Mixed { readonly '~dsl' = 'ImportPyDsl'; protected isFrom: boolean = true; protected module: string = ''; protected names?: ReadonlyArray; constructor(module: string); constructor(module: string, isFrom: boolean); constructor(module: string, names: ReadonlyArray, isFrom: boolean); constructor( module: string, namesOrIsFrom?: ReadonlyArray | boolean, isFrom?: boolean, ) { super(); this.module = module; if (typeof namesOrIsFrom === 'boolean') { this.isFrom = namesOrIsFrom; } else if (Array.isArray(namesOrIsFrom)) { this.names = namesOrIsFrom; this.isFrom = isFrom ?? true; } else { this.isFrom = true; } } static from(module: string, names?: ReadonlyArray): ImportPyDsl { return names ? new ImportPyDsl(module, names, true) : new ImportPyDsl(module, true); } static direct(module: string): ImportPyDsl { return new ImportPyDsl(module, false); } override analyze(_ctx: AnalysisContext): void { super.analyze(_ctx); } override toAst() { return py.factory.createImportStatement(this.module, this.names, this.isFrom); } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/raise.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; // import { LiteralPyDsl } from '../expr/literal'; const Mixed = PyDsl; export class RaisePyDsl extends Mixed { readonly '~dsl' = 'RaisePyDsl'; protected _error?: string | MaybePyDsl; // protected msg?: string | MaybePyDsl; constructor(error?: string | MaybePyDsl) { super(); this._error = error; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._error); // ctx.analyze(this.msg); } // /** Sets the message argument for the exception (e.g. `raise ValueError('msg')`). */ // message(value: string | MaybePyDsl): this { // this.msg = value; // return this; // } override toAst() { // Python's `raise` can be bare (re-raise), or `raise `. // Unlike JS `throw new Error(msg)`, Python uses `raise ErrorType(msg)` directly, // so the caller constructs the call expression themselves. const errorNode = this._error ? this.$node(this._error) : undefined; return py.factory.createRaiseStatement(errorNode); } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/return.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import { f } from '../utils/factories'; export type ReturnExpr = NodeName | MaybePyDsl; export type ReturnCtor = (expr?: ReturnExpr) => ReturnPyDsl; const Mixed = PyDsl; export class ReturnPyDsl extends Mixed { readonly '~dsl' = 'ReturnPyDsl'; protected _returnExpr?: Ref; constructor(expr?: ReturnExpr) { super(); if (expr) this._returnExpr = ref(expr); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._returnExpr); } override toAst() { return py.factory.createReturnStatement(this.$node(this._returnExpr)); } } f.return.set((...args) => new ReturnPyDsl(...args)); ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/stmt.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; const Mixed = PyDsl; export class StmtPyDsl extends Mixed { readonly '~dsl' = 'StmtPyDsl'; protected _inner: py.Expression | py.Statement | PyDsl; constructor(inner: py.Expression | py.Statement | PyDsl) { super(); this._inner = inner; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._inner); } override toAst() { const node = this.$node(this._inner); if (isStatement(node)) return node; return py.factory.createExpressionStatement(node); } } /** Checks whether a Python AST node is a statement. */ function isStatement(node: py.Expression | py.Statement): node is py.Statement { const statementKinds = new Set([ py.PyNodeKind.Assignment, py.PyNodeKind.AugmentedAssignment, py.PyNodeKind.Block, py.PyNodeKind.BreakStatement, py.PyNodeKind.ClassDeclaration, py.PyNodeKind.Comment, py.PyNodeKind.ContinueStatement, py.PyNodeKind.EmptyStatement, py.PyNodeKind.ExpressionStatement, py.PyNodeKind.ForStatement, py.PyNodeKind.FunctionDeclaration, py.PyNodeKind.IfStatement, py.PyNodeKind.ImportStatement, py.PyNodeKind.RaiseStatement, py.PyNodeKind.ReturnStatement, py.PyNodeKind.TryStatement, py.PyNodeKind.WhileStatement, py.PyNodeKind.WithStatement, ]); return statementKinds.has(node.kind); } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/try.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { BlockPyDsl } from './block'; const Mixed = PyDsl; type ExceptType = string | MaybePyDsl; interface ExceptEntry { body: Array; name?: Ref; types: Array; } function exceptKey(types: Array): string { return types .map((t) => (typeof t === 'string' ? t : '<>')) .sort() .join(','); } export class TryPyDsl extends Mixed { readonly '~dsl' = 'TryPyDsl'; /** * Ordered list of except clauses. We also keep a lookup map * (`_exceptIndex`) keyed by the normalised type key so that * repeated `.except()` calls with the same type set merge their * body statements instead of creating duplicate clauses. */ protected _excepts: Array = []; protected _exceptIndex: Map = new Map(); protected _finally?: Array; protected _try?: Array; constructor(...tryBlock: Array) { super(); this.try(...tryBlock); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); if (this._try) { ctx.pushScope(); try { for (const stmt of this._try) ctx.analyze(stmt); } finally { ctx.popScope(); } } for (const entry of this._excepts) { ctx.pushScope(); try { ctx.analyze(entry.name); for (const t of entry.types) ctx.analyze(t); for (const stmt of entry.body) ctx.analyze(stmt); } finally { ctx.popScope(); } } if (this._finally) { ctx.pushScope(); try { for (const stmt of this._finally) ctx.analyze(stmt); } finally { ctx.popScope(); } } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** * Add (or merge into) an except clause. * * ```ts * $.try(...) * .except('ValueError', 'e', body1, body2) // except ValueError as e: * .except(['TypeError', 'KeyError'], 'e', ...) // except (TypeError, KeyError) as e: * .except('ValueError', moreBody) // merges into first clause * ``` * * @param types Single exception type or array of types. * @param nameOrBody Either the `as` variable name (`NodeName`) or the * first body expression. If it looks like a `NodeName` (string that * is a valid Python identifier and is *not* a DSL node), it is treated * as the name; pass body items after it. * @param body Remaining body statements. */ except( types: MaybeArray, nameOrBody?: NodeName | DoExpr, ...body: Array ): this { const typeArr = Array.isArray(types) ? types : [types]; const key = exceptKey(typeArr); let name: Ref | undefined; let bodyItems: Array; // Disambiguate: if the second arg is a plain string that looks like // an identifier (no dots, no spaces, not a DSL node) treat it as // the `as` name. Otherwise it's the first body expression. if (nameOrBody !== undefined && this._isNodeName(nameOrBody)) { name = ref(nameOrBody as NodeName); bodyItems = body; } else if (nameOrBody !== undefined) { bodyItems = [nameOrBody as DoExpr, ...body]; } else { bodyItems = body; } const existing = this._exceptIndex.get(key); if (existing !== undefined) { const entry = this._excepts[existing]!; entry.body.push(...bodyItems); if (name !== undefined) entry.name = name; } else { this._exceptIndex.set(key, this._excepts.length); this._excepts.push({ body: bodyItems, name, types: typeArr }); } return this; } /** Add a bare `except:` clause (catches everything). */ exceptAll(...body: Array): this { const key = ''; const existing = this._exceptIndex.get(key); if (existing !== undefined) { this._excepts[existing]!.body.push(...body); } else { this._exceptIndex.set(key, this._excepts.length); this._excepts.push({ body, types: [] }); } return this; } finally(...items: Array): this { this._finally = items; return this; } try(...items: Array): this { this._try = items; return this; } override toAst() { this.$validate(); const tryStatements = new BlockPyDsl(...this._try!).$do(); let exceptClauses: Array | undefined; if (this._excepts.length) { exceptClauses = this._excepts.map((entry) => { const bodyStatements = new BlockPyDsl(...entry.body).$do(); let exceptionType: py.Expression | undefined; if (entry.types.length === 1) { exceptionType = this.$node(entry.types[0]!); } else if (entry.types.length > 1) { exceptionType = py.factory.createTupleExpression(entry.types.map((t) => this.$node(t))); } const exceptionName = entry.name ? py.factory.createIdentifier(this.$name(entry.name) || String(entry.name['~ref'])) : undefined; return py.factory.createExceptClause([...bodyStatements], exceptionType, exceptionName); }); } const finallyStatements = this._finally ? [...new BlockPyDsl(...this._finally).$do()] : undefined; return py.factory.createTryStatement( [...tryStatements], exceptClauses, undefined, finallyStatements, ); } $validate(): asserts this is this & { _try: Array; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Try statement missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._try || this._try.length === 0) missing.push('.try()'); return missing; } /** * Heuristic: a value is a `NodeName` (intended as the `as` variable) * if it is a plain string matching a Python identifier pattern, or a * Symbol. */ private _isNodeName(value: unknown): boolean { if (typeof value === 'string') { return /^[A-Za-z_]\w*$/.test(value); } // Symbols from codegen-core have `~brand` if (value && typeof value === 'object' && '~brand' in value) { return true; } return false; } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/var.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { isSymbol, ref } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import { PyDsl } from '../base'; import { ValueMixin } from '../mixins/value'; import { safeRuntimeName } from '../utils/name'; const Mixed = ValueMixin(PyDsl); export type VarType = NodeName | PyDsl; export class VarPyDsl extends Mixed { readonly '~dsl' = 'VarPyDsl'; override readonly nameSanitizer = safeRuntimeName; protected _type?: Ref; constructor(name?: NodeName) { super(); if (name) this.name.set(name); if (isSymbol(name)) { name.setKind('var'); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.analyze(this._type); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the type annotation for the variable. */ type(type: VarType): this { this._type = ref(type); return this; } override toAst() { this.$validate(); const target = this.$node(this.name)!; const type = this.$type(); const value = this.$value(); return py.factory.createAssignment(target, type, value); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Variable assignment missing ${missing.join(' and ')}`); } protected $type(): py.Expression | undefined { return this.$node(this._type); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.$node(this.name)) missing.push('name'); const hasAnnotation = this.$type(); const hasValue = this.$value(); if (!hasAnnotation && !hasValue) { missing.push('.type() or .assign()'); } return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/while.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { BlockPyDsl } from './block'; const Mixed = PyDsl; export class WhilePyDsl extends Mixed { readonly '~dsl' = 'WhilePyDsl'; protected _body?: Array; protected _condition?: MaybePyDsl; protected _else?: Array; constructor(condition: MaybePyDsl, ...body: Array) { super(); this._condition = condition; this._body = body; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); if (this._condition) ctx.analyze(this._condition); if (this._body) { ctx.pushScope(); try { for (const stmt of this._body) ctx.analyze(stmt); } finally { ctx.popScope(); } } if (this._else) { ctx.pushScope(); try { for (const stmt of this._else) ctx.analyze(stmt); } finally { ctx.popScope(); } } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } body(...items: Array): this { this._body = items; return this; } else(...items: Array): this { this._else = items; return this; } override toAst() { this.$validate(); const body = new BlockPyDsl(...this._body!).$do(); const elseBlock = this._else ? new BlockPyDsl(...this._else).$do() : undefined; return py.factory.createWhileStatement( this.$node(this._condition!), [...body], elseBlock ? [...elseBlock] : undefined, ); } $validate(): asserts this is this & { _body: Array; _condition: MaybePyDsl; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`While statement missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._condition) missing.push('condition'); if (!this._body || this._body.length === 0) missing.push('body'); return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/stmt/with.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; import type { MaybePyDsl } from '../base'; import { PyDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { BlockPyDsl } from './block'; const Mixed = PyDsl; export type WithItemInput = | MaybePyDsl | { alias?: MaybePyDsl; context: MaybePyDsl }; export class WithPyDsl extends Mixed { readonly '~dsl' = 'WithPyDsl'; protected _body?: Array; protected _items: Array = []; protected _modifier?: MaybePyDsl; constructor(...items: Array) { super(); this._items = items; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const item of this._items) { if (typeof item === 'object' && 'context' in item) { ctx.analyze(item.context); ctx.analyze(item.alias); } else { ctx.analyze(item); } } if (this._modifier) ctx.analyze(this._modifier); if (this._body) { ctx.pushScope(); try { for (const stmt of this._body) ctx.analyze(stmt); } finally { ctx.popScope(); } } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } body(...items: Array): this { this._body = items; return this; } item(item: WithItemInput): this { this._items.push(item); return this; } modifier(expr: MaybePyDsl): this { this._modifier = expr; return this; } async(): this { this._modifier = py.factory.createIdentifier('async'); return this; } override toAst() { this.$validate(); const astItems = this._items.map((item) => { if (typeof item === 'object' && 'context' in item) { return py.factory.createWithItem(this.$node(item.context), this.$node(item.alias)); } return py.factory.createWithItem(this.$node(item), undefined); }); const body = new BlockPyDsl(...this._body!).$do(); return py.factory.createWithStatement( astItems, [...body], this._modifier ? [this.$node(this._modifier)] : undefined, ); } $validate(): asserts this is this & { _body: Array; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`With statement missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._items.length) missing.push('items'); if (!this._body || this._body.length === 0) missing.push('.body()'); return missing; } } ================================================ FILE: packages/openapi-python/src/py-dsl/utils/__tests__/name.test.ts ================================================ import { describe, expect, it } from 'vitest'; import { safeRuntimeName } from '../name'; describe('safeRuntimeName', () => { const scenarios = [ // Digits: valid as regular char, can reprocess → leading underscore { name: '3foo', output: '_3foo' }, { name: '123', output: '_123' }, // $ sign: invalid in Python as regular char → single underscore, skip reprocess { name: '$schema', output: '_schema' }, { name: '$foo', output: '_foo' }, // Hyphen: first char is valid (a, f), hyphen becomes underscore in loop { name: 'api-version', output: 'api_version' }, { name: 'foo-bar', output: 'foo_bar' }, // Normal cases { name: 'foo', output: 'foo' }, { name: '_private', output: '_private' }, // Reserved words { name: 'class', output: 'class_' }, ] as const; it.each(scenarios)('transforms $name -> $output', ({ name, output }) => { expect(safeRuntimeName(name)).toEqual(output); }); }); ================================================ FILE: packages/openapi-python/src/py-dsl/utils/__tests__/render-utils.test.ts ================================================ import { moduleSortKey } from '../render-utils'; const createFile = (finalPath: string, external = false) => { const parts = finalPath.split('/'); const filename = parts.at(-1)!; const dotIndex = filename.lastIndexOf('.'); return { extension: dotIndex > 0 ? filename.slice(dotIndex) : undefined, external, finalPath, name: dotIndex > 0 ? filename.slice(0, dotIndex) : filename, }; }; const root = '/project/src'; describe('moduleSortKey', () => { describe('external imports (group 0)', () => { it('returns external module path unchanged', () => { const file = createFile('/project/src/client.py'); const fromFile = createFile('httpx', true); const [group, distance, modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(group).toBe(0); expect(distance).toBe(0); expect(modulePath).toBe('httpx'); }); }); describe('local imports (group 2)', () => { describe('same directory', () => { it('converts sibling file to relative import', () => { const file = createFile('/project/src/api/client.py'); const fromFile = createFile('/project/src/api/types.py'); const [group, distance, modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(group).toBe(2); expect(distance).toBe(0); expect(modulePath).toBe('.types'); }); it('handles index.py as implicit module', () => { const file = createFile('/project/src/api/client.py'); const fromFile = createFile('/project/src/api/index.py'); const [, , modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(modulePath).toBe('.'); }); it('handles __init__.py as implicit module', () => { const file = createFile('/project/src/api/client.py'); const fromFile = createFile('/project/src/api/__init__.py'); const [, , modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(modulePath).toBe('.'); }); }); describe('child directory', () => { it('converts nested path to dotted module', () => { const file = createFile('/project/src/client.py'); const fromFile = createFile('/project/src/models/user.py'); const [group, distance, modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(group).toBe(2); expect(distance).toBe(0); expect(modulePath).toBe('.models.user'); }); it('handles deeply nested paths', () => { const file = createFile('/project/src/client.py'); const fromFile = createFile('/project/src/api/v1/endpoints/users.py'); const [, , modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(modulePath).toBe('.api.v1.endpoints.users'); }); it('handles index.py in child directory', () => { const file = createFile('/project/src/client.py'); const fromFile = createFile('/project/src/models/index.py'); const [, , modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(modulePath).toBe('.models'); }); }); describe('parent directory', () => { it('converts single parent traversal', () => { const file = createFile('/project/src/api/client.py'); const fromFile = createFile('/project/src/types.py'); const [group, distance, modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(group).toBe(2); expect(distance).toBe(1); expect(modulePath).toBe('..types'); }); it('converts double parent traversal', () => { const file = createFile('/project/src/api/v1/client.py'); const fromFile = createFile('/project/src/types.py'); const [, distance, modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(distance).toBe(2); expect(modulePath).toBe('...types'); }); it('handles index.py in parent directory', () => { const file = createFile('/project/src/api/client.py'); const fromFile = createFile('/project/src/index.py'); const [, , modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(modulePath).toBe('..'); }); }); describe('sibling directory', () => { it('converts sibling directory path', () => { const file = createFile('/project/src/api/client.py'); const fromFile = createFile('/project/src/models/user.py'); const [, distance, modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(distance).toBe(1); expect(modulePath).toBe('..models.user'); }); it('handles index.py in sibling directory', () => { const file = createFile('/project/src/api/client.py'); const fromFile = createFile('/project/src/models/index.py'); const [, , modulePath] = moduleSortKey({ file, fromFile, preferFileExtension: '.py', root, }); expect(modulePath).toBe('..models'); }); }); }); }); ================================================ FILE: packages/openapi-python/src/py-dsl/utils/context.ts ================================================ import type { BindingKind } from '@hey-api/codegen-core'; // import type { BindingKind, NodeScope, Symbol } from '@hey-api/codegen-core'; // import { isSymbol } from '@hey-api/codegen-core'; import type { MaybeFunc } from '@hey-api/types'; import type { py } from '../../py-compiler'; import type { DollarPyDsl } from '../../py-dsl'; // import { $, PythonRenderer } from '../../py-dsl'; import type { PyDsl } from '../base'; import type { CallArgs } from '../expr/call'; export type NodeChain = ReadonlyArray; export interface AccessOptions { /** The access context. */ context?: 'example'; /** Enable debug mode. */ debug?: boolean; /** Transform function for each node in the access chain. */ transform?: (node: PyDsl, index: number, chain: NodeChain) => PyDsl; } // export type AccessResult = ReturnType; export interface ExampleOptions { /** Import kind for the root node. */ importKind?: BindingKind; /** Import name for the root node. */ importName?: string; /** Setup to run before calling the example. */ importSetup?: MaybeFunc< ( ctx: DollarPyDsl & { /** The imported expression. */ node: PyDsl; }, ) => PyDsl >; /** Module to import from. */ moduleName?: string; /** Example request payload. */ payload?: MaybeFunc<(ctx: DollarPyDsl) => CallArgs | CallArgs[number]>; /** Variable name for setup node. */ setupName?: string; } // function accessChainToNode(accessChain: NodeChain): T { // let result!: AccessResult; // accessChain.forEach((node, index) => { // if (index === 0) { // // assume correct node // result = node as typeof result; // } else { // result = result.attr(node.name); // } // }); // return result as T; // } // function getAccessChainForNode(node: PyDsl): NodeChain { // const structuralChain = [...getStructuralChainForNode(node, new Set())]; // const accessChain = structuralToAccessChain(structuralChain); // if (accessChain.length === 0) { // // I _think_ this should not happen, but it does and this fix works for now. // // I assume this will cause issues with imports in some cases, investigate // // when it actually happens. // return [node.clone()]; // } // return accessChain.map((node) => node.clone()); // } // function getScope(node: PyDsl): NodeScope { // return node.scope ?? 'value'; // } // function getStructuralChainForNode(node: PyDsl, visited: Set): NodeChain { // if (visited.has(node)) return []; // visited.add(node); // if (isStopNode(node)) return []; // if (node.structuralParents) { // for (const [parent] of node.structuralParents) { // if (getScope(parent) !== getScope(node)) continue; // const chain = getStructuralChainForNode(parent, visited); // if (chain.length > 0) return [...chain, node]; // } // } // if (!node.root) return []; // return [node]; // } // function isAccessorNode(node: PyDsl): boolean { // return ( // node['~dsl'] === 'FieldPyDsl' || // node['~dsl'] === 'GetterPyDsl' || // node['~dsl'] === 'MethodPyDsl' // ); // } // function isStopNode(node: PyDsl): boolean { // return node['~dsl'] === 'FuncPyDsl' || node['~dsl'] === 'TemplatePyDsl'; // } /** * Fold a structural chain to an access chain by removing * non-accessor nodes. */ // function structuralToAccessChain(structuralChain: NodeChain): NodeChain { // const accessChain: Array = []; // structuralChain.forEach((node, index) => { // // assume first node is always included // if (index === 0) { // accessChain.push(node); // } else if (isAccessorNode(node)) { // accessChain.push(node); // } // }); // return accessChain; // } // function transformAccessChain(accessChain: NodeChain, options: AccessOptions = {}): NodeChain { // return accessChain.map((node, index) => { // const transformedNode = options.transform?.(node, index, accessChain); // if (transformedNode) return transformedNode; // const accessNode = node.toAccessNode?.(node, options, { // chain: accessChain, // index, // isLeaf: index === accessChain.length - 1, // isRoot: index === 0, // length: accessChain.length, // }); // if (accessNode) return accessNode; // if (index === 0) { // if (node['~dsl'] === 'ClassPyDsl') { // const nextNode = accessChain[index + 1]; // if (nextNode && isAccessorNode(nextNode)) { // if ((nextNode as ReturnType).hasModifier('static')) { // return $(node.name); // } // } // return $.new(node.name).args(); // } // return $(node.name); // } // return node; // }); // } export class PyDslContext { /** * Build an expression for accessing the node. * * @param node - The node or symbol to build access for * @param options - Access options * @returns Expression for accessing the node * * @example * ```ts * ctx.access(node); // → Expression for accessing the node * ``` */ // access(node: PyDsl | Symbol, options?: AccessOptions): T { // const n = isSymbol(node) ? node.node : node; // if (!n) { // throw new Error(`Symbol ${node.name} is not resolved to a node.`); // } // const accessChain = getAccessChainForNode(n); // const finalChain = transformAccessChain(accessChain, options); // return accessChainToNode(finalChain); // } /** * Build an example. * * @param node - The node to generate an example for * @param options - Example options * @returns Full example string * * @example * ```ts * ctx.example(node, { moduleName: 'my-sdk' }); // → Full example string * ``` */ // example( // node: PyDsl, // options?: ExampleOptions, // astOptions?: Parameters[0], // ): string { // if (astOptions) { // return PythonRenderer.astToString(astOptions); // } // options ||= {}; // const accessChain = getAccessChainForNode(node); // if (options.importName) { // accessChain[0]!.name.set(options.importName); // } // const importNode = $(accessChain[0]!.name.toString()); // must store name before transform // const finalChain = transformAccessChain(accessChain, { // context: 'example', // }); // const setupNode = options.importSetup // ? typeof options.importSetup === 'function' // ? options.importSetup({ $, node: importNode }) // : options.importSetup // : (finalChain[0]! as PyDsl); // const setupName = options.setupName; // let payload = typeof options.payload === 'function' ? options.payload({ $ }) : options.payload; // payload = payload instanceof Array ? payload : payload ? [payload] : []; // let nodes: Array = []; // if (setupName) { // nodes = [ // $.const(setupName).assign(setupNode), // $.await(accessChainToNode([$(setupName), ...finalChain.slice(1)]).call(...payload)), // ]; // } else { // nodes = [$.await(accessChainToNode([setupNode, ...finalChain.slice(1)]).call(...payload))]; // } // const localName = importNode.name.toString(); // return PythonRenderer.astToString({ // imports: [ // [ // { // imports: // !options.importKind || options.importKind === 'named' // ? [ // { // isTypeOnly: false, // localName, // sourceName: localName, // }, // ] // : [], // isTypeOnly: false, // kind: options.importKind ?? 'named', // localName: options.importKind !== 'named' ? localName : undefined, // modulePath: options.moduleName ?? 'your-package', // }, // ], // ], // nodes, // trailingNewline: false, // }); // } } export const ctx = new PyDslContext(); ================================================ FILE: packages/openapi-python/src/py-dsl/utils/factories.ts ================================================ import type { AttrCtor } from '../expr/attr'; import type { CallCtor } from '../expr/call'; import type { SubscriptCtor } from '../expr/subscript'; import type { ReturnCtor } from '../stmt/return'; type Ctor = (...args: Array) => any; type Factory = { (...args: Parameters): ReturnType; /** Sets the implementation of this factory. */ set(fn: T): void; }; function createFactory(name: string): Factory { let impl: T | undefined; const slot = ((...args: Parameters) => { if (!impl) throw new Error(`${name} factory not registered`); return impl(...args); }) as Factory; slot.set = (fn: T) => { impl = fn; }; return slot; } export const f = { /** Factory for creating property access expressions (e.g. `obj.foo`). */ attr: createFactory('attr'), /** Factory for creating function or method call expressions (e.g. `fn(arg)`). */ call: createFactory('call'), /** Factory for creating return statements. */ return: createFactory('return'), /** Factory for creating slice expressions. */ slice: createFactory('slice'), }; ================================================ FILE: packages/openapi-python/src/py-dsl/utils/keywords.ts ================================================ const pythonKeywords = [ 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'False', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'None', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'True', 'try', 'while', 'with', 'yield', ]; const pythonBuiltins = [ 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip', ]; export const keywords = { pythonBuiltins, pythonKeywords, }; ================================================ FILE: packages/openapi-python/src/py-dsl/utils/lazy.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type { py } from '../../py-compiler'; import { PyDsl } from '../base'; import type { PyDslContext } from './context'; import { ctx } from './context'; export type LazyThunk = (ctx: PyDslContext) => PyDsl; export class LazyPyDsl extends PyDsl { readonly '~dsl' = 'LazyPyDsl'; private _thunk: LazyThunk; constructor(thunk: LazyThunk) { super(); this._thunk = thunk; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.toResult()); } toResult(): PyDsl { return this._thunk(ctx); } override toAst() { return this.toResult().toAst(); } } ================================================ FILE: packages/openapi-python/src/py-dsl/utils/name.ts ================================================ import { regexp } from './regexp'; import type { ReservedList } from './reserved'; import { reserved } from './reserved'; export const safeAccessorName = (name: string): string => { regexp.number.lastIndex = 0; if (regexp.number.test(name)) { return name.startsWith('-') ? `'${name}'` : name; } regexp.pythonIdentifier.lastIndex = 0; if (regexp.pythonIdentifier.test(name)) { return name; } return `'${name}'`; }; const validPythonChar = /^[a-zA-Z0-9_]$/; const safeName = (name: string, reserved: ReservedList): string => { let sanitized = ''; let index: number; const first = name[0] ?? ''; regexp.illegalStartCharacters.lastIndex = 0; if (regexp.illegalStartCharacters.test(first)) { // Check if character becomes valid when not in leading position (e.g., digits) if (validPythonChar.test(first)) { sanitized += '_'; index = 0; } else { sanitized += '_'; index = 1; } } else { sanitized += first; index = 1; } while (index < name.length) { const char = name[index] ?? ''; sanitized += validPythonChar.test(char) ? char : '_'; index += 1; } if (reserved['~values'].has(sanitized)) { sanitized = `${sanitized}_`; } return sanitized || '_'; }; export const safeRuntimeName = (name: string): string => safeName(name, reserved.runtime); export const safeKeywordName = (name: string): string => safeName(name, reserved.keywords); ================================================ FILE: packages/openapi-python/src/py-dsl/utils/regexp.ts ================================================ /** * Matches characters from the start that are not valid Python identifier starts. * Python identifiers: starts with letter/underscore, followed by letters/digits/underscores. */ const illegalStartCharactersRegExp = /^[^a-zA-Z_]+/; /** * Matches if string contains only digits and optionally decimal point or leading minus. */ const numberRegExp = /^-?\d+(\.\d+)?$/; /** * Python identifier pattern: starts with letter or underscore, * followed by letters, digits, or underscores. * Uses Unicode categories for full Python 3 compliance. */ const validPythonIdentifierRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/u; /** * Matches if a string looks like a valid Python identifier. */ const looksLikeIdentifierRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/; export const regexp = { /** * Matches characters from the start that are not valid Python identifier starts. */ illegalStartCharacters: illegalStartCharactersRegExp, /** * Simpler pattern for quick identifier checks. */ looksLikeIdentifier: looksLikeIdentifierRegExp, /** * Matches if string contains only digits and optionally decimal point or leading minus. */ number: numberRegExp, /** * Python identifier pattern for validation. */ pythonIdentifier: validPythonIdentifierRegExp, }; ================================================ FILE: packages/openapi-python/src/py-dsl/utils/render-utils.ts ================================================ import path from 'node:path'; import type { ExportModule, File, ImportModule } from '@hey-api/codegen-core'; import { py } from '../../py-compiler'; const printer = py.createPrinter({ indentSize: 4, }); /** Print a Python node to a string. */ export function astToString(node: py.Node): string { const result = printer.printFile(node); return result; } export type SortGroup = number; export type SortDistance = number; export type SortModule = string; export type SortKey = [SortGroup, SortDistance, SortModule]; export type ModuleExport = Omit & { /** Module specifier for re-exports, e.g. `./foo`. */ modulePath: string; }; export type ModuleImport = Omit & { /** Module specifier for imports, e.g. `./foo`. */ modulePath: string; }; export function moduleSortKey({ file, fromFile, root, }: { file: Pick; fromFile: Pick; preferFileExtension: string; root: string; }): SortKey { const filePath = file.finalPath!.split(path.sep).join('/'); let modulePath = fromFile.finalPath!.split(path.sep).join('/'); // built-ins // TODO // external if (fromFile.external && !path.isAbsolute(modulePath)) { return [0, 0, modulePath]; } // outside project root if (!modulePath.startsWith(root.split(path.sep).join('/'))) { return [1, 0, modulePath]; } // local const rel = path .relative(path.dirname(filePath), path.dirname(modulePath)) .split(path.sep) .join('/'); const segments = rel ? rel.split('/') : []; const parentCount = segments.filter((s) => s === '..').length; const leadingDots = '.'.repeat(parentCount + 1); const pathSegments = segments.filter((s) => s !== '..' && s !== '.'); const filename = modulePath.split('/').at(-1)!; // TODO: replace with extension check, there's an issue with external files // not having extension set const moduleName = filename.replace(/\.[^.]+$/, ''); // const moduleName = fromFile.extension // ? filename.slice(0, -fromFile.extension.length) // : filename; // index/__init__ are implicit const isImplicitModule = moduleName === 'index' || moduleName === '__init__'; if (!isImplicitModule) { pathSegments.push(moduleName); } modulePath = pathSegments.length > 0 ? leadingDots + pathSegments.join('.') : leadingDots; return [2, parentCount, modulePath]; } ================================================ FILE: packages/openapi-python/src/py-dsl/utils/render.ts ================================================ import type { RenderContext, Renderer } from '@hey-api/codegen-core'; import type { BaseOutput } from '@hey-api/shared'; import type { MaybeArray, MaybeFunc } from '@hey-api/types'; import { py } from '../../py-compiler'; import type { PyDsl } from '../../py-dsl'; import type { ModuleExport, ModuleImport, SortGroup, SortKey, SortModule } from './render-utils'; import { astToString, moduleSortKey } from './render-utils'; type Exports = ReadonlyArray>; type ExportsOptions = { preferExportAll?: boolean; }; type Header = MaybeArray | null | undefined; type HeaderArg = MaybeFunc<(ctx: RenderContext) => Header>; type Imports = Array>; function headerToLines(header: Header): ReadonlyArray { if (!header) return []; const lines: Array = []; if (typeof header === 'string') { lines.push(...header.split(/\r?\n/)); return lines; } for (const line of header) { lines.push(...line.split(/\r?\n/)); } return lines; } export class PythonRenderer implements Renderer { /** * Function to generate a file header. * * @private */ private _header?: HeaderArg; /** * Options for module specifier resolution. * * @private */ private _module?: Partial['module']; /** * Whether `export * from 'module'` should be used when possible instead of named exports. * * @private */ private _preferExportAll: boolean; constructor( args: Pick, 'module'> & { header?: HeaderArg; preferExportAll?: boolean; } = {}, ) { this._header = args.header; this._module = args.module; this._preferExportAll = args.preferExportAll ?? false; } render(ctx: RenderContext): string { const header = typeof this._header === 'function' ? this._header(ctx) : this._header; return PythonRenderer.astToString({ exports: this.getExports(ctx), exportsOptions: { preferExportAll: this._preferExportAll, }, header, imports: this.getImports(ctx), nodes: ctx.file.nodes, }); } supports(ctx: RenderContext): boolean { return ctx.file.language === 'python'; } static astToString(args: { exports?: Exports; exportsOptions?: ExportsOptions; header?: Header; imports?: Imports; nodes?: ReadonlyArray; /** * Whether to include a trailing newline at the end of the file. * * @default true */ trailingNewline?: boolean; }): string { let text = ''; for (const header of headerToLines(args.header)) { text += `${header}\n`; } const argsImports = args.imports ?? []; for (const group of args.exports ?? []) { for (const exp of group) { let found = false; for (const impGroup of argsImports) { if (found) break; for (const imp of impGroup) { if (imp.modulePath === exp.modulePath) { // TODO: merge imports and exports from the same module found = true; break; } } } if (!found) { argsImports.push([ { imports: exp.exports.map((exp) => ({ isTypeOnly: exp.isTypeOnly, localName: exp.exportedName, sourceName: exp.exportedName, })), isTypeOnly: false, kind: 'named', modulePath: exp.modulePath, }, ]); } } } let imports = ''; for (const group of argsImports) { if (imports) imports += '\n'; for (const imp of group) { imports += `${astToString(PythonRenderer.toImportAst(imp))}`; } } text = `${text}${text && imports ? '\n' : ''}${imports}`; let exports = ''; for (const group of args.exports ?? []) { if (exports) exports += '\n'; for (const exp of group) { exports += `${astToString(PythonRenderer.toExportAst(exp, args.exportsOptions))}`; } } text = `${text}${text && exports ? '\n' : ''}${exports}`; let nodes = ''; for (const node of args.nodes ?? []) { if (nodes) nodes += '\n\n'; nodes += `${astToString(node.toAst())}`; } text = `${text}${text && nodes ? '\n\n' : ''}${nodes}`; if (args.trailingNewline === false && text.endsWith('\n')) { text = text.slice(0, -1); } return text; } // eslint-disable-next-line @typescript-eslint/no-unused-vars static toExportAst(group: ModuleExport, options?: ExportsOptions): py.Assignment { const specifiers = group.exports.map((exp) => py.factory.createLiteral(exp.exportedName)); return py.factory.createAssignment( py.factory.createIdentifier('__all__'), undefined, py.factory.createListExpression(specifiers), ); } static toImportAst(group: ModuleImport): py.ImportStatement { const names: Array<{ alias?: string; name: string; }> = group.imports.map((imp) => ({ alias: imp.localName !== imp.sourceName ? imp.localName : undefined, name: imp.sourceName, })); return py.factory.createImportStatement(group.modulePath, names, group.imports.length > 0); } private getExports(ctx: RenderContext): Exports { type ModuleEntry = { group: ModuleExport; sortKey: SortKey; }; const groups = new Map>(); for (const exp of ctx.file.exports) { const sortKey = moduleSortKey({ file: ctx.file, fromFile: exp.from, preferFileExtension: this._module?.extension || '', root: ctx.project.root, }); const modulePath = this._module?.resolve?.(sortKey[2], ctx) ?? sortKey[2]; const [groupIndex] = sortKey; if (!groups.has(groupIndex)) groups.set(groupIndex, new Map()); const moduleMap = groups.get(groupIndex)!; if (!moduleMap.has(modulePath)) { moduleMap.set(modulePath, { group: { canExportAll: exp.canExportAll, exports: exp.exports, isTypeOnly: exp.isTypeOnly, modulePath, namespaceExport: exp.namespaceExport, }, sortKey, }); } } const exports: Array> = Array.from(groups.entries()) .sort((a, b) => a[0] - b[0]) .map(([, moduleMap]) => { const entries = Array.from(moduleMap.values()); entries.sort((a, b) => { const d = a.sortKey[1] - b.sortKey[1]; return d !== 0 ? d : a.group.modulePath.localeCompare(b.group.modulePath); }); return entries.map((e) => { const group = e.group; if (group.namespaceExport) { group.exports = []; } else { const isTypeOnly = !group.exports.find((exp) => !exp.isTypeOnly); if (isTypeOnly) { group.isTypeOnly = true; for (const exp of group.exports) { exp.isTypeOnly = false; } } group.exports.sort((a, b) => a.exportedName.localeCompare(b.exportedName)); } return group; }); }); return exports; } private getImports(ctx: RenderContext): Imports { type ModuleEntry = { group: ModuleImport; sortKey: SortKey; }; const groups = new Map>(); for (const imp of ctx.file.imports) { const sortKey = moduleSortKey({ file: ctx.file, fromFile: imp.from, preferFileExtension: this._module?.extension || '', root: ctx.project.root, }); const modulePath = this._module?.resolve?.(sortKey[2], ctx) ?? sortKey[2]; const [groupIndex] = sortKey; if (!groups.has(groupIndex)) groups.set(groupIndex, new Map()); const moduleMap = groups.get(groupIndex)!; if (!moduleMap.has(modulePath)) { moduleMap.set(modulePath, { group: { imports: [], isTypeOnly: false, kind: imp.kind, modulePath, }, sortKey, }); } const entry = moduleMap.get(modulePath)!; const group = entry.group; if (imp.kind !== 'named') { group.isTypeOnly = imp.isTypeOnly; group.kind = imp.kind; group.localName = imp.localName; } else { group.imports.push(...imp.imports); } } const imports: Array> = Array.from(groups.entries()) .sort((a, b) => a[0] - b[0]) .map(([, moduleMap]) => { const entries = Array.from(moduleMap.values()); entries.sort((a, b) => { const d = a.sortKey[1] - b.sortKey[1]; return d !== 0 ? d : a.group.modulePath.localeCompare(b.group.modulePath); }); return entries.map((e) => { const group = e.group; if (group.kind === 'namespace') { group.imports = []; } else { const isTypeOnly = !group.imports.find((imp) => !imp.isTypeOnly); if (isTypeOnly) { group.isTypeOnly = true; for (const imp of group.imports) { imp.isTypeOnly = false; } } group.imports.sort((a, b) => a.localName.localeCompare(b.localName)); } return group; }); }); return imports; } } ================================================ FILE: packages/openapi-python/src/py-dsl/utils/reserved.ts ================================================ import { keywords } from './keywords'; type List = ReadonlyArray; export class ReservedList { private _array: List; private _set: Set; constructor(values: List) { this._array = values; this._set = new Set(values); } get '~values'() { return this._set; } /** * Updates the reserved list with new values. * * @param values New reserved values or a function that receives the previous * reserved values and returns the new ones. */ set(values: List | ((prev: List) => List)): void { const vals = typeof values === 'function' ? values(this._array) : values; this._array = vals; this._set = new Set(vals); } } const runtimeReserved = new ReservedList([...keywords.pythonKeywords, ...keywords.pythonBuiltins]); const keywordReserved = new ReservedList([...keywords.pythonKeywords]); /** * Reserved names for identifiers. These names will not be used * for variables, functions, classes, or other identifiers in generated code. */ export const reserved = { /** * Reserved names for Python language keywords. These names are syntactically * invalid as identifiers in any scope. */ keywords: keywordReserved, /** * Reserved names for runtime identifiers. These names will not be used * for variables, functions, classes, or other runtime identifiers in * generated code. */ runtime: runtimeReserved, }; ================================================ FILE: packages/openapi-python/src/run.ts ================================================ #!/usr/bin/env node import { runCli } from './cli'; runCli(); ================================================ FILE: packages/openapi-python/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "composite": true, "rootDir": "src", "outDir": "dist", "types": ["vitest/globals", "node"] }, "include": ["src"], "references": [ { "path": "../types" }, { "path": "../codegen-core" }, { "path": "../shared" }, { "path": "../json-schema-ref-parser" } ] } ================================================ FILE: packages/openapi-python/tsdown.config.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { defineConfig } from 'tsdown'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); export default defineConfig({ clean: true, dts: true, entry: ['./src/{index,run}.ts'], format: ['esm'], minify: false, onSuccess: async () => { // Copy client files to dist folder for runtime access const pluginNames = ['client-httpx']; for (const pluginName of pluginNames) { const srcPath = path.resolve(__dirname, 'src', 'plugins', '@hey-api', pluginName, 'bundle'); const destPath = path.resolve( __dirname, 'dist', 'clients', pluginName.slice('client-'.length), ); if (fs.existsSync(srcPath)) { fs.mkdirSync(path.dirname(destPath), { recursive: true }); fs.cpSync(srcPath, destPath, { recursive: true }); // replace core imports in client bundle // const clientFiles = fs.readdirSync(destPath); // for (const file of clientFiles) { // replaceCoreImports(path.resolve(destPath, file)); // } } } }, sourcemap: true, treeshake: true, }); ================================================ FILE: packages/openapi-python/turbo.json ================================================ { "$schema": "../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-python/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-python-tests/pydantic/v2/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/openapi-python-tests/pydantic/v2/__snapshots__/3.1.x/opencode/pydantic_gen.py ================================================ # This file is auto-generated by @hey-api/openapi-python from enum import Enum from pydantic import BaseModel, Field from typing import Any, Literal, Optional, TypeAlias, Union class EventInstallationUpdatedProperties(BaseModel): version: str class EventInstallationUpdated(BaseModel): type_: Literal["installation.updated"] = Field(..., alias="type") properties: EventInstallationUpdatedProperties class EventInstallationUpdateAvailableProperties(BaseModel): version: str class EventInstallationUpdateAvailable(BaseModel): type_: Literal["installation.update-available"] = Field(..., alias="type") properties: EventInstallationUpdateAvailableProperties class ProjectIcon(BaseModel): url: Optional[str] = Field(default=None) color: Optional[str] = Field(default=None) class ProjectTime(BaseModel): created: float updated: float initialized: Optional[float] = Field(default=None) class Project(BaseModel): id_: str = Field(..., alias="id") worktree: str vcs: Optional[Literal["git"]] = Field(default=None) name: Optional[str] = Field(default=None) icon: Optional[ProjectIcon] = Field(default=None) time: ProjectTime class EventProjectUpdated(BaseModel): type_: Literal["project.updated"] = Field(..., alias="type") properties: Project class EventServerInstanceDisposedProperties(BaseModel): directory: str class EventServerInstanceDisposed(BaseModel): type_: Literal["server.instance.disposed"] = Field(..., alias="type") properties: EventServerInstanceDisposedProperties class EventLspClientDiagnosticsProperties(BaseModel): server_id: str = Field(..., alias="serverID") path: str class EventLspClientDiagnostics(BaseModel): type_: Literal["lsp.client.diagnostics"] = Field(..., alias="type") properties: EventLspClientDiagnosticsProperties class EventLspUpdated(BaseModel): type_: Literal["lsp.updated"] = Field(..., alias="type") properties: dict[str, Any] class FileDiff(BaseModel): file: str before: str after: str additions: float deletions: float class UserMessageTime(BaseModel): created: float class UserMessageSummary(BaseModel): title: Optional[str] = Field(default=None) body: Optional[str] = Field(default=None) diffs: list[FileDiff] class UserMessageModel(BaseModel): provider_id: str = Field(..., alias="providerID") model_id: str = Field(..., alias="modelID") class UserMessage(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") role: Literal["user"] time: UserMessageTime summary: Optional[UserMessageSummary] = Field(default=None) agent: str model: UserMessageModel system: Optional[str] = Field(default=None) tools: Optional[dict[str, Any]] = Field(default=None) variant: Optional[str] = Field(default=None) class ProviderAuthErrorData(BaseModel): provider_id: str = Field(..., alias="providerID") message: str class ProviderAuthError(BaseModel): name: Literal["ProviderAuthError"] data: ProviderAuthErrorData class UnknownErrorData(BaseModel): message: str class UnknownError(BaseModel): name: Literal["UnknownError"] data: UnknownErrorData class MessageOutputLengthError(BaseModel): name: Literal["MessageOutputLengthError"] data: dict[str, Any] class MessageAbortedErrorData(BaseModel): message: str class MessageAbortedError(BaseModel): name: Literal["MessageAbortedError"] data: MessageAbortedErrorData class ApiErrorData(BaseModel): message: str status_code: Optional[float] = Field(default=None, alias="statusCode") is_retryable: bool = Field(..., alias="isRetryable") response_headers: Optional[dict[str, Any]] = Field(default=None, alias="responseHeaders") response_body: Optional[str] = Field(default=None, alias="responseBody") metadata: Optional[dict[str, Any]] = Field(default=None) class ApiError(BaseModel): name: Literal["APIError"] data: ApiErrorData class AssistantMessageTime(BaseModel): created: float completed: Optional[float] = Field(default=None) class AssistantMessagePath(BaseModel): cwd: str root: str class AssistantMessageTokensCache(BaseModel): read: float write: float class AssistantMessageTokens(BaseModel): input_: float = Field(..., alias="input") output: float reasoning: float cache: AssistantMessageTokensCache class AssistantMessage(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") role: Literal["assistant"] time: AssistantMessageTime error: Optional[Union[ProviderAuthError, UnknownError, MessageOutputLengthError, MessageAbortedError, ApiError]] = Field(default=None) parent_id: str = Field(..., alias="parentID") model_id: str = Field(..., alias="modelID") provider_id: str = Field(..., alias="providerID") mode: str agent: str path: AssistantMessagePath summary: Optional[bool] = Field(default=None) cost: float tokens: AssistantMessageTokens finish: Optional[str] = Field(default=None) Message: TypeAlias = Union[UserMessage, AssistantMessage] class EventMessageUpdatedProperties(BaseModel): info: Message class EventMessageUpdated(BaseModel): type_: Literal["message.updated"] = Field(..., alias="type") properties: EventMessageUpdatedProperties class EventMessageRemovedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") class EventMessageRemoved(BaseModel): type_: Literal["message.removed"] = Field(..., alias="type") properties: EventMessageRemovedProperties class TextPartTime(BaseModel): start: float end: Optional[float] = Field(default=None) class TextPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["text"] = Field(..., alias="type") text: str synthetic: Optional[bool] = Field(default=None) ignored: Optional[bool] = Field(default=None) time: Optional[TextPartTime] = Field(default=None) metadata: Optional[dict[str, Any]] = Field(default=None) class ReasoningPartTime(BaseModel): start: float end: Optional[float] = Field(default=None) class ReasoningPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["reasoning"] = Field(..., alias="type") text: str metadata: Optional[dict[str, Any]] = Field(default=None) time: ReasoningPartTime class FilePartSourceText(BaseModel): value: str start: int = Field(..., ge=-9007199254740991, le=9007199254740991) end: int = Field(..., ge=-9007199254740991, le=9007199254740991) class FileSource(BaseModel): text: FilePartSourceText type_: Literal["file"] = Field(..., alias="type") path: str class RangeStart(BaseModel): line: float character: float class RangeEnd(BaseModel): line: float character: float class Range(BaseModel): start: RangeStart end: RangeEnd class SymbolSource(BaseModel): text: FilePartSourceText type_: Literal["symbol"] = Field(..., alias="type") path: str range_: Range = Field(..., alias="range") name: str kind: int = Field(..., ge=-9007199254740991, le=9007199254740991) FilePartSource: TypeAlias = Union[FileSource, SymbolSource] class FilePart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["file"] = Field(..., alias="type") mime: str filename: Optional[str] = Field(default=None) url: str source: Optional[FilePartSource] = Field(default=None) class ToolStatePending(BaseModel): status: Literal["pending"] input_: dict[str, Any] = Field(..., alias="input") raw: str class ToolStateRunningTime(BaseModel): start: float class ToolStateRunning(BaseModel): status: Literal["running"] input_: dict[str, Any] = Field(..., alias="input") title: Optional[str] = Field(default=None) metadata: Optional[dict[str, Any]] = Field(default=None) time: ToolStateRunningTime class ToolStateCompletedTime(BaseModel): start: float end: float compacted: Optional[float] = Field(default=None) class ToolStateCompleted(BaseModel): status: Literal["completed"] input_: dict[str, Any] = Field(..., alias="input") output: str title: str metadata: dict[str, Any] time: ToolStateCompletedTime attachments: Optional[list[FilePart]] = Field(default=None) class ToolStateErrorTime(BaseModel): start: float end: float class ToolStateError(BaseModel): status: Literal["error"] input_: dict[str, Any] = Field(..., alias="input") error: str metadata: Optional[dict[str, Any]] = Field(default=None) time: ToolStateErrorTime ToolState: TypeAlias = Union[ToolStatePending, ToolStateRunning, ToolStateCompleted, ToolStateError] class ToolPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["tool"] = Field(..., alias="type") call_id: str = Field(..., alias="callID") tool: str state: ToolState metadata: Optional[dict[str, Any]] = Field(default=None) class StepStartPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["step-start"] = Field(..., alias="type") snapshot: Optional[str] = Field(default=None) class StepFinishPartTokensCache(BaseModel): read: float write: float class StepFinishPartTokens(BaseModel): input_: float = Field(..., alias="input") output: float reasoning: float cache: StepFinishPartTokensCache class StepFinishPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["step-finish"] = Field(..., alias="type") reason: str snapshot: Optional[str] = Field(default=None) cost: float tokens: StepFinishPartTokens class SnapshotPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["snapshot"] = Field(..., alias="type") snapshot: str class PatchPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["patch"] = Field(..., alias="type") hash_: str = Field(..., alias="hash") files: list[str] class AgentPartSource(BaseModel): value: str start: int = Field(..., ge=-9007199254740991, le=9007199254740991) end: int = Field(..., ge=-9007199254740991, le=9007199254740991) class AgentPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["agent"] = Field(..., alias="type") name: str source: Optional[AgentPartSource] = Field(default=None) class RetryPartTime(BaseModel): created: float class RetryPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["retry"] = Field(..., alias="type") attempt: float error: ApiError time: RetryPartTime class CompactionPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["compaction"] = Field(..., alias="type") auto: bool class Part(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["subtask"] = Field(..., alias="type") prompt: str description: str agent: str command: Optional[str] = Field(default=None) Part_2: TypeAlias = Union[TextPart, Part, ReasoningPart, FilePart, ToolPart, StepStartPart, StepFinishPart, SnapshotPart, PatchPart, AgentPart, RetryPart, CompactionPart] class EventMessagePartUpdatedProperties(BaseModel): part: Part_2 delta: Optional[str] = Field(default=None) class EventMessagePartUpdated(BaseModel): type_: Literal["message.part.updated"] = Field(..., alias="type") properties: EventMessagePartUpdatedProperties class EventMessagePartRemovedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") part_id: str = Field(..., alias="partID") class EventMessagePartRemoved(BaseModel): type_: Literal["message.part.removed"] = Field(..., alias="type") properties: EventMessagePartRemovedProperties class PermissionRequestTool(BaseModel): message_id: str = Field(..., alias="messageID") call_id: str = Field(..., alias="callID") class PermissionRequest(BaseModel): id_: str = Field(..., alias="id", pattern="^per.*") session_id: str = Field(..., alias="sessionID", pattern="^ses.*") permission: str patterns: list[str] metadata: dict[str, Any] always: list[str] tool: Optional[PermissionRequestTool] = Field(default=None) class EventPermissionAsked(BaseModel): type_: Literal["permission.asked"] = Field(..., alias="type") properties: PermissionRequest class EventPermissionRepliedPropertiesReply(Enum, str): ONCE = "once" ALWAYS = "always" REJECT = "reject" class EventPermissionRepliedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") request_id: str = Field(..., alias="requestID") reply: EventPermissionRepliedPropertiesReply class EventPermissionReplied(BaseModel): type_: Literal["permission.replied"] = Field(..., alias="type") properties: EventPermissionRepliedProperties class SessionStatus(BaseModel): type_: Literal["idle"] = Field(..., alias="type") class SessionStatus_2(BaseModel): type_: Literal["retry"] = Field(..., alias="type") attempt: float message: str next_: float = Field(..., alias="next") class SessionStatus_3(BaseModel): type_: Literal["busy"] = Field(..., alias="type") SessionStatus_4: TypeAlias = Union[SessionStatus, SessionStatus_2, SessionStatus_3] class EventSessionStatusProperties(BaseModel): session_id: str = Field(..., alias="sessionID") status: SessionStatus_4 class EventSessionStatus(BaseModel): type_: Literal["session.status"] = Field(..., alias="type") properties: EventSessionStatusProperties class EventSessionIdleProperties(BaseModel): session_id: str = Field(..., alias="sessionID") class EventSessionIdle(BaseModel): type_: Literal["session.idle"] = Field(..., alias="type") properties: EventSessionIdleProperties class EventSessionCompactedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") class EventSessionCompacted(BaseModel): type_: Literal["session.compacted"] = Field(..., alias="type") properties: EventSessionCompactedProperties class EventFileEditedProperties(BaseModel): file: str class EventFileEdited(BaseModel): type_: Literal["file.edited"] = Field(..., alias="type") properties: EventFileEditedProperties class Todo(BaseModel): content: str = Field(..., description="Brief description of the task") status: str = Field(..., description="Current status of the task: pending, in_progress, completed, cancelled") priority: str = Field(..., description="Priority level of the task: high, medium, low") id_: str = Field(..., alias="id", description="Unique identifier for the todo item") class EventTodoUpdatedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") todos: list[Todo] class EventTodoUpdated(BaseModel): type_: Literal["todo.updated"] = Field(..., alias="type") properties: EventTodoUpdatedProperties class EventTuiPromptAppendProperties(BaseModel): text: str class EventTuiPromptAppend(BaseModel): type_: Literal["tui.prompt.append"] = Field(..., alias="type") properties: EventTuiPromptAppendProperties class EventTuiCommandExecutePropertiesCommand(Enum, str): SESSION_LIST = "session.list" SESSION_NEW = "session.new" SESSION_SHARE = "session.share" SESSION_INTERRUPT = "session.interrupt" SESSION_COMPACT = "session.compact" SESSION_PAGE_UP = "session.page.up" SESSION_PAGE_DOWN = "session.page.down" SESSION_HALF_PAGE_UP = "session.half.page.up" SESSION_HALF_PAGE_DOWN = "session.half.page.down" SESSION_FIRST = "session.first" SESSION_LAST = "session.last" PROMPT_CLEAR = "prompt.clear" PROMPT_SUBMIT = "prompt.submit" AGENT_CYCLE = "agent.cycle" class EventTuiCommandExecuteProperties(BaseModel): command: Union[EventTuiCommandExecutePropertiesCommand, str] class EventTuiCommandExecute(BaseModel): type_: Literal["tui.command.execute"] = Field(..., alias="type") properties: EventTuiCommandExecuteProperties class EventTuiToastShowPropertiesVariant(Enum, str): INFO = "info" SUCCESS = "success" WARNING = "warning" ERROR = "error" class EventTuiToastShowProperties(BaseModel): title: Optional[str] = Field(default=None) message: str variant: EventTuiToastShowPropertiesVariant duration: Optional[float] = Field(default=5000, description="Duration in milliseconds") class EventTuiToastShow(BaseModel): type_: Literal["tui.toast.show"] = Field(..., alias="type") properties: EventTuiToastShowProperties class EventMcpToolsChangedProperties(BaseModel): server: str class EventMcpToolsChanged(BaseModel): type_: Literal["mcp.tools.changed"] = Field(..., alias="type") properties: EventMcpToolsChangedProperties class EventCommandExecutedProperties(BaseModel): name: str session_id: str = Field(..., alias="sessionID", pattern="^ses.*") arguments: str message_id: str = Field(..., alias="messageID", pattern="^msg.*") class EventCommandExecuted(BaseModel): type_: Literal["command.executed"] = Field(..., alias="type") properties: EventCommandExecutedProperties class PermissionAction(Enum, str): ALLOW = "allow" DENY = "deny" ASK = "ask" class PermissionRule(BaseModel): permission: str pattern: str action: PermissionAction PermissionRuleset: TypeAlias = list[PermissionRule] class SessionSummary(BaseModel): additions: float deletions: float files: float diffs: Optional[list[FileDiff]] = Field(default=None) class SessionShare(BaseModel): url: str class SessionTime(BaseModel): created: float updated: float compacting: Optional[float] = Field(default=None) archived: Optional[float] = Field(default=None) class SessionRevert(BaseModel): message_id: str = Field(..., alias="messageID") part_id: Optional[str] = Field(default=None, alias="partID") snapshot: Optional[str] = Field(default=None) diff: Optional[str] = Field(default=None) class Session(BaseModel): id_: str = Field(..., alias="id", pattern="^ses.*") project_id: str = Field(..., alias="projectID") directory: str parent_id: Optional[str] = Field(default=None, alias="parentID", pattern="^ses.*") summary: Optional[SessionSummary] = Field(default=None) share: Optional[SessionShare] = Field(default=None) title: str version: str time: SessionTime permission: Optional[PermissionRuleset] = Field(default=None) revert: Optional[SessionRevert] = Field(default=None) class EventSessionCreatedProperties(BaseModel): info: Session class EventSessionCreated(BaseModel): type_: Literal["session.created"] = Field(..., alias="type") properties: EventSessionCreatedProperties class EventSessionUpdatedProperties(BaseModel): info: Session class EventSessionUpdated(BaseModel): type_: Literal["session.updated"] = Field(..., alias="type") properties: EventSessionUpdatedProperties class EventSessionDeletedProperties(BaseModel): info: Session class EventSessionDeleted(BaseModel): type_: Literal["session.deleted"] = Field(..., alias="type") properties: EventSessionDeletedProperties class EventSessionDiffProperties(BaseModel): session_id: str = Field(..., alias="sessionID") diff: list[FileDiff] class EventSessionDiff(BaseModel): type_: Literal["session.diff"] = Field(..., alias="type") properties: EventSessionDiffProperties class EventSessionErrorProperties(BaseModel): session_id: Optional[str] = Field(default=None, alias="sessionID") error: Optional[Union[ProviderAuthError, UnknownError, MessageOutputLengthError, MessageAbortedError, ApiError]] = Field(default=None) class EventSessionError(BaseModel): type_: Literal["session.error"] = Field(..., alias="type") properties: EventSessionErrorProperties class EventFileWatcherUpdatedProperties(BaseModel): file: str event: Union[Literal["add"], Literal["change"], Literal["unlink"]] class EventFileWatcherUpdated(BaseModel): type_: Literal["file.watcher.updated"] = Field(..., alias="type") properties: EventFileWatcherUpdatedProperties class EventVcsBranchUpdatedProperties(BaseModel): branch: Optional[str] = Field(default=None) class EventVcsBranchUpdated(BaseModel): type_: Literal["vcs.branch.updated"] = Field(..., alias="type") properties: EventVcsBranchUpdatedProperties class PtyStatus(Enum, str): RUNNING = "running" EXITED = "exited" class Pty(BaseModel): id_: str = Field(..., alias="id", pattern="^pty.*") title: str command: str args: list[str] cwd: str status: PtyStatus pid: float class EventPtyCreatedProperties(BaseModel): info: Pty class EventPtyCreated(BaseModel): type_: Literal["pty.created"] = Field(..., alias="type") properties: EventPtyCreatedProperties class EventPtyUpdatedProperties(BaseModel): info: Pty class EventPtyUpdated(BaseModel): type_: Literal["pty.updated"] = Field(..., alias="type") properties: EventPtyUpdatedProperties class EventPtyExitedProperties(BaseModel): id_: str = Field(..., alias="id", pattern="^pty.*") exit_code: float = Field(..., alias="exitCode") class EventPtyExited(BaseModel): type_: Literal["pty.exited"] = Field(..., alias="type") properties: EventPtyExitedProperties class EventPtyDeletedProperties(BaseModel): id_: str = Field(..., alias="id", pattern="^pty.*") class EventPtyDeleted(BaseModel): type_: Literal["pty.deleted"] = Field(..., alias="type") properties: EventPtyDeletedProperties class EventServerConnected(BaseModel): type_: Literal["server.connected"] = Field(..., alias="type") properties: dict[str, Any] class EventGlobalDisposed(BaseModel): type_: Literal["global.disposed"] = Field(..., alias="type") properties: dict[str, Any] Event: TypeAlias = Union[EventInstallationUpdated, EventInstallationUpdateAvailable, EventProjectUpdated, EventServerInstanceDisposed, EventLspClientDiagnostics, EventLspUpdated, EventMessageUpdated, EventMessageRemoved, EventMessagePartUpdated, EventMessagePartRemoved, EventPermissionAsked, EventPermissionReplied, EventSessionStatus, EventSessionIdle, EventSessionCompacted, EventFileEdited, EventTodoUpdated, EventTuiPromptAppend, EventTuiCommandExecute, EventTuiToastShow, EventMcpToolsChanged, EventCommandExecuted, EventSessionCreated, EventSessionUpdated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventFileWatcherUpdated, EventVcsBranchUpdated, EventPtyCreated, EventPtyUpdated, EventPtyExited, EventPtyDeleted, EventServerConnected, EventGlobalDisposed] class GlobalEvent(BaseModel): directory: str payload: Event class BadRequestError(BaseModel): data: Any errors: list[dict[str, Any]] success: Literal[False] class NotFoundErrorData(BaseModel): message: str class NotFoundError(BaseModel): name: Literal["NotFoundError"] data: NotFoundErrorData class KeybindsConfig(BaseModel): leader: Optional[str] = Field(default="ctrl+x", description="Leader key for keybind combinations") app_exit: Optional[str] = Field(default="ctrl+c,ctrl+d,q", description="Exit the application") editor_open: Optional[str] = Field(default="e", description="Open external editor") theme_list: Optional[str] = Field(default="t", description="List available themes") sidebar_toggle: Optional[str] = Field(default="b", description="Toggle sidebar") scrollbar_toggle: Optional[str] = Field(default="none", description="Toggle session scrollbar") username_toggle: Optional[str] = Field(default="none", description="Toggle username visibility") status_view: Optional[str] = Field(default="s", description="View status") session_export: Optional[str] = Field(default="x", description="Export session to editor") session_new: Optional[str] = Field(default="n", description="Create a new session") session_list: Optional[str] = Field(default="l", description="List all sessions") session_timeline: Optional[str] = Field(default="g", description="Show session timeline") session_fork: Optional[str] = Field(default="none", description="Fork session from message") session_rename: Optional[str] = Field(default="none", description="Rename session") session_share: Optional[str] = Field(default="none", description="Share current session") session_unshare: Optional[str] = Field(default="none", description="Unshare current session") session_interrupt: Optional[str] = Field(default="escape", description="Interrupt current session") session_compact: Optional[str] = Field(default="c", description="Compact the session") messages_page_up: Optional[str] = Field(default="pageup", description="Scroll messages up by one page") messages_page_down: Optional[str] = Field(default="pagedown", description="Scroll messages down by one page") messages_half_page_up: Optional[str] = Field(default="ctrl+alt+u", description="Scroll messages up by half page") messages_half_page_down: Optional[str] = Field(default="ctrl+alt+d", description="Scroll messages down by half page") messages_first: Optional[str] = Field(default="ctrl+g,home", description="Navigate to first message") messages_last: Optional[str] = Field(default="ctrl+alt+g,end", description="Navigate to last message") messages_next: Optional[str] = Field(default="none", description="Navigate to next message") messages_previous: Optional[str] = Field(default="none", description="Navigate to previous message") messages_last_user: Optional[str] = Field(default="none", description="Navigate to last user message") messages_copy: Optional[str] = Field(default="y", description="Copy message") messages_undo: Optional[str] = Field(default="u", description="Undo message") messages_redo: Optional[str] = Field(default="r", description="Redo message") messages_toggle_conceal: Optional[str] = Field(default="h", description="Toggle code block concealment in messages") tool_details: Optional[str] = Field(default="none", description="Toggle tool details visibility") model_list: Optional[str] = Field(default="m", description="List available models") model_cycle_recent: Optional[str] = Field(default="f2", description="Next recently used model") model_cycle_recent_reverse: Optional[str] = Field(default="shift+f2", description="Previous recently used model") model_cycle_favorite: Optional[str] = Field(default="none", description="Next favorite model") model_cycle_favorite_reverse: Optional[str] = Field(default="none", description="Previous favorite model") command_list: Optional[str] = Field(default="ctrl+p", description="List available commands") agent_list: Optional[str] = Field(default="a", description="List agents") agent_cycle: Optional[str] = Field(default="tab", description="Next agent") agent_cycle_reverse: Optional[str] = Field(default="shift+tab", description="Previous agent") variant_cycle: Optional[str] = Field(default="ctrl+t", description="Cycle model variants") input_clear: Optional[str] = Field(default="ctrl+c", description="Clear input field") input_paste: Optional[str] = Field(default="ctrl+v", description="Paste from clipboard") input_submit: Optional[str] = Field(default="return", description="Submit input") input_newline: Optional[str] = Field(default="shift+return,ctrl+return,alt+return,ctrl+j", description="Insert newline in input") input_move_left: Optional[str] = Field(default="left,ctrl+b", description="Move cursor left in input") input_move_right: Optional[str] = Field(default="right,ctrl+f", description="Move cursor right in input") input_move_up: Optional[str] = Field(default="up", description="Move cursor up in input") input_move_down: Optional[str] = Field(default="down", description="Move cursor down in input") input_select_left: Optional[str] = Field(default="shift+left", description="Select left in input") input_select_right: Optional[str] = Field(default="shift+right", description="Select right in input") input_select_up: Optional[str] = Field(default="shift+up", description="Select up in input") input_select_down: Optional[str] = Field(default="shift+down", description="Select down in input") input_line_home: Optional[str] = Field(default="ctrl+a", description="Move to start of line in input") input_line_end: Optional[str] = Field(default="ctrl+e", description="Move to end of line in input") input_select_line_home: Optional[str] = Field(default="ctrl+shift+a", description="Select to start of line in input") input_select_line_end: Optional[str] = Field(default="ctrl+shift+e", description="Select to end of line in input") input_visual_line_home: Optional[str] = Field(default="alt+a", description="Move to start of visual line in input") input_visual_line_end: Optional[str] = Field(default="alt+e", description="Move to end of visual line in input") input_select_visual_line_home: Optional[str] = Field(default="alt+shift+a", description="Select to start of visual line in input") input_select_visual_line_end: Optional[str] = Field(default="alt+shift+e", description="Select to end of visual line in input") input_buffer_home: Optional[str] = Field(default="home", description="Move to start of buffer in input") input_buffer_end: Optional[str] = Field(default="end", description="Move to end of buffer in input") input_select_buffer_home: Optional[str] = Field(default="shift+home", description="Select to start of buffer in input") input_select_buffer_end: Optional[str] = Field(default="shift+end", description="Select to end of buffer in input") input_delete_line: Optional[str] = Field(default="ctrl+shift+d", description="Delete line in input") input_delete_to_line_end: Optional[str] = Field(default="ctrl+k", description="Delete to end of line in input") input_delete_to_line_start: Optional[str] = Field(default="ctrl+u", description="Delete to start of line in input") input_backspace: Optional[str] = Field(default="backspace,shift+backspace", description="Backspace in input") input_delete: Optional[str] = Field(default="ctrl+d,delete,shift+delete", description="Delete character in input") input_undo: Optional[str] = Field(default="ctrl+-,super+z", description="Undo in input") input_redo: Optional[str] = Field(default="ctrl+.,super+shift+z", description="Redo in input") input_word_forward: Optional[str] = Field(default="alt+f,alt+right,ctrl+right", description="Move word forward in input") input_word_backward: Optional[str] = Field(default="alt+b,alt+left,ctrl+left", description="Move word backward in input") input_select_word_forward: Optional[str] = Field(default="alt+shift+f,alt+shift+right", description="Select word forward in input") input_select_word_backward: Optional[str] = Field(default="alt+shift+b,alt+shift+left", description="Select word backward in input") input_delete_word_forward: Optional[str] = Field(default="alt+d,alt+delete,ctrl+delete", description="Delete word forward in input") input_delete_word_backward: Optional[str] = Field(default="ctrl+w,ctrl+backspace,alt+backspace", description="Delete word backward in input") history_previous: Optional[str] = Field(default="up", description="Previous history item") history_next: Optional[str] = Field(default="down", description="Next history item") session_child_cycle: Optional[str] = Field(default="right", description="Next child session") session_child_cycle_reverse: Optional[str] = Field(default="left", description="Previous child session") session_parent: Optional[str] = Field(default="up", description="Go to parent session") terminal_suspend: Optional[str] = Field(default="ctrl+z", description="Suspend terminal") terminal_title_toggle: Optional[str] = Field(default="none", description="Toggle terminal title") tips_toggle: Optional[str] = Field(default="h", description="Toggle tips on home screen") class LogLevel(Enum, str): DEBUG = "DEBUG" INFO = "INFO" WARN = "WARN" ERROR = "ERROR" class ServerConfig(BaseModel): port: Optional[int] = Field(default=None, description="Port to listen on", gt=0, le=9007199254740991) hostname: Optional[str] = Field(default=None, description="Hostname to listen on") mdns: Optional[bool] = Field(default=None) cors: Optional[list[str]] = Field(default=None, description="Additional domains to allow for CORS") class PermissionActionConfig(Enum, str): ASK = "ask" ALLOW = "allow" DENY = "deny" PermissionObjectConfig: TypeAlias = dict[str, Any] PermissionRuleConfig: TypeAlias = Union[PermissionActionConfig, PermissionObjectConfig] class PermissionConfig(BaseModel): read: Optional[PermissionRuleConfig] = Field(default=None) edit: Optional[PermissionRuleConfig] = Field(default=None) glob: Optional[PermissionRuleConfig] = Field(default=None) grep: Optional[PermissionRuleConfig] = Field(default=None) list_: Optional[PermissionRuleConfig] = Field(default=None, alias="list") bash: Optional[PermissionRuleConfig] = Field(default=None) task: Optional[PermissionRuleConfig] = Field(default=None) external_directory: Optional[PermissionRuleConfig] = Field(default=None) todowrite: Optional[PermissionActionConfig] = Field(default=None) todoread: Optional[PermissionActionConfig] = Field(default=None) webfetch: Optional[PermissionActionConfig] = Field(default=None) websearch: Optional[PermissionActionConfig] = Field(default=None) codesearch: Optional[PermissionActionConfig] = Field(default=None) lsp: Optional[PermissionRuleConfig] = Field(default=None) doom_loop: Optional[PermissionActionConfig] = Field(default=None) PermissionConfig_2: TypeAlias = Union[PermissionConfig, PermissionActionConfig] AgentConfig: TypeAlias = dict[str, Any] class ProviderConfigModelsValueInterleavedField(Enum, str): REASONING_CONTENT = "reasoning_content" REASONING_DETAILS = "reasoning_details" class ProviderConfigModelsValueInterleaved(BaseModel): field: ProviderConfigModelsValueInterleavedField class ProviderConfigModelsValueCostContextOver200k(BaseModel): input_: float = Field(..., alias="input") output: float cache_read: Optional[float] = Field(default=None) cache_write: Optional[float] = Field(default=None) class ProviderConfigModelsValueCost(BaseModel): input_: float = Field(..., alias="input") output: float cache_read: Optional[float] = Field(default=None) cache_write: Optional[float] = Field(default=None) context_over_200k: Optional[ProviderConfigModelsValueCostContextOver200k] = Field(default=None) class ProviderConfigModelsValueLimit(BaseModel): context: float output: float class ProviderConfigModelsValueModalitiesInput(Enum, str): TEXT = "text" AUDIO = "audio" IMAGE = "image" VIDEO = "video" PDF = "pdf" class ProviderConfigModelsValueModalitiesOutput(Enum, str): TEXT = "text" AUDIO = "audio" IMAGE = "image" VIDEO = "video" PDF = "pdf" class ProviderConfigModelsValueModalities(BaseModel): input_: list[ProviderConfigModelsValueModalitiesInput] = Field(..., alias="input") output: list[ProviderConfigModelsValueModalitiesOutput] class ProviderConfigModelsValueStatus(Enum, str): ALPHA = "alpha" BETA = "beta" DEPRECATED = "deprecated" class ProviderConfigModelsValueProvider(BaseModel): npm: str ProviderConfigModelsValueVariantsValue: TypeAlias = dict[str, Any] class ProviderConfigModelsValue(BaseModel): id_: Optional[str] = Field(default=None, alias="id") name: Optional[str] = Field(default=None) family: Optional[str] = Field(default=None) release_date: Optional[str] = Field(default=None) attachment: Optional[bool] = Field(default=None) reasoning: Optional[bool] = Field(default=None) temperature: Optional[bool] = Field(default=None) tool_call: Optional[bool] = Field(default=None) interleaved: Optional[Union[Literal[True], ProviderConfigModelsValueInterleaved]] = Field(default=None) cost: Optional[ProviderConfigModelsValueCost] = Field(default=None) limit: Optional[ProviderConfigModelsValueLimit] = Field(default=None) modalities: Optional[ProviderConfigModelsValueModalities] = Field(default=None) experimental: Optional[bool] = Field(default=None) status: Optional[ProviderConfigModelsValueStatus] = Field(default=None) options: Optional[dict[str, Any]] = Field(default=None) headers: Optional[dict[str, Any]] = Field(default=None) provider: Optional[ProviderConfigModelsValueProvider] = Field(default=None) variants: Optional[dict[str, Any]] = Field(default=None) ProviderConfigOptions: TypeAlias = dict[str, Any] class ProviderConfig(BaseModel): api: Optional[str] = Field(default=None) name: Optional[str] = Field(default=None) env: Optional[list[str]] = Field(default=None) id_: Optional[str] = Field(default=None, alias="id") npm: Optional[str] = Field(default=None) models: Optional[dict[str, Any]] = Field(default=None) whitelist: Optional[list[str]] = Field(default=None) blacklist: Optional[list[str]] = Field(default=None) options: Optional[ProviderConfigOptions] = Field(default=None) class McpLocalConfig(BaseModel): type_: Literal["local"] = Field(..., alias="type") command: list[str] = Field(..., description="Command and arguments to run the MCP server") environment: Optional[dict[str, Any]] = Field(default=None) enabled: Optional[bool] = Field(default=None) timeout: Optional[int] = Field(default=None, description="Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.", gt=0, le=9007199254740991) class McpOAuthConfig(BaseModel): client_id: Optional[str] = Field(default=None, alias="clientId", description="OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted.") client_secret: Optional[str] = Field(default=None, alias="clientSecret", description="OAuth client secret (if required by the authorization server)") scope: Optional[str] = Field(default=None, description="OAuth scopes to request during authorization") class McpRemoteConfig(BaseModel): type_: Literal["remote"] = Field(..., alias="type") url: str = Field(..., description="URL of the remote MCP server") enabled: Optional[bool] = Field(default=None) headers: Optional[dict[str, Any]] = Field(default=None) oauth: Optional[Union[McpOAuthConfig, Literal[False]]] = Field(default=None, description="OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection.") timeout: Optional[int] = Field(default=None, description="Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.", gt=0, le=9007199254740991) class LayoutConfig(Enum, str): AUTO = "auto" STRETCH = "stretch" class ConfigTuiScrollAcceleration(BaseModel): enabled: bool class ConfigTuiDiffStyle(Enum, str): AUTO = "auto" STACKED = "stacked" class ConfigTui(BaseModel): scroll_speed: Optional[float] = Field(default=None, description="TUI scroll speed", ge=0.001) scroll_acceleration: Optional[ConfigTuiScrollAcceleration] = Field(default=None) diff_style: Optional[ConfigTuiDiffStyle] = Field(default=None) class ConfigCommandValue(BaseModel): template: str description: Optional[str] = Field(default=None) agent: Optional[str] = Field(default=None) model: Optional[str] = Field(default=None) subtask: Optional[bool] = Field(default=None) class ConfigWatcher(BaseModel): ignore: Optional[list[str]] = Field(default=None) class ConfigShare(Enum, str): MANUAL = "manual" AUTO = "auto" DISABLED = "disabled" class ConfigMode(BaseModel): build: Optional[AgentConfig] = Field(default=None) plan: Optional[AgentConfig] = Field(default=None) class ConfigAgent(BaseModel): plan: Optional[AgentConfig] = Field(default=None) build: Optional[AgentConfig] = Field(default=None) general: Optional[AgentConfig] = Field(default=None) explore: Optional[AgentConfig] = Field(default=None) title: Optional[AgentConfig] = Field(default=None) summary: Optional[AgentConfig] = Field(default=None) compaction: Optional[AgentConfig] = Field(default=None) class ConfigFormatterValue(BaseModel): disabled: Optional[bool] = Field(default=None) command: Optional[list[str]] = Field(default=None) environment: Optional[dict[str, Any]] = Field(default=None) extensions: Optional[list[str]] = Field(default=None) class ConfigEnterprise(BaseModel): url: Optional[str] = Field(default=None, description="Enterprise URL") class ConfigCompaction(BaseModel): auto: Optional[bool] = Field(default=None) prune: Optional[bool] = Field(default=None) class ConfigExperimentalHookFileEditedValue(BaseModel): command: list[str] environment: Optional[dict[str, Any]] = Field(default=None) class ConfigExperimentalHookSessionCompleted(BaseModel): command: list[str] environment: Optional[dict[str, Any]] = Field(default=None) class ConfigExperimentalHook(BaseModel): file_edited: Optional[dict[str, Any]] = Field(default=None) session_completed: Optional[list[ConfigExperimentalHookSessionCompleted]] = Field(default=None) class ConfigExperimental(BaseModel): hook: Optional[ConfigExperimentalHook] = Field(default=None) chat_max_retries: Optional[float] = Field(default=None, alias="chatMaxRetries", description="Number of retries for chat completions on failure") disable_paste_summary: Optional[bool] = Field(default=None) batch_tool: Optional[bool] = Field(default=None) open_telemetry: Optional[bool] = Field(default=None, alias="openTelemetry") primary_tools: Optional[list[str]] = Field(default=None, description="Tools that should only be available to primary agents.") continue_loop_on_deny: Optional[bool] = Field(default=None) mcp_timeout: Optional[int] = Field(default=None, description="Timeout in milliseconds for model context protocol (MCP) requests", gt=0, le=9007199254740991) class Config(BaseModel): schema: Optional[str] = Field(default=None, alias="$schema", description="JSON schema reference for configuration validation") theme: Optional[str] = Field(default=None, description="Theme name to use for the interface") keybinds: Optional[KeybindsConfig] = Field(default=None) log_level: Optional[LogLevel] = Field(default=None, alias="logLevel") tui: Optional[ConfigTui] = Field(default=None) server: Optional[ServerConfig] = Field(default=None) command: Optional[dict[str, Any]] = Field(default=None) watcher: Optional[ConfigWatcher] = Field(default=None) plugin: Optional[list[str]] = Field(default=None) snapshot: Optional[bool] = Field(default=None) share: Optional[ConfigShare] = Field(default=None) autoshare: Optional[bool] = Field(default=None) autoupdate: Optional[Union[bool, Literal["notify"]]] = Field(default=None, description="Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications") disabled_providers: Optional[list[str]] = Field(default=None, description="Disable providers that are loaded automatically") enabled_providers: Optional[list[str]] = Field(default=None, description="When set, ONLY these providers will be enabled. All other providers will be ignored") model: Optional[str] = Field(default=None, description="Model to use in the format of provider/model, eg anthropic/claude-2") small_model: Optional[str] = Field(default=None, description="Small model to use for tasks like title generation in the format of provider/model") default_agent: Optional[str] = Field(default=None, description="Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid.") username: Optional[str] = Field(default=None, description="Custom username to display in conversations instead of system username") mode: Optional[ConfigMode] = Field(default=None) agent: Optional[ConfigAgent] = Field(default=None) provider: Optional[dict[str, Any]] = Field(default=None) mcp: Optional[dict[str, Any]] = Field(default=None) formatter: Optional[Union[Literal[False], dict[str, Any]]] = Field(default=None) lsp: Optional[Union[Literal[False], dict[str, Any]]] = Field(default=None) instructions: Optional[list[str]] = Field(default=None, description="Additional instruction files or patterns to include") layout: Optional[LayoutConfig] = Field(default=None) permission: Optional[PermissionConfig_2] = Field(default=None) tools: Optional[dict[str, Any]] = Field(default=None) enterprise: Optional[ConfigEnterprise] = Field(default=None) compaction: Optional[ConfigCompaction] = Field(default=None) experimental: Optional[ConfigExperimental] = Field(default=None) ToolIds: TypeAlias = list[str] class ToolListItem(BaseModel): id_: str = Field(..., alias="id") description: str parameters: Any ToolList: TypeAlias = list[ToolListItem] class Path(BaseModel): home: str state: str config: str worktree: str directory: str class VcsInfo(BaseModel): branch: str class TextPartInputTime(BaseModel): start: float end: Optional[float] = Field(default=None) class TextPartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["text"] = Field(..., alias="type") text: str synthetic: Optional[bool] = Field(default=None) ignored: Optional[bool] = Field(default=None) time: Optional[TextPartInputTime] = Field(default=None) metadata: Optional[dict[str, Any]] = Field(default=None) class FilePartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["file"] = Field(..., alias="type") mime: str filename: Optional[str] = Field(default=None) url: str source: Optional[FilePartSource] = Field(default=None) class AgentPartInputSource(BaseModel): value: str start: int = Field(..., ge=-9007199254740991, le=9007199254740991) end: int = Field(..., ge=-9007199254740991, le=9007199254740991) class AgentPartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["agent"] = Field(..., alias="type") name: str source: Optional[AgentPartInputSource] = Field(default=None) class SubtaskPartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["subtask"] = Field(..., alias="type") prompt: str description: str agent: str command: Optional[str] = Field(default=None) class Command(BaseModel): name: str description: Optional[str] = Field(default=None) agent: Optional[str] = Field(default=None) model: Optional[str] = Field(default=None) mcp: Optional[bool] = Field(default=None) template: str subtask: Optional[bool] = Field(default=None) hints: list[str] class ModelApi(BaseModel): id_: str = Field(..., alias="id") url: str npm: str class ModelCapabilitiesInput(BaseModel): text: bool audio: bool image: bool video: bool pdf: bool class ModelCapabilitiesOutput(BaseModel): text: bool audio: bool image: bool video: bool pdf: bool class ModelCapabilitiesInterleavedField(Enum, str): REASONING_CONTENT = "reasoning_content" REASONING_DETAILS = "reasoning_details" class ModelCapabilitiesInterleaved(BaseModel): field: ModelCapabilitiesInterleavedField class ModelCapabilities(BaseModel): temperature: bool reasoning: bool attachment: bool toolcall: bool input_: ModelCapabilitiesInput = Field(..., alias="input") output: ModelCapabilitiesOutput interleaved: Union[bool, ModelCapabilitiesInterleaved] class ModelCostCache(BaseModel): read: float write: float class ModelCostExperimentalOver200kCache(BaseModel): read: float write: float class ModelCostExperimentalOver200k(BaseModel): input_: float = Field(..., alias="input") output: float cache: ModelCostExperimentalOver200kCache class ModelCost(BaseModel): input_: float = Field(..., alias="input") output: float cache: ModelCostCache experimental_over200k: Optional[ModelCostExperimentalOver200k] = Field(default=None, alias="experimentalOver200K") class ModelLimit(BaseModel): context: float output: float class ModelStatus(Enum, str): ALPHA = "alpha" BETA = "beta" DEPRECATED = "deprecated" ACTIVE = "active" class Model(BaseModel): id_: str = Field(..., alias="id") provider_id: str = Field(..., alias="providerID") api: ModelApi name: str family: Optional[str] = Field(default=None) capabilities: ModelCapabilities cost: ModelCost limit: ModelLimit status: ModelStatus options: dict[str, Any] headers: dict[str, Any] release_date: str variants: Optional[dict[str, Any]] = Field(default=None) class ProviderSource(Enum, str): ENV = "env" CONFIG = "config" CUSTOM = "custom" API = "api" class Provider(BaseModel): id_: str = Field(..., alias="id") name: str source: ProviderSource env: list[str] key: Optional[str] = Field(default=None) options: dict[str, Any] models: dict[str, Any] class ProviderAuthMethod(BaseModel): type_: Union[Literal["oauth"], Literal["api"]] = Field(..., alias="type") label: str class ProviderAuthAuthorization(BaseModel): url: str method: Union[Literal["auto"], Literal["code"]] instructions: str class SymbolLocation(BaseModel): uri: str range_: Range = Field(..., alias="range") class Symbol(BaseModel): name: str kind: float location: SymbolLocation class FileNodeType(Enum, str): FILE = "file" DIRECTORY = "directory" class FileNode(BaseModel): name: str path: str absolute: str type_: FileNodeType = Field(..., alias="type") ignored: bool class FileContentPatchHunks(BaseModel): old_start: float = Field(..., alias="oldStart") old_lines: float = Field(..., alias="oldLines") new_start: float = Field(..., alias="newStart") new_lines: float = Field(..., alias="newLines") lines: list[str] class FileContentPatch(BaseModel): old_file_name: str = Field(..., alias="oldFileName") new_file_name: str = Field(..., alias="newFileName") old_header: Optional[str] = Field(default=None, alias="oldHeader") new_header: Optional[str] = Field(default=None, alias="newHeader") hunks: list[FileContentPatchHunks] index: Optional[str] = Field(default=None) class FileContent(BaseModel): type_: Literal["text"] = Field(..., alias="type") content: str diff: Optional[str] = Field(default=None) patch: Optional[FileContentPatch] = Field(default=None) encoding: Optional[Literal["base64"]] = Field(default=None) mime_type: Optional[str] = Field(default=None, alias="mimeType") class FileStatus(Enum, str): ADDED = "added" DELETED = "deleted" MODIFIED = "modified" class File(BaseModel): path: str added: int = Field(..., ge=-9007199254740991, le=9007199254740991) removed: int = Field(..., ge=-9007199254740991, le=9007199254740991) status: FileStatus class AgentMode(Enum, str): SUBAGENT = "subagent" PRIMARY = "primary" ALL = "all" class AgentModel(BaseModel): model_id: str = Field(..., alias="modelID") provider_id: str = Field(..., alias="providerID") class Agent(BaseModel): name: str description: Optional[str] = Field(default=None) mode: AgentMode native: Optional[bool] = Field(default=None) hidden: Optional[bool] = Field(default=None) top_p: Optional[float] = Field(default=None, alias="topP") temperature: Optional[float] = Field(default=None) color: Optional[str] = Field(default=None) permission: PermissionRuleset model: Optional[AgentModel] = Field(default=None) prompt: Optional[str] = Field(default=None) options: dict[str, Any] steps: Optional[int] = Field(default=None, gt=0, le=9007199254740991) class McpStatusConnected(BaseModel): status: Literal["connected"] class McpStatusDisabled(BaseModel): status: Literal["disabled"] class McpStatusFailed(BaseModel): status: Literal["failed"] error: str class McpStatusNeedsAuth(BaseModel): status: Literal["needs_auth"] class McpStatusNeedsClientRegistration(BaseModel): status: Literal["needs_client_registration"] error: str McpStatus: TypeAlias = Union[McpStatusConnected, McpStatusDisabled, McpStatusFailed, McpStatusNeedsAuth, McpStatusNeedsClientRegistration] class LspStatus(BaseModel): id_: str = Field(..., alias="id") name: str root: str status: Union[Literal["connected"], Literal["error"]] class FormatterStatus(BaseModel): name: str extensions: list[str] enabled: bool class OAuth(BaseModel): type_: Literal["oauth"] = Field(..., alias="type") refresh: str access: str expires: float enterprise_url: Optional[str] = Field(default=None, alias="enterpriseUrl") class ApiAuth(BaseModel): type_: Literal["api"] = Field(..., alias="type") key: str class WellKnownAuth(BaseModel): type_: Literal["wellknown"] = Field(..., alias="type") key: str token: str Auth: TypeAlias = Union[OAuth, ApiAuth, WellKnownAuth] ================================================ FILE: packages/openapi-python-tests/pydantic/v2/package.json ================================================ { "name": "@test/openapi-python-pydantic-v2", "version": "0.0.0", "private": true, "type": "module", "devDependencies": { "@hey-api/openapi-python": "workspace:*", "typescript": "5.9.3" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-python-tests/pydantic/v2/test/opencode.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-python'; import { getFilePaths } from '../../../utils'; import { createPydanticConfig, getSnapshotsPath, getTempSnapshotsPath } from './utils'; const version = '3.1.x'; const outputDir = path.join(getTempSnapshotsPath(), version); const snapshotsDir = path.join(getSnapshotsPath(), version); describe(`Pydantic: OpenAPI ${version}`, () => { const createConfig = createPydanticConfig({ openApiVersion: version, outputDir, }); const scenarios = [ { config: createConfig({ input: 'opencode.yaml', output: 'opencode', }), description: 'OpenCode spec', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-python-tests/pydantic/v2/test/utils.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { type UserConfig } from '@hey-api/openapi-python'; import { getSpecsPath } from '../../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export const createPydanticConfig = ({ openApiVersion, outputDir }: { openApiVersion: string; outputDir: string }) => (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0]! : userConfig.input; const inputPath = path.join( getSpecsPath(), openApiVersion, typeof input === 'string' ? input : (input.path as string), ); return { plugins: ['pydantic'], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', path: './logs', }, output: path.join(outputDir, typeof userConfig.output === 'string' ? userConfig.output : ''), } as const satisfies UserConfig; }; export const getSnapshotsPath = (): string => path.join(__dirname, '..', '__snapshots__'); export const getTempSnapshotsPath = (): string => path.join(__dirname, '..', '.gen', 'snapshots'); ================================================ FILE: packages/openapi-python-tests/pydantic/v2/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["test/**/*"], "exclude": [".gen/**/*"], "references": [{ "path": "../../../openapi-python" }] } ================================================ FILE: packages/openapi-python-tests/pydantic/v2/turbo.json ================================================ { "$schema": "../../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-python-tests/pydantic/v2/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-python-tests/sdks/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/openapi-python-tests/sdks/__snapshots__/opencode/default/__init__.py ================================================ # This file is auto-generated by @hey-api/openapi-python from .sdk_gen import App, Auth, Auth_2, Command, Config, Control, Event, File, Find, Formatter, Global, Instance, Lsp, Mcp, Oauth, Part, Path, Permission, Project, Provider, Pty, Sdk, Session, Tool, Tui, Vcs __all__ = ["App", "Auth", "Auth_2", "Command", "Config", "Control", "Event", "File", "Find", "Formatter", "Global", "Instance", "Lsp", "Mcp", "Oauth", "Part", "Path", "Permission", "Project", "Provider", "Pty", "Sdk", "Session", "Tool", "Tui", "Vcs"] ================================================ FILE: packages/openapi-python-tests/sdks/__snapshots__/opencode/default/client/__init__.py ================================================ # This file is auto-generated by @hey-api/openapi-python from .client_gen import Client, build_client_params, create_client __all__ = ["Client", "build_client_params", "create_client"] ================================================ FILE: packages/openapi-python-tests/sdks/__snapshots__/opencode/default/client/client_gen.py ================================================ # This file is auto-generated by @hey-api/openapi-python from typing import Any, Optional import httpx EXTRA_PREFIXES_MAP = { "$body_": "json", "$headers_": "headers", "$path_": "path", "$query_": "params", } def build_client_params(fields: list[dict[str, Any]], **kwargs) -> dict[str, Any]: """Build client parameters from flat keyword arguments. Args: fields: List of field configurations with 'in', 'key', and optional 'map'. **kwargs: Flat parameters passed to the SDK method. Returns: Dict suitable for httpx client methods: {params: {...}, headers: {...}, json: Any} """ result: dict[str, Any] = {} key_map = {} for field in fields: key = field.get("key") if key: key_map[key] = { "in": field.get("in"), "map": field.get("map", key), } for key, value in kwargs.items(): if value is None: continue field = key_map.get(key) if field: in_slot = field["in"] map_key = field["map"] slot = "json" if in_slot == "body" else in_slot if in_slot == "body": result[slot] = value else: if slot not in result: result[slot] = {} result[slot][map_key] = value else: for prefix, slot in EXTRA_PREFIXES_MAP.items(): if key.startswith(prefix): actual_key = key[len(prefix) :] if slot not in result: result[slot] = {} result[slot][actual_key] = value break else: if "params" not in result: result["params"] = {} result["params"][key] = value for slot in list(result.keys()): if not result[slot]: del result[slot] return result class BaseClient: """Base HTTP client using httpx that SDK classes extend.""" def __init__(self, client: Optional[httpx.Client] = None, base_url: Optional[str] = None, **kwargs): if client is not None: self._client = client else: self._client = httpx.Client(base_url=base_url or "", **kwargs) @property def client(self) -> httpx.Client: """Get the httpx client instance.""" return self._client def request(self, method: str, url: str, **kwargs) -> httpx.Response: """Make an HTTP request.""" return self._client.request(method, url, **kwargs) def get(self, url: str, **kwargs) -> httpx.Response: """Make a GET request.""" return self._client.get(url, **kwargs) def post(self, url: str, **kwargs) -> httpx.Response: """Make a POST request.""" return self._client.post(url, **kwargs) def put(self, url: str, **kwargs) -> httpx.Response: """Make a PUT request.""" return self._client.put(url, **kwargs) def patch(self, url: str, **kwargs) -> httpx.Response: """Make a PATCH request.""" return self._client.patch(url, **kwargs) def delete(self, url: str, **kwargs) -> httpx.Response: """Make a DELETE request.""" return self._client.delete(url, **kwargs) def close(self): """Close the client.""" self._client.close() def __enter__(self): return self def __exit__(self, *args): self.close() class Client(BaseClient): """HTTP client using httpx (alias for BaseClient).""" pass def create_client(base_url: Optional[str] = None, **kwargs) -> Client: """Create a new HTTP client instance.""" return Client(base_url=base_url, **kwargs) ================================================ FILE: packages/openapi-python-tests/sdks/__snapshots__/opencode/default/pydantic_gen.py ================================================ # This file is auto-generated by @hey-api/openapi-python from enum import Enum from pydantic import BaseModel, Field from typing import Any, Literal, Optional, TypeAlias, Union class EventInstallationUpdatedProperties(BaseModel): version: str class EventInstallationUpdated(BaseModel): type_: Literal["installation.updated"] = Field(..., alias="type") properties: EventInstallationUpdatedProperties class EventInstallationUpdateAvailableProperties(BaseModel): version: str class EventInstallationUpdateAvailable(BaseModel): type_: Literal["installation.update-available"] = Field(..., alias="type") properties: EventInstallationUpdateAvailableProperties class ProjectIcon(BaseModel): url: Optional[str] = Field(default=None) color: Optional[str] = Field(default=None) class ProjectTime(BaseModel): created: float updated: float initialized: Optional[float] = Field(default=None) class Project(BaseModel): id_: str = Field(..., alias="id") worktree: str vcs: Optional[Literal["git"]] = Field(default=None) name: Optional[str] = Field(default=None) icon: Optional[ProjectIcon] = Field(default=None) time: ProjectTime class EventProjectUpdated(BaseModel): type_: Literal["project.updated"] = Field(..., alias="type") properties: Project class EventServerInstanceDisposedProperties(BaseModel): directory: str class EventServerInstanceDisposed(BaseModel): type_: Literal["server.instance.disposed"] = Field(..., alias="type") properties: EventServerInstanceDisposedProperties class EventLspClientDiagnosticsProperties(BaseModel): server_id: str = Field(..., alias="serverID") path: str class EventLspClientDiagnostics(BaseModel): type_: Literal["lsp.client.diagnostics"] = Field(..., alias="type") properties: EventLspClientDiagnosticsProperties class EventLspUpdated(BaseModel): type_: Literal["lsp.updated"] = Field(..., alias="type") properties: dict[str, Any] class FileDiff(BaseModel): file: str before: str after: str additions: float deletions: float class UserMessageTime(BaseModel): created: float class UserMessageSummary(BaseModel): title: Optional[str] = Field(default=None) body: Optional[str] = Field(default=None) diffs: list[FileDiff] class UserMessageModel(BaseModel): provider_id: str = Field(..., alias="providerID") model_id: str = Field(..., alias="modelID") class UserMessage(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") role: Literal["user"] time: UserMessageTime summary: Optional[UserMessageSummary] = Field(default=None) agent: str model: UserMessageModel system: Optional[str] = Field(default=None) tools: Optional[dict[str, Any]] = Field(default=None) variant: Optional[str] = Field(default=None) class ProviderAuthErrorData(BaseModel): provider_id: str = Field(..., alias="providerID") message: str class ProviderAuthError(BaseModel): name: Literal["ProviderAuthError"] data: ProviderAuthErrorData class UnknownErrorData(BaseModel): message: str class UnknownError(BaseModel): name: Literal["UnknownError"] data: UnknownErrorData class MessageOutputLengthError(BaseModel): name: Literal["MessageOutputLengthError"] data: dict[str, Any] class MessageAbortedErrorData(BaseModel): message: str class MessageAbortedError(BaseModel): name: Literal["MessageAbortedError"] data: MessageAbortedErrorData class ApiErrorData(BaseModel): message: str status_code: Optional[float] = Field(default=None, alias="statusCode") is_retryable: bool = Field(..., alias="isRetryable") response_headers: Optional[dict[str, Any]] = Field(default=None, alias="responseHeaders") response_body: Optional[str] = Field(default=None, alias="responseBody") metadata: Optional[dict[str, Any]] = Field(default=None) class ApiError(BaseModel): name: Literal["APIError"] data: ApiErrorData class AssistantMessageTime(BaseModel): created: float completed: Optional[float] = Field(default=None) class AssistantMessagePath(BaseModel): cwd: str root: str class AssistantMessageTokensCache(BaseModel): read: float write: float class AssistantMessageTokens(BaseModel): input_: float = Field(..., alias="input") output: float reasoning: float cache: AssistantMessageTokensCache class AssistantMessage(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") role: Literal["assistant"] time: AssistantMessageTime error: Optional[Union[ProviderAuthError, UnknownError, MessageOutputLengthError, MessageAbortedError, ApiError]] = Field(default=None) parent_id: str = Field(..., alias="parentID") model_id: str = Field(..., alias="modelID") provider_id: str = Field(..., alias="providerID") mode: str agent: str path: AssistantMessagePath summary: Optional[bool] = Field(default=None) cost: float tokens: AssistantMessageTokens finish: Optional[str] = Field(default=None) Message: TypeAlias = Union[UserMessage, AssistantMessage] class EventMessageUpdatedProperties(BaseModel): info: Message class EventMessageUpdated(BaseModel): type_: Literal["message.updated"] = Field(..., alias="type") properties: EventMessageUpdatedProperties class EventMessageRemovedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") class EventMessageRemoved(BaseModel): type_: Literal["message.removed"] = Field(..., alias="type") properties: EventMessageRemovedProperties class TextPartTime(BaseModel): start: float end: Optional[float] = Field(default=None) class TextPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["text"] = Field(..., alias="type") text: str synthetic: Optional[bool] = Field(default=None) ignored: Optional[bool] = Field(default=None) time: Optional[TextPartTime] = Field(default=None) metadata: Optional[dict[str, Any]] = Field(default=None) class ReasoningPartTime(BaseModel): start: float end: Optional[float] = Field(default=None) class ReasoningPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["reasoning"] = Field(..., alias="type") text: str metadata: Optional[dict[str, Any]] = Field(default=None) time: ReasoningPartTime class FilePartSourceText(BaseModel): value: str start: int = Field(..., ge=-9007199254740991, le=9007199254740991) end: int = Field(..., ge=-9007199254740991, le=9007199254740991) class FileSource(BaseModel): text: FilePartSourceText type_: Literal["file"] = Field(..., alias="type") path: str class RangeStart(BaseModel): line: float character: float class RangeEnd(BaseModel): line: float character: float class Range(BaseModel): start: RangeStart end: RangeEnd class SymbolSource(BaseModel): text: FilePartSourceText type_: Literal["symbol"] = Field(..., alias="type") path: str range_: Range = Field(..., alias="range") name: str kind: int = Field(..., ge=-9007199254740991, le=9007199254740991) FilePartSource: TypeAlias = Union[FileSource, SymbolSource] class FilePart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["file"] = Field(..., alias="type") mime: str filename: Optional[str] = Field(default=None) url: str source: Optional[FilePartSource] = Field(default=None) class ToolStatePending(BaseModel): status: Literal["pending"] input_: dict[str, Any] = Field(..., alias="input") raw: str class ToolStateRunningTime(BaseModel): start: float class ToolStateRunning(BaseModel): status: Literal["running"] input_: dict[str, Any] = Field(..., alias="input") title: Optional[str] = Field(default=None) metadata: Optional[dict[str, Any]] = Field(default=None) time: ToolStateRunningTime class ToolStateCompletedTime(BaseModel): start: float end: float compacted: Optional[float] = Field(default=None) class ToolStateCompleted(BaseModel): status: Literal["completed"] input_: dict[str, Any] = Field(..., alias="input") output: str title: str metadata: dict[str, Any] time: ToolStateCompletedTime attachments: Optional[list[FilePart]] = Field(default=None) class ToolStateErrorTime(BaseModel): start: float end: float class ToolStateError(BaseModel): status: Literal["error"] input_: dict[str, Any] = Field(..., alias="input") error: str metadata: Optional[dict[str, Any]] = Field(default=None) time: ToolStateErrorTime ToolState: TypeAlias = Union[ToolStatePending, ToolStateRunning, ToolStateCompleted, ToolStateError] class ToolPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["tool"] = Field(..., alias="type") call_id: str = Field(..., alias="callID") tool: str state: ToolState metadata: Optional[dict[str, Any]] = Field(default=None) class StepStartPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["step-start"] = Field(..., alias="type") snapshot: Optional[str] = Field(default=None) class StepFinishPartTokensCache(BaseModel): read: float write: float class StepFinishPartTokens(BaseModel): input_: float = Field(..., alias="input") output: float reasoning: float cache: StepFinishPartTokensCache class StepFinishPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["step-finish"] = Field(..., alias="type") reason: str snapshot: Optional[str] = Field(default=None) cost: float tokens: StepFinishPartTokens class SnapshotPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["snapshot"] = Field(..., alias="type") snapshot: str class PatchPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["patch"] = Field(..., alias="type") hash_: str = Field(..., alias="hash") files: list[str] class AgentPartSource(BaseModel): value: str start: int = Field(..., ge=-9007199254740991, le=9007199254740991) end: int = Field(..., ge=-9007199254740991, le=9007199254740991) class AgentPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["agent"] = Field(..., alias="type") name: str source: Optional[AgentPartSource] = Field(default=None) class RetryPartTime(BaseModel): created: float class RetryPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["retry"] = Field(..., alias="type") attempt: float error: ApiError time: RetryPartTime class CompactionPart(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["compaction"] = Field(..., alias="type") auto: bool class Part(BaseModel): id_: str = Field(..., alias="id") session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") type_: Literal["subtask"] = Field(..., alias="type") prompt: str description: str agent: str command: Optional[str] = Field(default=None) Part_2: TypeAlias = Union[TextPart, Part, ReasoningPart, FilePart, ToolPart, StepStartPart, StepFinishPart, SnapshotPart, PatchPart, AgentPart, RetryPart, CompactionPart] class EventMessagePartUpdatedProperties(BaseModel): part: Part_2 delta: Optional[str] = Field(default=None) class EventMessagePartUpdated(BaseModel): type_: Literal["message.part.updated"] = Field(..., alias="type") properties: EventMessagePartUpdatedProperties class EventMessagePartRemovedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") message_id: str = Field(..., alias="messageID") part_id: str = Field(..., alias="partID") class EventMessagePartRemoved(BaseModel): type_: Literal["message.part.removed"] = Field(..., alias="type") properties: EventMessagePartRemovedProperties class PermissionRequestTool(BaseModel): message_id: str = Field(..., alias="messageID") call_id: str = Field(..., alias="callID") class PermissionRequest(BaseModel): id_: str = Field(..., alias="id", pattern="^per.*") session_id: str = Field(..., alias="sessionID", pattern="^ses.*") permission: str patterns: list[str] metadata: dict[str, Any] always: list[str] tool: Optional[PermissionRequestTool] = Field(default=None) class EventPermissionAsked(BaseModel): type_: Literal["permission.asked"] = Field(..., alias="type") properties: PermissionRequest class EventPermissionRepliedPropertiesReply(Enum, str): ONCE = "once" ALWAYS = "always" REJECT = "reject" class EventPermissionRepliedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") request_id: str = Field(..., alias="requestID") reply: EventPermissionRepliedPropertiesReply class EventPermissionReplied(BaseModel): type_: Literal["permission.replied"] = Field(..., alias="type") properties: EventPermissionRepliedProperties class SessionStatus(BaseModel): type_: Literal["idle"] = Field(..., alias="type") class SessionStatus_2(BaseModel): type_: Literal["retry"] = Field(..., alias="type") attempt: float message: str next_: float = Field(..., alias="next") class SessionStatus_3(BaseModel): type_: Literal["busy"] = Field(..., alias="type") SessionStatus_4: TypeAlias = Union[SessionStatus, SessionStatus_2, SessionStatus_3] class EventSessionStatusProperties(BaseModel): session_id: str = Field(..., alias="sessionID") status: SessionStatus_4 class EventSessionStatus(BaseModel): type_: Literal["session.status"] = Field(..., alias="type") properties: EventSessionStatusProperties class EventSessionIdleProperties(BaseModel): session_id: str = Field(..., alias="sessionID") class EventSessionIdle(BaseModel): type_: Literal["session.idle"] = Field(..., alias="type") properties: EventSessionIdleProperties class EventSessionCompactedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") class EventSessionCompacted(BaseModel): type_: Literal["session.compacted"] = Field(..., alias="type") properties: EventSessionCompactedProperties class EventFileEditedProperties(BaseModel): file: str class EventFileEdited(BaseModel): type_: Literal["file.edited"] = Field(..., alias="type") properties: EventFileEditedProperties class Todo(BaseModel): content: str = Field(..., description="Brief description of the task") status: str = Field(..., description="Current status of the task: pending, in_progress, completed, cancelled") priority: str = Field(..., description="Priority level of the task: high, medium, low") id_: str = Field(..., alias="id", description="Unique identifier for the todo item") class EventTodoUpdatedProperties(BaseModel): session_id: str = Field(..., alias="sessionID") todos: list[Todo] class EventTodoUpdated(BaseModel): type_: Literal["todo.updated"] = Field(..., alias="type") properties: EventTodoUpdatedProperties class EventTuiPromptAppendProperties(BaseModel): text: str class EventTuiPromptAppend(BaseModel): type_: Literal["tui.prompt.append"] = Field(..., alias="type") properties: EventTuiPromptAppendProperties class EventTuiCommandExecutePropertiesCommand(Enum, str): SESSION_LIST = "session.list" SESSION_NEW = "session.new" SESSION_SHARE = "session.share" SESSION_INTERRUPT = "session.interrupt" SESSION_COMPACT = "session.compact" SESSION_PAGE_UP = "session.page.up" SESSION_PAGE_DOWN = "session.page.down" SESSION_HALF_PAGE_UP = "session.half.page.up" SESSION_HALF_PAGE_DOWN = "session.half.page.down" SESSION_FIRST = "session.first" SESSION_LAST = "session.last" PROMPT_CLEAR = "prompt.clear" PROMPT_SUBMIT = "prompt.submit" AGENT_CYCLE = "agent.cycle" class EventTuiCommandExecuteProperties(BaseModel): command: Union[EventTuiCommandExecutePropertiesCommand, str] class EventTuiCommandExecute(BaseModel): type_: Literal["tui.command.execute"] = Field(..., alias="type") properties: EventTuiCommandExecuteProperties class EventTuiToastShowPropertiesVariant(Enum, str): INFO = "info" SUCCESS = "success" WARNING = "warning" ERROR = "error" class EventTuiToastShowProperties(BaseModel): title: Optional[str] = Field(default=None) message: str variant: EventTuiToastShowPropertiesVariant duration: Optional[float] = Field(default=5000, description="Duration in milliseconds") class EventTuiToastShow(BaseModel): type_: Literal["tui.toast.show"] = Field(..., alias="type") properties: EventTuiToastShowProperties class EventMcpToolsChangedProperties(BaseModel): server: str class EventMcpToolsChanged(BaseModel): type_: Literal["mcp.tools.changed"] = Field(..., alias="type") properties: EventMcpToolsChangedProperties class EventCommandExecutedProperties(BaseModel): name: str session_id: str = Field(..., alias="sessionID", pattern="^ses.*") arguments: str message_id: str = Field(..., alias="messageID", pattern="^msg.*") class EventCommandExecuted(BaseModel): type_: Literal["command.executed"] = Field(..., alias="type") properties: EventCommandExecutedProperties class PermissionAction(Enum, str): ALLOW = "allow" DENY = "deny" ASK = "ask" class PermissionRule(BaseModel): permission: str pattern: str action: PermissionAction PermissionRuleset: TypeAlias = list[PermissionRule] class SessionSummary(BaseModel): additions: float deletions: float files: float diffs: Optional[list[FileDiff]] = Field(default=None) class SessionShare(BaseModel): url: str class SessionTime(BaseModel): created: float updated: float compacting: Optional[float] = Field(default=None) archived: Optional[float] = Field(default=None) class SessionRevert(BaseModel): message_id: str = Field(..., alias="messageID") part_id: Optional[str] = Field(default=None, alias="partID") snapshot: Optional[str] = Field(default=None) diff: Optional[str] = Field(default=None) class Session(BaseModel): id_: str = Field(..., alias="id", pattern="^ses.*") project_id: str = Field(..., alias="projectID") directory: str parent_id: Optional[str] = Field(default=None, alias="parentID", pattern="^ses.*") summary: Optional[SessionSummary] = Field(default=None) share: Optional[SessionShare] = Field(default=None) title: str version: str time: SessionTime permission: Optional[PermissionRuleset] = Field(default=None) revert: Optional[SessionRevert] = Field(default=None) class EventSessionCreatedProperties(BaseModel): info: Session class EventSessionCreated(BaseModel): type_: Literal["session.created"] = Field(..., alias="type") properties: EventSessionCreatedProperties class EventSessionUpdatedProperties(BaseModel): info: Session class EventSessionUpdated(BaseModel): type_: Literal["session.updated"] = Field(..., alias="type") properties: EventSessionUpdatedProperties class EventSessionDeletedProperties(BaseModel): info: Session class EventSessionDeleted(BaseModel): type_: Literal["session.deleted"] = Field(..., alias="type") properties: EventSessionDeletedProperties class EventSessionDiffProperties(BaseModel): session_id: str = Field(..., alias="sessionID") diff: list[FileDiff] class EventSessionDiff(BaseModel): type_: Literal["session.diff"] = Field(..., alias="type") properties: EventSessionDiffProperties class EventSessionErrorProperties(BaseModel): session_id: Optional[str] = Field(default=None, alias="sessionID") error: Optional[Union[ProviderAuthError, UnknownError, MessageOutputLengthError, MessageAbortedError, ApiError]] = Field(default=None) class EventSessionError(BaseModel): type_: Literal["session.error"] = Field(..., alias="type") properties: EventSessionErrorProperties class EventFileWatcherUpdatedProperties(BaseModel): file: str event: Union[Literal["add"], Literal["change"], Literal["unlink"]] class EventFileWatcherUpdated(BaseModel): type_: Literal["file.watcher.updated"] = Field(..., alias="type") properties: EventFileWatcherUpdatedProperties class EventVcsBranchUpdatedProperties(BaseModel): branch: Optional[str] = Field(default=None) class EventVcsBranchUpdated(BaseModel): type_: Literal["vcs.branch.updated"] = Field(..., alias="type") properties: EventVcsBranchUpdatedProperties class PtyStatus(Enum, str): RUNNING = "running" EXITED = "exited" class Pty(BaseModel): id_: str = Field(..., alias="id", pattern="^pty.*") title: str command: str args: list[str] cwd: str status: PtyStatus pid: float class EventPtyCreatedProperties(BaseModel): info: Pty class EventPtyCreated(BaseModel): type_: Literal["pty.created"] = Field(..., alias="type") properties: EventPtyCreatedProperties class EventPtyUpdatedProperties(BaseModel): info: Pty class EventPtyUpdated(BaseModel): type_: Literal["pty.updated"] = Field(..., alias="type") properties: EventPtyUpdatedProperties class EventPtyExitedProperties(BaseModel): id_: str = Field(..., alias="id", pattern="^pty.*") exit_code: float = Field(..., alias="exitCode") class EventPtyExited(BaseModel): type_: Literal["pty.exited"] = Field(..., alias="type") properties: EventPtyExitedProperties class EventPtyDeletedProperties(BaseModel): id_: str = Field(..., alias="id", pattern="^pty.*") class EventPtyDeleted(BaseModel): type_: Literal["pty.deleted"] = Field(..., alias="type") properties: EventPtyDeletedProperties class EventServerConnected(BaseModel): type_: Literal["server.connected"] = Field(..., alias="type") properties: dict[str, Any] class EventGlobalDisposed(BaseModel): type_: Literal["global.disposed"] = Field(..., alias="type") properties: dict[str, Any] Event: TypeAlias = Union[EventInstallationUpdated, EventInstallationUpdateAvailable, EventProjectUpdated, EventServerInstanceDisposed, EventLspClientDiagnostics, EventLspUpdated, EventMessageUpdated, EventMessageRemoved, EventMessagePartUpdated, EventMessagePartRemoved, EventPermissionAsked, EventPermissionReplied, EventSessionStatus, EventSessionIdle, EventSessionCompacted, EventFileEdited, EventTodoUpdated, EventTuiPromptAppend, EventTuiCommandExecute, EventTuiToastShow, EventMcpToolsChanged, EventCommandExecuted, EventSessionCreated, EventSessionUpdated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventFileWatcherUpdated, EventVcsBranchUpdated, EventPtyCreated, EventPtyUpdated, EventPtyExited, EventPtyDeleted, EventServerConnected, EventGlobalDisposed] class GlobalEvent(BaseModel): directory: str payload: Event class BadRequestError(BaseModel): data: Any errors: list[dict[str, Any]] success: Literal[False] class NotFoundErrorData(BaseModel): message: str class NotFoundError(BaseModel): name: Literal["NotFoundError"] data: NotFoundErrorData class KeybindsConfig(BaseModel): leader: Optional[str] = Field(default="ctrl+x", description="Leader key for keybind combinations") app_exit: Optional[str] = Field(default="ctrl+c,ctrl+d,q", description="Exit the application") editor_open: Optional[str] = Field(default="e", description="Open external editor") theme_list: Optional[str] = Field(default="t", description="List available themes") sidebar_toggle: Optional[str] = Field(default="b", description="Toggle sidebar") scrollbar_toggle: Optional[str] = Field(default="none", description="Toggle session scrollbar") username_toggle: Optional[str] = Field(default="none", description="Toggle username visibility") status_view: Optional[str] = Field(default="s", description="View status") session_export: Optional[str] = Field(default="x", description="Export session to editor") session_new: Optional[str] = Field(default="n", description="Create a new session") session_list: Optional[str] = Field(default="l", description="List all sessions") session_timeline: Optional[str] = Field(default="g", description="Show session timeline") session_fork: Optional[str] = Field(default="none", description="Fork session from message") session_rename: Optional[str] = Field(default="none", description="Rename session") session_share: Optional[str] = Field(default="none", description="Share current session") session_unshare: Optional[str] = Field(default="none", description="Unshare current session") session_interrupt: Optional[str] = Field(default="escape", description="Interrupt current session") session_compact: Optional[str] = Field(default="c", description="Compact the session") messages_page_up: Optional[str] = Field(default="pageup", description="Scroll messages up by one page") messages_page_down: Optional[str] = Field(default="pagedown", description="Scroll messages down by one page") messages_half_page_up: Optional[str] = Field(default="ctrl+alt+u", description="Scroll messages up by half page") messages_half_page_down: Optional[str] = Field(default="ctrl+alt+d", description="Scroll messages down by half page") messages_first: Optional[str] = Field(default="ctrl+g,home", description="Navigate to first message") messages_last: Optional[str] = Field(default="ctrl+alt+g,end", description="Navigate to last message") messages_next: Optional[str] = Field(default="none", description="Navigate to next message") messages_previous: Optional[str] = Field(default="none", description="Navigate to previous message") messages_last_user: Optional[str] = Field(default="none", description="Navigate to last user message") messages_copy: Optional[str] = Field(default="y", description="Copy message") messages_undo: Optional[str] = Field(default="u", description="Undo message") messages_redo: Optional[str] = Field(default="r", description="Redo message") messages_toggle_conceal: Optional[str] = Field(default="h", description="Toggle code block concealment in messages") tool_details: Optional[str] = Field(default="none", description="Toggle tool details visibility") model_list: Optional[str] = Field(default="m", description="List available models") model_cycle_recent: Optional[str] = Field(default="f2", description="Next recently used model") model_cycle_recent_reverse: Optional[str] = Field(default="shift+f2", description="Previous recently used model") model_cycle_favorite: Optional[str] = Field(default="none", description="Next favorite model") model_cycle_favorite_reverse: Optional[str] = Field(default="none", description="Previous favorite model") command_list: Optional[str] = Field(default="ctrl+p", description="List available commands") agent_list: Optional[str] = Field(default="a", description="List agents") agent_cycle: Optional[str] = Field(default="tab", description="Next agent") agent_cycle_reverse: Optional[str] = Field(default="shift+tab", description="Previous agent") variant_cycle: Optional[str] = Field(default="ctrl+t", description="Cycle model variants") input_clear: Optional[str] = Field(default="ctrl+c", description="Clear input field") input_paste: Optional[str] = Field(default="ctrl+v", description="Paste from clipboard") input_submit: Optional[str] = Field(default="return", description="Submit input") input_newline: Optional[str] = Field(default="shift+return,ctrl+return,alt+return,ctrl+j", description="Insert newline in input") input_move_left: Optional[str] = Field(default="left,ctrl+b", description="Move cursor left in input") input_move_right: Optional[str] = Field(default="right,ctrl+f", description="Move cursor right in input") input_move_up: Optional[str] = Field(default="up", description="Move cursor up in input") input_move_down: Optional[str] = Field(default="down", description="Move cursor down in input") input_select_left: Optional[str] = Field(default="shift+left", description="Select left in input") input_select_right: Optional[str] = Field(default="shift+right", description="Select right in input") input_select_up: Optional[str] = Field(default="shift+up", description="Select up in input") input_select_down: Optional[str] = Field(default="shift+down", description="Select down in input") input_line_home: Optional[str] = Field(default="ctrl+a", description="Move to start of line in input") input_line_end: Optional[str] = Field(default="ctrl+e", description="Move to end of line in input") input_select_line_home: Optional[str] = Field(default="ctrl+shift+a", description="Select to start of line in input") input_select_line_end: Optional[str] = Field(default="ctrl+shift+e", description="Select to end of line in input") input_visual_line_home: Optional[str] = Field(default="alt+a", description="Move to start of visual line in input") input_visual_line_end: Optional[str] = Field(default="alt+e", description="Move to end of visual line in input") input_select_visual_line_home: Optional[str] = Field(default="alt+shift+a", description="Select to start of visual line in input") input_select_visual_line_end: Optional[str] = Field(default="alt+shift+e", description="Select to end of visual line in input") input_buffer_home: Optional[str] = Field(default="home", description="Move to start of buffer in input") input_buffer_end: Optional[str] = Field(default="end", description="Move to end of buffer in input") input_select_buffer_home: Optional[str] = Field(default="shift+home", description="Select to start of buffer in input") input_select_buffer_end: Optional[str] = Field(default="shift+end", description="Select to end of buffer in input") input_delete_line: Optional[str] = Field(default="ctrl+shift+d", description="Delete line in input") input_delete_to_line_end: Optional[str] = Field(default="ctrl+k", description="Delete to end of line in input") input_delete_to_line_start: Optional[str] = Field(default="ctrl+u", description="Delete to start of line in input") input_backspace: Optional[str] = Field(default="backspace,shift+backspace", description="Backspace in input") input_delete: Optional[str] = Field(default="ctrl+d,delete,shift+delete", description="Delete character in input") input_undo: Optional[str] = Field(default="ctrl+-,super+z", description="Undo in input") input_redo: Optional[str] = Field(default="ctrl+.,super+shift+z", description="Redo in input") input_word_forward: Optional[str] = Field(default="alt+f,alt+right,ctrl+right", description="Move word forward in input") input_word_backward: Optional[str] = Field(default="alt+b,alt+left,ctrl+left", description="Move word backward in input") input_select_word_forward: Optional[str] = Field(default="alt+shift+f,alt+shift+right", description="Select word forward in input") input_select_word_backward: Optional[str] = Field(default="alt+shift+b,alt+shift+left", description="Select word backward in input") input_delete_word_forward: Optional[str] = Field(default="alt+d,alt+delete,ctrl+delete", description="Delete word forward in input") input_delete_word_backward: Optional[str] = Field(default="ctrl+w,ctrl+backspace,alt+backspace", description="Delete word backward in input") history_previous: Optional[str] = Field(default="up", description="Previous history item") history_next: Optional[str] = Field(default="down", description="Next history item") session_child_cycle: Optional[str] = Field(default="right", description="Next child session") session_child_cycle_reverse: Optional[str] = Field(default="left", description="Previous child session") session_parent: Optional[str] = Field(default="up", description="Go to parent session") terminal_suspend: Optional[str] = Field(default="ctrl+z", description="Suspend terminal") terminal_title_toggle: Optional[str] = Field(default="none", description="Toggle terminal title") tips_toggle: Optional[str] = Field(default="h", description="Toggle tips on home screen") class LogLevel(Enum, str): DEBUG = "DEBUG" INFO = "INFO" WARN = "WARN" ERROR = "ERROR" class ServerConfig(BaseModel): port: Optional[int] = Field(default=None, description="Port to listen on", gt=0, le=9007199254740991) hostname: Optional[str] = Field(default=None, description="Hostname to listen on") mdns: Optional[bool] = Field(default=None) cors: Optional[list[str]] = Field(default=None, description="Additional domains to allow for CORS") class PermissionActionConfig(Enum, str): ASK = "ask" ALLOW = "allow" DENY = "deny" PermissionObjectConfig: TypeAlias = dict[str, Any] PermissionRuleConfig: TypeAlias = Union[PermissionActionConfig, PermissionObjectConfig] class PermissionConfig(BaseModel): read: Optional[PermissionRuleConfig] = Field(default=None) edit: Optional[PermissionRuleConfig] = Field(default=None) glob: Optional[PermissionRuleConfig] = Field(default=None) grep: Optional[PermissionRuleConfig] = Field(default=None) list_: Optional[PermissionRuleConfig] = Field(default=None, alias="list") bash: Optional[PermissionRuleConfig] = Field(default=None) task: Optional[PermissionRuleConfig] = Field(default=None) external_directory: Optional[PermissionRuleConfig] = Field(default=None) todowrite: Optional[PermissionActionConfig] = Field(default=None) todoread: Optional[PermissionActionConfig] = Field(default=None) webfetch: Optional[PermissionActionConfig] = Field(default=None) websearch: Optional[PermissionActionConfig] = Field(default=None) codesearch: Optional[PermissionActionConfig] = Field(default=None) lsp: Optional[PermissionRuleConfig] = Field(default=None) doom_loop: Optional[PermissionActionConfig] = Field(default=None) PermissionConfig_2: TypeAlias = Union[PermissionConfig, PermissionActionConfig] AgentConfig: TypeAlias = dict[str, Any] class ProviderConfigModelsValueInterleavedField(Enum, str): REASONING_CONTENT = "reasoning_content" REASONING_DETAILS = "reasoning_details" class ProviderConfigModelsValueInterleaved(BaseModel): field: ProviderConfigModelsValueInterleavedField class ProviderConfigModelsValueCostContextOver200k(BaseModel): input_: float = Field(..., alias="input") output: float cache_read: Optional[float] = Field(default=None) cache_write: Optional[float] = Field(default=None) class ProviderConfigModelsValueCost(BaseModel): input_: float = Field(..., alias="input") output: float cache_read: Optional[float] = Field(default=None) cache_write: Optional[float] = Field(default=None) context_over_200k: Optional[ProviderConfigModelsValueCostContextOver200k] = Field(default=None) class ProviderConfigModelsValueLimit(BaseModel): context: float output: float class ProviderConfigModelsValueModalitiesInput(Enum, str): TEXT = "text" AUDIO = "audio" IMAGE = "image" VIDEO = "video" PDF = "pdf" class ProviderConfigModelsValueModalitiesOutput(Enum, str): TEXT = "text" AUDIO = "audio" IMAGE = "image" VIDEO = "video" PDF = "pdf" class ProviderConfigModelsValueModalities(BaseModel): input_: list[ProviderConfigModelsValueModalitiesInput] = Field(..., alias="input") output: list[ProviderConfigModelsValueModalitiesOutput] class ProviderConfigModelsValueStatus(Enum, str): ALPHA = "alpha" BETA = "beta" DEPRECATED = "deprecated" class ProviderConfigModelsValueProvider(BaseModel): npm: str ProviderConfigModelsValueVariantsValue: TypeAlias = dict[str, Any] class ProviderConfigModelsValue(BaseModel): id_: Optional[str] = Field(default=None, alias="id") name: Optional[str] = Field(default=None) family: Optional[str] = Field(default=None) release_date: Optional[str] = Field(default=None) attachment: Optional[bool] = Field(default=None) reasoning: Optional[bool] = Field(default=None) temperature: Optional[bool] = Field(default=None) tool_call: Optional[bool] = Field(default=None) interleaved: Optional[Union[Literal[True], ProviderConfigModelsValueInterleaved]] = Field(default=None) cost: Optional[ProviderConfigModelsValueCost] = Field(default=None) limit: Optional[ProviderConfigModelsValueLimit] = Field(default=None) modalities: Optional[ProviderConfigModelsValueModalities] = Field(default=None) experimental: Optional[bool] = Field(default=None) status: Optional[ProviderConfigModelsValueStatus] = Field(default=None) options: Optional[dict[str, Any]] = Field(default=None) headers: Optional[dict[str, Any]] = Field(default=None) provider: Optional[ProviderConfigModelsValueProvider] = Field(default=None) variants: Optional[dict[str, Any]] = Field(default=None) ProviderConfigOptions: TypeAlias = dict[str, Any] class ProviderConfig(BaseModel): api: Optional[str] = Field(default=None) name: Optional[str] = Field(default=None) env: Optional[list[str]] = Field(default=None) id_: Optional[str] = Field(default=None, alias="id") npm: Optional[str] = Field(default=None) models: Optional[dict[str, Any]] = Field(default=None) whitelist: Optional[list[str]] = Field(default=None) blacklist: Optional[list[str]] = Field(default=None) options: Optional[ProviderConfigOptions] = Field(default=None) class McpLocalConfig(BaseModel): type_: Literal["local"] = Field(..., alias="type") command: list[str] = Field(..., description="Command and arguments to run the MCP server") environment: Optional[dict[str, Any]] = Field(default=None) enabled: Optional[bool] = Field(default=None) timeout: Optional[int] = Field(default=None, description="Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.", gt=0, le=9007199254740991) class McpOAuthConfig(BaseModel): client_id: Optional[str] = Field(default=None, alias="clientId", description="OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted.") client_secret: Optional[str] = Field(default=None, alias="clientSecret", description="OAuth client secret (if required by the authorization server)") scope: Optional[str] = Field(default=None, description="OAuth scopes to request during authorization") class McpRemoteConfig(BaseModel): type_: Literal["remote"] = Field(..., alias="type") url: str = Field(..., description="URL of the remote MCP server") enabled: Optional[bool] = Field(default=None) headers: Optional[dict[str, Any]] = Field(default=None) oauth: Optional[Union[McpOAuthConfig, Literal[False]]] = Field(default=None, description="OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection.") timeout: Optional[int] = Field(default=None, description="Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.", gt=0, le=9007199254740991) class LayoutConfig(Enum, str): AUTO = "auto" STRETCH = "stretch" class ConfigTuiScrollAcceleration(BaseModel): enabled: bool class ConfigTuiDiffStyle(Enum, str): AUTO = "auto" STACKED = "stacked" class ConfigTui(BaseModel): scroll_speed: Optional[float] = Field(default=None, description="TUI scroll speed", ge=0.001) scroll_acceleration: Optional[ConfigTuiScrollAcceleration] = Field(default=None) diff_style: Optional[ConfigTuiDiffStyle] = Field(default=None) class ConfigCommandValue(BaseModel): template: str description: Optional[str] = Field(default=None) agent: Optional[str] = Field(default=None) model: Optional[str] = Field(default=None) subtask: Optional[bool] = Field(default=None) class ConfigWatcher(BaseModel): ignore: Optional[list[str]] = Field(default=None) class ConfigShare(Enum, str): MANUAL = "manual" AUTO = "auto" DISABLED = "disabled" class ConfigMode(BaseModel): build: Optional[AgentConfig] = Field(default=None) plan: Optional[AgentConfig] = Field(default=None) class ConfigAgent(BaseModel): plan: Optional[AgentConfig] = Field(default=None) build: Optional[AgentConfig] = Field(default=None) general: Optional[AgentConfig] = Field(default=None) explore: Optional[AgentConfig] = Field(default=None) title: Optional[AgentConfig] = Field(default=None) summary: Optional[AgentConfig] = Field(default=None) compaction: Optional[AgentConfig] = Field(default=None) class ConfigFormatterValue(BaseModel): disabled: Optional[bool] = Field(default=None) command: Optional[list[str]] = Field(default=None) environment: Optional[dict[str, Any]] = Field(default=None) extensions: Optional[list[str]] = Field(default=None) class ConfigEnterprise(BaseModel): url: Optional[str] = Field(default=None, description="Enterprise URL") class ConfigCompaction(BaseModel): auto: Optional[bool] = Field(default=None) prune: Optional[bool] = Field(default=None) class ConfigExperimentalHookFileEditedValue(BaseModel): command: list[str] environment: Optional[dict[str, Any]] = Field(default=None) class ConfigExperimentalHookSessionCompleted(BaseModel): command: list[str] environment: Optional[dict[str, Any]] = Field(default=None) class ConfigExperimentalHook(BaseModel): file_edited: Optional[dict[str, Any]] = Field(default=None) session_completed: Optional[list[ConfigExperimentalHookSessionCompleted]] = Field(default=None) class ConfigExperimental(BaseModel): hook: Optional[ConfigExperimentalHook] = Field(default=None) chat_max_retries: Optional[float] = Field(default=None, alias="chatMaxRetries", description="Number of retries for chat completions on failure") disable_paste_summary: Optional[bool] = Field(default=None) batch_tool: Optional[bool] = Field(default=None) open_telemetry: Optional[bool] = Field(default=None, alias="openTelemetry") primary_tools: Optional[list[str]] = Field(default=None, description="Tools that should only be available to primary agents.") continue_loop_on_deny: Optional[bool] = Field(default=None) mcp_timeout: Optional[int] = Field(default=None, description="Timeout in milliseconds for model context protocol (MCP) requests", gt=0, le=9007199254740991) class Config(BaseModel): schema: Optional[str] = Field(default=None, alias="$schema", description="JSON schema reference for configuration validation") theme: Optional[str] = Field(default=None, description="Theme name to use for the interface") keybinds: Optional[KeybindsConfig] = Field(default=None) log_level: Optional[LogLevel] = Field(default=None, alias="logLevel") tui: Optional[ConfigTui] = Field(default=None) server: Optional[ServerConfig] = Field(default=None) command: Optional[dict[str, Any]] = Field(default=None) watcher: Optional[ConfigWatcher] = Field(default=None) plugin: Optional[list[str]] = Field(default=None) snapshot: Optional[bool] = Field(default=None) share: Optional[ConfigShare] = Field(default=None) autoshare: Optional[bool] = Field(default=None) autoupdate: Optional[Union[bool, Literal["notify"]]] = Field(default=None, description="Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications") disabled_providers: Optional[list[str]] = Field(default=None, description="Disable providers that are loaded automatically") enabled_providers: Optional[list[str]] = Field(default=None, description="When set, ONLY these providers will be enabled. All other providers will be ignored") model: Optional[str] = Field(default=None, description="Model to use in the format of provider/model, eg anthropic/claude-2") small_model: Optional[str] = Field(default=None, description="Small model to use for tasks like title generation in the format of provider/model") default_agent: Optional[str] = Field(default=None, description="Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid.") username: Optional[str] = Field(default=None, description="Custom username to display in conversations instead of system username") mode: Optional[ConfigMode] = Field(default=None) agent: Optional[ConfigAgent] = Field(default=None) provider: Optional[dict[str, Any]] = Field(default=None) mcp: Optional[dict[str, Any]] = Field(default=None) formatter: Optional[Union[Literal[False], dict[str, Any]]] = Field(default=None) lsp: Optional[Union[Literal[False], dict[str, Any]]] = Field(default=None) instructions: Optional[list[str]] = Field(default=None, description="Additional instruction files or patterns to include") layout: Optional[LayoutConfig] = Field(default=None) permission: Optional[PermissionConfig_2] = Field(default=None) tools: Optional[dict[str, Any]] = Field(default=None) enterprise: Optional[ConfigEnterprise] = Field(default=None) compaction: Optional[ConfigCompaction] = Field(default=None) experimental: Optional[ConfigExperimental] = Field(default=None) ToolIds: TypeAlias = list[str] class ToolListItem(BaseModel): id_: str = Field(..., alias="id") description: str parameters: Any ToolList: TypeAlias = list[ToolListItem] class Path(BaseModel): home: str state: str config: str worktree: str directory: str class VcsInfo(BaseModel): branch: str class TextPartInputTime(BaseModel): start: float end: Optional[float] = Field(default=None) class TextPartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["text"] = Field(..., alias="type") text: str synthetic: Optional[bool] = Field(default=None) ignored: Optional[bool] = Field(default=None) time: Optional[TextPartInputTime] = Field(default=None) metadata: Optional[dict[str, Any]] = Field(default=None) class FilePartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["file"] = Field(..., alias="type") mime: str filename: Optional[str] = Field(default=None) url: str source: Optional[FilePartSource] = Field(default=None) class AgentPartInputSource(BaseModel): value: str start: int = Field(..., ge=-9007199254740991, le=9007199254740991) end: int = Field(..., ge=-9007199254740991, le=9007199254740991) class AgentPartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["agent"] = Field(..., alias="type") name: str source: Optional[AgentPartInputSource] = Field(default=None) class SubtaskPartInput(BaseModel): id_: Optional[str] = Field(default=None, alias="id") type_: Literal["subtask"] = Field(..., alias="type") prompt: str description: str agent: str command: Optional[str] = Field(default=None) class Command(BaseModel): name: str description: Optional[str] = Field(default=None) agent: Optional[str] = Field(default=None) model: Optional[str] = Field(default=None) mcp: Optional[bool] = Field(default=None) template: str subtask: Optional[bool] = Field(default=None) hints: list[str] class ModelApi(BaseModel): id_: str = Field(..., alias="id") url: str npm: str class ModelCapabilitiesInput(BaseModel): text: bool audio: bool image: bool video: bool pdf: bool class ModelCapabilitiesOutput(BaseModel): text: bool audio: bool image: bool video: bool pdf: bool class ModelCapabilitiesInterleavedField(Enum, str): REASONING_CONTENT = "reasoning_content" REASONING_DETAILS = "reasoning_details" class ModelCapabilitiesInterleaved(BaseModel): field: ModelCapabilitiesInterleavedField class ModelCapabilities(BaseModel): temperature: bool reasoning: bool attachment: bool toolcall: bool input_: ModelCapabilitiesInput = Field(..., alias="input") output: ModelCapabilitiesOutput interleaved: Union[bool, ModelCapabilitiesInterleaved] class ModelCostCache(BaseModel): read: float write: float class ModelCostExperimentalOver200kCache(BaseModel): read: float write: float class ModelCostExperimentalOver200k(BaseModel): input_: float = Field(..., alias="input") output: float cache: ModelCostExperimentalOver200kCache class ModelCost(BaseModel): input_: float = Field(..., alias="input") output: float cache: ModelCostCache experimental_over200k: Optional[ModelCostExperimentalOver200k] = Field(default=None, alias="experimentalOver200K") class ModelLimit(BaseModel): context: float output: float class ModelStatus(Enum, str): ALPHA = "alpha" BETA = "beta" DEPRECATED = "deprecated" ACTIVE = "active" class Model(BaseModel): id_: str = Field(..., alias="id") provider_id: str = Field(..., alias="providerID") api: ModelApi name: str family: Optional[str] = Field(default=None) capabilities: ModelCapabilities cost: ModelCost limit: ModelLimit status: ModelStatus options: dict[str, Any] headers: dict[str, Any] release_date: str variants: Optional[dict[str, Any]] = Field(default=None) class ProviderSource(Enum, str): ENV = "env" CONFIG = "config" CUSTOM = "custom" API = "api" class Provider(BaseModel): id_: str = Field(..., alias="id") name: str source: ProviderSource env: list[str] key: Optional[str] = Field(default=None) options: dict[str, Any] models: dict[str, Any] class ProviderAuthMethod(BaseModel): type_: Union[Literal["oauth"], Literal["api"]] = Field(..., alias="type") label: str class ProviderAuthAuthorization(BaseModel): url: str method: Union[Literal["auto"], Literal["code"]] instructions: str class SymbolLocation(BaseModel): uri: str range_: Range = Field(..., alias="range") class Symbol(BaseModel): name: str kind: float location: SymbolLocation class FileNodeType(Enum, str): FILE = "file" DIRECTORY = "directory" class FileNode(BaseModel): name: str path: str absolute: str type_: FileNodeType = Field(..., alias="type") ignored: bool class FileContentPatchHunks(BaseModel): old_start: float = Field(..., alias="oldStart") old_lines: float = Field(..., alias="oldLines") new_start: float = Field(..., alias="newStart") new_lines: float = Field(..., alias="newLines") lines: list[str] class FileContentPatch(BaseModel): old_file_name: str = Field(..., alias="oldFileName") new_file_name: str = Field(..., alias="newFileName") old_header: Optional[str] = Field(default=None, alias="oldHeader") new_header: Optional[str] = Field(default=None, alias="newHeader") hunks: list[FileContentPatchHunks] index: Optional[str] = Field(default=None) class FileContent(BaseModel): type_: Literal["text"] = Field(..., alias="type") content: str diff: Optional[str] = Field(default=None) patch: Optional[FileContentPatch] = Field(default=None) encoding: Optional[Literal["base64"]] = Field(default=None) mime_type: Optional[str] = Field(default=None, alias="mimeType") class FileStatus(Enum, str): ADDED = "added" DELETED = "deleted" MODIFIED = "modified" class File(BaseModel): path: str added: int = Field(..., ge=-9007199254740991, le=9007199254740991) removed: int = Field(..., ge=-9007199254740991, le=9007199254740991) status: FileStatus class AgentMode(Enum, str): SUBAGENT = "subagent" PRIMARY = "primary" ALL = "all" class AgentModel(BaseModel): model_id: str = Field(..., alias="modelID") provider_id: str = Field(..., alias="providerID") class Agent(BaseModel): name: str description: Optional[str] = Field(default=None) mode: AgentMode native: Optional[bool] = Field(default=None) hidden: Optional[bool] = Field(default=None) top_p: Optional[float] = Field(default=None, alias="topP") temperature: Optional[float] = Field(default=None) color: Optional[str] = Field(default=None) permission: PermissionRuleset model: Optional[AgentModel] = Field(default=None) prompt: Optional[str] = Field(default=None) options: dict[str, Any] steps: Optional[int] = Field(default=None, gt=0, le=9007199254740991) class McpStatusConnected(BaseModel): status: Literal["connected"] class McpStatusDisabled(BaseModel): status: Literal["disabled"] class McpStatusFailed(BaseModel): status: Literal["failed"] error: str class McpStatusNeedsAuth(BaseModel): status: Literal["needs_auth"] class McpStatusNeedsClientRegistration(BaseModel): status: Literal["needs_client_registration"] error: str McpStatus: TypeAlias = Union[McpStatusConnected, McpStatusDisabled, McpStatusFailed, McpStatusNeedsAuth, McpStatusNeedsClientRegistration] class LspStatus(BaseModel): id_: str = Field(..., alias="id") name: str root: str status: Union[Literal["connected"], Literal["error"]] class FormatterStatus(BaseModel): name: str extensions: list[str] enabled: bool class OAuth(BaseModel): type_: Literal["oauth"] = Field(..., alias="type") refresh: str access: str expires: float enterprise_url: Optional[str] = Field(default=None, alias="enterpriseUrl") class ApiAuth(BaseModel): type_: Literal["api"] = Field(..., alias="type") key: str class WellKnownAuth(BaseModel): type_: Literal["wellknown"] = Field(..., alias="type") key: str token: str Auth: TypeAlias = Union[OAuth, ApiAuth, WellKnownAuth] ================================================ FILE: packages/openapi-python-tests/sdks/__snapshots__/opencode/default/sdk_gen.py ================================================ # This file is auto-generated by @hey-api/openapi-python from functools import cached_property from .client import Client class Global(Client): def health(self): """ Get health Get health information about the OpenCode server. """ return self.client.get("/global/health") def event(self): """ Get global events Subscribe to global events from the OpenCode system using server-sent events. """ return self.client.get("/global/event") def dispose(self): """ Dispose instance Clean up and dispose all OpenCode instances, releasing all resources. """ return self.client.post("/global/dispose") class Project(Client): def list(self): """ List all projects Get a list of projects that have been opened with OpenCode. """ return self.client.get("/project") def current(self): """ Get current project Retrieve the currently active project that OpenCode is working with. """ return self.client.get("/project/current") def update(self): """ Update project Update project properties such as name, icon and color. """ return self.client.patch("/project/{projectID}") class Pty(Client): def list(self): """ List PTY sessions Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode. """ return self.client.get("/pty") def create(self): """ Create PTY session Create a new pseudo-terminal (PTY) session for running shell commands and processes. """ return self.client.post("/pty") def remove(self): """ Remove PTY session Remove and terminate a specific pseudo-terminal (PTY) session. """ return self.client.delete("/pty/{ptyID}") def get(self): """ Get PTY session Retrieve detailed information about a specific pseudo-terminal (PTY) session. """ return self.client.get("/pty/{ptyID}") def update(self): """ Update PTY session Update properties of an existing pseudo-terminal (PTY) session. """ return self.client.put("/pty/{ptyID}") def connect(self): """ Connect to PTY session Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time. """ return self.client.get("/pty/{ptyID}/connect") class Config(Client): def get(self): """ Get configuration Retrieve the current OpenCode configuration settings and preferences. """ return self.client.get("/config") def update(self): """ Update configuration Update OpenCode configuration settings and preferences. """ return self.client.patch("/config") def providers(self): """ List config providers Get a list of all configured AI providers and their default models. """ return self.client.get("/config/providers") class Tool(Client): def ids(self): """ List tool IDs Get a list of all available tool IDs, including both built-in tools and dynamically registered tools. """ return self.client.get("/experimental/tool/ids") def list(self): """ List tools Get a list of available tools with their JSON schema parameters for a specific provider and model combination. """ return self.client.get("/experimental/tool") class Instance(Client): def dispose(self): """ Dispose instance Clean up and dispose the current OpenCode instance, releasing all resources. """ return self.client.post("/instance/dispose") class Path(Client): def get(self): """ Get paths Retrieve the current working directory and related path information for the OpenCode instance. """ return self.client.get("/path") class Vcs(Client): def get(self): """ Get VCS info Retrieve version control system (VCS) information for the current project, such as git branch. """ return self.client.get("/vcs") class Session(Client): def list(self): """ List sessions Get a list of all OpenCode sessions, sorted by most recently updated. """ return self.client.get("/session") def create(self): """ Create session Create a new OpenCode session for interacting with AI assistants and managing conversations. """ return self.client.post("/session") def status(self): """ Get session status Retrieve the current status of all sessions, including active, idle, and completed states. """ return self.client.get("/session/status") def delete(self): """ Delete session Delete a session and permanently remove all associated data, including messages and history. """ return self.client.delete("/session/{sessionID}") def get(self): """ Get session Retrieve detailed information about a specific OpenCode session. """ return self.client.get("/session/{sessionID}") def update(self): """ Update session Update properties of an existing session, such as title or other metadata. """ return self.client.patch("/session/{sessionID}") def children(self): """ Get session children Retrieve all child sessions that were forked from the specified parent session. """ return self.client.get("/session/{sessionID}/children") def todo(self): """ Get session todos Retrieve the todo list associated with a specific session, showing tasks and action items. """ return self.client.get("/session/{sessionID}/todo") def init(self): """ Initialize session Analyze the current application and create an AGENTS.md file with project-specific agent configurations. """ return self.client.post("/session/{sessionID}/init") def fork(self): """ Fork session Create a new session by forking an existing session at a specific message point. """ return self.client.post("/session/{sessionID}/fork") def abort(self): """ Abort session Abort an active session and stop any ongoing AI processing or command execution. """ return self.client.post("/session/{sessionID}/abort") def unshare(self): """ Unshare session Remove the shareable link for a session, making it private again. """ return self.client.delete("/session/{sessionID}/share") def share(self): """ Share session Create a shareable link for a session, allowing others to view the conversation. """ return self.client.post("/session/{sessionID}/share") def diff(self): """ Get session diff Get all file changes (diffs) made during this session. """ return self.client.get("/session/{sessionID}/diff") def summarize(self): """ Summarize session Generate a concise summary of the session using AI compaction to preserve key information. """ return self.client.post("/session/{sessionID}/summarize") def messages(self): """ Get session messages Retrieve all messages in a session, including user prompts and AI responses. """ return self.client.get("/session/{sessionID}/message") def prompt(self): """ Send message Create and send a new message to a session, streaming the AI response. """ return self.client.post("/session/{sessionID}/message") def message(self): """ Get message Retrieve a specific message from a session by its message ID. """ return self.client.get("/session/{sessionID}/message/{messageID}") def prompt_async(self): """ Send async message Create and send a new message to a session asynchronously, starting the session if needed and returning immediately. """ return self.client.post("/session/{sessionID}/prompt_async") def command(self): """ Send command Send a new command to a session for execution by the AI assistant. """ return self.client.post("/session/{sessionID}/command") def shell(self): """ Run shell command Execute a shell command within the session context and return the AI's response. """ return self.client.post("/session/{sessionID}/shell") def revert(self): """ Revert message Revert a specific message in a session, undoing its effects and restoring the previous state. """ return self.client.post("/session/{sessionID}/revert") def unrevert(self): """ Restore reverted messages Restore all previously reverted messages in a session. """ return self.client.post("/session/{sessionID}/unrevert") class Part(Client): def delete(self): """Delete a part from a message""" return self.client.delete("/session/{sessionID}/message/{messageID}/part/{partID}") def update(self): """Update a part in a message""" return self.client.patch("/session/{sessionID}/message/{messageID}/part/{partID}") class Permission(Client): def respond(self): """ Respond to permission Approve or deny a permission request from the AI assistant. Deprecated. """ return self.client.post("/session/{sessionID}/permissions/{permissionID}") def reply(self): """ Respond to permission request Approve or deny a permission request from the AI assistant. """ return self.client.post("/permission/{requestID}/reply") def list(self): """ List pending permissions Get all pending permission requests across all sessions. """ return self.client.get("/permission") class Command(Client): def list(self): """ List commands Get a list of all available commands in the OpenCode system. """ return self.client.get("/command") class Oauth(Client): def authorize(self): """ OAuth authorize Initiate OAuth authorization for a specific AI provider to get an authorization URL. """ return self.client.post("/provider/{providerID}/oauth/authorize") def callback(self): """ OAuth callback Handle the OAuth callback from a provider after user authorization. """ return self.client.post("/provider/{providerID}/oauth/callback") class Provider(Client): def list(self): """ List providers Get a list of all available AI providers, including both available and connected ones. """ return self.client.get("/provider") def auth(self): """ Get provider auth methods Retrieve available authentication methods for all AI providers. """ return self.client.get("/provider/auth") @cached_property def oauth(self) -> Oauth: return Oauth(client=self.client) class Find(Client): def text(self): """ Find text Search for text patterns across files in the project using ripgrep. """ return self.client.get("/find") def files(self): """ Find files Search for files or directories by name or pattern in the project directory. """ return self.client.get("/find/file") def symbols(self): """ Find symbols Search for workspace symbols like functions, classes, and variables using LSP. """ return self.client.get("/find/symbol") class File(Client): def list(self): """ List files List files and directories in a specified path. """ return self.client.get("/file") def read(self): """ Read file Read the content of a specified file. """ return self.client.get("/file/content") def status(self): """ Get file status Get the git status of all files in the project. """ return self.client.get("/file/status") class App(Client): def log(self): """ Write log Write a log entry to the server logs with specified level and metadata. """ return self.client.post("/log") def agents(self): """ List agents Get a list of all available AI agents in the OpenCode system. """ return self.client.get("/agent") class Auth(Client): def remove(self): """ Remove MCP OAuth Remove OAuth credentials for an MCP server """ return self.client.delete("/mcp/{name}/auth") def start(self): """ Start MCP OAuth Start OAuth authentication flow for a Model Context Protocol (MCP) server. """ return self.client.post("/mcp/{name}/auth") def callback(self): """ Complete MCP OAuth Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code. """ return self.client.post("/mcp/{name}/auth/callback") def authenticate(self): """ Authenticate MCP OAuth Start OAuth flow and wait for callback (opens browser) """ return self.client.post("/mcp/{name}/auth/authenticate") class Mcp(Client): def status(self): """ Get MCP status Get the status of all Model Context Protocol (MCP) servers. """ return self.client.get("/mcp") def add(self): """ Add MCP server Dynamically add a new Model Context Protocol (MCP) server to the system. """ return self.client.post("/mcp") def connect(self): """Connect an MCP server""" return self.client.post("/mcp/{name}/connect") def disconnect(self): """Disconnect an MCP server""" return self.client.post("/mcp/{name}/disconnect") @cached_property def auth(self) -> Auth: return Auth(client=self.client) class Lsp(Client): def status(self): """ Get LSP status Get LSP server status """ return self.client.get("/lsp") class Formatter(Client): def status(self): """ Get formatter status Get formatter status """ return self.client.get("/formatter") class Control(Client): def next(self): """ Get next TUI request Retrieve the next TUI (Terminal User Interface) request from the queue for processing. """ return self.client.get("/tui/control/next") def response(self): """ Submit TUI response Submit a response to the TUI request queue to complete a pending request. """ return self.client.post("/tui/control/response") class Tui(Client): def append_prompt(self): """ Append TUI prompt Append prompt to the TUI """ return self.client.post("/tui/append-prompt") def open_help(self): """ Open help dialog Open the help dialog in the TUI to display user assistance information. """ return self.client.post("/tui/open-help") def open_sessions(self): """ Open sessions dialog Open the session dialog """ return self.client.post("/tui/open-sessions") def open_themes(self): """ Open themes dialog Open the theme dialog """ return self.client.post("/tui/open-themes") def open_models(self): """ Open models dialog Open the model dialog """ return self.client.post("/tui/open-models") def submit_prompt(self): """ Submit TUI prompt Submit the prompt """ return self.client.post("/tui/submit-prompt") def clear_prompt(self): """ Clear TUI prompt Clear the prompt """ return self.client.post("/tui/clear-prompt") def execute_command(self): """ Execute TUI command Execute a TUI command (e.g. agent_cycle) """ return self.client.post("/tui/execute-command") def show_toast(self): """ Show TUI toast Show a toast notification in the TUI """ return self.client.post("/tui/show-toast") def publish(self): """ Publish TUI event Publish a TUI event """ return self.client.post("/tui/publish") @cached_property def control(self) -> Control: return Control(client=self.client) class Auth_2(Client): def set(self): """ Set auth credentials Set authentication credentials """ return self.client.put("/auth/{providerID}") class Event(Client): def subscribe(self): """ Subscribe to events Get events """ return self.client.get("/event") class Sdk(Client): @cached_property def global_(self) -> Global: return Global(client=self.client) @cached_property def project(self) -> Project: return Project(client=self.client) @cached_property def pty(self) -> Pty: return Pty(client=self.client) @cached_property def config(self) -> Config: return Config(client=self.client) @cached_property def tool(self) -> Tool: return Tool(client=self.client) @cached_property def instance(self) -> Instance: return Instance(client=self.client) @cached_property def path(self) -> Path: return Path(client=self.client) @cached_property def vcs(self) -> Vcs: return Vcs(client=self.client) @cached_property def session(self) -> Session: return Session(client=self.client) @cached_property def part(self) -> Part: return Part(client=self.client) @cached_property def permission(self) -> Permission: return Permission(client=self.client) @cached_property def command(self) -> Command: return Command(client=self.client) @cached_property def provider(self) -> Provider: return Provider(client=self.client) @cached_property def find(self) -> Find: return Find(client=self.client) @cached_property def file(self) -> File: return File(client=self.client) @cached_property def app(self) -> App: return App(client=self.client) @cached_property def mcp(self) -> Mcp: return Mcp(client=self.client) @cached_property def lsp(self) -> Lsp: return Lsp(client=self.client) @cached_property def formatter(self) -> Formatter: return Formatter(client=self.client) @cached_property def tui(self) -> Tui: return Tui(client=self.client) @cached_property def auth(self) -> Auth_2: return Auth_2(client=self.client) @cached_property def event(self) -> Event: return Event(client=self.client) ================================================ FILE: packages/openapi-python-tests/sdks/package.json ================================================ { "name": "@test/openapi-python-sdks", "version": "0.0.0", "private": true, "type": "module", "devDependencies": { "@hey-api/openapi-python": "workspace:*", "typescript": "5.9.3" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-python-tests/sdks/test/opencode.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-python'; import { getFilePaths, getSpecsPath } from '../../utils'; import { createSdkConfig, getSnapshotsPath, getTempSnapshotsPath } from './utils'; const namespace = 'opencode'; const outputDir = path.join(getTempSnapshotsPath(), namespace); const snapshotsDir = path.join(getSnapshotsPath(), namespace); const specPath = path.join(getSpecsPath(), '3.1.x', 'opencode.yaml'); describe(`Python SDK: ${namespace}`, () => { const createConfig = createSdkConfig({ outputDir, }); const scenarios = [ { config: createConfig({ input: specPath, output: 'default', plugins: ['@hey-api/python-sdk'], }), description: 'default', }, ]; it.each(scenarios)( '$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths( typeof config.output === 'string' ? config.output : config.output.path, ); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }, 15_000, ); }); ================================================ FILE: packages/openapi-python-tests/sdks/test/utils.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { type UserConfig } from '@hey-api/openapi-python'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export const createSdkConfig = ({ outputDir }: { outputDir: string }) => (userConfig: UserConfig) => ({ ...userConfig, logs: { level: 'silent', path: './logs', }, output: typeof userConfig.output === 'string' ? path.join(outputDir, userConfig.output) : { ...userConfig.output, path: path.join( outputDir, userConfig.output instanceof Array ? '' : userConfig.output.path, ), }, }) as const satisfies UserConfig; export const getSnapshotsPath = (): string => path.join(__dirname, '..', '__snapshots__'); export const getTempSnapshotsPath = (): string => path.join(__dirname, '..', '.gen', 'snapshots'); ================================================ FILE: packages/openapi-python-tests/sdks/tsconfig.json ================================================ { "extends": "../tsconfig.base.json", "include": ["test/**/*"], "exclude": [".gen/**/*"], "references": [{ "path": "../../openapi-python" }] } ================================================ FILE: packages/openapi-python-tests/sdks/turbo.json ================================================ { "$schema": "../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-python-tests/sdks/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-python-tests/tsconfig.base.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "declaration": false, "declarationMap": false, "noEmit": true, "noImplicitOverride": true, "noImplicitReturns": true, "noUnusedLocals": true, "noUnusedParameters": true, "types": ["vitest/globals"], "useUnknownInCatchVariables": false } } ================================================ FILE: packages/openapi-python-tests/utils.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; export const getFilePaths = (dirPath: string): Array => { let filePaths: Array = []; const files = fs.readdirSync(dirPath); for (const file of files) { const filePath = path.join(dirPath, file); const stat = fs.statSync(filePath); if (stat.isDirectory()) { filePaths = filePaths.concat(getFilePaths(filePath)); } else { filePaths.push(filePath); } } return filePaths; }; export const getSpecsPath = (): string => path.join(__dirname, '..', '..', 'specs'); ================================================ FILE: packages/openapi-ts/.gitignore ================================================ .DS_Store .idea .tsdown .tmp junit.xml logs node_modules npm-debug.log* temp *.iml dist coverage .env ================================================ FILE: packages/openapi-ts/CHANGELOG.md ================================================ # @hey-api/openapi-ts ## 0.94.4 ### Patch Changes - **plugin(orpc)**: initial release ([#3264](https://github.com/hey-api/openapi-ts/pull/3264)) ([`8e1e62d`](https://github.com/hey-api/openapi-ts/commit/8e1e62dbf88590542ac8bdf3584f9be881ea25fc)) by [@hyoban](https://github.com/hyoban) ## 0.94.3 ### Patch Changes - **output**: pass context as second argument in `module.resolve()` function ([#3615](https://github.com/hey-api/openapi-ts/pull/3615)) ([`b6a65d6`](https://github.com/hey-api/openapi-ts/commit/b6a65d6bb3ff1895f2189af858e3424733154bdf)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/client-nuxt)**: preserve AbortSignal, FormData, and ReadableStream in unwrapRefs ([#3614](https://github.com/hey-api/openapi-ts/pull/3614)) ([`129afa0`](https://github.com/hey-api/openapi-ts/commit/129afa052b61d71fe4d0d7f5568b4ea38dead44c)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: fix: self-referencing discriminator ([#3601](https://github.com/hey-api/openapi-ts/pull/3601)) ([`857eb19`](https://github.com/hey-api/openapi-ts/commit/857eb1983fa1ab0f048d426a31835ede563a2c00)) by [@pgraug](https://github.com/pgraug) - **output**: add `module` option ([#3616](https://github.com/hey-api/openapi-ts/pull/3616)) ([`e4eea23`](https://github.com/hey-api/openapi-ts/commit/e4eea23ab23fb704dfdb9aaad63989be34d5093c)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/transformers)**: expose `plugin` and `$` in transformer function context ([#3610](https://github.com/hey-api/openapi-ts/pull/3610)) ([`18ccc81`](https://github.com/hey-api/openapi-ts/commit/18ccc81ae75718157949c9724d86d6225f0c0eb0)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/shared@0.2.5 - @hey-api/codegen-core@0.7.4 ## 0.94.2 ### Patch Changes - **internal**: export Plugins namespace ([#3586](https://github.com/hey-api/openapi-ts/pull/3586)) ([`12827e3`](https://github.com/hey-api/openapi-ts/commit/12827e333b9c1b810607c8a948ab3a909a920678)) by [@mrlubos](https://github.com/mrlubos) - **plugin(nestjs)**: initial release ([#3573](https://github.com/hey-api/openapi-ts/pull/3573)) ([`e596edb`](https://github.com/hey-api/openapi-ts/commit/e596edbe799e51c21783239bfb524c7342df365b)) by [@mikhin](https://github.com/mikhin) - **internal**: expand TypeScript peer dependency range ([#3588](https://github.com/hey-api/openapi-ts/pull/3588)) ([`ae5ecc9`](https://github.com/hey-api/openapi-ts/commit/ae5ecc943f41c19bdc77a477c00b68ceb8ab3d52)) by [@mrlubos](https://github.com/mrlubos) - **output**: pass default value to `header` function ([#3585](https://github.com/hey-api/openapi-ts/pull/3585)) ([`c076e4d`](https://github.com/hey-api/openapi-ts/commit/c076e4d3e9697d8bbc72db13a31d44627c814c2d)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/shared@0.2.4 - @hey-api/codegen-core@0.7.3 - @hey-api/types@0.1.4 ## 0.94.1 ### Patch Changes - **plugin(@hey-api/typescript)**: add Resolvers API ([#3531](https://github.com/hey-api/openapi-ts/pull/3531)) ([`0e47fcb`](https://github.com/hey-api/openapi-ts/commit/0e47fcbf87560f1d59b74d01c704a0e42648febb)) by [@mrlubos](https://github.com/mrlubos) - **dsl**: expand list of JavaScript globals ([#3508](https://github.com/hey-api/openapi-ts/pull/3508)) ([`1e00a69`](https://github.com/hey-api/openapi-ts/commit/1e00a6983eaa56acaf98663310fb9e3122d1d575)) by [@mrlubos](https://github.com/mrlubos) - **plugin(valibot)**: provide more resolvers ([#3547](https://github.com/hey-api/openapi-ts/pull/3547)) ([`854ee1c`](https://github.com/hey-api/openapi-ts/commit/854ee1cbdf322f7c3f02441d02eeb4b0dbe747aa)) by [@mrlubos](https://github.com/mrlubos) - **cli**: show environment value in development ([#3546](https://github.com/hey-api/openapi-ts/pull/3546)) ([`571bc8a`](https://github.com/hey-api/openapi-ts/commit/571bc8a32b55647083bb506d4a5b575c4736cb94)) by [@mrlubos](https://github.com/mrlubos) - **plugin(zod)**: handle `guid` string format ([#3552](https://github.com/hey-api/openapi-ts/pull/3552)) ([`7acb228`](https://github.com/hey-api/openapi-ts/commit/7acb228c7c4e1dd5d7b70ee576a007ee1c9682cd)) by [@erikwski](https://github.com/erikwski) - **plugin(@hey-api/typescript)**: implement `getName()` symbol hook ([#3556](https://github.com/hey-api/openapi-ts/pull/3556)) ([`68c750a`](https://github.com/hey-api/openapi-ts/commit/68c750ab7ad37c71c4f9b267ddc9e1c90c89924a)) by [@mrlubos](https://github.com/mrlubos) - **plugin(zod)**: implement `getName()` symbol hook ([#3556](https://github.com/hey-api/openapi-ts/pull/3556)) ([`68c750a`](https://github.com/hey-api/openapi-ts/commit/68c750ab7ad37c71c4f9b267ddc9e1c90c89924a)) by [@mrlubos](https://github.com/mrlubos) - **config(plugins)**: show warning when plugin infer fails ([#3540](https://github.com/hey-api/openapi-ts/pull/3540)) ([`0512650`](https://github.com/hey-api/openapi-ts/commit/0512650988ce3c411492172e6bbe300f5440408f)) by [@mrlubos](https://github.com/mrlubos) - **plugin(valibot)**: implement `getName()` symbol hook ([#3556](https://github.com/hey-api/openapi-ts/pull/3556)) ([`68c750a`](https://github.com/hey-api/openapi-ts/commit/68c750ab7ad37c71c4f9b267ddc9e1c90c89924a)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/transformers)**: fix: support `anyOf` schema with null ([#3504](https://github.com/hey-api/openapi-ts/pull/3504)) ([`4b6b398`](https://github.com/hey-api/openapi-ts/commit/4b6b398c59746167b93857f6ab475a7a88ddbcd4)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(zod)**: provide more resolvers ([#3554](https://github.com/hey-api/openapi-ts/pull/3554)) ([`bfa255c`](https://github.com/hey-api/openapi-ts/commit/bfa255c0db03a869dd99cd16736acef6abe39987)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.7.2 - @hey-api/shared@0.2.3 ## 0.94.0 ### Minor Changes - **BREAKING** **client**: `buildUrl()` function includes `baseUrl` from config by default ([#3491](https://github.com/hey-api/openapi-ts/pull/3491)) ([`c0cbffb`](https://github.com/hey-api/openapi-ts/commit/c0cbffb9413c6f1cc12b41069af6ddb031401742)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ### Patch Changes - **dsl(reserved)**: expand reserved keywords with more globals ([#3487](https://github.com/hey-api/openapi-ts/pull/3487)) ([`89a9151`](https://github.com/hey-api/openapi-ts/commit/89a9151b8d456796aa861c2a015af9bc1a300eb2)) by [@mrlubos](https://github.com/mrlubos) - **parser**: fix: explicit discriminator mapping wins over fallback in nested `allOf` ([#3490](https://github.com/hey-api/openapi-ts/pull/3490)) ([`a67d589`](https://github.com/hey-api/openapi-ts/commit/a67d589e1f8e5860bd05d5caff134dd6a7eed6e2)) by [@pgraug](https://github.com/pgraug) - **plugin(@pinia/colada)**: fix: pass error type generic to `defineQueryOptions` ([#3483](https://github.com/hey-api/openapi-ts/pull/3483)) ([`8e5a578`](https://github.com/hey-api/openapi-ts/commit/8e5a57855c03a2a49f9c62398f5bdf1fa989f4de)) by [@lukaspodmelle](https://github.com/lukaspodmelle) - **plugin(@tanstack/react-query)**: support generating `useMutation` hooks ([#3432](https://github.com/hey-api/openapi-ts/pull/3432)) ([`12d7660`](https://github.com/hey-api/openapi-ts/commit/12d76605e3dfb4204f9971dff7254be69c0a7359)) by [@nmokkenstorm](https://github.com/nmokkenstorm) - **plugin(typescript)**: fix: reference enum object when creating enum types ([#3500](https://github.com/hey-api/openapi-ts/pull/3500)) ([`127e67b`](https://github.com/hey-api/openapi-ts/commit/127e67b9b761889751e25d95fe5900508e6fd151)) by [@mrlubos](https://github.com/mrlubos) - **output(header)**: fix: support function signature in client and core files ([#3486](https://github.com/hey-api/openapi-ts/pull/3486)) ([`942913a`](https://github.com/hey-api/openapi-ts/commit/942913af15ae10c5fc3c5e456800829b7dd9c10a)) by [@mrlubos](https://github.com/mrlubos) - **output**: fix: avoid double sanitizing leading character ([#3448](https://github.com/hey-api/openapi-ts/pull/3448)) ([`c50f7bc`](https://github.com/hey-api/openapi-ts/commit/c50f7bcf5676f2783a412288d243aeaeabd9f8bd)) by [@mrlubos](https://github.com/mrlubos) - **internal**: fix: simplify dev mode check ([#3498](https://github.com/hey-api/openapi-ts/pull/3498)) ([`ea2538b`](https://github.com/hey-api/openapi-ts/commit/ea2538b221605ee1ba900d173394cd4f0aab8b12)) by [@mrlubos](https://github.com/mrlubos) - **plugin(zod)**: support function in `metadata` option ([#3497](https://github.com/hey-api/openapi-ts/pull/3497)) ([`1ed39bc`](https://github.com/hey-api/openapi-ts/commit/1ed39bc3ed713edd7ecdcc997fac1c7487b07105)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(valibot)**: support function in `metadata` option ([#3497](https://github.com/hey-api/openapi-ts/pull/3497)) ([`202cc05`](https://github.com/hey-api/openapi-ts/commit/202cc054a7221d8ea7b63881785d314104ab01d2)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **internal**: log symbol meta if name is falsy ([#3448](https://github.com/hey-api/openapi-ts/pull/3448)) ([`c50f7bc`](https://github.com/hey-api/openapi-ts/commit/c50f7bcf5676f2783a412288d243aeaeabd9f8bd)) by [@mrlubos](https://github.com/mrlubos) - **client**: fix: change serializer types from `any` to `unknown` ([#3471](https://github.com/hey-api/openapi-ts/pull/3471)) ([`ad11be2`](https://github.com/hey-api/openapi-ts/commit/ad11be241c494d23930ce8f76e57eb7afa631c67)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@tanstack/preact-query)**: initial release ([#3499](https://github.com/hey-api/openapi-ts/pull/3499)) ([`873839e`](https://github.com/hey-api/openapi-ts/commit/873839e065a7919fcf736348c15238bd3b6c3d15)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/shared@0.2.2 - @hey-api/codegen-core@0.7.1 ## 0.93.1 ### Patch Changes - **plugin(@tanstack/query)**: fix: skip mutation queries for SSE endpoints ([#3470](https://github.com/hey-api/openapi-ts/pull/3470)) ([`3ca4f31`](https://github.com/hey-api/openapi-ts/commit/3ca4f317e422bb58345cb794faf979e26f10d127)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **client**: fix: avoid removing empty arrays from flat arguments ([#3451](https://github.com/hey-api/openapi-ts/pull/3451)) ([`1518fda`](https://github.com/hey-api/openapi-ts/commit/1518fda8372b5fb27085f4b296a77b922c340885)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(zod)**: fix: apply nullable modifier to `additionalProperties` schema ([#3452](https://github.com/hey-api/openapi-ts/pull/3452)) ([`2e903af`](https://github.com/hey-api/openapi-ts/commit/2e903af5d09881949b042bbd9aba516f3237764d)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **cli**: fix: do not set `logs.file` to `true` by default ([#3469](https://github.com/hey-api/openapi-ts/pull/3469)) ([`9e3d347`](https://github.com/hey-api/openapi-ts/commit/9e3d347d4b7a36c9d04b2f9c2d4988ece03677d8)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/sdk)**: fix: correctly set required flat parameters ([#3458](https://github.com/hey-api/openapi-ts/pull/3458)) ([`bf50a55`](https://github.com/hey-api/openapi-ts/commit/bf50a559670311a866ff8b104c169ef7619fb202)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(zod)**: add `u` flag on regex patterns with unicode property escapes ([#3468](https://github.com/hey-api/openapi-ts/pull/3468)) ([`67ad86a`](https://github.com/hey-api/openapi-ts/commit/67ad86a7e37a16125fc5a26eaad5859de43ccac3)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(valibot)**: add `u` flag on regex patterns with unicode property escapes ([#3468](https://github.com/hey-api/openapi-ts/pull/3468)) ([`003d914`](https://github.com/hey-api/openapi-ts/commit/003d91422cc831de782015c640b9bcbce9f17dd9)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/typescript)**: simplify union types if a member is `unknown` ([#3454](https://github.com/hey-api/openapi-ts/pull/3454)) ([`96d87df`](https://github.com/hey-api/openapi-ts/commit/96d87df7cf49bd1e8ce2dc196fcacc57270e4954)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **client(@hey-api/nuxt)**: fix: do not unwrap blob values ([#3459](https://github.com/hey-api/openapi-ts/pull/3459)) ([`b7233d1`](https://github.com/hey-api/openapi-ts/commit/b7233d1d3cc5de84b02c9dc8a27c3cb84235d752)) by [@LeiCraft](https://github.com/LeiCraft) - **client**: support async `createClientConfig` ([#3445](https://github.com/hey-api/openapi-ts/pull/3445)) ([`cd33d86`](https://github.com/hey-api/openapi-ts/commit/cd33d867857fbe9b4daf3c164f892d89946c4beb)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.93.0 ### Minor Changes - **plugin(valibot)**: remove `enum.nodes.nullable` resolver node ([#3396](https://github.com/hey-api/openapi-ts/pull/3396)) ([`ea6f386`](https://github.com/hey-api/openapi-ts/commit/ea6f3865c8e381b3160e1526435c4522f0dc6aa4)) by [@mrlubos](https://github.com/mrlubos) ### Removed resolver node Valibot plugin no longer exposes the `enum.nodes.nullable` node. It was refactored so that nullable values are handled outside of resolvers. - **plugin(zod)**: remove `enum.nodes.nullable` resolver node ([#3398](https://github.com/hey-api/openapi-ts/pull/3398)) ([`737730c`](https://github.com/hey-api/openapi-ts/commit/737730c9c6450c60a81a8949259336e790e9b4f4)) by [@mrlubos](https://github.com/mrlubos) ### Removed resolver node Zod plugin no longer exposes the `enum.nodes.nullable` node. It was refactored so that nullable values are handled outside of resolvers. ### Patch Changes - **parser**: prefer unprefixed schema names from external files ([#3417](https://github.com/hey-api/openapi-ts/pull/3417)) ([`f3a264b`](https://github.com/hey-api/openapi-ts/commit/f3a264b2c5d7af06bb44fa0350ef613bde3aff87)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser(patch)**: support callback for `patch.schemas` ([#3415](https://github.com/hey-api/openapi-ts/pull/3415)) ([`e494f4d`](https://github.com/hey-api/openapi-ts/commit/e494f4dd828167a0096a0a488b222a013f911055)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **output**: fix: apply `output.header` to bundled files ([#3438](https://github.com/hey-api/openapi-ts/pull/3438)) ([`bcd0a87`](https://github.com/hey-api/openapi-ts/commit/bcd0a87cdd366cef572eb920b59c115ae65f67bb)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: handle OpenAPI 3.1 `contentMediaType` keyword as binary format when file-like ([#3431](https://github.com/hey-api/openapi-ts/pull/3431)) ([`d6a8538`](https://github.com/hey-api/openapi-ts/commit/d6a85381e3c52b4fd1c4af43ee57506459db7a45)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **input**: fix: improve returned status code when spec fetch fails ([#3427](https://github.com/hey-api/openapi-ts/pull/3427)) ([`37dd92c`](https://github.com/hey-api/openapi-ts/commit/37dd92c6629511860ae434c64ac8af9154ed6aed)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **client**: expose `onRequest` in RequestOptions for SSE request interception ([#3392](https://github.com/hey-api/openapi-ts/pull/3392)) ([`8fc4681`](https://github.com/hey-api/openapi-ts/commit/8fc46819d5df1d4a353be5ae7cd45a8c669a5d7e)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: add `patch.input` and shorthand `patch()` option for full specification transformations ([#3411](https://github.com/hey-api/openapi-ts/pull/3411)) ([`ba9f893`](https://github.com/hey-api/openapi-ts/commit/ba9f893d71b959721e177717ae85fce34d697002)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: fix: preserve `unevaluatedProperties` keyword in transforms ([#3435](https://github.com/hey-api/openapi-ts/pull/3435)) ([`f659b38`](https://github.com/hey-api/openapi-ts/commit/f659b38701795d2c2b61c8d3f5c43af93893481a)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(zod)**: use `.nullable()` and `.nullish()` methods ([#3398](https://github.com/hey-api/openapi-ts/pull/3398)) ([`737730c`](https://github.com/hey-api/openapi-ts/commit/737730c9c6450c60a81a8949259336e790e9b4f4)) by [@mrlubos](https://github.com/mrlubos) - **parser**: fix: resolve sibling schemas from external files during bundling ([#3422](https://github.com/hey-api/openapi-ts/pull/3422)) ([`19fd80a`](https://github.com/hey-api/openapi-ts/commit/19fd80aff26b1198d6838d48357702c39ad05501)) by [@j-westover](https://github.com/j-westover) - **parser(transforms)**: add `schemaName` transform ([#3416](https://github.com/hey-api/openapi-ts/pull/3416)) ([`4b9d032`](https://github.com/hey-api/openapi-ts/commit/4b9d032c6a144fa79cedc28e077782b9d67803a3)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(valibot)**: use `.nullable()` and `.nullish()` methods ([#3396](https://github.com/hey-api/openapi-ts/pull/3396)) ([`ea6f386`](https://github.com/hey-api/openapi-ts/commit/ea6f3865c8e381b3160e1526435c4522f0dc6aa4)) by [@mrlubos](https://github.com/mrlubos) - **input**: fix: avoid prefixing sources if paths do not collide on operations ([#3436](https://github.com/hey-api/openapi-ts/pull/3436)) ([`b1a419a`](https://github.com/hey-api/openapi-ts/commit/b1a419a835c312a1f8bf36a5b781109368041220)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser(patch)**: support callback for `patch.operations` ([#3420](https://github.com/hey-api/openapi-ts/pull/3420)) ([`e1cd970`](https://github.com/hey-api/openapi-ts/commit/e1cd970e4f3028b29ace44a58b2d2cae18a6c45f)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: add support for non-string discriminator property types ([#3385](https://github.com/hey-api/openapi-ts/pull/3385)) ([`dd0be9c`](https://github.com/hey-api/openapi-ts/commit/dd0be9c6ca93552c3367ca8e8ba785381295a112)) by [@SipanP](https://github.com/SipanP) ### Updated Dependencies: - @hey-api/shared@0.2.1 - @hey-api/json-schema-ref-parser@1.3.1 ## 0.92.4 ### Patch Changes - **plugin(@hey-api/transformers)**: fix: false positive warning for discriminated `oneOf` schemas ([#3379](https://github.com/hey-api/openapi-ts/pull/3379)) ([`1f7c262`](https://github.com/hey-api/openapi-ts/commit/1f7c262f17b45093ae19d060ae26270c91b3ad41)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/client-nuxt)**: fix: forward `asyncDataOptions` to `useFetch` and `useLazyFetch` ([#3382](https://github.com/hey-api/openapi-ts/pull/3382)) ([`a4b7399`](https://github.com/hey-api/openapi-ts/commit/a4b73998e1985f236aee1bbe76611e8d3413f4c6)) by [@rigtigeEmil](https://github.com/rigtigeEmil) - **output**: detect `importFileExtension` from tsconfig `module` option ([#3380](https://github.com/hey-api/openapi-ts/pull/3380)) ([`4cbc307`](https://github.com/hey-api/openapi-ts/commit/4cbc307862e4357a42afe8fb595036f86279babd)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/typescript)**: fix: deduplicate enum keys to avoid name collision ([#3376](https://github.com/hey-api/openapi-ts/pull/3376)) ([`54138b6`](https://github.com/hey-api/openapi-ts/commit/54138b6771618d464f3b930fdf7af23290c00076)) by [@spikesagal](https://github.com/spikesagal) - **plugin(@hey-api/client-nuxt)**: unwrap `ComputedRef` body before initial serialization ([#3361](https://github.com/hey-api/openapi-ts/pull/3361)) ([`ca52649`](https://github.com/hey-api/openapi-ts/commit/ca52649a2f479478cc2842677c21c1bcfac69160)) by [@rigtigeEmil](https://github.com/rigtigeEmil) - **plugin(@angular/common)**: use generics for HttpRequests ([#3384](https://github.com/hey-api/openapi-ts/pull/3384)) ([`a94f50f`](https://github.com/hey-api/openapi-ts/commit/a94f50fef84f2387b9ca686ff47370030007e7a2)) by [@quartepie](https://github.com/quartepie) - **plugin(@hey-api/transformers)**: fix: handle `$ref` keywords in `allOf` compositions ([#3374](https://github.com/hey-api/openapi-ts/pull/3374)) ([`4b781aa`](https://github.com/hey-api/openapi-ts/commit/4b781aa18bc9f5bfde302c0359bfe9f3ad3effa7)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **internal**: use shared schema processor ([#3370](https://github.com/hey-api/openapi-ts/pull/3370)) ([`27cd91f`](https://github.com/hey-api/openapi-ts/commit/27cd91f530bd77da6ea95df1704b2947917b4626)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/shared@0.2.0 - @hey-api/json-schema-ref-parser@1.3.0 ## 0.92.3 ### Patch Changes - **plugin(zod)**: use namespace import for zod v4 ([#3325](https://github.com/hey-api/openapi-ts/pull/3325)) ([`e54db3e`](https://github.com/hey-api/openapi-ts/commit/e54db3e7e34e86c17d5c1fba90d9df9778c4b32d)) by [@mrlubos](https://github.com/mrlubos) ## 0.92.2 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.1.2 - @hey-api/codegen-core@0.7.0 ## 0.92.1 ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.1.2 - @hey-api/codegen-core@0.7.0 ## 0.92.0 ### Minor Changes - **BREAKING:** **symbol**: replace `exportFrom` array with `getExportFromFilePath()` function ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) ### Updated Symbol interface The `exportFrom` property has been replaced with the `getExportFromFilePath()` function. This allows you to dynamically determine export paths based on symbol properties. This is a low-level feature, so you're most likely unaffected. ### Patch Changes - **config**: rename `exportFromIndex` option to `includeInEntry` ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) - **config**: `includeInEntry` accepts function in addition to primitive value ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) - **parser**: add `getExportFromFilePath()` hook ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) - **plugin**: add `comments` option to all plugins ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) - **types**: improve `defineConfig()` types ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) - **config**: rename `output.indexFile` to `output.entryFile` ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) - **fix**: improve dev mode detection causing builds to fail ([#3318](https://github.com/hey-api/openapi-ts/pull/3318)) ([`fefa70e`](https://github.com/hey-api/openapi-ts/commit/fefa70e6810a539607441535289e98c69a604c0d)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/shared@0.1.2 - @hey-api/codegen-core@0.7.0 ## 0.91.1 ### Patch Changes ### Updated Dependencies: - @hey-api/codegen-core@0.6.1 - @hey-api/shared@0.1.1 ## 0.91.0 ### Minor Changes - **BREAKING**: Drop CommonJS (CJS) support. This package is now **ESM-only**. ([#3251](https://github.com/hey-api/openapi-ts/pull/3251)) ([`7f19d59`](https://github.com/hey-api/openapi-ts/commit/7f19d5921dadfa96ecae84a5298b7aee1daee56d)) by [@mrlubos](https://github.com/mrlubos) ### Removed CommonJS (CJS) support `@hey-api/openapi-ts` is now ESM-only. This change simplifies the codebase, improves tree-shaking, and enables better integration with modern bundlers and TypeScript tooling. CommonJS entry points (`require()`, `module.exports`) are no longer supported. If you are in a CJS environment, you can still load the package dynamically using `import()` like: ```js const { defineConfig } = await import("@hey-api/openapi-ts"); ``` If you have previously written: ```js const { defineConfig } = require("@hey-api/openapi-ts"); ``` Migrate by updating your static imports: ```js import { defineConfig } from "@hey-api/openapi-ts"; ``` If your environment cannot use ESM, pin to a previous version. ### Patch Changes ### Updated Dependencies: - @hey-api/shared@0.1.0 - @hey-api/codegen-core@0.6.0 - @hey-api/types@0.1.3 ## 0.90.10 ### Patch Changes - **plugin(@tanstack/solid-query)**: index mutation options symbol ([#3253](https://github.com/hey-api/openapi-ts/pull/3253)) ([`c5f379e`](https://github.com/hey-api/openapi-ts/commit/c5f379ea5534272d63a423c671427ff1ef13197a)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@tanstack/svelte-query)**: index mutation options symbol ([#3253](https://github.com/hey-api/openapi-ts/pull/3253)) ([`c5f379e`](https://github.com/hey-api/openapi-ts/commit/c5f379ea5534272d63a423c671427ff1ef13197a)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@tanstack/vue-query)**: index mutation options symbol ([#3253](https://github.com/hey-api/openapi-ts/pull/3253)) ([`c5f379e`](https://github.com/hey-api/openapi-ts/commit/c5f379ea5534272d63a423c671427ff1ef13197a)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@tanstack/react-query)**: index mutation options symbol ([#3253](https://github.com/hey-api/openapi-ts/pull/3253)) ([`c5f379e`](https://github.com/hey-api/openapi-ts/commit/c5f379ea5534272d63a423c671427ff1ef13197a)) by [@mrlubos](https://github.com/mrlubos) - **parser**: inline deep path `$ref` references ([#3242](https://github.com/hey-api/openapi-ts/pull/3242)) ([`00cfaed`](https://github.com/hey-api/openapi-ts/commit/00cfaed32a3b1d2a7bbd5c4c2a946a9f7be262b2)) by [@chrg1001](https://github.com/chrg1001) - **plugin(@tanstack/angular-query-experimental)**: index mutation options symbol ([#3249](https://github.com/hey-api/openapi-ts/pull/3249)) ([`5977f56`](https://github.com/hey-api/openapi-ts/commit/5977f56362351a9e4f1e9715c141a8e37130a4bb)) by [@j-ibarra](https://github.com/j-ibarra) - **plugin(@hey-api/sdk)**: correctly map body keys in flat mode ([#3255](https://github.com/hey-api/openapi-ts/pull/3255)) ([`9ca5471`](https://github.com/hey-api/openapi-ts/commit/9ca547168c7a89acb0523bd05a5ee24aee7d8638)) by [@jsjames](https://github.com/jsjames) ## 0.90.9 ### Patch Changes - **ts-dsl**: allow removing object properties by passing `null` ([#3247](https://github.com/hey-api/openapi-ts/pull/3247)) ([`7be1561`](https://github.com/hey-api/openapi-ts/commit/7be1561a862d2bb217703003d5e6cbc4a6a09586)) by [@mrlubos](https://github.com/mrlubos) - **cli**: clean up interface ([#3244](https://github.com/hey-api/openapi-ts/pull/3244)) ([`4f52bce`](https://github.com/hey-api/openapi-ts/commit/4f52bce79d8ac6573472f32a05b7f70913b90605)) by [@mrlubos](https://github.com/mrlubos) - **ts-dsl**: override object properties when called multiple times with the same name ([#3247](https://github.com/hey-api/openapi-ts/pull/3247)) ([`7be1561`](https://github.com/hey-api/openapi-ts/commit/7be1561a862d2bb217703003d5e6cbc4a6a09586)) by [@mrlubos](https://github.com/mrlubos) - **config**: move `loadConfigFile` function to `@hey-api/codegen-core` ([#3244](https://github.com/hey-api/openapi-ts/pull/3244)) ([`4f52bce`](https://github.com/hey-api/openapi-ts/commit/4f52bce79d8ac6573472f32a05b7f70913b90605)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/types@0.1.2 - @hey-api/codegen-core@0.5.5 ## 0.90.8 ### Patch Changes - **internal**: move logger to codegen-core ([#3235](https://github.com/hey-api/openapi-ts/pull/3235)) ([`88532f0`](https://github.com/hey-api/openapi-ts/commit/88532f01200e1111818e82a4af7bd5cf8cf26e3b)) by [@mrlubos](https://github.com/mrlubos) - **cli**: do not show ascii logo on generate command ([#3238](https://github.com/hey-api/openapi-ts/pull/3238)) ([`72e17f3`](https://github.com/hey-api/openapi-ts/commit/72e17f39d6e2d00eff24671e7f2b88801443489a)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.5.4 ## 0.90.7 ### Patch Changes - **deps**: move @hey-api/types to dependencies to fix broken types ([#3232](https://github.com/hey-api/openapi-ts/pull/3232)) ([`edfce48`](https://github.com/hey-api/openapi-ts/commit/edfce4875cb9279d3ab8bfd438ff177e8ba7845c)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.5.3 ## 0.90.6 ### Patch Changes - **plugin(@hey-api/sdk)**: do not warn on mutualTLS security schemes ([#3227](https://github.com/hey-api/openapi-ts/pull/3227)) ([`384e52f`](https://github.com/hey-api/openapi-ts/commit/384e52fdc06c99872b4ad5551acf8bcad616e024)) by [@mrlubos](https://github.com/mrlubos) ## 0.90.5 ### Patch Changes - **plugin(@hey-api/sdk)**: do not warn on mutualTLS security schemes ([#3218](https://github.com/hey-api/openapi-ts/pull/3218)) ([`97c0a2e`](https://github.com/hey-api/openapi-ts/commit/97c0a2ec60490f135f4ad438108e36a4229d2c35)) by [@mrlubos](https://github.com/mrlubos) ## 0.90.4 ### Patch Changes - **plugin(@hey-api/client-next)**: fix: JSON parsing error on empty response bodies without Content-Length header ([#3201](https://github.com/hey-api/openapi-ts/pull/3201)) ([`8428ca5`](https://github.com/hey-api/openapi-ts/commit/8428ca5152c66d393bcfee9570a6c1d7ad1155c7)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/client-fetch)**: fix: JSON parsing error on empty response bodies without Content-Length header ([#3201](https://github.com/hey-api/openapi-ts/pull/3201)) ([`2af4d9a`](https://github.com/hey-api/openapi-ts/commit/2af4d9ab56293c042459e6ae31787cd628be6037)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/client-ky)**: fix: JSON parsing error on empty response bodies without Content-Length header ([#3201](https://github.com/hey-api/openapi-ts/pull/3201)) ([`c0563fb`](https://github.com/hey-api/openapi-ts/commit/c0563fbd0f0ec66d25e5316bda0274380ac26639)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(valibot)**: add `enum` resolver ([#3209](https://github.com/hey-api/openapi-ts/pull/3209)) ([`f6723eb`](https://github.com/hey-api/openapi-ts/commit/f6723eb59cba4b2c2ffbdbddce3fc26d668e2d4a)) by [@thyming](https://github.com/thyming) - **plugin(zod)**: add `enum` resolver ([#3209](https://github.com/hey-api/openapi-ts/pull/3209)) ([`57334d8`](https://github.com/hey-api/openapi-ts/commit/57334d8c9c83169773a626193ca4c661b3957d37)) by [@thyming](https://github.com/thyming) ## 0.90.3 ### Patch Changes - **output**: add `oxfmt` preset ([#3197](https://github.com/hey-api/openapi-ts/pull/3197)) ([`701a69c`](https://github.com/hey-api/openapi-ts/commit/701a69cae24d3068235d80561e2cf9d18d7ccac9)) by [@mrlubos](https://github.com/mrlubos) ## 0.90.2 ### Patch Changes - **build**: do not minify bundles for better code readability and debugging ([#3186](https://github.com/hey-api/openapi-ts/pull/3186)) ([`4d46130`](https://github.com/hey-api/openapi-ts/commit/4d46130b53d9d8d5d3c178343a1b4fc3645b2628)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/sdk)**: fix: do not use bodySerializer if format is binary ([#3190](https://github.com/hey-api/openapi-ts/pull/3190)) ([`dc28c4c`](https://github.com/hey-api/openapi-ts/commit/dc28c4c6504724104bdef01332b9e3eb52ba3333)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.5.2 ## 0.90.1 ### Patch Changes - **plugin(@hey-api/sdk)**: add `examples` option ([#3175](https://github.com/hey-api/openapi-ts/pull/3175)) ([`b985053`](https://github.com/hey-api/openapi-ts/commit/b985053ffa64accc4ff01b7c0f301bb5cd84ff48)) by [@mrlubos](https://github.com/mrlubos) The SDK plugin can generate ready-to-use code examples for each operation, showing how to call the SDK methods with proper parameters and setup. Learn how to generate examples on the [SDK plugin](https://heyapi.dev/openapi-ts/plugins/sdk#code-examples) page. - **output**: add `source` option ([#3175](https://github.com/hey-api/openapi-ts/pull/3175)) ([`b985053`](https://github.com/hey-api/openapi-ts/commit/b985053ffa64accc4ff01b7c0f301bb5cd84ff48)) by [@mrlubos](https://github.com/mrlubos) Source is a copy of the input specification used to generate your output. It can be used to power documentation tools or to persist a stable snapshot alongside your generated files. Learn how to use the source on the [Output](https://heyapi.dev/openapi-ts/configuration/output#source) page. ### Updated Dependencies: - @hey-api/codegen-core@0.5.1 ## 0.90.0 ### Minor Changes - **plugin(valibot)**: **BREAKING:** standardize `~resolvers` API ([#3147](https://github.com/hey-api/openapi-ts/pull/3147)) ([`ab80a4b`](https://github.com/hey-api/openapi-ts/commit/ab80a4b2c37423c522aa864afbcb688db76615ba)) by [@mrlubos](https://github.com/mrlubos) The [Resolvers API](https://heyapi.dev/openapi-ts/plugins/concepts/resolvers) has been simplified and expanded to provide a more consistent behavior across plugins. You can view a few common examples on the [Resolvers](https://heyapi.dev/openapi-ts/plugins/concepts/resolvers) page. - **plugin(sdk)**: **BREAKING**: Structure API ([#3109](https://github.com/hey-api/openapi-ts/pull/3109)) ([`815a3de`](https://github.com/hey-api/openapi-ts/commit/815a3de0af434c28ac6d13ff92b85ce1fc146999)) by [@mrlubos](https://github.com/mrlubos) ### Structure API The [SDK plugin](https://heyapi.dev/openapi-ts/plugins/sdk) now implements the Structure API, enabling more complex structures and fixing several known issues. Some Structure APIs are incompatible with the previous configuration, most notably the `methodNameBuilder` function, which accepted the operation object as an argument. You can read the [SDK Output](https://heyapi.dev/openapi-ts/plugins/sdk#output) section to familiarize yourself with the Structure API. Please [open an issue](https://github.com/hey-api/openapi-ts/issues) if you're unable to migrate your configuration to the new syntax. - **plugin(zod)**: **BREAKING:** standardize `~resolvers` API ([#3147](https://github.com/hey-api/openapi-ts/pull/3147)) ([`ab80a4b`](https://github.com/hey-api/openapi-ts/commit/ab80a4b2c37423c522aa864afbcb688db76615ba)) by [@mrlubos](https://github.com/mrlubos) The [Resolvers API](https://heyapi.dev/openapi-ts/plugins/concepts/resolvers) has been simplified and expanded to provide a more consistent behavior across plugins. You can view a few common examples on the [Resolvers](https://heyapi.dev/openapi-ts/plugins/concepts/resolvers) page. - **plugin(@angular/common)**: **BREAKING**: Structure API ([#3109](https://github.com/hey-api/openapi-ts/pull/3109)) ([`815a3de`](https://github.com/hey-api/openapi-ts/commit/815a3de0af434c28ac6d13ff92b85ce1fc146999)) by [@mrlubos](https://github.com/mrlubos) ### Structure API The [Angular plugin](https://heyapi.dev/openapi-ts/plugins/angular) now implements the Structure API, enabling more complex structures and fixing several known issues. Some Structure APIs are incompatible with the previous configuration, most notably the `methodNameBuilder` function, which accepted the operation object as an argument. You can read the [SDK Output](https://heyapi.dev/openapi-ts/plugins/sdk#output) section to familiarize yourself with the Structure API. Please [open an issue](https://github.com/hey-api/openapi-ts/issues) if you're unable to migrate your configuration to the new syntax. ### Patch Changes - **plugin(@hey-api/client-nuxt)**: use serialized body in SSE requests ([#3123](https://github.com/hey-api/openapi-ts/pull/3123)) ([`6505659`](https://github.com/hey-api/openapi-ts/commit/6505659a5b776d03e943582e700a718eddcc2912)) by [@bilby91](https://github.com/bilby91) - **plugin(zod)**: expand support for bigint types ([#3145](https://github.com/hey-api/openapi-ts/pull/3145)) ([`4a32dcf`](https://github.com/hey-api/openapi-ts/commit/4a32dcfae503e76db81fa21ca71c71f20ea28c34)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/client-angular)**: use serialized body in SSE requests ([#3171](https://github.com/hey-api/openapi-ts/pull/3171)) ([`e63f0cf`](https://github.com/hey-api/openapi-ts/commit/e63f0cf1018e3014c3c125189fe18ed3fa40d078)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/client-next)**: use serialized body in SSE requests ([#3171](https://github.com/hey-api/openapi-ts/pull/3171)) ([`e63f0cf`](https://github.com/hey-api/openapi-ts/commit/e63f0cf1018e3014c3c125189fe18ed3fa40d078)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/client-axios)**: use serialized body in SSE requests ([#3171](https://github.com/hey-api/openapi-ts/pull/3171)) ([`e63f0cf`](https://github.com/hey-api/openapi-ts/commit/e63f0cf1018e3014c3c125189fe18ed3fa40d078)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/client-fetch)**: use serialized body in SSE requests ([#3171](https://github.com/hey-api/openapi-ts/pull/3171)) ([`e63f0cf`](https://github.com/hey-api/openapi-ts/commit/e63f0cf1018e3014c3c125189fe18ed3fa40d078)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/client-nuxt)**: preserve null in `WithRefs` type for nullable fields ([#3131](https://github.com/hey-api/openapi-ts/pull/3131)) ([`3935034`](https://github.com/hey-api/openapi-ts/commit/39350343fe77b6a2700c2b57f03c5b838a92f09e)) by [@rigtigeEmil](https://github.com/rigtigeEmil) - **renderer**: correctly render default import ([#3109](https://github.com/hey-api/openapi-ts/pull/3109)) ([`815a3de`](https://github.com/hey-api/openapi-ts/commit/815a3de0af434c28ac6d13ff92b85ce1fc146999)) by [@mrlubos](https://github.com/mrlubos) - **plugin(@hey-api/client-ky)**: use serialized body in SSE requests ([#3171](https://github.com/hey-api/openapi-ts/pull/3171)) ([`e63f0cf`](https://github.com/hey-api/openapi-ts/commit/e63f0cf1018e3014c3c125189fe18ed3fa40d078)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.5.0 ## 0.89.2 ### Patch Changes - **plugin(@hey-api/typescript)**: improve type narrowing in discriminated types ([#3120](https://github.com/hey-api/openapi-ts/pull/3120)) ([`6f8a43c`](https://github.com/hey-api/openapi-ts/commit/6f8a43c7ffcc8685700c3789c6339aabbac07d2b)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/client-axios)**: revert use `query` option when no `paramsSerializer` is provided ([#3125](https://github.com/hey-api/openapi-ts/pull/3125)) ([`34c9a92`](https://github.com/hey-api/openapi-ts/commit/34c9a9214008ede461251f46ab750de37da96bbb)) by [@mrlubos](https://github.com/mrlubos) ## 0.89.1 ### Patch Changes - **parser**: expose OpenAPI extension keywords ([#3119](https://github.com/hey-api/openapi-ts/pull/3119)) ([`c50190b`](https://github.com/hey-api/openapi-ts/commit/c50190b02ef2a6b77703a2dbf84b826c4432d56e)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **plugin(@hey-api/client-axios)**: use `query` option when no `paramsSerializer` is provided ([#3062](https://github.com/hey-api/openapi-ts/pull/3062)) ([`4dcc210`](https://github.com/hey-api/openapi-ts/commit/4dcc2100b7a96799f36cc64833f7ab69f09d1c54)) by [@JanST123GS](https://github.com/JanST123GS) - **plugin(@hey-api/sdk)**: lazily initialize sub-resources to improve performance ([#3099](https://github.com/hey-api/openapi-ts/pull/3099)) ([`f481f5c`](https://github.com/hey-api/openapi-ts/commit/f481f5cb11f9a8a5e0b1a0baee367f07dd327730)) by [@mrlubos](https://github.com/mrlubos) - **output**: sanitize reserved names with underscore suffix instead of prefix ([#3102](https://github.com/hey-api/openapi-ts/pull/3102)) ([`9116082`](https://github.com/hey-api/openapi-ts/commit/91160826f3c1d0b87090395140d163d930399639)) by [@mrlubos](https://github.com/mrlubos) - **parser**: improve discriminator support in nested `allOf` fields ([#3117](https://github.com/hey-api/openapi-ts/pull/3117)) ([`ec1224d`](https://github.com/hey-api/openapi-ts/commit/ec1224d97d2a8f97d66327bdd372dc82fa794955)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **output**: default to `.js` extension when module resolution is set to `node16` ([#3115](https://github.com/hey-api/openapi-ts/pull/3115)) ([`18d218a`](https://github.com/hey-api/openapi-ts/commit/18d218a69f7b2b1b899ad29d3f3892374edf2910)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.89.0 ### Minor Changes - **output**: add `preferExportAll` option ([#2990](https://github.com/hey-api/openapi-ts/pull/2990)) ([`c3a81e8`](https://github.com/hey-api/openapi-ts/commit/c3a81e89ba5ed3f373409582c5f814e1d10cae06)) by [@mrlubos](https://github.com/mrlubos) ### Prefer named exports This release changes the default for `index.ts` to prefer named exports. Named exports may lead to better IDE and bundler performance compared to asterisk (`*`) as your tooling doesn't have to inspect the underlying module to discover exports. While this change is merely cosmetic, you can set `output.preferExportAll` to `true` if you prefer to use the asterisk. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: { path: "src/client", preferExportAll: true, }, }; ``` - **parser**: removed `symbol:setValue:*` events ([#2990](https://github.com/hey-api/openapi-ts/pull/2990)) ([`c3a81e8`](https://github.com/hey-api/openapi-ts/commit/c3a81e89ba5ed3f373409582c5f814e1d10cae06)) by [@mrlubos](https://github.com/mrlubos) ### Removed `symbol:setValue:*` events These events have been removed in favor of `node:set:*` events. ### Patch Changes - **output**: add `nameConflictResolver` option ([#2990](https://github.com/hey-api/openapi-ts/pull/2990)) ([`c3a81e8`](https://github.com/hey-api/openapi-ts/commit/c3a81e89ba5ed3f373409582c5f814e1d10cae06)) by [@mrlubos](https://github.com/mrlubos) ## Name Conflicts As your project grows, the chances of name conflicts increase. We use a simple conflict resolver that appends numeric suffixes to duplicate identifiers. If you prefer a different strategy, you can provide your own `nameConflictResolver` function. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: { nameConflictResolver({ attempt, baseName }) { return attempt === 0 ? baseName : `${baseName}_N${attempt + 1}`; }, path: "src/client", }, }; ``` Example output: ```ts export type ChatCompletion = string; export type ChatCompletion_N2 = number; ``` ### Updated Dependencies: - @hey-api/codegen-core@0.4.0 ## 0.88.2 ### Patch Changes - **clients**: handle CR and CRLF line endings in SSE ([#3055](https://github.com/hey-api/openapi-ts/pull/3055)) ([`d663232`](https://github.com/hey-api/openapi-ts/commit/d663232d8f10cb29744beeba073532e2f6b3b27a)) by [@nachogarcia](https://github.com/nachogarcia) ## 0.88.1 ### Patch Changes - **@hey-api/sdk**: correctly map flat parameters ([#3047](https://github.com/hey-api/openapi-ts/pull/3047)) ([`55ef279`](https://github.com/hey-api/openapi-ts/commit/55ef27994740ba0af0bc8db17b3e71bfb5c11714)) by [@mrlubos](https://github.com/mrlubos) ## 0.88.0 ### Minor Changes - **output**: use TypeScript DSL ([#2986](https://github.com/hey-api/openapi-ts/pull/2986)) ([`37ff4ab`](https://github.com/hey-api/openapi-ts/commit/37ff4ab6bc89463778bf3709687ab84d3dab0618)) by [@mrlubos](https://github.com/mrlubos) ### Removed `compiler` and `tsc` exports This release removes the `compiler` utility functions. Instead, it introduces a new TypeScript DSL exposed under the `$` symbol. All plugins now use this interface, so you may notice slight changes in the generated output. ## 0.87.5 ### Patch Changes - **client-ofetch**: fix FormData boundary mismatch ([#2940](https://github.com/hey-api/openapi-ts/pull/2940)) ([`b290ec9`](https://github.com/hey-api/openapi-ts/commit/b290ec9a944c4e536d204e481d942f79ac02c5b9)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.87.4 ### Patch Changes - **valibot**: expose validator resolvers ([#2980](https://github.com/hey-api/openapi-ts/pull/2980)) ([`6226f6f`](https://github.com/hey-api/openapi-ts/commit/6226f6fa271369b5ff06853c1f623557a2ebe837)) by [@mrlubos](https://github.com/mrlubos) - **zod**: expose validator resolvers ([#2980](https://github.com/hey-api/openapi-ts/pull/2980)) ([`6226f6f`](https://github.com/hey-api/openapi-ts/commit/6226f6fa271369b5ff06853c1f623557a2ebe837)) by [@mrlubos](https://github.com/mrlubos) ## 0.87.3 ### Patch Changes - **valibot**: allow generating custom pipes with `~resolvers` ([#2975](https://github.com/hey-api/openapi-ts/pull/2975)) ([`62a4745`](https://github.com/hey-api/openapi-ts/commit/62a4745c2de331330480d77c9838aa9429e950d7)) by [@mrlubos](https://github.com/mrlubos) - **zod**: allow generating custom chains with `~resolvers` ([#2975](https://github.com/hey-api/openapi-ts/pull/2975)) ([`62a4745`](https://github.com/hey-api/openapi-ts/commit/62a4745c2de331330480d77c9838aa9429e950d7)) by [@mrlubos](https://github.com/mrlubos) - **@tanstack/query**: add type annotations to `queryOptions()` ([#2964](https://github.com/hey-api/openapi-ts/pull/2964)) ([`7e1b017`](https://github.com/hey-api/openapi-ts/commit/7e1b01794911b590febaf821369aae0d4d798301)) by [@NovakAnton](https://github.com/NovakAnton) - **client-fetch**: intercept AbortError ([#2970](https://github.com/hey-api/openapi-ts/pull/2970)) ([`9075309`](https://github.com/hey-api/openapi-ts/commit/90753091a72796f6c6dffb6789ef42ecc4fd4e6b)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **@tanstack/query**: prettier mutation options ([#2972](https://github.com/hey-api/openapi-ts/pull/2972)) ([`50266bd`](https://github.com/hey-api/openapi-ts/commit/50266bdb1524aec72e1fdf5e903bad6bebded5e5)) by [@mrlubos](https://github.com/mrlubos) ## 0.87.2 ### Patch Changes - **clients**: add support for Ky client ([#2958](https://github.com/hey-api/openapi-ts/pull/2958)) ([`212fcaf`](https://github.com/hey-api/openapi-ts/commit/212fcaf5570ce05370dac6ace6e2751eecddb2d4)) by [@SebastiaanWouters](https://github.com/SebastiaanWouters) - **parser**: merge `default` keyword with `$ref` in OpenAPI 3.1 ([#2946](https://github.com/hey-api/openapi-ts/pull/2946)) ([`15a178d`](https://github.com/hey-api/openapi-ts/commit/15a178dd6a998bf88ebd17c64de151922e94765a)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **output**: run lint before format ([#2937](https://github.com/hey-api/openapi-ts/pull/2937)) ([`eb23ee8`](https://github.com/hey-api/openapi-ts/commit/eb23ee89fd09368385a07cd2a3885e3e5ce111e6)) by [@FloEdelmann](https://github.com/FloEdelmann) - **@pinia/colada**: correctly access instantiated SDKs ([#2942](https://github.com/hey-api/openapi-ts/pull/2942)) ([`c041e96`](https://github.com/hey-api/openapi-ts/commit/c041e962604765e0f342fda970a2550367aa2142)) by [@mrlubos](https://github.com/mrlubos) - **valibot**: use `.strictObject()` instead of `.objectWithRest()` when additional properties are not allowed ([#2945](https://github.com/hey-api/openapi-ts/pull/2945)) ([`3786d2b`](https://github.com/hey-api/openapi-ts/commit/3786d2b3b2316ddcc00b7d87f7dff15b61e29719)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **@tanstack/query**: prettier query options ([#2947](https://github.com/hey-api/openapi-ts/pull/2947)) ([`0b79b89`](https://github.com/hey-api/openapi-ts/commit/0b79b894bd263b2d28cbbb59dfab3aed4ba6736d)) by [@mrlubos](https://github.com/mrlubos) ## 0.87.1 ### Patch Changes - fix(typescript): remove legacy options ([#2929](https://github.com/hey-api/openapi-ts/pull/2929)) ([`97c1f0e`](https://github.com/hey-api/openapi-ts/commit/97c1f0e94f8eb8ca2d74f4f5ebe51a53f347641b)) by [@mrlubos](https://github.com/mrlubos) - fix(tanstack-query): correctly access instantiated SDKs ([#2939](https://github.com/hey-api/openapi-ts/pull/2939)) ([`01a1fb4`](https://github.com/hey-api/openapi-ts/commit/01a1fb48a2e2d4e14a33cf3e81b44b5fad76e72a)) by [@mrlubos](https://github.com/mrlubos) ## 0.87.0 ### Minor Changes - feat: remove legacy clients and plugins ([#2925](https://github.com/hey-api/openapi-ts/pull/2925)) ([`c9fb65d`](https://github.com/hey-api/openapi-ts/commit/c9fb65d2f5757f389383f8b9007baf6a5e26f45a)) by [@mrlubos](https://github.com/mrlubos) ### Removed legacy clients This release removes support for legacy clients and plugins. Please migrate to the new clients if you haven't done so yet. If you're unable to do so due to a missing feature, let us know on [GitHub](https://github.com/hey-api/openapi-ts/issues). ## 0.86.12 ### Patch Changes - fix(transformers): do not reference undefined transformers ([#2924](https://github.com/hey-api/openapi-ts/pull/2924)) ([`b3f4f91`](https://github.com/hey-api/openapi-ts/commit/b3f4f91bbf6ac1db504b7605a73c986b37003880)) by [@mrlubos](https://github.com/mrlubos) - fix(sdk): add `paramsStructure` option ([#2909](https://github.com/hey-api/openapi-ts/pull/2909)) ([`d9dd389`](https://github.com/hey-api/openapi-ts/commit/d9dd38927ce5c7901ce46bfe439454935b2053fa)) by [@mrlubos](https://github.com/mrlubos) - fix(sdk): handle conflicts between method names and subclasses in class-based SDKs ([#2920](https://github.com/hey-api/openapi-ts/pull/2920)) ([`48c7fa3`](https://github.com/hey-api/openapi-ts/commit/48c7fa3db65ef1ee146b6e09e53ae500483d4b22)) by [@mrlubos](https://github.com/mrlubos) - fix: bundled context types ([#2923](https://github.com/hey-api/openapi-ts/pull/2923)) ([`f5a91c4`](https://github.com/hey-api/openapi-ts/commit/f5a91c4e068f64987d8138fadb0e969f1e28081f)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.3.3 ## 0.86.11 ### Patch Changes - fix(types): use unique generic names in `PluginInstance` to avoid typing issues ([#2897](https://github.com/hey-api/openapi-ts/pull/2897)) ([`a625980`](https://github.com/hey-api/openapi-ts/commit/a625980e7bbcba1f4bb91aecae9546ff51942964)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.86.10 ### Patch Changes - fix(parser): handle OpenAPI 2.0 body as JSON by default if not explicitly defined ([#2893](https://github.com/hey-api/openapi-ts/pull/2893)) ([`767ad18`](https://github.com/hey-api/openapi-ts/commit/767ad185d5a2bb5a7344ca1c297e8d2b1c16d638)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.86.9 ### Patch Changes - fix(valibot): handle `time` string format ([#2889](https://github.com/hey-api/openapi-ts/pull/2889)) ([`0db5a43`](https://github.com/hey-api/openapi-ts/commit/0db5a43b868511784cdffabbec8ea234c7841d19)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - refactor: replace plugin references with queries ([#2873](https://github.com/hey-api/openapi-ts/pull/2873)) ([`1cfc8f2`](https://github.com/hey-api/openapi-ts/commit/1cfc8f2b4673b53e0b1fff43f3d2078dcd595ca2)) by [@mrlubos](https://github.com/mrlubos) - fix: gracefully handle errors in debug reports ([#2884](https://github.com/hey-api/openapi-ts/pull/2884)) ([`d5c0a1c`](https://github.com/hey-api/openapi-ts/commit/d5c0a1c03edd3cefcd9438cee59d538cf87e9d3f)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ### Updated Dependencies: - @hey-api/codegen-core@0.3.2 ## 0.86.8 ### Patch Changes - fix(valibot): improve handling of additionalProperties type ([#2870](https://github.com/hey-api/openapi-ts/pull/2870)) ([`da88dd9`](https://github.com/hey-api/openapi-ts/commit/da88dd9962ff3a619f3d4853d641acc3637406f4)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.86.7 ### Patch Changes - fix(types): export Operation type ([#2862](https://github.com/hey-api/openapi-ts/pull/2862)) ([`857c464`](https://github.com/hey-api/openapi-ts/commit/857c464ac04832c3bf26f33af3c1c90ccf67fda1)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.86.6 ### Patch Changes - fix(transformers): revert function order to fix infinite cycle regression ([#2855](https://github.com/hey-api/openapi-ts/pull/2855)) ([`81f91a9`](https://github.com/hey-api/openapi-ts/commit/81f91a97e8e50427b45f21c80f72fdff7ce1deca)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.86.5 ### Patch Changes - fix(parser): write-only schema incorrectly used in response schemas ([#2850](https://github.com/hey-api/openapi-ts/pull/2850)) ([`16cc0e7`](https://github.com/hey-api/openapi-ts/commit/16cc0e7d50993e36dab6349eda1361421bdf44ac)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - fix(cli): move cli script to typescript ([#2852](https://github.com/hey-api/openapi-ts/pull/2852)) ([`b677f89`](https://github.com/hey-api/openapi-ts/commit/b677f893f9dc1848bb54164e736a90e617d1269d)) by [@mrlubos](https://github.com/mrlubos) ## 0.86.4 ### Patch Changes - feat(parser): pass tags to symbol meta ([#2845](https://github.com/hey-api/openapi-ts/pull/2845)) ([`e157288`](https://github.com/hey-api/openapi-ts/commit/e1572888aec1e95d23eb0124fb9a5f3383e89def)) by [@mrlubos](https://github.com/mrlubos) - feat(clients): granular query parameter serialization strategy ([#2837](https://github.com/hey-api/openapi-ts/pull/2837)) ([`e0e6ab3`](https://github.com/hey-api/openapi-ts/commit/e0e6ab37888ac9eb88fa9f0d45e0a9123f9f1158)) by [@pixelmord](https://github.com/pixelmord) ## 0.86.3 ### Patch Changes - feat(parser): add `events` hooks ([#2829](https://github.com/hey-api/openapi-ts/pull/2829)) ([`d5c85fc`](https://github.com/hey-api/openapi-ts/commit/d5c85fc29e985af0cdc6ce7ac7e8210c60171163)) by [@mrlubos](https://github.com/mrlubos) - fix(parser): writeOnly schema properties missing from request types in nested schemas ([#2793](https://github.com/hey-api/openapi-ts/pull/2793)) ([`7d1c475`](https://github.com/hey-api/openapi-ts/commit/7d1c47592a806c34fb627f21e3ee59e2ec3c015a)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.86.2 ### Patch Changes - fix(validators): do not reference variables before they are declared ([#2812](https://github.com/hey-api/openapi-ts/pull/2812)) ([`69783d1`](https://github.com/hey-api/openapi-ts/commit/69783d19be37014b5116a2ede5bb74adadbb8110)) by [@mrlubos](https://github.com/mrlubos) - fix(renderer): allow duplicate names when one symbol is a type ([#2812](https://github.com/hey-api/openapi-ts/pull/2812)) ([`523038e`](https://github.com/hey-api/openapi-ts/commit/523038e82c949a436a467486a26333d50ce0e7cd)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.3.1 ## 0.86.1 ### Patch Changes - fix(client-axios): revert return error when axios request fails ([#2804](https://github.com/hey-api/openapi-ts/pull/2804)) ([`5bba86e`](https://github.com/hey-api/openapi-ts/commit/5bba86e742c48f575f96f55f7d7ea3d636102ebe)) by [@mrlubos](https://github.com/mrlubos) ## 0.86.0 ### Minor Changes - feat: bump minimum Node version to 20.19.0 ([#2775](https://github.com/hey-api/openapi-ts/pull/2775)) ([`7c7702a`](https://github.com/hey-api/openapi-ts/commit/7c7702a9ed3bda0d75ef28d35d4284e3b6318b26)) by [@mrlubos](https://github.com/mrlubos) ### Patch Changes - fix: do not print error details if logs are set to silent ([#2776](https://github.com/hey-api/openapi-ts/pull/2776)) ([`2274344`](https://github.com/hey-api/openapi-ts/commit/227434440bc2d00f9336041d3b083fc9374f3639)) by [@mrlubos](https://github.com/mrlubos) - fix(client-axios): return error when axios request fails ([#2763](https://github.com/hey-api/openapi-ts/pull/2763)) ([`122a292`](https://github.com/hey-api/openapi-ts/commit/122a292e3a0293098e5c5e222e5dcf8e99639ba8)) by [@mauriciabad](https://github.com/mauriciabad) ### Updated Dependencies: - @hey-api/codegen-core@0.3.0 ## 0.85.2 ### Patch Changes - fix: dynamically load c12 to work with cjs modules ([#2755](https://github.com/hey-api/openapi-ts/pull/2755)) ([`e6472cf`](https://github.com/hey-api/openapi-ts/commit/e6472cf7f69db5ff2cb2f509c1d61e5c4438871e)) by [@mrlubos](https://github.com/mrlubos) - fix(cli): detect watch mode with input array ([#2751](https://github.com/hey-api/openapi-ts/pull/2751)) ([`3293cad`](https://github.com/hey-api/openapi-ts/commit/3293cada4f089107ac183fbcd03550541d95073a)) by [@warrenseine](https://github.com/warrenseine) ## 0.85.1 ### Patch Changes - fix(zod): allOf in array items being generated as union instead of intersection ([#2736](https://github.com/hey-api/openapi-ts/pull/2736)) ([`078face`](https://github.com/hey-api/openapi-ts/commit/078face47b40462033ce557ce0048ccf88246854)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.85.0 ### Minor Changes - refactor(config): replace 'off' with null to disable options ([#2718](https://github.com/hey-api/openapi-ts/pull/2718)) ([`fcdd73b`](https://github.com/hey-api/openapi-ts/commit/fcdd73b816d74babf47e6a1f46032f5b8ebb4b48)) by [@mrlubos](https://github.com/mrlubos) ### Updated `output` options We made the `output` configuration more consistent by using `null` to represent disabled options. [This change](https://heyapi.dev/openapi-ts/migrating#updated-output-options) does not affect boolean options. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: { format: null, lint: null, path: "src/client", tsConfigPath: null, }, }; ``` ### Patch Changes - feat: support multiple configurations ([#2602](https://github.com/hey-api/openapi-ts/pull/2602)) ([`c84f10e`](https://github.com/hey-api/openapi-ts/commit/c84f10e5a1b7c54320e3ef5edfc9d2fffe5183e9)) by [@carson2222](https://github.com/carson2222) - feat(config): add `output.importFileExtension` option ([#2718](https://github.com/hey-api/openapi-ts/pull/2718)) ([`fcdd73b`](https://github.com/hey-api/openapi-ts/commit/fcdd73b816d74babf47e6a1f46032f5b8ebb4b48)) by [@mrlubos](https://github.com/mrlubos) - feat(pinia-colada): query options use `defineQueryOptions` ([#2610](https://github.com/hey-api/openapi-ts/pull/2610)) ([`33e6b31`](https://github.com/hey-api/openapi-ts/commit/33e6b31fa2ab840dd4e6e2e3e0fbc6e207ccdf7e)) by [@brolnickij](https://github.com/brolnickij) ### Updated Pinia Colada query options Pinia Colada query options now use `defineQueryOptions` to improve reactivity support. Instead of calling the query options function, you can use one of the [following approaches](https://heyapi.dev/openapi-ts/migrating#updated-pinia-colada-query-options). #### No params ```ts useQuery(getPetsQuery); ``` #### Constant ```ts useQuery(getPetByIdQuery, () => ({ path: { petId: 1, }, })); ``` #### Reactive ```ts const petId = ref(1); useQuery(getPetByIdQuery, () => ({ path: { petId: petId.value, }, })); ``` #### Properties ```ts const petId = ref(1); useQuery(() => ({ ...getPetByIdQuery({ path: { petId: petId.value as number }, }), enabled: () => petId.value != null, })); ``` ## 0.84.4 ### Patch Changes - fix(client-ofetch): add missing credentials property support ([#2710](https://github.com/hey-api/openapi-ts/pull/2710)) ([`ba7e6dc`](https://github.com/hey-api/openapi-ts/commit/ba7e6dc1af3a8e64082bd101de6c1cd6e0e8fc17)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - fix(config): do not override interactive config from CLI if defined in config file ([#2708](https://github.com/hey-api/openapi-ts/pull/2708)) ([`21e9fa0`](https://github.com/hey-api/openapi-ts/commit/21e9fa089d2305714f37c1a16cb3e6f9fedb49b9)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - fix(zod): correct schemas for numeric and boolean enums ([#2704](https://github.com/hey-api/openapi-ts/pull/2704)) ([`59ea38e`](https://github.com/hey-api/openapi-ts/commit/59ea38ea9e47b515c54e55d169591fe6188990b4)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.84.3 ### Patch Changes - fix(validators): escaping slashes in regular expressions ([#2692](https://github.com/hey-api/openapi-ts/pull/2692)) ([`dba81bc`](https://github.com/hey-api/openapi-ts/commit/dba81bc23a7cb72696cd1fcf4fe1a17f00027fae)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.84.2 ### Patch Changes - fix(parser): add `propertiesRequiredByDefault` transform option ([#2678](https://github.com/hey-api/openapi-ts/pull/2678)) ([`9e59e07`](https://github.com/hey-api/openapi-ts/commit/9e59e07efa2bafec88e0af2935edac323b4e41dd)) by [@mrlubos](https://github.com/mrlubos) - fix(typescript): do not mark enums as types ([#2680](https://github.com/hey-api/openapi-ts/pull/2680)) ([`1cab011`](https://github.com/hey-api/openapi-ts/commit/1cab0115afa3a201acb4911dd552c1d5dd9ba9ac)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.84.1 ### Patch Changes - feat: add `ofetch` client available as `@hey-api/client-ofetch` ([#2642](https://github.com/hey-api/openapi-ts/pull/2642)) ([`da9e05f`](https://github.com/hey-api/openapi-ts/commit/da9e05f38f8952aaf2868094c2c0bc32c402d55e)) by [@brolnickij](https://github.com/brolnickij) - fix(renderer): replace default import placeholder ([#2674](https://github.com/hey-api/openapi-ts/pull/2674)) ([`762b20e`](https://github.com/hey-api/openapi-ts/commit/762b20e6c8b90d7011ce24a193a66b18e4f74136)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.84.0 ### Minor Changes - feat: Symbol API ### Symbol API This release improves the Symbol API, which adds the capability to place symbols in arbitrary files. We preserved the previous output structure for all plugins except Angular. You can preserve the previous Angular output by writing your own [placement function](https://heyapi.dev/openapi-ts/configuration/parser#hooks-symbols). ### Removed `output` plugin option Due to the Symbol API release, this option has been removed from the Plugin API. ([#2664](https://github.com/hey-api/openapi-ts/pull/2664)) ([`e1ede9c`](https://github.com/hey-api/openapi-ts/commit/e1ede9cabf52b5bbcb9195570deff58db8f43dbb)) by [@mrlubos](https://github.com/mrlubos) ### Patch Changes - fix(plugin): every plugin extends Plugin.Hooks interface ([#2664](https://github.com/hey-api/openapi-ts/pull/2664)) ([`e1ede9c`](https://github.com/hey-api/openapi-ts/commit/e1ede9cabf52b5bbcb9195570deff58db8f43dbb)) by [@mrlubos](https://github.com/mrlubos) - fix(renderer): group and sort imported modules ### TypeScript renderer We ship a dedicated TypeScript renderer for `.ts` files. This release improves the renderer's ability to group and sort imported modules, resulting in a more polished output. ([#2664](https://github.com/hey-api/openapi-ts/pull/2664)) ([`e1ede9c`](https://github.com/hey-api/openapi-ts/commit/e1ede9cabf52b5bbcb9195570deff58db8f43dbb)) by [@mrlubos](https://github.com/mrlubos) - fix(parser): expand schema deduplication by including validation constraints in type ID ([#2650](https://github.com/hey-api/openapi-ts/pull/2650)) ([`31b3933`](https://github.com/hey-api/openapi-ts/commit/31b3933b2caa1085dbead1ef94695bca4b83d6ac)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - fix(parser): bump support for OpenAPI 3.1.2 ([#2667](https://github.com/hey-api/openapi-ts/pull/2667)) ([`3511fb8`](https://github.com/hey-api/openapi-ts/commit/3511fb88cbe6b767b631af16336cb6c0722c3ff8)) by [@mrlubos](https://github.com/mrlubos) - fix(config): add `output.fileName` option ([#2664](https://github.com/hey-api/openapi-ts/pull/2664)) ([`e1ede9c`](https://github.com/hey-api/openapi-ts/commit/e1ede9cabf52b5bbcb9195570deff58db8f43dbb)) by [@mrlubos](https://github.com/mrlubos) ## File Name You can customize the naming and casing pattern for files using the `fileName` option. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: { fileName: "{{name}}", path: "src/client", }, }; ``` By default, we append every file name with a `.gen` suffix to highlight it's automatically generated. You can customize or disable this suffix using the `fileName.suffix` option. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: { fileName: { suffix: ".gen", }, path: "src/client", }, }; ``` - fix(axios): remove duplicate `baseURL` when using relative values ([#2624](https://github.com/hey-api/openapi-ts/pull/2624)) ([`8ffceec`](https://github.com/hey-api/openapi-ts/commit/8ffceec89fe471d4e14df17a172f3d5a254eb819)) by [@Ben-Pfirsich](https://github.com/Ben-Pfirsich) ### Updated Dependencies: - @hey-api/codegen-core@0.2.0 ## 0.83.1 ### Patch Changes - feat(typescript): add `topType` option allowing to choose `any` over `unknown` ([#2629](https://github.com/hey-api/openapi-ts/pull/2629)) ([`444a49a`](https://github.com/hey-api/openapi-ts/commit/444a49a3f0855575c3ef1a3350fd102d42553f3e)) by [@mrlubos](https://github.com/mrlubos) - fix(client): expose all interceptor methods ([#2627](https://github.com/hey-api/openapi-ts/pull/2627)) ([`5a74da0`](https://github.com/hey-api/openapi-ts/commit/5a74da055e835b5160cb11e3d2be6921feeb18ad)) by [@mrlubos](https://github.com/mrlubos) - fix(config): correctly load user-defined hooks ([#2623](https://github.com/hey-api/openapi-ts/pull/2623)) ([`1193c4d`](https://github.com/hey-api/openapi-ts/commit/1193c4dce77e0cb02c32b25661f22065a18bd095)) by [@mrlubos](https://github.com/mrlubos) - fix(typescript): handle string and binary string in composite keywords ([#2630](https://github.com/hey-api/openapi-ts/pull/2630)) ([`43a0661`](https://github.com/hey-api/openapi-ts/commit/43a06617448344448375e0c13a156cb91666f3e9)) by [@mrlubos](https://github.com/mrlubos) ## 0.83.0 ### Minor Changes - feat: Symbol API ### Symbol API This release adds the Symbol API, which significantly reduces the risk of naming collisions. While the generated output should only include formatting changes, this feature introduces breaking changes to the Plugin API that affect custom plugins. We will update the [custom plugin guide](https://heyapi.dev/openapi-ts/plugins/custom) once the Plugin API becomes more stable. ([#2582](https://github.com/hey-api/openapi-ts/pull/2582)) ([`10aea89`](https://github.com/hey-api/openapi-ts/commit/10aea8910771ff72ef9b08d4eacdd6b028833c4c)) by [@mrlubos](https://github.com/mrlubos) - feat(pinia-colada): remove `groupByTag` option ### Removed `groupByTag` Pinia Colada option This option has been removed to provide a more consistent API across plugins. We plan to bring it back in a future release. ([#2582](https://github.com/hey-api/openapi-ts/pull/2582)) ([`10aea89`](https://github.com/hey-api/openapi-ts/commit/10aea8910771ff72ef9b08d4eacdd6b028833c4c)) by [@mrlubos](https://github.com/mrlubos) ### Patch Changes ### Updated Dependencies: - @hey-api/codegen-core@0.1.0 ## 0.82.5 ### Patch Changes - fix(client): `mergeHeaders` functions use `.forEach()` instead of `.entries()` ([#2585](https://github.com/hey-api/openapi-ts/pull/2585)) ([`debba72`](https://github.com/hey-api/openapi-ts/commit/debba72348e450f8dc884223681f10e80da77545)) by [@volesen](https://github.com/volesen) - fix(client): move `getValidRequestBody()` function to `client-core` ([#2605](https://github.com/hey-api/openapi-ts/pull/2605)) ([`b180e4e`](https://github.com/hey-api/openapi-ts/commit/b180e4e105d1d8008e4c92d79857d592080feac7)) by [@franworks](https://github.com/franworks) ## 0.82.4 ### Patch Changes - fix(client): improve handling of plain text, falsy, and unserialized request bodies ([#2564](https://github.com/hey-api/openapi-ts/pull/2564)) ([`074a459`](https://github.com/hey-api/openapi-ts/commit/074a4598c050036b161a9e04a4b5acae98d97b82)) by [@franworks](https://github.com/franworks) - feat(pinia-colada): implicit `$fetch` for `client-nuxt` (hide `composable`) ([#2598](https://github.com/hey-api/openapi-ts/pull/2598)) ([`7143078`](https://github.com/hey-api/openapi-ts/commit/7143078fde06b5b2fe00e7a7045317a2f5b40bb7)) by [@brolnickij](https://github.com/brolnickij) - fix(pinia-colada): optional `options` in mutation factory ([#2593](https://github.com/hey-api/openapi-ts/pull/2593)) ([`4137445`](https://github.com/hey-api/openapi-ts/commit/413744572f403f605c0ba6a69f3614da69fc6f15)) by [@brolnickij](https://github.com/brolnickij) - fix(parser): improve $ref handling ([#2588](https://github.com/hey-api/openapi-ts/pull/2588)) ([`c97e7a8`](https://github.com/hey-api/openapi-ts/commit/c97e7a8c8b1d24747356feb9a15840c296a9c1c8)) by [@carson2222](https://github.com/carson2222) ## 0.82.3 ### Patch Changes - fix(angular): allow `httpResource` to skip requests when `undefined` is returned ([#2572](https://github.com/hey-api/openapi-ts/pull/2572)) ([`ee35b33`](https://github.com/hey-api/openapi-ts/commit/ee35b337909c2dfa76b8aa915d4b6e185deafa2b)) by [@max-scopp](https://github.com/max-scopp) ## 0.82.2 ### Patch Changes - fix: update peer dependencies to be more permissible ([#2574](https://github.com/hey-api/openapi-ts/pull/2574)) ([`996021e`](https://github.com/hey-api/openapi-ts/commit/996021e4ce306ce762dfd55f2a7ec8099be4f24c)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.0.1 ## 0.82.1 ### Patch Changes - [#2541](https://github.com/hey-api/openapi-ts/pull/2541) [`ad3c633`](https://github.com/hey-api/openapi-ts/commit/ad3c633b21d241ba72f27828870c354bfc00bd7e) Thanks [@ixnas](https://github.com/ixnas)! - feat(typescript): add `typescript-const` to `enums.mode` for generating TypeScript enums as constants - [#2556](https://github.com/hey-api/openapi-ts/pull/2556) [`74c16f2`](https://github.com/hey-api/openapi-ts/commit/74c16f219706d22aebbc166e8bbb95412a2a5b6f) Thanks [@carson2222](https://github.com/carson2222)! - fix(parser): prune `required` array after removing properties - [#2559](https://github.com/hey-api/openapi-ts/pull/2559) [`5012a72`](https://github.com/hey-api/openapi-ts/commit/5012a721e7b7064910e5e4056cb4adf3ae63f19b) Thanks [@jgoz](https://github.com/jgoz)! - fix(output): avoid appending `.gen` to file names multiple times when `output.clean` is `false` ## 0.82.0 ### Minor Changes - [#2505](https://github.com/hey-api/openapi-ts/pull/2505) [`97c57f6`](https://github.com/hey-api/openapi-ts/commit/97c57f68af1f907f278707fb526289c73b33ea89) Thanks [@SebastiaanWouters](https://github.com/SebastiaanWouters)! - feat(parser): add Hooks API ### Added Hooks API This release adds the [Hooks API](https://heyapi.dev/openapi-ts/configuration/parser#hooks), giving you granular control over which operations generate queries and mutations. As a result, we tightened the previous behavior and POST operations no longer generate queries by default. To preserve the old behavior, add a custom matcher. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: "src/client", parser: { hooks: { operations: { isQuery: (op) => (op.method === "post" ? true : undefined), }, }, }, }; ``` ### Patch Changes - [#2542](https://github.com/hey-api/openapi-ts/pull/2542) [`c12f7c7`](https://github.com/hey-api/openapi-ts/commit/c12f7c71287ced429db4036678b254a967da3dea) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): pass fetch option to sse client - [#2505](https://github.com/hey-api/openapi-ts/pull/2505) [`80dc015`](https://github.com/hey-api/openapi-ts/commit/80dc01515d67bd335427af3dc9be0d49a417b9e3) Thanks [@SebastiaanWouters](https://github.com/SebastiaanWouters)! - feat(plugin): add `@pinia/colada` plugin - [#2535](https://github.com/hey-api/openapi-ts/pull/2535) [`efdeedc`](https://github.com/hey-api/openapi-ts/commit/efdeedce6765e6b4d3c2e288b0473c1ced6c487f) Thanks [@alexedme](https://github.com/alexedme)! - feat(client): added angular, axios, fetch, next & nuxt client type export for external typing purposes. - [#2544](https://github.com/hey-api/openapi-ts/pull/2544) [`d4cd30e`](https://github.com/hey-api/openapi-ts/commit/d4cd30e3486fef6c459d4c04d3ca3f7ac19f8d83) Thanks [@carson2222](https://github.com/carson2222)! - fix(parser): improve handling multiple references to shared external variable - [#2519](https://github.com/hey-api/openapi-ts/pull/2519) [`95f00fa`](https://github.com/hey-api/openapi-ts/commit/95f00fa28a4c56f8f614649f8b4fd73a08f8b81f) Thanks [@volesen](https://github.com/volesen)! - fix(client): improve empty response body handling - [#1680](https://github.com/hey-api/openapi-ts/pull/1680) [`9e4cc3d`](https://github.com/hey-api/openapi-ts/commit/9e4cc3df784999ead1691848a4db0b7238e45809) Thanks [@josh-hemphill](https://github.com/josh-hemphill)! - feat(plugin): add `@pinia/colada` plugin - [#2530](https://github.com/hey-api/openapi-ts/pull/2530) [`8d1cfc4`](https://github.com/hey-api/openapi-ts/commit/8d1cfc4e415239266760498ea126c465c53f588c) Thanks [@carson2222](https://github.com/carson2222)! - fix(parser): improve `readWrite` transformer splitting logic - [#2523](https://github.com/hey-api/openapi-ts/pull/2523) [`7f6de44`](https://github.com/hey-api/openapi-ts/commit/7f6de44be7f445425c70c82833bc0442db2fcbcd) Thanks [@carson2222](https://github.com/carson2222)! - fix(parser): handle `patternProperties` in OpenAPI 3.1 ## 0.81.1 ### Patch Changes - [#2516](https://github.com/hey-api/openapi-ts/pull/2516) [`c71d5db`](https://github.com/hey-api/openapi-ts/commit/c71d5dbfc5888f03ab06a7c763ada42c1af6c096) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(typescript): add webhooks configuration options - [#2515](https://github.com/hey-api/openapi-ts/pull/2515) [`b81051e`](https://github.com/hey-api/openapi-ts/commit/b81051e27945e330c0a7c157aff49029bcd6dfda) Thanks [@malcolm-kee](https://github.com/malcolm-kee)! - fix(parser): correctly handle schema extending discriminated schema - [#2513](https://github.com/hey-api/openapi-ts/pull/2513) [`34fa59f`](https://github.com/hey-api/openapi-ts/commit/34fa59fe2f0e6b4ba6578f25a6e64f964c04155c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): move sse functions into their own namespace - [#2516](https://github.com/hey-api/openapi-ts/pull/2516) [`c71d5db`](https://github.com/hey-api/openapi-ts/commit/c71d5dbfc5888f03ab06a7c763ada42c1af6c096) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(validator): add webhooks configuration options - [#2516](https://github.com/hey-api/openapi-ts/pull/2516) [`c71d5db`](https://github.com/hey-api/openapi-ts/commit/c71d5dbfc5888f03ab06a7c763ada42c1af6c096) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(parser): handle webhooks in OpenAPI 3.1 ## 0.81.0 ### Minor Changes - [#2510](https://github.com/hey-api/openapi-ts/pull/2510) [`d43ef3f`](https://github.com/hey-api/openapi-ts/commit/d43ef3f3bb47bad3f4fafbcf7be86b328543f440) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(client): add support for server-sent events (SSE) ## 0.80.18 ### Patch Changes - [#2502](https://github.com/hey-api/openapi-ts/pull/2502) [`ac7efbf`](https://github.com/hey-api/openapi-ts/commit/ac7efbfd96e7a5e530e91655df6ac481c9a5eaa5) Thanks [@malcolm-kee](https://github.com/malcolm-kee)! - fix(parser): OpenAPI 3.1 parser handles multiple `type` values ## 0.80.17 ### Patch Changes - [#2500](https://github.com/hey-api/openapi-ts/pull/2500) [`98d7bc3`](https://github.com/hey-api/openapi-ts/commit/98d7bc37387e16c6f38194a111d6df384eee3a82) Thanks [@max-scopp](https://github.com/max-scopp)! - fix(client): Angular client correctly applies default GET method ## 0.80.16 ### Patch Changes - [#2490](https://github.com/hey-api/openapi-ts/pull/2490) [`03f37ea`](https://github.com/hey-api/openapi-ts/commit/03f37ea9481a28c7c05dba5f0fddfc2bc225e6a0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): Nuxt client receives raw body in request validators - [#2479](https://github.com/hey-api/openapi-ts/pull/2479) [`4038e1c`](https://github.com/hey-api/openapi-ts/commit/4038e1cef96c031acde97ccf82176a0fedbb3f8c) Thanks [@dracomithril](https://github.com/dracomithril)! - fix(parser): deduplicate security schemas based on name - [#2489](https://github.com/hey-api/openapi-ts/pull/2489) [`9bfbb63`](https://github.com/hey-api/openapi-ts/commit/9bfbb63bff087da4cffc76603f8c9f45f34f430a) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(parser): input supports Hey API Registry shorthand - [#2485](https://github.com/hey-api/openapi-ts/pull/2485) [`e074a36`](https://github.com/hey-api/openapi-ts/commit/e074a3600701badc7f220b283a55188dc85a5572) Thanks [@bombillazo](https://github.com/bombillazo)! - feat(parser): input supports ReadMe API Registry with `readme:` prefix - [#2491](https://github.com/hey-api/openapi-ts/pull/2491) [`ce602fe`](https://github.com/hey-api/openapi-ts/commit/ce602fede185ba622398bdd42e38d3f78323c32c) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(parser): input supports Scalar API Registry with `scalar:` prefix ## 0.80.15 ### Patch Changes - [#2480](https://github.com/hey-api/openapi-ts/pull/2480) [`d9af1bb`](https://github.com/hey-api/openapi-ts/commit/d9af1bb3d1abb4c8caa4f8fd6a3fcef50d2187d9) Thanks [@dracomithril](https://github.com/dracomithril)! - fix(client): call `auth()` function for every unique security `name` - [#2481](https://github.com/hey-api/openapi-ts/pull/2481) [`7e8264e`](https://github.com/hey-api/openapi-ts/commit/7e8264eae199f4ce52f1666937bca838626cacc3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): cache parent to children nodes ## 0.80.14 ### Patch Changes - [#2475](https://github.com/hey-api/openapi-ts/pull/2475) [`b9204ad`](https://github.com/hey-api/openapi-ts/commit/b9204ad1603374713d507deaa416ed56d6ce6aea) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): cache visited graph nodes to boost performance ## 0.80.13 ### Patch Changes - [#2471](https://github.com/hey-api/openapi-ts/pull/2471) [`82af768`](https://github.com/hey-api/openapi-ts/commit/82af768a102409f981006a4b6f0219f9d86256dc) Thanks [@josstn](https://github.com/josstn)! - fix(parser): handle non-ascii characters in discriminator ## 0.80.12 ### Patch Changes - [#2467](https://github.com/hey-api/openapi-ts/pull/2467) [`c76a8de`](https://github.com/hey-api/openapi-ts/commit/c76a8decad12a4a67cab83827bb007b36d794f6a) Thanks [@bjornhenriksson](https://github.com/bjornhenriksson)! - fix(zod): add `dates.local` option to allow unqualified (timezone-less) datetimes ## 0.80.11 ### Patch Changes - [#2452](https://github.com/hey-api/openapi-ts/pull/2452) [`fb5b621`](https://github.com/hey-api/openapi-ts/commit/fb5b621f89bfc7acf33b0156ffcdca87646d667f) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(client): add `@hey-api/client-angular` client - [#2423](https://github.com/hey-api/openapi-ts/pull/2423) [`554e9a6`](https://github.com/hey-api/openapi-ts/commit/554e9a6b4513eff4785ef48a927c6fea7a8eb873) Thanks [@max-scopp](https://github.com/max-scopp)! - feat(plugin): add `@angular/common` plugin ## 0.80.10 ### Patch Changes - [#2438](https://github.com/hey-api/openapi-ts/pull/2438) [`760fd61`](https://github.com/hey-api/openapi-ts/commit/760fd61701080a890ba8e8efc5eac46699db4bbf) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): handle dates in formdata serializer ## 0.80.9 ### Patch Changes - [#2426](https://github.com/hey-api/openapi-ts/pull/2426) [`7308d9b`](https://github.com/hey-api/openapi-ts/commit/7308d9b8f5eb96d984dc323b5e6276eafcd30382) Thanks [@flow96](https://github.com/flow96)! - fix(sdk): handle infinite loop in nested operation IDs and tags with duplicate values ## 0.80.8 ### Patch Changes - [#2418](https://github.com/hey-api/openapi-ts/pull/2418) [`340a6cd`](https://github.com/hey-api/openapi-ts/commit/340a6cd8f90fac70ff752c11abfa4691180bd34a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): add auto-generated header to client files - [#2418](https://github.com/hey-api/openapi-ts/pull/2418) [`969d7cf`](https://github.com/hey-api/openapi-ts/commit/969d7cfd7ff17705148477e4ce2b0ca3cee81de9) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): correctly rename client files with nodenext bundler - [#2416](https://github.com/hey-api/openapi-ts/pull/2416) [`9cff8c8`](https://github.com/hey-api/openapi-ts/commit/9cff8c871e2707b22f9ea521bce95c6ffd532079) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): set correct name for pagination parameters in infinite query options ## 0.80.7 ### Patch Changes - [#2396](https://github.com/hey-api/openapi-ts/pull/2396) [`b0958a0`](https://github.com/hey-api/openapi-ts/commit/b0958a05c308c4fcd8ca17d61d8691b6fb3471fe) Thanks [@Shinigami92](https://github.com/Shinigami92)! - fix(client): add `.gen` to client files ## 0.80.6 ### Patch Changes - [#2399](https://github.com/hey-api/openapi-ts/pull/2399) [`ef32c27`](https://github.com/hey-api/openapi-ts/commit/ef32c27a147c85216773ac1fb392363034f23fd1) Thanks [@ahmedrowaihi](https://github.com/ahmedrowaihi)! - feat(tanstack-query): support generating `meta` fields - [#2406](https://github.com/hey-api/openapi-ts/pull/2406) [`04fc0f3`](https://github.com/hey-api/openapi-ts/commit/04fc0f3106b33c1de8a78a401187617c3a788bc5) Thanks [@dovca](https://github.com/dovca)! - feat(clients): pass raw `body` to interceptors, provide serialized body in `serializedBody` - [#2407](https://github.com/hey-api/openapi-ts/pull/2407) [`9704055`](https://github.com/hey-api/openapi-ts/commit/970405534e26ddebaaaed71e2a7a242e005ca44e) Thanks [@flow96](https://github.com/flow96)! - fix(sdk): prevent infinite loop when a schema tag matches operation ID ## 0.80.5 ### Patch Changes - [#2401](https://github.com/hey-api/openapi-ts/pull/2401) [`42566ef`](https://github.com/hey-api/openapi-ts/commit/42566ef86fe5af1f4768eaf08f0cafaa84c69044) Thanks [@mrclrchtr](https://github.com/mrclrchtr)! - fix: resolve Yarn PnP compatibility issues with client bundle generation ## 0.80.4 ### Patch Changes - [#2391](https://github.com/hey-api/openapi-ts/pull/2391) [`ac3456f`](https://github.com/hey-api/openapi-ts/commit/ac3456f4c793f7f8b8f535766382476d6d410219) Thanks [@ahmedrowaihi](https://github.com/ahmedrowaihi)! - fix(tanstack-query): add `queryKeys.tags` and `infiniteQueryKeys.tags` options ## 0.80.3 ### Patch Changes - [#2287](https://github.com/hey-api/openapi-ts/pull/2287) [`6df1237`](https://github.com/hey-api/openapi-ts/commit/6df1237cefcb803da55cb780285fc82be05e019a) Thanks [@MaxwellAt](https://github.com/MaxwellAt)! - fix(zod): improve handling of additional properties ## 0.80.2 ### Patch Changes - [#2383](https://github.com/hey-api/openapi-ts/pull/2383) [`2ac456f`](https://github.com/hey-api/openapi-ts/commit/2ac456f0f6247ef51a83a8ddbe9a03d9b2dabae7) Thanks [@j-ibarra](https://github.com/j-ibarra)! - fix(transformers): add `typeTransformers` option allowing passing custom transform functions - [#2382](https://github.com/hey-api/openapi-ts/pull/2382) [`3a23362`](https://github.com/hey-api/openapi-ts/commit/3a2336204fb06b8fa69faa24de976122ad44c16a) Thanks [@idbenami](https://github.com/idbenami)! - fix(client-axios): allow passing `AxiosInstance` into `axios` field ## 0.80.1 ### Patch Changes - [#2344](https://github.com/hey-api/openapi-ts/pull/2344) [`fb7b724`](https://github.com/hey-api/openapi-ts/commit/fb7b7243663ca40bf79bd76bd7af7a9376474505) Thanks [@Daschi1](https://github.com/Daschi1)! - fix(valibot): expand support for `format: int64` ## 0.80.0 ### Minor Changes - [#2341](https://github.com/hey-api/openapi-ts/pull/2341) [`9954bcf`](https://github.com/hey-api/openapi-ts/commit/9954bcf139efca45f0c0cd0c25e5236dbf5c7121) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(zod): add support for Zod 4 and Zod Mini ### Added Zod 4 and Zod Mini This release adds support for Zod 4 and Zod Mini. By default, the `zod` plugin will generate output for Zod 4. If you want to preserve the previous output for Zod 3 or use Zod Mini, set `compatibilityVersion` to `3` or `mini`. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: "src/client", plugins: [ // ...other plugins { name: "zod", compatibilityVersion: 3, }, ], }; ``` ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: "src/client", plugins: [ // ...other plugins { name: "zod", compatibilityVersion: "mini", }, ], }; ``` ## 0.79.2 ### Patch Changes - [#2034](https://github.com/hey-api/openapi-ts/pull/2034) [`257dd07`](https://github.com/hey-api/openapi-ts/commit/257dd0711f81221c49d26dc57c079f1ae956ca6e) Thanks [@Le0Developer](https://github.com/Le0Developer)! - fix(typescript): add support for TypeID types - [#2041](https://github.com/hey-api/openapi-ts/pull/2041) [`2755be9`](https://github.com/hey-api/openapi-ts/commit/2755be939376227969d2b216f556666cef67f01a) Thanks [@alexvuka1](https://github.com/alexvuka1)! - fix(parser): respect `output.case` when generating operation id ## 0.79.1 ### Patch Changes - [#2336](https://github.com/hey-api/openapi-ts/pull/2336) [`6302793`](https://github.com/hey-api/openapi-ts/commit/63027931f85bad817a8111c263579fd018cb39cb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: respect NO_INTERACTIVE and NO_INTERACTION environment variables - [#2331](https://github.com/hey-api/openapi-ts/pull/2331) [`a309fc7`](https://github.com/hey-api/openapi-ts/commit/a309fc799d4c0899b781e40a721dd1aa834e42f3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): update Axios headers types - [#2334](https://github.com/hey-api/openapi-ts/pull/2334) [`298be27`](https://github.com/hey-api/openapi-ts/commit/298be2715106c840067f54648ee8e94314dfc742) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve handlebars types for jsr compliance - [#2333](https://github.com/hey-api/openapi-ts/pull/2333) [`566c8e9`](https://github.com/hey-api/openapi-ts/commit/566c8e99aeaa6142aa65b8af370f2ff7e0f4d219) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): set query key base url from options if defined ## 0.79.0 ### Minor Changes - [#2284](https://github.com/hey-api/openapi-ts/pull/2284) [`236550f`](https://github.com/hey-api/openapi-ts/commit/236550fa56645dffe855f051fc144b8d8342f5fc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): removed `typescript+namespace` enums mode ### Removed `typescript+namespace` enums mode Due to a simpler TypeScript plugin implementation, the `typescript+namespace` enums mode is no longer necessary. This mode was used in the past to group inline enums under the same namespace. With the latest changes, this behavior is no longer supported. You can either choose to ignore inline enums (default), or use the `enums` transform (added in v0.78.0) to convert them into reusable components which will get exported as usual. ## 0.78.3 ### Patch Changes - [#2290](https://github.com/hey-api/openapi-ts/pull/2290) [`4a77615`](https://github.com/hey-api/openapi-ts/commit/4a776157d0168f4f5f267581874861c2e84ef544) Thanks [@btmnk](https://github.com/btmnk)! - fix(client): improve types to pass `@total-typescript/ts-reset` rules ## 0.78.2 ### Patch Changes - [#2281](https://github.com/hey-api/openapi-ts/pull/2281) [`565830b`](https://github.com/hey-api/openapi-ts/commit/565830b97c34efe632db69b423c2d10b80693b76) Thanks [@j-ibarra](https://github.com/j-ibarra)! - fix(transformers): add `transformers` option allowing passing custom transform functions ## 0.78.1 ### Patch Changes - [#2275](https://github.com/hey-api/openapi-ts/pull/2275) [`1581b5c`](https://github.com/hey-api/openapi-ts/commit/1581b5cd9b2ff160d10c19ff8c195063155c66ae) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(valibot): properly handle array minLength and maxLength - [#2279](https://github.com/hey-api/openapi-ts/pull/2279) [`f0549f6`](https://github.com/hey-api/openapi-ts/commit/f0549f62d50da8a92a330bcdc73b22ee6d211be3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): handle additionalProperties in propertyNames - [#2277](https://github.com/hey-api/openapi-ts/pull/2277) [`25fc54c`](https://github.com/hey-api/openapi-ts/commit/25fc54cd9088240faa47ff7c9607e17c2e52780d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(clients): annotate serializer return types - [#2280](https://github.com/hey-api/openapi-ts/pull/2280) [`ae9c45a`](https://github.com/hey-api/openapi-ts/commit/ae9c45a79cac56362552033b49ebf2958e11324c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(zod): add `dates.offset` option ## 0.78.0 ### Minor Changes - [#2246](https://github.com/hey-api/openapi-ts/pull/2246) [`a11a8c5`](https://github.com/hey-api/openapi-ts/commit/a11a8c5d0e3fd3f8564e4b0873babdee0dfea2d3) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(config): add `parser` options ### Added `parser` options Previously, `@hey-api/typescript` would generate correct types, but the validator plugins would have to re-implement the same logic or generate schemas that didn't match the generated types. Since neither option was ideal, this release adds a dedicated place for `parser` options. Parser is responsible for preparing the input so plugins can generate more accurate output with less effort. You can learn more about configuring parser on the [Parser](https://heyapi.dev/openapi-ts/configuration/parser) page. ### Moved `input` options The following options were moved to the new `parser` group. - `input.filters` moved to `parser.filters` - `input.pagination` moved to `parser.pagination` - `input.patch` moved to `parser.patch` - `input.validate_EXPERIMENTAL` moved to `parser.validate_EXPERIMENTAL` ### Updated `typescript` options The following options were renamed. - `enumsCase` moved to `enums.case` - `enumsConstantsIgnoreNull` moved to `enums.constantsIgnoreNull` ### Moved `typescript` options The following options were moved to the new `parser` group. - `exportInlineEnums` moved to `parser.transforms.enums` - `readOnlyWriteOnlyBehavior` moved to `parser.transforms.readWrite.enabled` - `readableNameBuilder` moved to `parser.transforms.readWrite.responses.name` - `writableNameBuilder` moved to `parser.transforms.readWrite.requests.name` ### Updated `readWrite.responses` name Additionally, the naming pattern for response schemas has changed from `{name}Readable` to `{name}`. This is to prevent your code from breaking by default when using a schema that gets updated with a write-only field. ### Patch Changes - [#2246](https://github.com/hey-api/openapi-ts/pull/2246) [`d901bd5`](https://github.com/hey-api/openapi-ts/commit/d901bd55e17c9a06abfa5af4d9ac62a06dd6c82e) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(config): add `operations` option to `parser.patch` ## 0.77.0 ### Minor Changes - [#2227](https://github.com/hey-api/openapi-ts/pull/2227) [`4ea6f24`](https://github.com/hey-api/openapi-ts/commit/4ea6f24d02d8e8867313073d003f0b573f2054db) Thanks [@mrlubos](https://github.com/mrlubos)! - refactor(plugin): add `DefinePlugin` utility types ### Updated Plugin API Please refer to the [custom plugin](https://heyapi.dev/openapi-ts/plugins/custom) tutorial for the latest guide. - [#2227](https://github.com/hey-api/openapi-ts/pull/2227) [`4ea6f24`](https://github.com/hey-api/openapi-ts/commit/4ea6f24d02d8e8867313073d003f0b573f2054db) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(sdk): update `validator` option ### Updated `sdk.validator` option Clients can now validate both request and response data. As a result, passing a boolean or string to `validator` will control both of these options. To preserve the previous behavior, set `validator.request` to `false` and `validator.response` to your previous configuration. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: "src/client", plugins: [ // ...other plugins { name: "@hey-api/sdk", validator: { request: false, response: true, }, }, ], }; ``` ### Patch Changes - [#2227](https://github.com/hey-api/openapi-ts/pull/2227) [`4ea6f24`](https://github.com/hey-api/openapi-ts/commit/4ea6f24d02d8e8867313073d003f0b573f2054db) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(client): add requestValidator option ## 0.76.0 ### Minor Changes - [#2226](https://github.com/hey-api/openapi-ts/pull/2226) [`1c66d88`](https://github.com/hey-api/openapi-ts/commit/1c66d8866fa25dc9cf978ef94eab3bf8ca64d9f3) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(valibot): generate a single schema for requests ### Single Valibot schema per request Previously, we generated a separate schema for each endpoint parameter and request body. In v0.76.0, a single request schema is generated for the whole endpoint. It may contain a request body, parameters, and headers. ```ts const vData = v.object({ body: v.optional( v.object({ foo: v.optional(v.string()), bar: v.optional(v.union([v.number(), v.null()])), }) ), headers: v.optional(v.never()), path: v.object({ baz: v.string(), }), query: v.optional(v.never()), }); ``` If you need to access individual fields, you can do so using the [`.entries`](https://valibot.dev/api/object/) API. For example, we can get the request body schema with `vData.entries.body`. ### Patch Changes - [#2221](https://github.com/hey-api/openapi-ts/pull/2221) [`e335e1e`](https://github.com/hey-api/openapi-ts/commit/e335e1ea31256b3b284b7ef968d566c1315096b3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): prefer JSON media type - [#2226](https://github.com/hey-api/openapi-ts/pull/2226) [`1c66d88`](https://github.com/hey-api/openapi-ts/commit/1c66d8866fa25dc9cf978ef94eab3bf8ca64d9f3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(valibot): add `metadata` option to generate additional metadata for documentation, code generation, AI structured outputs, form validation, and other purposes ## 0.75.0 ### Minor Changes - [#2215](https://github.com/hey-api/openapi-ts/pull/2215) [`82e56e9`](https://github.com/hey-api/openapi-ts/commit/82e56e926e90d8575302db7fa4843b3663ac3971) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(parser): replace `plugin.subscribe()` with `plugin.forEach()` ### Added `plugin.forEach()` method This method replaces the `.subscribe()` method. Additionally, `.forEach()` is executed immediately, which means we don't need the `before` and `after` events – simply move your code before and after the `.forEach()` block. ```ts plugin.forEach("operation", "schema", (event) => { // do something with event }); ``` - [#2218](https://github.com/hey-api/openapi-ts/pull/2218) [`e5ff024`](https://github.com/hey-api/openapi-ts/commit/e5ff024d4ff2c715276fda88269e7c1668cb929e) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(tanstack-query): add name and case options ### Updated TanStack Query options The TanStack Query plugin options have been expanded to support more naming and casing patterns. As a result, the following options have been renamed. - `queryOptionsNameBuilder` renamed to `queryOptions` - `infiniteQueryOptionsNameBuilder` renamed to `infiniteQueryOptions` - `mutationOptionsNameBuilder` renamed to `mutationOptions` - `queryKeyNameBuilder` renamed to `queryKeys` - `infiniteQueryKeyNameBuilder` renamed to `infiniteQueryKeys` ### Patch Changes - [#2219](https://github.com/hey-api/openapi-ts/pull/2219) [`4df6fa0`](https://github.com/hey-api/openapi-ts/commit/4df6fa0540c4e0e0adce485cb813ea57bf97b908) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make output pass stricter tsconfig configurations" - [#2213](https://github.com/hey-api/openapi-ts/pull/2213) [`2ffb612`](https://github.com/hey-api/openapi-ts/commit/2ffb61253b302d746c4f08beae9daeec345343f6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(validators): handle additional properties object when no other properties are defined - [#2216](https://github.com/hey-api/openapi-ts/pull/2216) [`1456f87`](https://github.com/hey-api/openapi-ts/commit/1456f878cbe7ad7d2894a3ba8dddcc8b79d04920) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): add `meta` and `version` options to input.patch - [#2210](https://github.com/hey-api/openapi-ts/pull/2210) [`5b1362a`](https://github.com/hey-api/openapi-ts/commit/5b1362ae8bebf9aef846140e1400270131cbe64f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(cli): correctly detect watch mode ## 0.74.0 ### Minor Changes - [#2201](https://github.com/hey-api/openapi-ts/pull/2201) [`ab8cede`](https://github.com/hey-api/openapi-ts/commit/ab8cedefe0ca99492d064dfc191f5445bd8102fb) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(zod): generate a single schema for requests ### Single Zod schema per request Previously, we generated a separate schema for each endpoint parameter and request body. In v0.74.0, a single request schema is generated for the whole endpoint. It may contain a request body, parameters, and headers. ```ts const zData = z.object({ body: z .object({ foo: z.string().optional(), bar: z.union([z.number(), z.null()]).optional(), }) .optional(), headers: z.never().optional(), path: z.object({ baz: z.string(), }), query: z.never().optional(), }); ``` If you need to access individual fields, you can do so using the [`.shape`](https://zod.dev/api?id=shape) API. For example, we can get the request body schema with `zData.shape.body`. ### Patch Changes - [#2192](https://github.com/hey-api/openapi-ts/pull/2192) [`7a740ed`](https://github.com/hey-api/openapi-ts/commit/7a740ed2007b81c0088f4d80dd3401c9af673767) Thanks [@Daschi1](https://github.com/Daschi1)! - fix(valibot): use `isoTimestamp` instead of `isoDateTime` for date-time format - [#2201](https://github.com/hey-api/openapi-ts/pull/2201) [`a889c3c`](https://github.com/hey-api/openapi-ts/commit/a889c3c899b54aec73a3ecffc071a412b44c112a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): do not mark schemas as duplicate if they have different format ## 0.73.0 ### Minor Changes - [#2172](https://github.com/hey-api/openapi-ts/pull/2172) [`29605a0`](https://github.com/hey-api/openapi-ts/commit/29605a0e1b58e986458275833a98a396eede9089) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: bundle `@hey-api/client-*` plugins ### Bundle `@hey-api/client-*` plugins In previous releases, you had to install a separate client package to generate a fully working output, e.g. `npm install @hey-api/client-fetch`. This created a few challenges: getting started was slower, upgrading was sometimes painful, and bundling too. Beginning with v0.73.0, all Hey API clients are bundled by default and don't require installing any additional dependencies. You can remove any installed client packages and re-run `@hey-api/openapi-ts`. ```sh npm uninstall @hey-api/client-fetch ``` ### Patch Changes - [#2172](https://github.com/hey-api/openapi-ts/pull/2172) [`9afbf66`](https://github.com/hey-api/openapi-ts/commit/9afbf666614ecb597f68ec809981f2acc28c66dc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: respect logs setting if initialization fails - [#2170](https://github.com/hey-api/openapi-ts/pull/2170) [`c18dd1e`](https://github.com/hey-api/openapi-ts/commit/c18dd1e41b1c055306932ca6d3fa905c14ad1dd4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export default pagination keywords ## 0.72.2 ### Patch Changes - [#2163](https://github.com/hey-api/openapi-ts/pull/2163) [`9769998`](https://github.com/hey-api/openapi-ts/commit/9769998550b1cb77f838827a9617b9dbbfa54537) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(zod): add `metadata` option to generate additional metadata for documentation, code generation, AI structured outputs, form validation, and other purposes - [#2167](https://github.com/hey-api/openapi-ts/pull/2167) [`a46259e`](https://github.com/hey-api/openapi-ts/commit/a46259eb4d2ed1c95908a5ad3d69b0495a8aacb4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): add name builder options for all generated artifacts - [#2166](https://github.com/hey-api/openapi-ts/pull/2166) [`594f3a6`](https://github.com/hey-api/openapi-ts/commit/594f3a6c7a154294fd99f5f76f2b0a9589a1e7f3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): filter orphans only when there are some operations - [#2166](https://github.com/hey-api/openapi-ts/pull/2166) [`594f3a6`](https://github.com/hey-api/openapi-ts/commit/594f3a6c7a154294fd99f5f76f2b0a9589a1e7f3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(zod): support tuple types - [#2167](https://github.com/hey-api/openapi-ts/pull/2167) [`a46259e`](https://github.com/hey-api/openapi-ts/commit/a46259eb4d2ed1c95908a5ad3d69b0495a8aacb4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): set correct subscription context for plugins ## 0.72.1 ### Patch Changes - [#2159](https://github.com/hey-api/openapi-ts/pull/2159) [`87b2d6c`](https://github.com/hey-api/openapi-ts/commit/87b2d6cf075a3d0466a2e510a2fc89b409d57e3e) Thanks [@Joshua-hypt](https://github.com/Joshua-hypt)! - fix(zod): handle array union types ## 0.72.0 ### Minor Changes - [#2141](https://github.com/hey-api/openapi-ts/pull/2141) [`557769d`](https://github.com/hey-api/openapi-ts/commit/557769d10a7b4da55489239a437c9611a3c41a24) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(sdk): add `classStructure` option supporting dot or slash `operationId` notation when generating class-based SDKs ### Added `sdk.classStructure` option When generating class-based SDKs, we now try to infer the ideal structure using `operationId` keywords. If you'd like to preserve the previous behavior, set `classStructure` to `off`. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: "src/client", plugins: [ // ...other plugins { classStructure: "off", name: "@hey-api/sdk", }, ], }; ``` ### Patch Changes - [#2151](https://github.com/hey-api/openapi-ts/pull/2151) [`0ea8130`](https://github.com/hey-api/openapi-ts/commit/0ea8130ff6b2e047dbc4fd6a30d08f54da367d0c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add crash report prompt - [#2153](https://github.com/hey-api/openapi-ts/pull/2153) [`b272bd9`](https://github.com/hey-api/openapi-ts/commit/b272bd9e4adfb0d87a05b023bc078246e7ee4937) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): handle `propertyNames` keyword - [#2152](https://github.com/hey-api/openapi-ts/pull/2152) [`6d5ad37`](https://github.com/hey-api/openapi-ts/commit/6d5ad37e474ad659efb8ffdc649829ac4e1e1b8a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(validators): correctly generate default value for `BigInt` - [#2151](https://github.com/hey-api/openapi-ts/pull/2151) [`aef80c3`](https://github.com/hey-api/openapi-ts/commit/aef80c397b254f391543ff11cac417fab8397c8b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): handle nested inline objects with write/read only fields ## 0.71.1 ### Patch Changes - [#2139](https://github.com/hey-api/openapi-ts/pull/2139) [`0c27937`](https://github.com/hey-api/openapi-ts/commit/0c279378b9be7bf0eaa29586999ecd3b983a26a4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): skip schema if it's an array or tuple and its items don't have any matching readable or writable scopes - [#2140](https://github.com/hey-api/openapi-ts/pull/2140) [`54049fe`](https://github.com/hey-api/openapi-ts/commit/54049fe262336f5b439a540cbe362478ecbe8317) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): validate operationId keyword - [#2137](https://github.com/hey-api/openapi-ts/pull/2137) [`058dbc9`](https://github.com/hey-api/openapi-ts/commit/058dbc9fa81c95dca02788ad58231915cb1c4de3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): respect exportFromIndex option when using legacy clients ## 0.71.0 ### Minor Changes - [#2130](https://github.com/hey-api/openapi-ts/pull/2130) [`dc7535e`](https://github.com/hey-api/openapi-ts/commit/dc7535e6ed5b01ef722d536b909202e28ab16b46) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(sdk): rename `serviceNameBuilder` to `classNameBuilder` ### Patch Changes - [#2117](https://github.com/hey-api/openapi-ts/pull/2117) [`a1435b9`](https://github.com/hey-api/openapi-ts/commit/a1435b915a272d9ffa599c194ee52c2a33f77fcd) Thanks [@johnny-mh](https://github.com/johnny-mh)! - feat(parser): allow patching specs with `input.patch` - [#2132](https://github.com/hey-api/openapi-ts/pull/2132) [`9473613`](https://github.com/hey-api/openapi-ts/commit/9473613187a72a4ae4ed3047994b076c89285737) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): better detect enum namespace - [#2130](https://github.com/hey-api/openapi-ts/pull/2130) [`dc7535e`](https://github.com/hey-api/openapi-ts/commit/dc7535e6ed5b01ef722d536b909202e28ab16b46) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(sdk): add `instance` option for instantiable SDKs ## 0.70.0 ### Minor Changes - [#2123](https://github.com/hey-api/openapi-ts/pull/2123) [`4d8c030`](https://github.com/hey-api/openapi-ts/commit/4d8c03038979c9a75315cc158789b3c198c62f90) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(sdk): add responseStyle option **BREAKING**: Update your client to the latest version. ### Patch Changes - [#2116](https://github.com/hey-api/openapi-ts/pull/2116) [`21ddf25`](https://github.com/hey-api/openapi-ts/commit/21ddf252fd556827240334a8f1f8cf3bae8ff5da) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): ensure generated enum uses unique namespace to avoid conflicts with non-enum declarations - [#2116](https://github.com/hey-api/openapi-ts/pull/2116) [`08f3f89`](https://github.com/hey-api/openapi-ts/commit/08f3f898a8b5939a9e6eed70f6424d2bc5084da8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): handle duplicate inline enum names ## 0.69.2 ### Patch Changes - [#2110](https://github.com/hey-api/openapi-ts/pull/2110) [`323a966`](https://github.com/hey-api/openapi-ts/commit/323a9661213e41723af1d7944232064022814d2b) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(parser): add validate_EXPERIMENTAL option - [#2114](https://github.com/hey-api/openapi-ts/pull/2114) [`55980f5`](https://github.com/hey-api/openapi-ts/commit/55980f533812cb33dc32e034f22aee1d58fe6c19) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(validators): do not wrap regular expression in slashes if the pattern is already wrapped - [#2115](https://github.com/hey-api/openapi-ts/pull/2115) [`a94d3c0`](https://github.com/hey-api/openapi-ts/commit/a94d3c0503bbeeff026e9fea362f907a0e5d4cb7) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): create a shallow copy of queryKey in createInfiniteParams function ## 0.69.1 ### Patch Changes - [#2109](https://github.com/hey-api/openapi-ts/pull/2109) [`6d6b087`](https://github.com/hey-api/openapi-ts/commit/6d6b08771e78d184c6b17c97c6baa5a750b84581) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(valibot): use isoDate instead of date for date strings - [#2108](https://github.com/hey-api/openapi-ts/pull/2108) [`7e604fa`](https://github.com/hey-api/openapi-ts/commit/7e604fa03f34bcf621033f3ca633fa2365a79c53) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): generates union of arrays when items use nested oneOf - [#2106](https://github.com/hey-api/openapi-ts/pull/2106) [`b0cb0ab`](https://github.com/hey-api/openapi-ts/commit/b0cb0abe0f63f144380cde5fe3a2381f61038e5f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(schema): nameBuilder can be a string - [#2106](https://github.com/hey-api/openapi-ts/pull/2106) [`b0cb0ab`](https://github.com/hey-api/openapi-ts/commit/b0cb0abe0f63f144380cde5fe3a2381f61038e5f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(sdk): serviceNameBuilder can be a function ## 0.69.0 ### Minor Changes - [#2094](https://github.com/hey-api/openapi-ts/pull/2094) [`8152aaf`](https://github.com/hey-api/openapi-ts/commit/8152aaf4892c48b79fd3dc486eb3c0ea333dc3e6) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(sdk): use responses/errors map instead of union **BREAKING**: Update your client to the latest version. ### Patch Changes - [#2100](https://github.com/hey-api/openapi-ts/pull/2100) [`54757a2`](https://github.com/hey-api/openapi-ts/commit/54757a2cf266a0ee49277baaa6765e078c95f2a3) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(validators): generate schemas for request parameters - [#2099](https://github.com/hey-api/openapi-ts/pull/2099) [`a9484e0`](https://github.com/hey-api/openapi-ts/commit/a9484e0792dded8ccba280f0f4b55b72d22b3d83) Thanks [@mrlubos](https://github.com/mrlubos)! - feat(validators): generate schemas for request bodies - [#2097](https://github.com/hey-api/openapi-ts/pull/2097) [`d95802f`](https://github.com/hey-api/openapi-ts/commit/d95802f92e504f19130bd2e18a4355ce51e38ce0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(sdk): skip spreading required headers when there are conflicting Content-Type headers - [#2096](https://github.com/hey-api/openapi-ts/pull/2096) [`22e0b3b`](https://github.com/hey-api/openapi-ts/commit/22e0b3bccf94b49fd82665e96074ab76eb241109) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(pagination): improved schema resolver for parameters ## 0.68.1 ### Patch Changes - [#2086](https://github.com/hey-api/openapi-ts/pull/2086) [`ae8aacd`](https://github.com/hey-api/openapi-ts/commit/ae8aacd8bf2a80bb4a2af2cae2b7993e988ee17a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): add back support for regular expressions in input filters - [#2086](https://github.com/hey-api/openapi-ts/pull/2086) [`ae8aacd`](https://github.com/hey-api/openapi-ts/commit/ae8aacd8bf2a80bb4a2af2cae2b7993e988ee17a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): extend input filters to handle reusable parameters and responses ## 0.68.0 ### Minor Changes - [#2072](https://github.com/hey-api/openapi-ts/pull/2072) [`8bea7d2`](https://github.com/hey-api/openapi-ts/commit/8bea7d23a6280ee8dc843be656da820179140403) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: upgraded input filters ### Upgraded input filters Input filters now avoid generating invalid output without requiring you to specify every missing schema as in the previous releases. As part of this release, we changed the way filters are configured and removed the support for regular expressions. Let us know if regular expressions are still useful for you and want to bring them back! ```js export default { input: { // match only the schema named `foo` and `GET` operation for the `/api/v1/foo` path filters: { operations: { include: ['GET /api/v1/foo'], // [!code ++] }, schemas: { include: ['foo'], // [!code ++] }, }, include: '^(#/components/schemas/foo|#/paths/api/v1/foo/get) ``` ## 0.67.6 ### Patch Changes - [#2068](https://github.com/hey-api/openapi-ts/pull/2068) [`93b62fd`](https://github.com/hey-api/openapi-ts/commit/93b62fd433a09f28c75f58852e1baaa2b6fbd641) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): require options when sdk client is set to false - [#2060](https://github.com/hey-api/openapi-ts/pull/2060) [`373e15a`](https://github.com/hey-api/openapi-ts/commit/373e15a34fd81ac596a0797ddb133a47aeceee1f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(valibot): add valibot plugin ## 0.67.5 ### Patch Changes - [#2052](https://github.com/hey-api/openapi-ts/pull/2052) [`f430eaa`](https://github.com/hey-api/openapi-ts/commit/f430eaad13d83d2191fff12802d9283099d7a527) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): add SDK function comments to TanStack Query output - [#2058](https://github.com/hey-api/openapi-ts/pull/2058) [`e9fda0b`](https://github.com/hey-api/openapi-ts/commit/e9fda0bff09c534333691f981363f445dc97129f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): exclude $refs in readable/writable schemas when referenced schemas don't contain any readable/writable fields - [#2059](https://github.com/hey-api/openapi-ts/pull/2059) [`af2082f`](https://github.com/hey-api/openapi-ts/commit/af2082f75dd02a52f8196709d7497dc99c5321e5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): add enumsConstantsIgnoreNull option to skip nulls from generated JavaScript objects ## 0.67.4 ### Patch Changes - [#2043](https://github.com/hey-api/openapi-ts/pull/2043) [`e3997c8`](https://github.com/hey-api/openapi-ts/commit/e3997c8d9a9e8a6da7bc4b417769e751887ff6ac) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle enum keyword with array type ## 0.67.3 ### Patch Changes - [#2020](https://github.com/hey-api/openapi-ts/pull/2020) [`27cb409`](https://github.com/hey-api/openapi-ts/commit/27cb4095383aff35f1d78094b8b73fb36f432d33) Thanks [@0xfurai](https://github.com/0xfurai)! - fix: handle references to properties ## 0.67.2 ### Patch Changes - [#2023](https://github.com/hey-api/openapi-ts/pull/2023) [`c6f01f3`](https://github.com/hey-api/openapi-ts/commit/c6f01f39493e241f01dd7997ccdb8b6bc3d1519c) Thanks [@kennidenni](https://github.com/kennidenni)! - fix: handle relative paths in client's `baseUrl` field ## 0.67.1 ### Patch Changes - [#2010](https://github.com/hey-api/openapi-ts/pull/2010) [`13c9577`](https://github.com/hey-api/openapi-ts/commit/13c9577f122eab7b7fdd92f67ac77cb334cbdcd5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not use named imports from typescript module ## 0.67.0 ### Minor Changes - [#2003](https://github.com/hey-api/openapi-ts/pull/2003) [`1504a06`](https://github.com/hey-api/openapi-ts/commit/1504a0642fdb4f856d1650fade2d30988b35b4ff) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: respect `moduleResolution` value in `tsconfig.json` ### Respecting `moduleResolution` value in `tsconfig.json` This release introduces functionality related to your `tsconfig.json` file. The initial feature properly respects the value of your `moduleResolution` field. If you're using `nodenext`, the relative module paths in your output will be appended with `.js`. To preserve the previous behavior where we never appended `.js` to relative module paths, set `output.tsConfigPath` to `off`. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: { path: "src/client", tsConfigPath: "off", }, }; ``` ### Patch Changes - [#2006](https://github.com/hey-api/openapi-ts/pull/2006) [`aa10522`](https://github.com/hey-api/openapi-ts/commit/aa10522f2bd018a417d875e5ab12ed0a848d2e49) Thanks [@Liooo](https://github.com/Liooo)! - fix: make discriminator field required when used with `oneOf` keyword - [#2009](https://github.com/hey-api/openapi-ts/pull/2009) [`f45ba8e`](https://github.com/hey-api/openapi-ts/commit/f45ba8e96872a13be71c0d07e134f8c6717458d4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: avoid including underscore for appended types (e.g. data, error, response) when preserving identifier case ## 0.66.7 ### Patch Changes - [#1981](https://github.com/hey-api/openapi-ts/pull/1981) [`955b95a`](https://github.com/hey-api/openapi-ts/commit/955b95ab051401bdbeaa8cfb93a7a7b707cb7529) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle schemas with all write-only or read-only fields - [#1990](https://github.com/hey-api/openapi-ts/pull/1990) [`2fb1689`](https://github.com/hey-api/openapi-ts/commit/2fb1689b6538d32d123235175159d412df988241) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: avoid generating duplicate operation ids when sanitizing input - [#1991](https://github.com/hey-api/openapi-ts/pull/1991) [`b6e654a`](https://github.com/hey-api/openapi-ts/commit/b6e654a6e18698f3c554848f8b8113e30f108fc4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod schemas use .and() instead of .merge() - [#1919](https://github.com/hey-api/openapi-ts/pull/1919) [`ec62470`](https://github.com/hey-api/openapi-ts/commit/ec624709b1fb07da8d7234fe851561054dc68150) Thanks [@ngalluzzo](https://github.com/ngalluzzo)! - fix: correctly handle numeric property names with signs - [#1984](https://github.com/hey-api/openapi-ts/pull/1984) [`0f305e0`](https://github.com/hey-api/openapi-ts/commit/0f305e06337758ee16c801ad437d9ce0996fc8b0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod plugin handles nullable enums - [#1986](https://github.com/hey-api/openapi-ts/pull/1986) [`dbebff8`](https://github.com/hey-api/openapi-ts/commit/dbebff8dcba4c93d0c534e6e48e59e2aaaffd540) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle discriminator with multiple mappings to the same schema - [#1980](https://github.com/hey-api/openapi-ts/pull/1980) [`0d7bede`](https://github.com/hey-api/openapi-ts/commit/0d7bede6e40553ae1c4c888770c84e55732b3cae) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod schemas with BigInt and min/max constraints - [#1987](https://github.com/hey-api/openapi-ts/pull/1987) [`71e2fd0`](https://github.com/hey-api/openapi-ts/commit/71e2fd029f2374ed8d2eaa01beecf254757e08d8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correct path to nested plugin files when using exportFromIndex - [#1978](https://github.com/hey-api/openapi-ts/pull/1978) [`267f4b3`](https://github.com/hey-api/openapi-ts/commit/267f4b3730f2a477906e4e1593154dcd1723e554) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle extended `$ref` with `type` keyword in OpenAPI 3.1 - [#1982](https://github.com/hey-api/openapi-ts/pull/1982) [`1e6d74f`](https://github.com/hey-api/openapi-ts/commit/1e6d74f8321af5c61f86318b835d25db38609b03) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle additionalProperties empty object as unknown instead of preserving an empty interface ## 0.66.6 ### Patch Changes - [#1971](https://github.com/hey-api/openapi-ts/pull/1971) [`e1fb199`](https://github.com/hey-api/openapi-ts/commit/e1fb199a22a30653b95d498e6aaca2c59ed2b13b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle Zod circular reference ## 0.66.5 ### Patch Changes - [#1951](https://github.com/hey-api/openapi-ts/pull/1951) [`4be46e5`](https://github.com/hey-api/openapi-ts/commit/4be46e506db1b2c53d1ddbf66e9919b5072f1cc0) Thanks [@devNameAsyraf](https://github.com/devNameAsyraf)! - fix: don't use JSON serializer for `application/octet-stream` - [#1938](https://github.com/hey-api/openapi-ts/pull/1938) [`2a03e37`](https://github.com/hey-api/openapi-ts/commit/2a03e371715b5948ba568009975ad65ccbf7bfd7) Thanks [@sredni](https://github.com/sredni)! - fix: repeat tuple type `maxItems` times ## 0.66.4 ### Patch Changes - [#1936](https://github.com/hey-api/openapi-ts/pull/1936) [`ba2e5ca`](https://github.com/hey-api/openapi-ts/commit/ba2e5ca8af1cfe478963d72ff76d7d7ae026c5a5) Thanks [@seriouslag](https://github.com/seriouslag)! - fix: add return type to TanStack Query mutations - [#1934](https://github.com/hey-api/openapi-ts/pull/1934) [`d4df550`](https://github.com/hey-api/openapi-ts/commit/d4df5503369b7aa105c7f6a49e1c7b43e0e50f49) Thanks [@seriouslag](https://github.com/seriouslag)! - fix: export some internal functions ## 0.66.3 ### Patch Changes - [#1917](https://github.com/hey-api/openapi-ts/pull/1917) [`d7af22c`](https://github.com/hey-api/openapi-ts/commit/d7af22c771af4bd2dab28acc69430717da390670) Thanks [@Freddis](https://github.com/Freddis)! - fix: handle nullable dates in transformers ## 0.66.2 ### Patch Changes - [#1913](https://github.com/hey-api/openapi-ts/pull/1913) [`7cfa4a7`](https://github.com/hey-api/openapi-ts/commit/7cfa4a76b13ca97d49c5f0366ba7264f94753d8b) Thanks [@BogdanMaier](https://github.com/BogdanMaier)! - fix: prevent crash when optional pagination field is missing ## 0.66.1 ### Patch Changes - [#1906](https://github.com/hey-api/openapi-ts/pull/1906) [`d1928d1`](https://github.com/hey-api/openapi-ts/commit/d1928d17710240bb42a6aa12da4618a9dd962df2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: exclude and include expressions can be an array - [#1906](https://github.com/hey-api/openapi-ts/pull/1906) [`d1928d1`](https://github.com/hey-api/openapi-ts/commit/d1928d17710240bb42a6aa12da4618a9dd962df2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support excluding deprecated fields with '@deprecated' ## 0.66.0 ### Minor Changes - [#1896](https://github.com/hey-api/openapi-ts/pull/1896) [`8840ed7`](https://github.com/hey-api/openapi-ts/commit/8840ed73df5ee718e803aa6e27b66e0c82ec3651) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support read-only and write-only properties ### Read-only and write-only fields Starting with v0.66.0, `@hey-api/typescript` will generate separate types for payloads and responses if it detects any read-only or write-only fields. To preserve the previous behavior and generate a single type regardless, set `readOnlyWriteOnlyBehavior` to `off`. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: "src/client", plugins: [ // ...other plugins { name: "@hey-api/typescript", readOnlyWriteOnlyBehavior: "off", // [!code ++] }, ], }; ``` ## 0.65.0 ### Minor Changes - [#1889](https://github.com/hey-api/openapi-ts/pull/1889) [`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support custom clients ### Patch Changes - [#1892](https://github.com/hey-api/openapi-ts/pull/1892) [`29fa764`](https://github.com/hey-api/openapi-ts/commit/29fa764986af3d3af842793c74d61681c7e967a1) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow passing fetch options to the request resolving a specification - [#1877](https://github.com/hey-api/openapi-ts/pull/1877) [`6971f5b`](https://github.com/hey-api/openapi-ts/commit/6971f5bca4dd17ea65400c504ad0a4ffb083a38b) Thanks [@Matsuuu](https://github.com/Matsuuu)! - feat: ability to disable writing a log file via a `--no-log-file` flag or `logs.file` = `false` ## 0.64.15 ### Patch Changes - [#1850](https://github.com/hey-api/openapi-ts/pull/1850) [`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1) Thanks [@kelnos](https://github.com/kelnos)! - feat: add support for cookies auth ## 0.64.14 ### Patch Changes - [#1827](https://github.com/hey-api/openapi-ts/pull/1827) [`9dd43db`](https://github.com/hey-api/openapi-ts/commit/9dd43db54f2b7ebf87c5c7c118fdf149162a533d) Thanks [@john-cremit](https://github.com/john-cremit)! - feat: allow customizing pagination keywords using `input.pagination.keywords` ## 0.64.13 ### Patch Changes - [#1822](https://github.com/hey-api/openapi-ts/pull/1822) [`c73b0d4`](https://github.com/hey-api/openapi-ts/commit/c73b0d401c2bfa6f0b0d89d844a6aa09f2685a69) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: bump json-schema-ref-parser package - [#1826](https://github.com/hey-api/openapi-ts/pull/1826) [`90886c1`](https://github.com/hey-api/openapi-ts/commit/90886c1372a999e8cb59d5da218762f6ee6cd459) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow config to be a function ## 0.64.12 ### Patch Changes - [#1816](https://github.com/hey-api/openapi-ts/pull/1816) [`b9e1b4b`](https://github.com/hey-api/openapi-ts/commit/b9e1b4bec5e1c5d1f2b5b9cfc7fa145274ae604d) Thanks [@shemsiu](https://github.com/shemsiu)! - Allow `scheme` property to be case-insensitive ## 0.64.11 ### Patch Changes - [#1800](https://github.com/hey-api/openapi-ts/pull/1800) [`a4811bd`](https://github.com/hey-api/openapi-ts/commit/a4811bdf178ec1a7f1602e0483a32fe7303f4eac) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support Hey API platform input arguments - [#1800](https://github.com/hey-api/openapi-ts/pull/1800) [`a4811bd`](https://github.com/hey-api/openapi-ts/commit/a4811bdf178ec1a7f1602e0483a32fe7303f4eac) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle raw OpenAPI specification input ## 0.64.10 ### Patch Changes - [#1779](https://github.com/hey-api/openapi-ts/pull/1779) [`57fcec8`](https://github.com/hey-api/openapi-ts/commit/57fcec804e339cfe508cfba4afd203c22495bff2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: don't throw on missing performance marks - [#1767](https://github.com/hey-api/openapi-ts/pull/1767) [`2de84ea`](https://github.com/hey-api/openapi-ts/commit/2de84ea3dbd2cba50150808a872aea8242c33014) Thanks [@Schroedi](https://github.com/Schroedi)! - fix: handle nested dates in transformers ## 0.64.9 ### Patch Changes - [#1774](https://github.com/hey-api/openapi-ts/pull/1774) [`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: announce Hey API platform ## 0.64.8 ### Patch Changes - [#1764](https://github.com/hey-api/openapi-ts/pull/1764) [`b3ecac3`](https://github.com/hey-api/openapi-ts/commit/b3ecac31d49a269ab400db4dbb84a22f1047e19a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: reduce minimum Node.js 22 version to 22.10.0 ## 0.64.7 ### Patch Changes - [#1755](https://github.com/hey-api/openapi-ts/pull/1755) [`82f7c14`](https://github.com/hey-api/openapi-ts/commit/82f7c1425dd903b75d15cf532b88580d180f281a) Thanks [@Matsuuu](https://github.com/Matsuuu)! - fix: Wrap the GET request in watch mode with try-catch to prevent crashes on no-head watch targets ## 0.64.6 ### Patch Changes - [#1748](https://github.com/hey-api/openapi-ts/pull/1748) [`7326d25`](https://github.com/hey-api/openapi-ts/commit/7326d2550ae3336fd8f754f8d4a25f1a40c13a2b) Thanks [@Matsuuu](https://github.com/Matsuuu)! - fix: Wrap HEAD request in a try-catch to prevent watch mode crashes on server reloads ## 0.64.5 ### Patch Changes - [#1728](https://github.com/hey-api/openapi-ts/pull/1728) [`cc8dabb`](https://github.com/hey-api/openapi-ts/commit/cc8dabbf1cb94879bb08fe66ecb04c4d0801e9cc) Thanks [@georgesmith46](https://github.com/georgesmith46)! - fix: correctly generate zod regex expressions when using patterns ## 0.64.4 ### Patch Changes - [#1710](https://github.com/hey-api/openapi-ts/pull/1710) [`4afdaa1`](https://github.com/hey-api/openapi-ts/commit/4afdaa1247b0bf0629817a51c29ca25840569b77) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use relative path to custom config file if provided when resolving relative paths ## 0.64.3 ### Patch Changes - [#1701](https://github.com/hey-api/openapi-ts/pull/1701) [`e86629b`](https://github.com/hey-api/openapi-ts/commit/e86629bfa9ae2a47131d3a9a240a6aa2a4f67911) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly type default value for Nuxt client ## 0.64.2 ### Patch Changes - [#1697](https://github.com/hey-api/openapi-ts/pull/1697) [`dec3fed`](https://github.com/hey-api/openapi-ts/commit/dec3fedb5f51aad4711fec15a006c525cb0bf7d8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add exportFromIndex option to all plugins - [#1699](https://github.com/hey-api/openapi-ts/pull/1699) [`8ff188f`](https://github.com/hey-api/openapi-ts/commit/8ff188fb269cf46321538dbe846e1b9ae3b8de42) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow passing arbitrary values to SDK functions via `meta` field - [#1687](https://github.com/hey-api/openapi-ts/pull/1687) [`04c7cea`](https://github.com/hey-api/openapi-ts/commit/04c7ceac940a81cbed6a4070d9244aa5052ba4a2) Thanks [@hunshcn](https://github.com/hunshcn)! - sanitize "+" in uri to avoid plus in function name ## 0.64.1 ### Patch Changes - [#1668](https://github.com/hey-api/openapi-ts/pull/1668) [`7a03341`](https://github.com/hey-api/openapi-ts/commit/7a03341301d9d56ae93b4e4e3bd1ca469444f886) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: watch mode handles servers not exposing HEAD method for spec - [#1668](https://github.com/hey-api/openapi-ts/pull/1668) [`7a03341`](https://github.com/hey-api/openapi-ts/commit/7a03341301d9d56ae93b4e4e3bd1ca469444f886) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add watch.timeout option ## 0.64.0 ### Minor Changes - [#1661](https://github.com/hey-api/openapi-ts/pull/1661) [`ccefe43`](https://github.com/hey-api/openapi-ts/commit/ccefe434ee83f1202769547ce128e1c134dee25f) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: added `client.baseUrl` option ### Added `client.baseUrl` option You can use this option to configure the default base URL for the generated client. By default, we will attempt to resolve the first defined server or infer the base URL from the input path. If you'd like to preserve the previous behavior, set `baseUrl` to `false`. ```js export default { input: "path/to/openapi.json", output: "src/client", plugins: [ { baseUrl: false, // [!code ++] name: "@hey-api/client-fetch", }, ], }; ``` - [#1661](https://github.com/hey-api/openapi-ts/pull/1661) [`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make createConfig, CreateClientConfig, and Config accept ClientOptions generic ### Added `ClientOptions` interface The `Config` interface now accepts an optional generic extending `ClientOptions` instead of `boolean` type `ThrowOnError`. ```ts type Foo = Config; // [!code --] type Foo = Config<{ throwOnError: false }>; // [!code ++] ``` ## 0.63.2 ### Patch Changes - [#1651](https://github.com/hey-api/openapi-ts/pull/1651) [`df350f3`](https://github.com/hey-api/openapi-ts/commit/df350f31dae957d063010ba46c5008ae831b3a32) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: lower Node version requirements ## 0.63.1 ### Patch Changes - [#1637](https://github.com/hey-api/openapi-ts/pull/1637) [`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update keywords in package.json - [#1637](https://github.com/hey-api/openapi-ts/pull/1637) [`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add Next.js client - [#1646](https://github.com/hey-api/openapi-ts/pull/1646) [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support required client in SDK using sdk.client = false - [#1648](https://github.com/hey-api/openapi-ts/pull/1648) [`66a9e45`](https://github.com/hey-api/openapi-ts/commit/66a9e4517d2306da8c60750dc3380e6774a7177b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for openIdConnect auth flow ## 0.63.0 ### Minor Changes - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: move clients to plugins ### Client plugins Clients are now plugins generating their own `client.gen.ts` file. There's no migration needed if you're using CLI. If you're using the configuration file, move `client` options to `plugins`. ```js export default { client: "@hey-api/client-fetch", // [!code --] input: "path/to/openapi.json", output: "src/client", plugins: ["@hey-api/client-fetch"], // [!code ++] }; ``` ### Patch Changes - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: move sdk.throwOnError option to client.throwOnError ### Moved `sdk.throwOnError` option This SDK configuration option has been moved to the client plugins where applicable. Not every client can be configured to throw on error, so it didn't make sense to expose the option when it didn't have any effect. ```js export default { input: "path/to/openapi.json", output: "src/client", plugins: [ { name: "@hey-api/client-fetch", throwOnError: true, // [!code ++] }, { name: "@hey-api/sdk", throwOnError: true, // [!code --] }, ], }; ``` - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: sdks import client from client.gen.ts instead of defining it inside the file ### Added `client.gen.ts` file The internal `client` instance previously located in `sdk.gen.ts` is now defined in `client.gen.ts`. If you're importing it in your code, update the import module. ```js import { client } from "client/sdk.gen"; // [!code --] import { client } from "client/client.gen"; // [!code ++] ``` - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: throw if inferred plugin not found ## 0.62.3 ### Patch Changes - [#1600](https://github.com/hey-api/openapi-ts/pull/1600) [`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: bundle clients from compiled index file - [#1594](https://github.com/hey-api/openapi-ts/pull/1594) [`bc66cde`](https://github.com/hey-api/openapi-ts/commit/bc66cde1ebe0e2df08c8d04b3ddc9504e4952cf3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate correct response for text/plain content type - [#1596](https://github.com/hey-api/openapi-ts/pull/1596) [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not use a body serializer on text/plain sdks - [#1602](https://github.com/hey-api/openapi-ts/pull/1602) [`194f941`](https://github.com/hey-api/openapi-ts/commit/194f94110545f2cae07bde13b863cd0cb5284d8a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support all oauth2 flows in sdk auth - [#1596](https://github.com/hey-api/openapi-ts/pull/1596) [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add null to valid bodySerializer types ## 0.62.2 ### Patch Changes - [#1519](https://github.com/hey-api/openapi-ts/pull/1519) [`14d3c4c`](https://github.com/hey-api/openapi-ts/commit/14d3c4ce0393d543e2d3aaebbfcf8f0cf32483b0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for Nuxt client ## 0.62.1 ### Patch Changes - [#1574](https://github.com/hey-api/openapi-ts/pull/1574) [`51bf7fc`](https://github.com/hey-api/openapi-ts/commit/51bf7fc88cb6e9ab392106b85f900a75540e524f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate bigint type instead of BigInt - [#1572](https://github.com/hey-api/openapi-ts/pull/1572) [`0e4882a`](https://github.com/hey-api/openapi-ts/commit/0e4882ae3b0dc048a2d9a2a0b5c39fbdeed6de8d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add ability to skip generating index file with output.indexFile ## 0.62.0 ### Minor Changes - [#1568](https://github.com/hey-api/openapi-ts/pull/1568) [`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: change the default parser ### Patch Changes - [#1566](https://github.com/hey-api/openapi-ts/pull/1566) [`39d558a`](https://github.com/hey-api/openapi-ts/commit/39d558afc6af97fe8de1a6471b9d1f172ec2960a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: spread sdk options at the end to allow overriding generated values ## 0.61.3 ### Patch Changes - [#1552](https://github.com/hey-api/openapi-ts/pull/1552) [`ceb8bd7`](https://github.com/hey-api/openapi-ts/commit/ceb8bd74207566871e9f179cb28b2d8c440ef2c8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use z.coerce before calling z.bigint ## 0.61.2 ### Patch Changes - [#1543](https://github.com/hey-api/openapi-ts/pull/1543) [`7a2d6dc`](https://github.com/hey-api/openapi-ts/commit/7a2d6dcd6e30411178ac5c78db3f1dbbcc8d6b27) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: send GET request only on first spec fetch ## 0.61.1 ### Patch Changes - [#1530](https://github.com/hey-api/openapi-ts/pull/1530) [`67b7295`](https://github.com/hey-api/openapi-ts/commit/67b72959be499ff59f5f68bfdaa7e5568f5de02f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: detect pagination in composite schemas with null type - [#1535](https://github.com/hey-api/openapi-ts/pull/1535) [`d4cfa05`](https://github.com/hey-api/openapi-ts/commit/d4cfa05ed425d57f79b28efe76e6a33f1e892ec5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle primitive constants in Zod and types ## 0.61.0 ### Minor Changes - [#1520](https://github.com/hey-api/openapi-ts/pull/1520) [`b3c23ba`](https://github.com/hey-api/openapi-ts/commit/b3c23ba99c361bdca3ab9c44017b6e5c044f40a7) Thanks [@chriswiggins](https://github.com/chriswiggins)! - Add support for HTTP Bearer Authentication Scheme - [#1525](https://github.com/hey-api/openapi-ts/pull/1525) [`7b7313e`](https://github.com/hey-api/openapi-ts/commit/7b7313eeaf9a749fb81465546bc4e4bdce31d5ab) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add OpenAPI 2.0 support to experimental parser - [#1511](https://github.com/hey-api/openapi-ts/pull/1511) [`4e8064d`](https://github.com/hey-api/openapi-ts/commit/4e8064d9a589e14b42d2b1a329e2436f242884da) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add watch mode ## Watch Mode ::: warning Watch mode currently supports only remote files via URL. ::: If your schema changes frequently, you may want to automatically regenerate the output during development. To watch your input file for changes, enable `watch` mode in your configuration or pass the `--watch` flag to the CLI. ### Config ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", watch: true, }; ``` ### CLI ```sh npx @hey-api/openapi-ts \ -c @hey-api/client-fetch \ -i path/to/openapi.json \ -o src/client \ -w ``` - **BREAKING**: please update `@hey-api/client-*` packages to the latest version feat: add support for basic http auth ### Patch Changes - [#1529](https://github.com/hey-api/openapi-ts/pull/1529) [`ccc0bbc`](https://github.com/hey-api/openapi-ts/commit/ccc0bbcbdeace22bbd8e92caadebdca81e61e393) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for long integers - [#1512](https://github.com/hey-api/openapi-ts/pull/1512) [`dd0e0a2`](https://github.com/hey-api/openapi-ts/commit/dd0e0a266153e34448fbc3db6b0f864f75483280) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add `sdk.throwOnError` option - [#1525](https://github.com/hey-api/openapi-ts/pull/1525) [`7b7313e`](https://github.com/hey-api/openapi-ts/commit/7b7313eeaf9a749fb81465546bc4e4bdce31d5ab) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: preserve leading separators in enum keys ## 0.60.1 ### Patch Changes - [#1468](https://github.com/hey-api/openapi-ts/pull/1468) [`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle indexed access checks - [#1469](https://github.com/hey-api/openapi-ts/pull/1469) [`a7608c2`](https://github.com/hey-api/openapi-ts/commit/a7608c27ced3419dee228f4b0cd96479b3dc2c04) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: zod: generate patterns and improve plain schemas - [#1471](https://github.com/hey-api/openapi-ts/pull/1471) [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add links to the experimental parser callouts - [#1462](https://github.com/hey-api/openapi-ts/pull/1462) [`893d6ef`](https://github.com/hey-api/openapi-ts/commit/893d6ef5677d17b96174f505937f6da686abb2bc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update types for custom plugins so defineConfig does not throw - [#1464](https://github.com/hey-api/openapi-ts/pull/1464) [`787d59c`](https://github.com/hey-api/openapi-ts/commit/787d59c307549f5faf9f83314a8e9692bb01eb5d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export IR types - [#1467](https://github.com/hey-api/openapi-ts/pull/1467) [`3a3f8d7`](https://github.com/hey-api/openapi-ts/commit/3a3f8d7ea4c993d4372e4bc52f6d9525bf1e45b6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export utils - [#1457](https://github.com/hey-api/openapi-ts/pull/1457) [`bc03c37`](https://github.com/hey-api/openapi-ts/commit/bc03c373f4df61d8d715dc13badba2a6c5a3a450) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow plugins to explicitly declare whether they should be re-exported from the index file ## 0.60.0 ### Minor Changes - [#1430](https://github.com/hey-api/openapi-ts/pull/1430) [`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: require sdk.transformer to use generated transformers ### Added `sdk.transformer` option When generating SDKs, you now have to specify `transformer` in order to modify response data. By default, adding `@hey-api/transformers` to your plugins will only produce additional output. To preserve the previous functionality, set `sdk.transformer` to `true`. ```js import { defaultPlugins } from "@hey-api/openapi-ts"; export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", plugins: [ ...defaultPlugins, { dates: true, name: "@hey-api/transformers", }, { name: "@hey-api/sdk", transformer: true, // [!code ++] }, ], }; ``` - [#1447](https://github.com/hey-api/openapi-ts/pull/1447) [`200821b`](https://github.com/hey-api/openapi-ts/commit/200821b3ceea8ffca7656fe3f6e2ef98b7110a2a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: revert license to MIT ### Patch Changes - [#1430](https://github.com/hey-api/openapi-ts/pull/1430) [`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: Zod plugin generates response schemas ## 0.59.2 ### Patch Changes - [#1420](https://github.com/hey-api/openapi-ts/pull/1420) [`8010dbb`](https://github.com/hey-api/openapi-ts/commit/8010dbb1ab8b91d1d49d5cf16276183764a63ff3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate querySerializer options for Axios client - [#1419](https://github.com/hey-api/openapi-ts/pull/1419) [`4555796`](https://github.com/hey-api/openapi-ts/commit/4555796df3a33fb3fdf7d7417f7d1f3b22d89bcf) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: infer responseType in SDKs for axios client - [#1409](https://github.com/hey-api/openapi-ts/pull/1409) [`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support oauth2 and apiKey security schemes - [#1416](https://github.com/hey-api/openapi-ts/pull/1416) [`2a605b7`](https://github.com/hey-api/openapi-ts/commit/2a605b7e43655b3100e302e10b9979fbbad6cdfe) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: zod plugin handles recursive schemas ## 0.59.1 ### Patch Changes - [#1398](https://github.com/hey-api/openapi-ts/pull/1398) [`a88e7d9`](https://github.com/hey-api/openapi-ts/commit/a88e7d9f8a313c641cf651256a710d0610b95b5d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: prefix restricted identifier names with underscore - [#1394](https://github.com/hey-api/openapi-ts/pull/1394) [`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: disallow additional query parameters in experimental parser output ## 0.59.0 ### Minor Changes - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`7c4335d`](https://github.com/hey-api/openapi-ts/commit/7c4335d12782c73b5b242e7d5786ec8778857d1d) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add `logs.level` option ### Added `logs.level` option You can now configure different log levels. As part of this feature, we had to introduce a breaking change by moving the `debug` option to `logs.level`. This will affect you if you're calling `@hey-api/openapi-ts` from Node.js (not CLI) or using the configuration file. ```js export default { client: "@hey-api/client-fetch", debug: true, // [!code --] input: "path/to/openapi.json", logs: { level: "debug", // [!code ++] }, output: "src/client", }; ``` - [#1389](https://github.com/hey-api/openapi-ts/pull/1389) [`f4c98ec`](https://github.com/hey-api/openapi-ts/commit/f4c98ec429ee989ae1c76328f4d42d44f14cb52e) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: remove `@hey-api/schemas` from default plugins ### Updated default `plugins` `@hey-api/schemas` has been removed from the default plugins. To continue using it, add it to your plugins array. ```js import { defaultPlugins } from "@hey-api/openapi-ts"; export default { client: "@hey-api/client-fetch", experimentalParser: true, input: "path/to/openapi.json", output: "src/client", plugins: [ ...defaultPlugins, "@hey-api/schemas", // [!code ++] ], }; ``` ### Patch Changes - [#1382](https://github.com/hey-api/openapi-ts/pull/1382) [`3580c1e`](https://github.com/hey-api/openapi-ts/commit/3580c1eec4640d235a1e0f78bf76581e532aaf8b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly resolve required properties in nested allOf composition - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`7c4335d`](https://github.com/hey-api/openapi-ts/commit/7c4335d12782c73b5b242e7d5786ec8778857d1d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add `--silent` or `-s` CLI option for silent log level - [#1382](https://github.com/hey-api/openapi-ts/pull/1382) [`3580c1e`](https://github.com/hey-api/openapi-ts/commit/3580c1eec4640d235a1e0f78bf76581e532aaf8b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: transformers handle allOf composition in experimental parser - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`0def82c`](https://github.com/hey-api/openapi-ts/commit/0def82c91d1be936702690b8cf5a21775974d946) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add `logs` configuration option to customize log directory - [#1390](https://github.com/hey-api/openapi-ts/pull/1390) [`8388c47`](https://github.com/hey-api/openapi-ts/commit/8388c4720dbb657899d5e30bd8d59c19583cad98) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow arbitrary object properties when additionalProperties is undefined - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`7c4335d`](https://github.com/hey-api/openapi-ts/commit/7c4335d12782c73b5b242e7d5786ec8778857d1d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support `DEBUG` environment variable ## 0.58.0 ### Minor Changes - [#1353](https://github.com/hey-api/openapi-ts/pull/1353) [`efd3e54`](https://github.com/hey-api/openapi-ts/commit/efd3e5444d208ea0c8dda7573f26bb04c31cc372) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add typescript.identifierCase option ### Added `typescript.identifierCase` option **This change affects only the experimental parser.** By default, the generated TypeScript interfaces will follow the PascalCase naming convention. In the previous versions, we tried to preserve the original name as much as possible. To keep the previous behavior, set `typescript.identifierCase` to `preserve`. ```js export default { client: "@hey-api/client-fetch", experimentalParser: true, input: "path/to/openapi.json", output: "src/client", plugins: [ // ...other plugins { identifierCase: "preserve", // [!code ++] name: "@hey-api/typescript", }, ], }; ``` - [#1360](https://github.com/hey-api/openapi-ts/pull/1360) [`5f6ddd7`](https://github.com/hey-api/openapi-ts/commit/5f6ddd796f0ce77bcca55fd13981f2a8481aecd3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: remove schemas and transformers re-exports from index.ts ### Removed `schemas.gen.ts` re-export `index.ts` will no longer re-export `schemas.gen.ts` to reduce the chance of producing broken output. Please update your code to import from `schemas.gen.ts` directly. ```js import { mySchema } from "client"; // [!code --] import { mySchema } from "client/schemas.gen"; // [!code ++] ``` ### Removed `transformers.gen.ts` re-export `index.ts` will no longer re-export `transformers.gen.ts` to reduce the chance of producing broken output. Please update your code to import from `transformers.gen.ts` directly. ```js import { myTransformer } from "client"; // [!code --] import { myTransformer } from "client/transformers.gen"; // [!code ++] ``` - [#1360](https://github.com/hey-api/openapi-ts/pull/1360) [`5f6ddd7`](https://github.com/hey-api/openapi-ts/commit/5f6ddd796f0ce77bcca55fd13981f2a8481aecd3) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add output.clean option ### Added `output.clean` option By default, the `output.path` folder will be emptied on every run. To preserve the previous behavior, set `output.clean` to `false`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: { clean: false, // [!code ++] path: "src/client", }, }; ``` - [#1362](https://github.com/hey-api/openapi-ts/pull/1362) [`3bf7169`](https://github.com/hey-api/openapi-ts/commit/3bf7169b620946d99c17cf5398d7a818d0099f94) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add typescript.enumsCase option ### Patch Changes - [#1361](https://github.com/hey-api/openapi-ts/pull/1361) [`a23c25e`](https://github.com/hey-api/openapi-ts/commit/a23c25ea1b5ca8bf421302bf93690168df3473cb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add before and after to pagination keywords - [#1368](https://github.com/hey-api/openapi-ts/pull/1368) [`cca2290`](https://github.com/hey-api/openapi-ts/commit/cca2290aeaab0b9807c928d73dbfc1e4bacadc4d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export Plugin API namespace - [#1369](https://github.com/hey-api/openapi-ts/pull/1369) [`11163f0`](https://github.com/hey-api/openapi-ts/commit/11163f0d6885633078126849c04c0646e7d19255) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: TanStack Query plugin handles conflict with internal function name in experimental parser ## 0.57.1 ### Patch Changes - [#1335](https://github.com/hey-api/openapi-ts/pull/1335) [`bb9a848`](https://github.com/hey-api/openapi-ts/commit/bb9a84869dc911861f3b12f725a470b8fd6b67fe) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: transformers correctly handle an array - [#1332](https://github.com/hey-api/openapi-ts/pull/1332) [`25b598b`](https://github.com/hey-api/openapi-ts/commit/25b598bcecd1dd3eb3da6b7c7f24f4adb0170114) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve camelcase with abbreviated plurals - [#1333](https://github.com/hey-api/openapi-ts/pull/1333) [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser generates url inside data types - [#1336](https://github.com/hey-api/openapi-ts/pull/1336) [`6857da8`](https://github.com/hey-api/openapi-ts/commit/6857da8a7f23829a89115b2237aaac9a71a38dfb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser transforms anyOf date and null - [#1330](https://github.com/hey-api/openapi-ts/pull/1330) [`3d68587`](https://github.com/hey-api/openapi-ts/commit/3d6858748c94d6e33fd4dae7ddbf6cb70d21aaee) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser handles empty string and null enum values in JavaScript mode - [#1340](https://github.com/hey-api/openapi-ts/pull/1340) [`c8511e0`](https://github.com/hey-api/openapi-ts/commit/c8511e0d84dd408407bf764fb0bae4938b70dacb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser exports reusable request bodies ## 0.57.0 ### Minor Changes - [#1324](https://github.com/hey-api/openapi-ts/pull/1324) [`4e62378`](https://github.com/hey-api/openapi-ts/commit/4e62378352d8306580293ee4aeef43756d245f85) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: rename Hey API plugins ### Renamed `@hey-api/services` plugin This plugin has been renamed to `@hey-api/sdk`. ### Changed `sdk.output` value To align with the updated name, the `@hey-api/sdk` plugin will generate an `sdk.gen.ts` file. This will result in a breaking change if you're importing from `services.gen.ts`. Please update your imports to reflect this change. ```js import { client } from "client/services.gen"; // [!code --] import { client } from "client/sdk.gen"; // [!code ++] ``` ### Renamed `@hey-api/types` plugin This plugin has been renamed to `@hey-api/typescript`. - [#1327](https://github.com/hey-api/openapi-ts/pull/1327) [`62e37d5`](https://github.com/hey-api/openapi-ts/commit/62e37d51e9d829e11d08a494060c1e808ce2e3f3) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add typescript.exportInlineEnums option ### Added `typescript.exportInlineEnums` option By default, inline enums (enums not defined as reusable components in the input file) will be generated only as inlined union types. You can set `exportInlineEnums` to `true` to treat inline enums as reusable components. When `true`, the exported enums will follow the style defined in `enums`. This is a breaking change since in the previous versions, inline enums were always treated as reusable components. To preserve your current output, set `exportInlineEnums` to `true`. This feature works only with the experimental parser. ```js export default { client: "@hey-api/client-fetch", experimentalParser: true, input: "path/to/openapi.json", output: "src/client", plugins: [ // ...other plugins { exportInlineEnums: true, // [!code ++] name: "@hey-api/typescript", }, ], }; ``` ### Patch Changes - [#1326](https://github.com/hey-api/openapi-ts/pull/1326) [`01c3d69`](https://github.com/hey-api/openapi-ts/commit/01c3d69e4c97262cd6dda5061f0a76f3b4fda31a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve generated enum keys in experimental parser ## 0.56.3 ### Patch Changes - [#1319](https://github.com/hey-api/openapi-ts/pull/1319) [`af76a77`](https://github.com/hey-api/openapi-ts/commit/af76a7705c585fcfae0c72872f358936f7d19d56) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod plugin handles value constraints and defaults ## 0.56.2 ### Patch Changes - [#1316](https://github.com/hey-api/openapi-ts/pull/1316) [`a79fac8`](https://github.com/hey-api/openapi-ts/commit/a79fac8919ed29eec7195cbd441ffa38b559d63c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add input.exclude option - [#1316](https://github.com/hey-api/openapi-ts/pull/1316) [`a79fac8`](https://github.com/hey-api/openapi-ts/commit/a79fac8919ed29eec7195cbd441ffa38b559d63c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make Zod plugin available in plugins options ## 0.56.1 ### Patch Changes - [#1309](https://github.com/hey-api/openapi-ts/pull/1309) [`785480b`](https://github.com/hey-api/openapi-ts/commit/785480b2d5f96a681dfc1f7f0fb626f744bb221f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: gracefully handle invalid schema type in experimental parser ## 0.56.0 ### Minor Changes - [#1286](https://github.com/hey-api/openapi-ts/pull/1286) [`5514de4`](https://github.com/hey-api/openapi-ts/commit/5514de46a8c913ddc40f07d0142c80266e9837cd) Thanks [@jacobinu](https://github.com/jacobinu)! - feat: add `fastify` plugin ### Patch Changes - [#1286](https://github.com/hey-api/openapi-ts/pull/1286) [`cebf327`](https://github.com/hey-api/openapi-ts/commit/cebf327046c801b375846bae6b07561b8ad1bdd6) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: export a map of error and response types by status code - [#1286](https://github.com/hey-api/openapi-ts/pull/1286) [`8a15a35`](https://github.com/hey-api/openapi-ts/commit/8a15a35e86ff22eca85dc218bc1793315b934556) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: deprecate types.tree option - [#1305](https://github.com/hey-api/openapi-ts/pull/1305) [`a3698a7`](https://github.com/hey-api/openapi-ts/commit/a3698a7f1680d7dfb913c6253f8685ebbdd132ca) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle file-like content media type without explicit schema ## 0.55.3 ### Patch Changes - [#1283](https://github.com/hey-api/openapi-ts/pull/1283) [`781d1a4`](https://github.com/hey-api/openapi-ts/commit/781d1a40d10ce380f1ca2cb2bc7aca7d3b169bc6) Thanks [@hougesen](https://github.com/hougesen)! - feat: add support for oxlint as linter ## 0.55.2 ### Patch Changes - [#1253](https://github.com/hey-api/openapi-ts/pull/1253) [`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update sponsorship links - [#1266](https://github.com/hey-api/openapi-ts/pull/1266) [`d60d260`](https://github.com/hey-api/openapi-ts/commit/d60d260342ff3013c2e228151e9b897224eb89cc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly generate array when items are a oneOf array with length 1 - [#1265](https://github.com/hey-api/openapi-ts/pull/1265) [`691cdc2`](https://github.com/hey-api/openapi-ts/commit/691cdc28b6ad5bc1a38e1ae9eb134a2b41d4ead8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle non-exploded array query parameters - [#1267](https://github.com/hey-api/openapi-ts/pull/1267) [`ff3aa4a`](https://github.com/hey-api/openapi-ts/commit/ff3aa4ac58068671d2b9eedbd7528eb4f9969386) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle discriminators in experimental parser ## 0.55.1 ### Patch Changes - [#1248](https://github.com/hey-api/openapi-ts/pull/1248) [`61cd848`](https://github.com/hey-api/openapi-ts/commit/61cd848262b20580fb185d023c28aa54754bf19c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle nullable enums in experimental parser - [#1251](https://github.com/hey-api/openapi-ts/pull/1251) [`07800d4`](https://github.com/hey-api/openapi-ts/commit/07800d4fbb849614ed2c23b8acc9c82f1ef74598) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for custom plugins - [#1250](https://github.com/hey-api/openapi-ts/pull/1250) [`9e07675`](https://github.com/hey-api/openapi-ts/commit/9e07675802c75b8f5105dd104bb7736aeb83ece6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: render void for empty response status codes in experimental parser ## 0.55.0 ### Minor Changes - [#1241](https://github.com/hey-api/openapi-ts/pull/1241) [`41cee41`](https://github.com/hey-api/openapi-ts/commit/41cee417055c50de6170e6fdeae65bd6e643d19c) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add input.include option ### Patch Changes - [#1239](https://github.com/hey-api/openapi-ts/pull/1239) [`319a28a`](https://github.com/hey-api/openapi-ts/commit/319a28af29541d7f61cca82389e1d486204f321f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle pagination with basic refs ## 0.54.4 ### Patch Changes - [#1237](https://github.com/hey-api/openapi-ts/pull/1237) [`63ccc07`](https://github.com/hey-api/openapi-ts/commit/63ccc0775e24a096bc46ac7ff29b99b694aad621) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: forbid any body, path, or query parameters if not defined in spec - [#1235](https://github.com/hey-api/openapi-ts/pull/1235) [`7a1a419`](https://github.com/hey-api/openapi-ts/commit/7a1a419f07d5ad39e07265771b30d49a4b754a88) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle additionalProperties: boolean in experimental parser - [#1233](https://github.com/hey-api/openapi-ts/pull/1233) [`08baa77`](https://github.com/hey-api/openapi-ts/commit/08baa77afdc5e2c49d4789b20673e949951ab0b2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update schemas plugin to handle experimental 3.0.x parser This release adds an experimental parser for OpenAPI versions 3.0.x. In the future, this will become the default parser. If you're using OpenAPI 3.0 or newer, we encourage you to try it out today. You can enable the experimental parser by setting the `experimentalParser` boolean flag to `true` in your configuration file or CLI. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", experimentalParser: true, }; ``` ```sh npx @hey-api/openapi-ts -i path/to/openapi.json -o src/client -c @hey-api/client-fetch -e ``` The generated output should not structurally change, despite few things being generated in a different order. In fact, the output should be cleaner! That's the immediate side effect you should notice. If that's not true, please leave feedback in [GitHub issues](https://github.com/hey-api/openapi-ts/issues). Hey API parser marks an important milestone towards v1 of `@hey-api/openapi-ts`. More features will be added to the parser in the future and the original parser from `openapi-typescript-codegen` will be deprecated and used only for generating legacy clients. If you'd like to work with the parser more closely (e.g. to generate code not natively supported by this package), feel free to reach out with any feedback or suggestions. Happy parsing! 🎉 ## 0.54.3 ### Patch Changes - [#1230](https://github.com/hey-api/openapi-ts/pull/1230) [`3e65ae0`](https://github.com/hey-api/openapi-ts/commit/3e65ae06bcd2823482cf012909388c7630e18229) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add OpenAPI 3.0.x experimental parser This release adds an experimental parser for OpenAPI versions 3.0.x. In the future, this will become the default parser. If you're using OpenAPI 3.0 or newer, we encourage you to try it out today. You can enable the experimental parser by setting the `experimentalParser` boolean flag to `true` in your configuration file or CLI. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", experimentalParser: true, }; ``` ```sh npx @hey-api/openapi-ts -i path/to/openapi.json -o src/client -c @hey-api/client-fetch -e ``` The generated output should not structurally change, despite few things being generated in a different order. In fact, the output should be cleaner! That's the immediate side effect you should notice. If that's not true, please leave feedback in [GitHub issues](https://github.com/hey-api/openapi-ts/issues). Hey API parser marks an important milestone towards v1 of `@hey-api/openapi-ts`. More features will be added to the parser in the future and the original parser from `openapi-typescript-codegen` will be deprecated and used only for generating legacy clients. If you'd like to work with the parser more closely (e.g. to generate code not natively supported by this package), feel free to reach out with any feedback or suggestions. Happy parsing! 🎉 ## 0.54.2 ### Patch Changes - [#1222](https://github.com/hey-api/openapi-ts/pull/1222) [`ceb4363`](https://github.com/hey-api/openapi-ts/commit/ceb4363d52893ebe947e21aac402b868ff2820d4) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add support for @tanstack/angular-query-experimental package ## 0.54.1 ### Patch Changes - [#1211](https://github.com/hey-api/openapi-ts/pull/1211) [`c8a3e3d`](https://github.com/hey-api/openapi-ts/commit/c8a3e3d7e59692698b7cf45182ca92494fc4af96) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: ignore name option when not used with legacy clients to avoid producing broken output - [#1209](https://github.com/hey-api/openapi-ts/pull/1209) [`3a80b9f`](https://github.com/hey-api/openapi-ts/commit/3a80b9fd009c8229d69f3f349acbfb19b7549a94) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for OpenAPI 3.1.1 to experimental parser ## 0.54.0 ### Minor Changes - [#1201](https://github.com/hey-api/openapi-ts/pull/1201) [`972a93a`](https://github.com/hey-api/openapi-ts/commit/972a93a91a945cc9ead73c08bb0fa9ee120433ba) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: make plugins first-class citizens This release makes plugins first-class citizens. In order to achieve that, the following breaking changes were introduced. ### Removed CLI options The `--types`, `--schemas`, and `--services` CLI options have been removed. You can list which plugins you'd like to use explicitly by passing a list of plugins as `--plugins ` ### Removed `*.export` option Previously, you could explicitly disable export of certain artifacts using the `*.export` option or its shorthand variant. These were both removed. You can now disable export of specific artifacts by manually defining an array of `plugins` and excluding the unwanted plugin. ::: code-group ```js [shorthand] export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", schemas: false, // [!code --] plugins: ["@hey-api/types", "@hey-api/services"], // [!code ++] }; ``` ```js [*.export] export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", schemas: { export: false, // [!code --] }, plugins: ["@hey-api/types", "@hey-api/services"], // [!code ++] }; ``` ::: ### Renamed `schemas.name` option Each plugin definition contains a `name` field. This was conflicting with the `schemas.name` option. As a result, it has been renamed to `nameBuilder`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", schemas: { name: (name) => `${name}Schema`, // [!code --] }, plugins: [ // ...other plugins { nameBuilder: (name) => `${name}Schema`, // [!code ++] name: "@hey-api/schemas", }, ], }; ``` ### Removed `services.include` shorthand option Previously, you could use a string value as a shorthand for the `services.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", services: "^MySchema", // [!code --] plugins: [ // ...other plugins { include: "^MySchema", // [!code ++] name: "@hey-api/services", }, ], }; ``` ### Renamed `services.name` option Each plugin definition contains a `name` field. This was conflicting with the `services.name` option. As a result, it has been renamed to `serviceNameBuilder`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", services: { name: "{{name}}Service", // [!code --] }, plugins: [ // ...other plugins { serviceNameBuilder: "{{name}}Service", // [!code ++] name: "@hey-api/services", }, ], }; ``` ### Renamed `types.dates` option Previously, you could set `types.dates` to a boolean or a string value, depending on whether you wanted to transform only type strings into dates, or runtime code too. Many people found these options confusing, so they have been simplified to a boolean and extracted into a separate `@hey-api/transformers` plugin. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", types: { dates: "types+transform", // [!code --] }, plugins: [ // ...other plugins { dates: true, // [!code ++] name: "@hey-api/transformers", }, ], }; ``` ### Removed `types.include` shorthand option Previously, you could use a string value as a shorthand for the `types.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", types: "^MySchema", // [!code --] plugins: [ // ...other plugins { include: "^MySchema", // [!code ++] name: "@hey-api/types", }, ], }; ``` ### Renamed `types.name` option Each plugin definition contains a `name` field. This was conflicting with the `types.name` option. As a result, it has been renamed to `style`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", types: { name: "PascalCase", // [!code --] }, plugins: [ // ...other plugins { name: "@hey-api/types", style: "PascalCase", // [!code ++] }, ], }; ``` ## 0.53.12 ### Patch Changes - [#1195](https://github.com/hey-api/openapi-ts/pull/1195) [`753643f`](https://github.com/hey-api/openapi-ts/commit/753643fae74d4248df8dc5fe9dda5f28a1dabdf1) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: TanStack Query plugin using missing import for infinite query - [#1194](https://github.com/hey-api/openapi-ts/pull/1194) [`c38deaf`](https://github.com/hey-api/openapi-ts/commit/c38deaf02b606b92edd9c316b1444b6b6c12916d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: pass TanStack query signal to client call ## 0.53.11 ### Patch Changes - [#1151](https://github.com/hey-api/openapi-ts/pull/1151) [`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update website domain, add license documentation ## 0.53.10 ### Patch Changes - [#1145](https://github.com/hey-api/openapi-ts/pull/1145) [`a0a5551`](https://github.com/hey-api/openapi-ts/commit/a0a55510d30a1a8dea0ade4908b5b13d51b5f9e6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update license field in package.json to match the license, revert client packages license to MIT ## 0.53.9 ### Patch Changes - [#1137](https://github.com/hey-api/openapi-ts/pull/1137) [`f4566c2`](https://github.com/hey-api/openapi-ts/commit/f4566c2bcd67f45f069bfa6220d3c710177f28cc) Thanks [@BierDav](https://github.com/BierDav)! - Add support for passing mutation specific options to `Mutation(options)` ## 0.53.8 ### Patch Changes - [#1123](https://github.com/hey-api/openapi-ts/pull/1123) [`032338c`](https://github.com/hey-api/openapi-ts/commit/032338c47506ccfd567bbbf915398942c8394bc2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use correct relative path to bundled client when imported from nested module ## 0.53.7 ### Patch Changes - [#1113](https://github.com/hey-api/openapi-ts/pull/1113) [`dc696e0`](https://github.com/hey-api/openapi-ts/commit/dc696e0b4500dba5ceb4c772110b123bd2f71b40) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: skip nested properties in oneOf and anyOf compositions - [#1115](https://github.com/hey-api/openapi-ts/pull/1115) [`5f077dd`](https://github.com/hey-api/openapi-ts/commit/5f077dd8d144bbfe71d8775bad5fe7ddda2315d6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: abstract page params logic in TanStack Query plugin ## 0.53.6 ### Patch Changes - [#1104](https://github.com/hey-api/openapi-ts/pull/1104) [`a1eada1`](https://github.com/hey-api/openapi-ts/commit/a1eada1896046f0de1710682635efc59434a1e2c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export spec-compliant OpenAPI 3.1 interface - [#1108](https://github.com/hey-api/openapi-ts/pull/1108) [`7677924`](https://github.com/hey-api/openapi-ts/commit/76779246534391deca5a371df2c7dc76e9d2eb73) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle multiple form-data parameters in Swagger 2.0 ## 0.53.5 ### Patch Changes - [#1096](https://github.com/hey-api/openapi-ts/pull/1096) [`b6e350a`](https://github.com/hey-api/openapi-ts/commit/b6e350a9cc2d82ac4496b7d57ec8b58978c951c2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make TanStack Query plugin work with class-based services - [#1095](https://github.com/hey-api/openapi-ts/pull/1095) [`11ee53f`](https://github.com/hey-api/openapi-ts/commit/11ee53f4f519643ae7e3f0997ce4fe9b6cb050a8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: avoid printing duplicate null nodes - [#1094](https://github.com/hey-api/openapi-ts/pull/1094) [`713ccd5`](https://github.com/hey-api/openapi-ts/commit/713ccd5e5e250a14cacf96fd1dffad252cc4cc6a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: attach TanStack Query infinite page params only if they exist ## 0.53.4 ### Patch Changes - [#1087](https://github.com/hey-api/openapi-ts/pull/1087) [`b528236`](https://github.com/hey-api/openapi-ts/commit/b528236b626d12d4ac03b98b8abecc425291c5e5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: import handlebars instead of runtime - [#1086](https://github.com/hey-api/openapi-ts/pull/1086) [`0bc1ebe`](https://github.com/hey-api/openapi-ts/commit/0bc1ebe318399d01296777746ce0bccc83c0e83d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support dynamic require in child_process ## 0.53.3 ### Patch Changes - [#1075](https://github.com/hey-api/openapi-ts/pull/1075) [`11a276a`](https://github.com/hey-api/openapi-ts/commit/11a276a1e35dde0735363e892d8142016fd87eec) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: properly handle dual publishing and type generation ## 0.53.2 ### Patch Changes - [#1060](https://github.com/hey-api/openapi-ts/pull/1060) [`8d66c08`](https://github.com/hey-api/openapi-ts/commit/8d66c085cf81e0e166c3e172ce319d5e2d4002bf) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle colon in operation path - [#1065](https://github.com/hey-api/openapi-ts/pull/1065) [`a756987`](https://github.com/hey-api/openapi-ts/commit/a756987ad396fd7e68cc5eff63f6615bffef3782) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow overriding generated headers from options - [#1068](https://github.com/hey-api/openapi-ts/pull/1068) [`a48be86`](https://github.com/hey-api/openapi-ts/commit/a48be8660f6d1d84fdf25a3952587fb963482e8a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export Operation interface - [#1067](https://github.com/hey-api/openapi-ts/pull/1067) [`5a52da1`](https://github.com/hey-api/openapi-ts/commit/5a52da1425abef9f4fef58ef077dbd05545e25a2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle named object property with no nested properties - [#1066](https://github.com/hey-api/openapi-ts/pull/1066) [`e8a38ae`](https://github.com/hey-api/openapi-ts/commit/e8a38ae4e3f021a105d18764ef3252db7efa9aa0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: transform any-of nullable dates ## 0.53.1 ### Patch Changes - [#1050](https://github.com/hey-api/openapi-ts/pull/1050) [`6922b5a`](https://github.com/hey-api/openapi-ts/commit/6922b5a3ebe67190d2034ea79674706a5e80e818) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: throw error on invalid client value ## 0.53.0 ### Minor Changes - [#1008](https://github.com/hey-api/openapi-ts/pull/1008) [`dc4a40d`](https://github.com/hey-api/openapi-ts/commit/dc4a40d517853e4cf5be532f5bf4874c84c924be) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: rename legacy clients with 'legacy/' prefix - [#1009](https://github.com/hey-api/openapi-ts/pull/1009) [`c6b044d`](https://github.com/hey-api/openapi-ts/commit/c6b044d0bc9dc54cb0eb58d23438f4e1d050cb38) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: change schemas name pattern, add schemas.name option ### Patch Changes - [#989](https://github.com/hey-api/openapi-ts/pull/989) [`bc78a42`](https://github.com/hey-api/openapi-ts/commit/bc78a421eafed1920102b796842e227cacda6ef0) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: make UserConfig interface instead of type - [#1010](https://github.com/hey-api/openapi-ts/pull/1010) [`b6e58c6`](https://github.com/hey-api/openapi-ts/commit/b6e58c64d1b71897533a85d1738cd7ce7ede178d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: set query key base url from supplied client if provided ## 0.52.11 ### Patch Changes - [#981](https://github.com/hey-api/openapi-ts/pull/981) [`afd8c43`](https://github.com/hey-api/openapi-ts/commit/afd8c4386fb7b2f86a54e73c9471945bdfad22ea) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export query key functions from TanStack Query plugin ## 0.52.10 ### Patch Changes - [#973](https://github.com/hey-api/openapi-ts/pull/973) [`8f7a14f`](https://github.com/hey-api/openapi-ts/commit/8f7a14f570e2d17053f1e612f6e045df774916f1) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: handle tree-shakeable angular client case ## 0.52.9 ### Patch Changes - [#948](https://github.com/hey-api/openapi-ts/pull/948) [`ebfd6ee`](https://github.com/hey-api/openapi-ts/commit/ebfd6eec434d7b84883a8f9058f31948fb1a40f2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle schemas with generics from C# - [#949](https://github.com/hey-api/openapi-ts/pull/949) [`16f8956`](https://github.com/hey-api/openapi-ts/commit/16f89566a7affeb09a6b928c43cfa2733e8b9adc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: rename infinite key in query key to \_infinite - [#946](https://github.com/hey-api/openapi-ts/pull/946) [`f873fa6`](https://github.com/hey-api/openapi-ts/commit/f873fa67befe60b2fd8f63bc2c8b73437591f686) Thanks [@mrlubos](https://github.com/mrlubos)! - chore: warn on duplicate operation ID - [#947](https://github.com/hey-api/openapi-ts/pull/947) [`7f0fefe`](https://github.com/hey-api/openapi-ts/commit/7f0fefec92b25ce18ed0d1c6a6edf1adbc7d4481) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly use parentheses around composed schemas - [#944](https://github.com/hey-api/openapi-ts/pull/944) [`2f7cc89`](https://github.com/hey-api/openapi-ts/commit/2f7cc8986c0644b41cc6a5526ddf52ebff880c79) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly handle integer type in additional properties ## 0.52.8 ### Patch Changes - [#932](https://github.com/hey-api/openapi-ts/pull/932) [`cdf01e8`](https://github.com/hey-api/openapi-ts/commit/cdf01e8cc0dc63213465b9e8fe33b80443d36f55) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: cherry pick keys in mutation page param type ## 0.52.7 ### Patch Changes - [#929](https://github.com/hey-api/openapi-ts/pull/929) [`b56c81c`](https://github.com/hey-api/openapi-ts/commit/b56c81ca67a2d069b33430c3139e2135a299b309) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle various issues with additionalProperties definitions - [#927](https://github.com/hey-api/openapi-ts/pull/927) [`65f151d`](https://github.com/hey-api/openapi-ts/commit/65f151dc0004ce817bc370486495bdd281439e55) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update TanStack Query key to contain base URL - [#927](https://github.com/hey-api/openapi-ts/pull/927) [`65f151d`](https://github.com/hey-api/openapi-ts/commit/65f151dc0004ce817bc370486495bdd281439e55) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: change TanStack Query mutation helpers to functions for consistent API ## 0.52.6 ### Patch Changes - [#920](https://github.com/hey-api/openapi-ts/pull/920) [`4ff2404`](https://github.com/hey-api/openapi-ts/commit/4ff24049457b7d0d5333c3704f488f1f45dd0c5b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add preview version of TanStack Query plugin ## 0.52.5 ### Patch Changes - [#910](https://github.com/hey-api/openapi-ts/pull/910) [`428dcad`](https://github.com/hey-api/openapi-ts/commit/428dcad06eba3ab14876c28092a6df81fcde7dbe) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: throw if prerequisite checks are not met - [#907](https://github.com/hey-api/openapi-ts/pull/907) [`a2a1ab8`](https://github.com/hey-api/openapi-ts/commit/a2a1ab8bd78c2cbbdcb7adb2ba3815250843dbe7) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly transform string to pascalcase when referenced inside schema - [#908](https://github.com/hey-api/openapi-ts/pull/908) [`225b640`](https://github.com/hey-api/openapi-ts/commit/225b640b5ac628cb7ba3b7afb39ff271a0608055) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not generate types tree by default if services are enabled as it is unused ## 0.52.4 ### Patch Changes - [#895](https://github.com/hey-api/openapi-ts/pull/895) [`44de8d8`](https://github.com/hey-api/openapi-ts/commit/44de8d89556b3abf48acc4e23c9b9c198059c757) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: define ThrowOnError generic as the last argument ## 0.52.3 ### Patch Changes - [#884](https://github.com/hey-api/openapi-ts/pull/884) [`62a39e6`](https://github.com/hey-api/openapi-ts/commit/62a39e63f645bce0801779fb6b90531401748e86) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate ThrowOnError generic for class-based client methods ## 0.52.2 ### Patch Changes - [#881](https://github.com/hey-api/openapi-ts/pull/881) [`a9ddfe6`](https://github.com/hey-api/openapi-ts/commit/a9ddfe6c4487fe5debd04a194ee6c6b6c611dc6b) Thanks [@hougesen](https://github.com/hougesen)! - fix: check if key is schema property before removing ## 0.52.1 ### Patch Changes - [#855](https://github.com/hey-api/openapi-ts/pull/855) [`7ac6274`](https://github.com/hey-api/openapi-ts/commit/7ac627463a15fa6be2c9d103b25200355df6b166) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: define multiple errors type as union instead of intersection - [#853](https://github.com/hey-api/openapi-ts/pull/853) [`6ab387d`](https://github.com/hey-api/openapi-ts/commit/6ab387d3440ec5ec524e7f198aedfa6734431d76) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: remove Content-Type header with multipart/form-data content type - [#861](https://github.com/hey-api/openapi-ts/pull/861) [`21ccf90`](https://github.com/hey-api/openapi-ts/commit/21ccf90b864590c211fbfa3de5c687dd3c48f897) Thanks [@qqilihq](https://github.com/qqilihq)! - fix: Additional properties key - [#869](https://github.com/hey-api/openapi-ts/pull/869) [`42d8a41`](https://github.com/hey-api/openapi-ts/commit/42d8a4151bace7b70af60a1abe46b7550ddad686) Thanks [@SamuelGuillemet](https://github.com/SamuelGuillemet)! - fix: add conditionnal generation for service related types ## 0.52.0 ### Minor Changes - [#835](https://github.com/hey-api/openapi-ts/pull/835) [`7ab277b`](https://github.com/hey-api/openapi-ts/commit/7ab277b22467fe268719af817aee701d6be3e828) Thanks [@LeeChSien](https://github.com/LeeChSien)! - feat: add namespace supporting for enums ### Patch Changes - [#830](https://github.com/hey-api/openapi-ts/pull/830) [`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate internal client for services when using standalone package ## 0.51.0 ### Minor Changes - [#828](https://github.com/hey-api/openapi-ts/pull/828) [`82a4696`](https://github.com/hey-api/openapi-ts/commit/82a4696b0b209ea2d9147f47f213479e61aed3d7) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: make `client` config option required ### Patch Changes - [#823](https://github.com/hey-api/openapi-ts/pull/823) [`23c9dcd`](https://github.com/hey-api/openapi-ts/commit/23c9dcd5de19de62d745cc539674c815b2588cd2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly process body parameter for OpenAPI 2.0 specs - [#827](https://github.com/hey-api/openapi-ts/pull/827) [`8d81c06`](https://github.com/hey-api/openapi-ts/commit/8d81c0605dbf4b4d19ec1c2dc51a93f8a2aca5b2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not ignore api-version param in standalone clients ## 0.50.2 ### Patch Changes - [#818](https://github.com/hey-api/openapi-ts/pull/818) [`85d123c`](https://github.com/hey-api/openapi-ts/commit/85d123c9160f4ecb4c48e8a2ead54abf604dd21b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle fully illegal schema names ## 0.50.1 ### Patch Changes - [#807](https://github.com/hey-api/openapi-ts/pull/807) [`ef249ba`](https://github.com/hey-api/openapi-ts/commit/ef249ba5bd04dbfb0e0a497caaa021f9c7de6949) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate types only for filtered services - [#807](https://github.com/hey-api/openapi-ts/pull/807) [`ef249ba`](https://github.com/hey-api/openapi-ts/commit/ef249ba5bd04dbfb0e0a497caaa021f9c7de6949) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow any key/value pair in object types with empty properties object ## 0.50.0 ### Minor Changes - [#790](https://github.com/hey-api/openapi-ts/pull/790) [`68c3921`](https://github.com/hey-api/openapi-ts/commit/68c3921fd6e9a5db41ebd9f06e4f3ef6e64ab051) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: allow bundling standalone clients with `client.bundle = true` ## 0.49.0 ### Minor Changes - [#787](https://github.com/hey-api/openapi-ts/pull/787) [`327c5fb`](https://github.com/hey-api/openapi-ts/commit/327c5fb629f0c7b9c727da87b6bc287b8e98bcd5) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: allow filtering service endpoints with `services.filter` ### Patch Changes - [#784](https://github.com/hey-api/openapi-ts/pull/784) [`f12dccf`](https://github.com/hey-api/openapi-ts/commit/f12dccf0ae3a05badb5783354bcd093f18f3ab74) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: suffix illegal service names - [#786](https://github.com/hey-api/openapi-ts/pull/786) [`20759e2`](https://github.com/hey-api/openapi-ts/commit/20759e2cc52d78974fc0f78f581e9d9cb2d21ca5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle references to schemas with illegal names - [#788](https://github.com/hey-api/openapi-ts/pull/788) [`ecd94f2`](https://github.com/hey-api/openapi-ts/commit/ecd94f2adab1dbe10e7a9c310d1fb6d1f170d332) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle application/x-www-form-urlencoded content in request body ## 0.48.3 ### Patch Changes - [#781](https://github.com/hey-api/openapi-ts/pull/781) [`df3b799`](https://github.com/hey-api/openapi-ts/commit/df3b79996d47a69e4f2fdad93cea18ae1a01c419) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use methodNameBuilder when asClass is false - [#782](https://github.com/hey-api/openapi-ts/pull/782) [`edfd2bd`](https://github.com/hey-api/openapi-ts/commit/edfd2bdbb64f6682ded16f6da30f88f1c113bbe0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow not generating types tree with types.tree = false ## 0.48.2 ### Patch Changes - [#746](https://github.com/hey-api/openapi-ts/pull/746) [`0448823`](https://github.com/hey-api/openapi-ts/commit/044882399d56d1532c7125df2e69cfb3b5fb4f34) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle formData parameters in generated types - [#742](https://github.com/hey-api/openapi-ts/pull/742) [`efc30f4`](https://github.com/hey-api/openapi-ts/commit/efc30f4a2327b165b62f8467c68351a8bf94ffe5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: ignore services.asClass setting for named clients - [#744](https://github.com/hey-api/openapi-ts/pull/744) [`1e9edde`](https://github.com/hey-api/openapi-ts/commit/1e9edde54abd8978405f91b821c99b97f067d566) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve default response type detection - [#745](https://github.com/hey-api/openapi-ts/pull/745) [`342772a`](https://github.com/hey-api/openapi-ts/commit/342772a560378c6718d25c29871eeab9a72c62a6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle properties in one-of composition ## 0.48.1 ### Patch Changes - [#734](https://github.com/hey-api/openapi-ts/pull/734) [`1f52b26`](https://github.com/hey-api/openapi-ts/commit/1f52b260807531edb2c14003473ea4907007ecdb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate service types when types are enabled, even if services are disabled - [#737](https://github.com/hey-api/openapi-ts/pull/737) [`0537fe8`](https://github.com/hey-api/openapi-ts/commit/0537fe8682a93cc95d7637d643db4b9780318ea1) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support custom config file path - [#736](https://github.com/hey-api/openapi-ts/pull/736) [`8410046`](https://github.com/hey-api/openapi-ts/commit/8410046c45d25db48ba940a0c6c7a7cda9e86b6a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle async response transformers ## 0.48.0 ### Minor Changes - [#696](https://github.com/hey-api/openapi-ts/pull/696) [`917405f`](https://github.com/hey-api/openapi-ts/commit/917405fcdcb2e978df693eb51720afa6fcf914e2) Thanks [@anchan828](https://github.com/anchan828)! - feat: pass the Operation object to methodNameBuilder ### Patch Changes - [#708](https://github.com/hey-api/openapi-ts/pull/708) [`36cf95d`](https://github.com/hey-api/openapi-ts/commit/36cf95d319b175149d3b3ecc382b8d739186e658) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make getHeaders() accept generic - [#712](https://github.com/hey-api/openapi-ts/pull/712) [`6a5b96b`](https://github.com/hey-api/openapi-ts/commit/6a5b96b59e4248f2acaf5422be262edde97427dd) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle void responses in transformers ## 0.47.2 ### Patch Changes - [#701](https://github.com/hey-api/openapi-ts/pull/701) [`1081bbf`](https://github.com/hey-api/openapi-ts/commit/1081bbf5082450c18547dac4737ecc0e312cdd0e) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add initial implementation of prefixItems ## 0.47.1 ### Patch Changes - [#690](https://github.com/hey-api/openapi-ts/pull/690) [`1017ace`](https://github.com/hey-api/openapi-ts/commit/1017acee80630d84a08bd8f0087c8fb0de270f1a) Thanks [@Nick-Lucas](https://github.com/Nick-Lucas)! - Fix an issue where transforms for endpoints with array returns were not generated correctly ## 0.47.0 ### Minor Changes - [#685](https://github.com/hey-api/openapi-ts/pull/685) [`8ca3e5e`](https://github.com/hey-api/openapi-ts/commit/8ca3e5e2990bc07ce0bac902245d08b67b6621e8) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add initial support for response transformers (string -> Date) - [#663](https://github.com/hey-api/openapi-ts/pull/663) [`e01c612`](https://github.com/hey-api/openapi-ts/commit/e01c61213e266afad5e3b159682b05957aac6534) Thanks [@Stono](https://github.com/Stono)! - Add support for customizing method names with `services.methodNameBuilder()` ## 0.46.3 ### Patch Changes - [#594](https://github.com/hey-api/openapi-ts/pull/594) [`9878381`](https://github.com/hey-api/openapi-ts/commit/98783811e0c90705ddac2cc5e54c524aae634865) Thanks [@SimenB](https://github.com/SimenB)! - Add explicit type annotations to `Interceptors` This allows the generated code to work with TypeScript 5.5's new `isolatedDeclarations` configuration. - [#635](https://github.com/hey-api/openapi-ts/pull/635) [`0b09940`](https://github.com/hey-api/openapi-ts/commit/0b0994050dbcb6c17e8b78ca1c77738fc8e0d498) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle 1XX response status codes - [#636](https://github.com/hey-api/openapi-ts/pull/636) [`498f459`](https://github.com/hey-api/openapi-ts/commit/498f45979b91bf93b319413c60492af94a08df48) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve default response status code classification ## 0.46.2 ### Patch Changes - fix: do not transform property names for standalone clients ([#616](https://github.com/hey-api/openapi-ts/pull/616)) ## 0.46.1 ### Patch Changes - fix: handle application/json content type in parameter definitions ([#614](https://github.com/hey-api/openapi-ts/pull/614)) ## 0.46.0 ### Minor Changes - feat: tree-shakeable services ([#602](https://github.com/hey-api/openapi-ts/pull/602)) ## 0.45.1 ### Patch Changes - fix: use generated types in request object instead of inlined duplicated params ([#582](https://github.com/hey-api/openapi-ts/pull/582)) ## 0.45.0 ### Minor Changes - feat: remove client inference ([#569](https://github.com/hey-api/openapi-ts/pull/569)) ### Patch Changes - fix: deduplicate inlined enums ([#573](https://github.com/hey-api/openapi-ts/pull/573)) - fix: generate correct optional key in types when using positional arguments (useOptions: false) ([#572](https://github.com/hey-api/openapi-ts/pull/572)) ## 0.44.0 ### Minor Changes - feat: move format and lint config options to output object ([#546](https://github.com/hey-api/openapi-ts/pull/546)) ### Patch Changes - fix: comment position in JavaScript enums ([#544](https://github.com/hey-api/openapi-ts/pull/544)) - fix: export inlined enums from components ([#563](https://github.com/hey-api/openapi-ts/pull/563)) - fix: remove unused enums option from CLI ([#565](https://github.com/hey-api/openapi-ts/pull/565)) - fix: Support typescript in peerDependencies ([#551](https://github.com/hey-api/openapi-ts/pull/551)) ## 0.43.2 ### Patch Changes - fix: deduplicate exported data and response types ([#538](https://github.com/hey-api/openapi-ts/pull/538)) ## 0.43.1 ### Patch Changes - fix: use optional chaining in bin catch block ([#528](https://github.com/hey-api/openapi-ts/pull/528)) - fix: broken encoding ([#532](https://github.com/hey-api/openapi-ts/pull/532)) - fix(parser): handle type array ([#533](https://github.com/hey-api/openapi-ts/pull/533)) ## 0.43.0 ### Minor Changes - feat: remove enum postfix, use typescript enums in types when generated, export enums from types.gen.ts ([#498](https://github.com/hey-api/openapi-ts/pull/498)) ### Patch Changes - fix: negative numbers in numeric enums ([#470](https://github.com/hey-api/openapi-ts/pull/470)) - fix: escape keys in schemas starting with digit but containing non-digit characters ([#502](https://github.com/hey-api/openapi-ts/pull/502)) - fix: issue causing code to not generate (t.filter is not a function) ([#507](https://github.com/hey-api/openapi-ts/pull/507)) - fix: handle additional properties union ([#499](https://github.com/hey-api/openapi-ts/pull/499)) - fix: do not export inline enums ([#508](https://github.com/hey-api/openapi-ts/pull/508)) - fix: prefix parameter type exports to avoid conflicts ([#501](https://github.com/hey-api/openapi-ts/pull/501)) - fix: export operation data and response types ([#500](https://github.com/hey-api/openapi-ts/pull/500)) - fix: handle cases where packages are installed globally ([#471](https://github.com/hey-api/openapi-ts/pull/471)) - fix: handle cases where package.json does not exist ([#471](https://github.com/hey-api/openapi-ts/pull/471)) ## 0.42.1 ### Patch Changes - fix: properly set formData and body when using options ([#461](https://github.com/hey-api/openapi-ts/pull/461)) ## 0.42.0 ### Minor Changes - change: config option `lint: true` has changed to `lint: 'eslint'` ([#455](https://github.com/hey-api/openapi-ts/pull/455)) - change: disable formatting with prettier by default ([#457](https://github.com/hey-api/openapi-ts/pull/457)) - feat: add support for biomejs as a formatter ([#455](https://github.com/hey-api/openapi-ts/pull/455)) - feat: move operationId config option to services object ([#441](https://github.com/hey-api/openapi-ts/pull/441)) - feat: add operation error type mappings ([#442](https://github.com/hey-api/openapi-ts/pull/442)) - feat: add support for biomejs as a linter ([#455](https://github.com/hey-api/openapi-ts/pull/455)) - change: config option `format: true` has changed to `format: 'prettier'` ([#455](https://github.com/hey-api/openapi-ts/pull/455)) ### Patch Changes - fix: do not destructure data when using use options ([#450](https://github.com/hey-api/openapi-ts/pull/450)) - feat: automatically handle dates in query string ([#443](https://github.com/hey-api/openapi-ts/pull/443)) - fix: only remove core directory when export core is true ([#449](https://github.com/hey-api/openapi-ts/pull/449)) - fix: add jsdoc comments with use options ([#439](https://github.com/hey-api/openapi-ts/pull/439)) ## 0.41.0 ### Minor Changes - feat: add form type option for schemas ([#433](https://github.com/hey-api/openapi-ts/pull/433)) - feat: replace useDateType with option in types object ([#435](https://github.com/hey-api/openapi-ts/pull/435)) - feat: replace serviceResponse with option in services object ([#434](https://github.com/hey-api/openapi-ts/pull/434)) - feat: replace postfixServices with configuration object ([#430](https://github.com/hey-api/openapi-ts/pull/430)) ### Patch Changes - fix: properly escape backticks in template literals ([#431](https://github.com/hey-api/openapi-ts/pull/431)) - fix: transform names of referenced types ([#422](https://github.com/hey-api/openapi-ts/pull/422)) - fix: use config interceptors passed to constructor when using named client ([#432](https://github.com/hey-api/openapi-ts/pull/432)) - fix: properly escape expressions in template literals ([#431](https://github.com/hey-api/openapi-ts/pull/431)) - fix: do not export common properties as schemas ([#424](https://github.com/hey-api/openapi-ts/pull/424)) ## 0.40.2 ### Patch Changes - fix: unhandled SyntaxKind unknown when specification has numeric enums ([#417](https://github.com/hey-api/openapi-ts/pull/417)) ## 0.40.1 ### Patch Changes - fix: revert to generating commonjs for esm and commonjs support ([#409](https://github.com/hey-api/openapi-ts/pull/409)) ## 0.40.0 ### Minor Changes - feat: allow choosing naming convention for types ([#402](https://github.com/hey-api/openapi-ts/pull/402)) ### Patch Changes - fix: rename exportModels to types ([#402](https://github.com/hey-api/openapi-ts/pull/402)) - fix: rename models.gen.ts to types.gen.ts ([#399](https://github.com/hey-api/openapi-ts/pull/399)) - fix: export enums from index.ts ([#399](https://github.com/hey-api/openapi-ts/pull/399)) ## 0.39.0 ### Minor Changes - feat: rename generated files ([#363](https://github.com/hey-api/openapi-ts/pull/363)) - feat: add JSON-LD to content parsing ([#390](https://github.com/hey-api/openapi-ts/pull/390)) - fix: generate enums into their own file ([#358](https://github.com/hey-api/openapi-ts/pull/358)) ### Patch Changes - fix: remove file if no contents to write to it ([#373](https://github.com/hey-api/openapi-ts/pull/373)) - fix: eslint properly fixes output ([#375](https://github.com/hey-api/openapi-ts/pull/375)) - fix: invalid typescript Record generated with circular dependencies ([#374](https://github.com/hey-api/openapi-ts/pull/374)) - fix: prefer unknown type over any ([#392](https://github.com/hey-api/openapi-ts/pull/392)) - fix: only delete generated files instead of whole output directory ([#362](https://github.com/hey-api/openapi-ts/pull/362)) - fix: handle decoding models with `%` in description ([#360](https://github.com/hey-api/openapi-ts/pull/360)) - fix: throw error when typescript is missing ([#366](https://github.com/hey-api/openapi-ts/pull/366)) ## 0.38.1 ### Patch Changes - fix: inconsistent indentation in models file when not using `format: true` ([#349](https://github.com/hey-api/openapi-ts/pull/349)) - fix: output path no longer required to be within cwd ([#353](https://github.com/hey-api/openapi-ts/pull/353)) ## 0.38.0 ### Minor Changes - fix: rename write to dryRun and invert value ([#326](https://github.com/hey-api/openapi-ts/pull/326)) ### Patch Changes - fix: generate constant size array types properly ([#345](https://github.com/hey-api/openapi-ts/pull/345)) - fix: support x-enumNames for custom enum names ([#334](https://github.com/hey-api/openapi-ts/pull/334)) - fix: export service types from single namespace ([#341](https://github.com/hey-api/openapi-ts/pull/341)) - fix: generate models with proper indentation when formatting is false ([#340](https://github.com/hey-api/openapi-ts/pull/340)) - fix: log errors to file ([#329](https://github.com/hey-api/openapi-ts/pull/329)) - fix: cleanup some styling issues when generating client without formatting ([#330](https://github.com/hey-api/openapi-ts/pull/330)) ## 0.37.3 ### Patch Changes - fix: do not ignore additionalProperties when object with properties object ([#323](https://github.com/hey-api/openapi-ts/pull/323)) ## 0.37.2 ### Patch Changes - fix: escape schema names ([#317](https://github.com/hey-api/openapi-ts/pull/317)) - fix: escape backticks in strings starting with backtick ([#315](https://github.com/hey-api/openapi-ts/pull/315)) ## 0.37.1 ### Patch Changes - fix: ensure strings with both single/double quotes and backticks are escaped properly ([#310](https://github.com/hey-api/openapi-ts/pull/310)) ([#310](https://github.com/hey-api/openapi-ts/pull/310)) ## 0.37.0 ### Minor Changes - remove: `generics` as valid option for serviceResponse ([#299](https://github.com/hey-api/openapi-ts/pull/299)) ### Patch Changes - fix: escape dollar sign in operation names ([#307](https://github.com/hey-api/openapi-ts/pull/307)) ## 0.36.2 ### Patch Changes - fix: move service types into models file ([#292](https://github.com/hey-api/openapi-ts/pull/292)) ## 0.36.1 ### Patch Changes - fix: do not throw when failing to decode URI ([#296](https://github.com/hey-api/openapi-ts/pull/296)) ## 0.36.0 ### Minor Changes - feat: export schemas directly from OpenAPI specification (ie. support exporting JSON schemas draft 2020-12 ([#285](https://github.com/hey-api/openapi-ts/pull/285)) ### Patch Changes - fix(config): rename exportSchemas to schemas ([#288](https://github.com/hey-api/openapi-ts/pull/288)) ## 0.35.0 ### Minor Changes - fix(config): remove postfixModels option ([#266](https://github.com/hey-api/openapi-ts/pull/266)) - fix(client): do not send default params ([#267](https://github.com/hey-api/openapi-ts/pull/267)) ### Patch Changes - fix(api): use TypeScript Compiler API to create schemas ([#271](https://github.com/hey-api/openapi-ts/pull/271)) - fix(client): export APIResult when using serviceResponse as 'response' ([#283](https://github.com/hey-api/openapi-ts/pull/283)) - fix(parser): use only isRequired to determine if field is required ([#264](https://github.com/hey-api/openapi-ts/pull/264)) ## 0.34.5 ### Patch Changes - fix(client): access service data type in namespace properly ([#258](https://github.com/hey-api/openapi-ts/pull/258)) ## 0.34.4 ### Patch Changes - fix(client): namespace service data types ([#246](https://github.com/hey-api/openapi-ts/pull/246)) ## 0.34.3 ### Patch Changes - fix(docs): link to docs hosted on vercel ([#244](https://github.com/hey-api/openapi-ts/pull/244)) ## 0.34.2 ### Patch Changes - docs(readme): update broken contributing link ([#236](https://github.com/hey-api/openapi-ts/pull/236)) - fix(config): support ts config files and `defineConfig` syntax ([`0c92222ab74bb7d2391d49587760db9ea9228d5a`](https://github.com/hey-api/openapi-ts/commit/0c92222ab74bb7d2391d49587760db9ea9228d5a)) ## 0.34.1 ### Patch Changes - fix(docs): ensure README is shown on NPMJS ([#229](https://github.com/hey-api/openapi-ts/pull/229)) ## 0.34.0 ### Minor Changes - feat(client): generate all services in single `services.ts` file ([#215](https://github.com/hey-api/openapi-ts/pull/215)) - feat(schema): add support for default values ([#197](https://github.com/hey-api/openapi-ts/pull/197)) - feat(schema): add array of enum values for enums ([#197](https://github.com/hey-api/openapi-ts/pull/197)) ### Patch Changes - fix(axios): use builtin form data to ensure blob form data works in node environment ([#211](https://github.com/hey-api/openapi-ts/pull/211)) - fix(enum): append index number on duplicate name ([#220](https://github.com/hey-api/openapi-ts/pull/220)) ## 0.33.2 ### Patch Changes - fix(axios): properly type content-type headers assignment ([#206](https://github.com/hey-api/openapi-ts/pull/206)) ## 0.33.1 ### Patch Changes - fix(axios): set content type to multipart/form-data when using form data ([#204](https://github.com/hey-api/openapi-ts/pull/204)) ## 0.33.0 ### Minor Changes - feat(fetch): detect form data repsonses properly ([#195](https://github.com/hey-api/openapi-ts/pull/195)) - feat(fetch): add application/octet-stream, application/pdf, and application/zip as binary response types ([#195](https://github.com/hey-api/openapi-ts/pull/195)) ### Patch Changes - fix(client): do not create or export empty files ([#200](https://github.com/hey-api/openapi-ts/pull/200)) - client(angular/fetch/xhr): detect all application/json or +json as JSON ([#195](https://github.com/hey-api/openapi-ts/pull/195)) ## 0.32.1 ### Patch Changes - fix(schema): allow minimums/maximums to be 0 ([#194](https://github.com/hey-api/openapi-ts/pull/194)) - fix(axios): let axios handle serializing form data ([#192](https://github.com/hey-api/openapi-ts/pull/192)) ## 0.32.0 ### Minor Changes - Support all HTTP error codes ([#188](https://github.com/hey-api/openapi-ts/pull/188)) - Use File or Blob type for binary types ([#186](https://github.com/hey-api/openapi-ts/pull/186)) - Check value instanceof Blob when using isBlob ([#186](https://github.com/hey-api/openapi-ts/pull/186)) ### Patch Changes - fix(cli): properly handle booleans ([#190](https://github.com/hey-api/openapi-ts/pull/190)) - Attempt to use body type as content type when sending Blob in node client ([#185](https://github.com/hey-api/openapi-ts/pull/185)) - fix(api): add experimental flag ([#191](https://github.com/hey-api/openapi-ts/pull/191)) ## 0.31.1 ### Patch Changes - merge enums and useLegacyEnums into one option ([#178](https://github.com/hey-api/openapi-ts/pull/178)) - use FormData from node-fetch in node client ([#173](https://github.com/hey-api/openapi-ts/pull/173)) ## 0.31.0 ### Minor Changes - Import all required models for a service in one import ([#172](https://github.com/hey-api/openapi-ts/pull/172)) - generate all models in single `models.ts` file ([#168](https://github.com/hey-api/openapi-ts/pull/168)) - generate all schemas in single `schemas.ts` file ([#168](https://github.com/hey-api/openapi-ts/pull/168)) ### Patch Changes - fix async response interceptors when using angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) - fix deprecation warning on `throwError` in Angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) - Do not create or export CancelablePromise when using Angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) - Fix issue causing type error when targeting lower than ES2015 ([#171](https://github.com/hey-api/openapi-ts/pull/171)) - fix various warnings in generated client code ([#164](https://github.com/hey-api/openapi-ts/pull/164)) - fix providing interceptors in Angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) ## 0.30.0 ### Minor Changes - add support for interceptors ([#153](https://github.com/hey-api/openapi-ts/pull/153)) ## 0.29.2 ### Patch Changes - Fix export types as type only when using useLegacyEnums ([#160](https://github.com/hey-api/openapi-ts/pull/160)) ## 0.29.1 ### Patch Changes - Properly export enums when using useLegacyEnums ([#158](https://github.com/hey-api/openapi-ts/pull/158)) ## 0.29.0 ### Minor Changes - Add useLegacyEnums options to generate TypeScript enums ([#147](https://github.com/hey-api/openapi-ts/pull/147)) ## 0.28.0 ### Minor Changes - Add `index.ts` file to models, schemas, and services ([#137](https://github.com/hey-api/openapi-ts/pull/137)) ## 0.27.39 ### Patch Changes - Warn users about missing dependencies used in the generated client ([#124](https://github.com/hey-api/openapi-ts/pull/124)) - Use AbortController in Axios client instead of deprecated CancelToken ([#124](https://github.com/hey-api/openapi-ts/pull/124)) ## 0.27.38 ### Minor Changes - Make useOptions default to true ## 0.27.37 ### Minor Changes - Fix import error in generated Node client - Update package dependencies - Use engine-strict in .npmrc ## 0.27.36 ### Minor Changes - Handle falsy values in header - Export schemas by default ## 0.27.35 ### Minor Changes - Update all project dependencies - Discard only null or undefined in query string ## 0.27.34 ### Minor Changes - Add flag for linting generated code (default: false) - Add flag for formatting generated code (default: true) ## 0.27.33 ### Minor Changes - Auto format with Eslint if available - Add types for programmatic API ## 0.27.32 ### Minor Changes - Rename Config type to UserConfig - Pass arguments in correct order in Angular client ## 0.27.31 ### Minor Changes - Add support for openapi-ts.config.js file - Use built-in flat map ## 0.27.30 ### Minor Changes - Prefer unknown instead of any in generated client ## 0.27.29 ### Minor Changes - Rename openapi command to openapi-ts - Add basic support for response that are Blobs ## 0.27.28 ### Minor Changes - Generate enums as JavaScript objects - Use shorthand object properties in service calls ## 0.27.27 ### Minor Changes - Handle cases where a project does not have dependencies when checking to run Prettier ## 0.27.26 ### Minor Changes - Skip global parameters if they are duplicates of path parameters - remove option to indent code ## 0.27.25 ### Minor Changes - Correctly set content-type header, even when body is falsy ## 0.27.24 ### Minor Changes - Remove union types flag (this is now default) ## 0.27.23 ### Minor Changes - Support printing exact arrays ## 0.27.22 ### Minor Changes - Add option to specify custom base path - Fix spacing in cancelable promise ## 0.27.21 ### Minor Changes - Add explicit flags for generics ## 0.27.20 ### Minor Changes - Do not require type to be set for object properties ## 0.27.19 ### Minor Changes - Do not insert generics into custom client ## 0.27.18 ### Minor Changes - Support returning raw result object - Allow passing config ## 0.27.17 ### Minor Changes - Generate nullable interface when isNullable is true ## 0.27.16 ### Minor Changes - Generate types for services when useOptions is true ## 0.27.15 ### Minor Changes - Fix wrong path on Windows ## 0.27.14 ### Minor Changes - Change imports to match project style ## 0.27.13 ### Minor Changes - Support printing Date instead of string for date-time formats in models ## 0.27.12 ### Minor Changes - Escape enum name when exported ## 0.27.11 ### Minor Changes - Fix typo in template header ## 0.27.10 ### Minor Changes - Escape newlines when outputting pattern string value in schemas ## 0.27.9 ### Minor Changes - Start passing options object instead of positional parameters - Handle composition of any-of and properties - Allow ignoring operation ID when generating operation names - Propagate useVersionId to Swagger V2 parser - Change --ingoreOperationId to --useOperationId ## 0.27.8 ### Minor Changes - Support non-ascii (unicode) characters in service name, operation name, and parameter name ## 0.27.7 ### Minor Changes - Bump dependencies ## 0.27.6 ### Minor Changes - Allow overriding request body name with x-body-name key ## 0.27.5 ### Minor Changes - Type additional properties with properties - Parse array items only if parent definition has type ## 0.27.4 ### Minor Changes - Bump dependencies ## 0.27.3 ### Minor Changes - Support autoformat option flag - Handle more cases of any-of - Support regexp to select models to export - Return optional success response on 204 status code - Fix nested any-of - Add const support ## 0.27.0 ### Minor Changes - Reverted `@apidevtools/json-schema-ref-parser` to version 10.1.0 ## 0.26.0 ### Minor Changes - Upgraded dependencies ## 0.25.0 ### Minor Changes - Upgraded dependencies - Allow usage of a custom axios instance - Added message in generated files ## 0.24.0 ### Minor Changes - Upgraded dependencies - Fixed issue with Cancelable promise - Fixed issue with escaping reserved keywords in schema names - Added `--postfixModels` option ## 0.23.0 ### Minor Changes - Upgraded dependencies - Added blank line at the end of generated files - Added support for Node.js v12 - Added `request` property inside `ApiError` - Added support for `@depricated` inside models and operations ## 0.22.0 ### Minor Changes - Upgraded dependencies - Fixed issue with `null` value inside comments for OpenAPI v2 enums - Fixed issue with compatibility for latest version of Axios (0.27.x) - Removed deprecated enum model generation ## 0.21.0 ### Minor Changes - Return `undefined` to match `noImplicitReturns` rule - Made `BaseHttpRequest` class abstract - Removed private fields using `#` inside `CancelablePromise` - Removed unneeded import `AbortController` from `node-fetch` client - Filter out wrong enum values ## 0.20.1 ### Patch Changes - Support enums with single quotes in names for V2 ## 0.20.0 ### Minor Changes - Updated dependencies - Support enums with single quotes in names for V3 - Generating better names when `operationId` is not given (breaking change) - Fixed issue where `x-enum` flags where breaking due to non-string values ## 0.19.0 ### Minor Changes - Support for Angular client with `--name` option - Added test cases for Angular client ## 0.18.2 ### Patch Changes - Updated dependencies - Fixed type definition - Added test cases for CLI commands - Added test cases for query parsing ## 0.18.1 ### Patch Changes - Escaping error description - Made `Client.request` and `BaseHttpRequest.config` props public ## 0.18.0 ### Minor Changes - Angular client generation! - Updated documentation with more examples and better descriptions ## 0.17.0 ### Minor Changes - Shorthand notation for properties passed through constructor - Simplified creation of headers - Prepare codebase for Angular client ## 0.16.2 ### Patch Changes - Removed dependency on `URLSearchParams` to support browser and node without any additional imports ## 0.16.1 ### Patch Changes - Correct export inside `index.ts` when giving a custom name ## 0.16.0 ### Minor Changes - Added option to set the indentation (spaces and tabs) - Added option to export separate client file that allows usage for multiple backends - Decoupled OpenAPI object from requests - Updated dependencies ## 0.15.0 ### Minor Changes - Added change log and releases on GitHub ## 0.14.0 ### Minor Changes - Added missing `postfix` options to typedef - Updated escaping of comments and descriptions - Better handling of services without tags - Updated dependencies , // [!code --] path: 'hey-api/backend', // sign up at app.heyapi.dev }, output: 'src/client', plugins: ['@hey-api/client-fetch'], }; ``` ``` ### Patch Changes - [#2079](https://github.com/hey-api/openapi-ts/pull/2079) [`d478d8a`](https://github.com/hey-api/openapi-ts/commit/d478d8a75b2691f2a113f3fe9cf7d1ce588baa0b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(validators): generate JSDoc comments for validator schemas - [#2081](https://github.com/hey-api/openapi-ts/pull/2081) [`4c076ee`](https://github.com/hey-api/openapi-ts/commit/4c076ee6e302ebdb587aaf4e7064aa086fd0bc5c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(parser): handle exclusiveMinimum and exclusiveMaximum in OpenAPI 3.1.x when they're 0 - [#2080](https://github.com/hey-api/openapi-ts/pull/2080) [`2698a40`](https://github.com/hey-api/openapi-ts/commit/2698a4095f836b23248869018b98665d0afbcde7) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(sdk,axios): add responseType field when it's json so validators run by default ## 0.67.6 ### Patch Changes - [#2068](https://github.com/hey-api/openapi-ts/pull/2068) [`93b62fd`](https://github.com/hey-api/openapi-ts/commit/93b62fd433a09f28c75f58852e1baaa2b6fbd641) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): require options when sdk client is set to false - [#2060](https://github.com/hey-api/openapi-ts/pull/2060) [`373e15a`](https://github.com/hey-api/openapi-ts/commit/373e15a34fd81ac596a0797ddb133a47aeceee1f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(valibot): add valibot plugin ## 0.67.5 ### Patch Changes - [#2052](https://github.com/hey-api/openapi-ts/pull/2052) [`f430eaa`](https://github.com/hey-api/openapi-ts/commit/f430eaad13d83d2191fff12802d9283099d7a527) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(tanstack-query): add SDK function comments to TanStack Query output - [#2058](https://github.com/hey-api/openapi-ts/pull/2058) [`e9fda0b`](https://github.com/hey-api/openapi-ts/commit/e9fda0bff09c534333691f981363f445dc97129f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): exclude $refs in readable/writable schemas when referenced schemas don't contain any readable/writable fields - [#2059](https://github.com/hey-api/openapi-ts/pull/2059) [`af2082f`](https://github.com/hey-api/openapi-ts/commit/af2082f75dd02a52f8196709d7497dc99c5321e5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix(typescript): add enumsConstantsIgnoreNull option to skip nulls from generated JavaScript objects ## 0.67.4 ### Patch Changes - [#2043](https://github.com/hey-api/openapi-ts/pull/2043) [`e3997c8`](https://github.com/hey-api/openapi-ts/commit/e3997c8d9a9e8a6da7bc4b417769e751887ff6ac) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle enum keyword with array type ## 0.67.3 ### Patch Changes - [#2020](https://github.com/hey-api/openapi-ts/pull/2020) [`27cb409`](https://github.com/hey-api/openapi-ts/commit/27cb4095383aff35f1d78094b8b73fb36f432d33) Thanks [@0xfurai](https://github.com/0xfurai)! - fix: handle references to properties ## 0.67.2 ### Patch Changes - [#2023](https://github.com/hey-api/openapi-ts/pull/2023) [`c6f01f3`](https://github.com/hey-api/openapi-ts/commit/c6f01f39493e241f01dd7997ccdb8b6bc3d1519c) Thanks [@kennidenni](https://github.com/kennidenni)! - fix: handle relative paths in client's `baseUrl` field ## 0.67.1 ### Patch Changes - [#2010](https://github.com/hey-api/openapi-ts/pull/2010) [`13c9577`](https://github.com/hey-api/openapi-ts/commit/13c9577f122eab7b7fdd92f67ac77cb334cbdcd5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not use named imports from typescript module ## 0.67.0 ### Minor Changes - [#2003](https://github.com/hey-api/openapi-ts/pull/2003) [`1504a06`](https://github.com/hey-api/openapi-ts/commit/1504a0642fdb4f856d1650fade2d30988b35b4ff) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: respect `moduleResolution` value in `tsconfig.json` ### Respecting `moduleResolution` value in `tsconfig.json` This release introduces functionality related to your `tsconfig.json` file. The initial feature properly respects the value of your `moduleResolution` field. If you're using `nodenext`, the relative module paths in your output will be appended with `.js`. To preserve the previous behavior where we never appended `.js` to relative module paths, set `output.tsConfigPath` to `off`. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: { path: "src/client", tsConfigPath: "off", }, }; ``` ### Patch Changes - [#2006](https://github.com/hey-api/openapi-ts/pull/2006) [`aa10522`](https://github.com/hey-api/openapi-ts/commit/aa10522f2bd018a417d875e5ab12ed0a848d2e49) Thanks [@Liooo](https://github.com/Liooo)! - fix: make discriminator field required when used with `oneOf` keyword - [#2009](https://github.com/hey-api/openapi-ts/pull/2009) [`f45ba8e`](https://github.com/hey-api/openapi-ts/commit/f45ba8e96872a13be71c0d07e134f8c6717458d4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: avoid including underscore for appended types (e.g. data, error, response) when preserving identifier case ## 0.66.7 ### Patch Changes - [#1981](https://github.com/hey-api/openapi-ts/pull/1981) [`955b95a`](https://github.com/hey-api/openapi-ts/commit/955b95ab051401bdbeaa8cfb93a7a7b707cb7529) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle schemas with all write-only or read-only fields - [#1990](https://github.com/hey-api/openapi-ts/pull/1990) [`2fb1689`](https://github.com/hey-api/openapi-ts/commit/2fb1689b6538d32d123235175159d412df988241) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: avoid generating duplicate operation ids when sanitizing input - [#1991](https://github.com/hey-api/openapi-ts/pull/1991) [`b6e654a`](https://github.com/hey-api/openapi-ts/commit/b6e654a6e18698f3c554848f8b8113e30f108fc4) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod schemas use .and() instead of .merge() - [#1919](https://github.com/hey-api/openapi-ts/pull/1919) [`ec62470`](https://github.com/hey-api/openapi-ts/commit/ec624709b1fb07da8d7234fe851561054dc68150) Thanks [@ngalluzzo](https://github.com/ngalluzzo)! - fix: correctly handle numeric property names with signs - [#1984](https://github.com/hey-api/openapi-ts/pull/1984) [`0f305e0`](https://github.com/hey-api/openapi-ts/commit/0f305e06337758ee16c801ad437d9ce0996fc8b0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod plugin handles nullable enums - [#1986](https://github.com/hey-api/openapi-ts/pull/1986) [`dbebff8`](https://github.com/hey-api/openapi-ts/commit/dbebff8dcba4c93d0c534e6e48e59e2aaaffd540) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle discriminator with multiple mappings to the same schema - [#1980](https://github.com/hey-api/openapi-ts/pull/1980) [`0d7bede`](https://github.com/hey-api/openapi-ts/commit/0d7bede6e40553ae1c4c888770c84e55732b3cae) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod schemas with BigInt and min/max constraints - [#1987](https://github.com/hey-api/openapi-ts/pull/1987) [`71e2fd0`](https://github.com/hey-api/openapi-ts/commit/71e2fd029f2374ed8d2eaa01beecf254757e08d8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correct path to nested plugin files when using exportFromIndex - [#1978](https://github.com/hey-api/openapi-ts/pull/1978) [`267f4b3`](https://github.com/hey-api/openapi-ts/commit/267f4b3730f2a477906e4e1593154dcd1723e554) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle extended `$ref` with `type` keyword in OpenAPI 3.1 - [#1982](https://github.com/hey-api/openapi-ts/pull/1982) [`1e6d74f`](https://github.com/hey-api/openapi-ts/commit/1e6d74f8321af5c61f86318b835d25db38609b03) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle additionalProperties empty object as unknown instead of preserving an empty interface ## 0.66.6 ### Patch Changes - [#1971](https://github.com/hey-api/openapi-ts/pull/1971) [`e1fb199`](https://github.com/hey-api/openapi-ts/commit/e1fb199a22a30653b95d498e6aaca2c59ed2b13b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle Zod circular reference ## 0.66.5 ### Patch Changes - [#1951](https://github.com/hey-api/openapi-ts/pull/1951) [`4be46e5`](https://github.com/hey-api/openapi-ts/commit/4be46e506db1b2c53d1ddbf66e9919b5072f1cc0) Thanks [@devNameAsyraf](https://github.com/devNameAsyraf)! - fix: don't use JSON serializer for `application/octet-stream` - [#1938](https://github.com/hey-api/openapi-ts/pull/1938) [`2a03e37`](https://github.com/hey-api/openapi-ts/commit/2a03e371715b5948ba568009975ad65ccbf7bfd7) Thanks [@sredni](https://github.com/sredni)! - fix: repeat tuple type `maxItems` times ## 0.66.4 ### Patch Changes - [#1936](https://github.com/hey-api/openapi-ts/pull/1936) [`ba2e5ca`](https://github.com/hey-api/openapi-ts/commit/ba2e5ca8af1cfe478963d72ff76d7d7ae026c5a5) Thanks [@seriouslag](https://github.com/seriouslag)! - fix: add return type to TanStack Query mutations - [#1934](https://github.com/hey-api/openapi-ts/pull/1934) [`d4df550`](https://github.com/hey-api/openapi-ts/commit/d4df5503369b7aa105c7f6a49e1c7b43e0e50f49) Thanks [@seriouslag](https://github.com/seriouslag)! - fix: export some internal functions ## 0.66.3 ### Patch Changes - [#1917](https://github.com/hey-api/openapi-ts/pull/1917) [`d7af22c`](https://github.com/hey-api/openapi-ts/commit/d7af22c771af4bd2dab28acc69430717da390670) Thanks [@Freddis](https://github.com/Freddis)! - fix: handle nullable dates in transformers ## 0.66.2 ### Patch Changes - [#1913](https://github.com/hey-api/openapi-ts/pull/1913) [`7cfa4a7`](https://github.com/hey-api/openapi-ts/commit/7cfa4a76b13ca97d49c5f0366ba7264f94753d8b) Thanks [@BogdanMaier](https://github.com/BogdanMaier)! - fix: prevent crash when optional pagination field is missing ## 0.66.1 ### Patch Changes - [#1906](https://github.com/hey-api/openapi-ts/pull/1906) [`d1928d1`](https://github.com/hey-api/openapi-ts/commit/d1928d17710240bb42a6aa12da4618a9dd962df2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: exclude and include expressions can be an array - [#1906](https://github.com/hey-api/openapi-ts/pull/1906) [`d1928d1`](https://github.com/hey-api/openapi-ts/commit/d1928d17710240bb42a6aa12da4618a9dd962df2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support excluding deprecated fields with '@deprecated' ## 0.66.0 ### Minor Changes - [#1896](https://github.com/hey-api/openapi-ts/pull/1896) [`8840ed7`](https://github.com/hey-api/openapi-ts/commit/8840ed73df5ee718e803aa6e27b66e0c82ec3651) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support read-only and write-only properties ### Read-only and write-only fields Starting with v0.66.0, `@hey-api/typescript` will generate separate types for payloads and responses if it detects any read-only or write-only fields. To preserve the previous behavior and generate a single type regardless, set `readOnlyWriteOnlyBehavior` to `off`. ```js export default { input: "hey-api/backend", // sign up at app.heyapi.dev output: "src/client", plugins: [ // ...other plugins { name: "@hey-api/typescript", readOnlyWriteOnlyBehavior: "off", // [!code ++] }, ], }; ``` ## 0.65.0 ### Minor Changes - [#1889](https://github.com/hey-api/openapi-ts/pull/1889) [`67c385b`](https://github.com/hey-api/openapi-ts/commit/67c385bf6289a79726b0cdd85fd81ca501cf2248) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support custom clients ### Patch Changes - [#1892](https://github.com/hey-api/openapi-ts/pull/1892) [`29fa764`](https://github.com/hey-api/openapi-ts/commit/29fa764986af3d3af842793c74d61681c7e967a1) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow passing fetch options to the request resolving a specification - [#1877](https://github.com/hey-api/openapi-ts/pull/1877) [`6971f5b`](https://github.com/hey-api/openapi-ts/commit/6971f5bca4dd17ea65400c504ad0a4ffb083a38b) Thanks [@Matsuuu](https://github.com/Matsuuu)! - feat: ability to disable writing a log file via a `--no-log-file` flag or `logs.file` = `false` ## 0.64.15 ### Patch Changes - [#1850](https://github.com/hey-api/openapi-ts/pull/1850) [`fe43b88`](https://github.com/hey-api/openapi-ts/commit/fe43b889c20a2001f56e259f93f64851a1caa1d1) Thanks [@kelnos](https://github.com/kelnos)! - feat: add support for cookies auth ## 0.64.14 ### Patch Changes - [#1827](https://github.com/hey-api/openapi-ts/pull/1827) [`9dd43db`](https://github.com/hey-api/openapi-ts/commit/9dd43db54f2b7ebf87c5c7c118fdf149162a533d) Thanks [@john-cremit](https://github.com/john-cremit)! - feat: allow customizing pagination keywords using `input.pagination.keywords` ## 0.64.13 ### Patch Changes - [#1822](https://github.com/hey-api/openapi-ts/pull/1822) [`c73b0d4`](https://github.com/hey-api/openapi-ts/commit/c73b0d401c2bfa6f0b0d89d844a6aa09f2685a69) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: bump json-schema-ref-parser package - [#1826](https://github.com/hey-api/openapi-ts/pull/1826) [`90886c1`](https://github.com/hey-api/openapi-ts/commit/90886c1372a999e8cb59d5da218762f6ee6cd459) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow config to be a function ## 0.64.12 ### Patch Changes - [#1816](https://github.com/hey-api/openapi-ts/pull/1816) [`b9e1b4b`](https://github.com/hey-api/openapi-ts/commit/b9e1b4bec5e1c5d1f2b5b9cfc7fa145274ae604d) Thanks [@shemsiu](https://github.com/shemsiu)! - Allow `scheme` property to be case-insensitive ## 0.64.11 ### Patch Changes - [#1800](https://github.com/hey-api/openapi-ts/pull/1800) [`a4811bd`](https://github.com/hey-api/openapi-ts/commit/a4811bdf178ec1a7f1602e0483a32fe7303f4eac) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support Hey API platform input arguments - [#1800](https://github.com/hey-api/openapi-ts/pull/1800) [`a4811bd`](https://github.com/hey-api/openapi-ts/commit/a4811bdf178ec1a7f1602e0483a32fe7303f4eac) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle raw OpenAPI specification input ## 0.64.10 ### Patch Changes - [#1779](https://github.com/hey-api/openapi-ts/pull/1779) [`57fcec8`](https://github.com/hey-api/openapi-ts/commit/57fcec804e339cfe508cfba4afd203c22495bff2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: don't throw on missing performance marks - [#1767](https://github.com/hey-api/openapi-ts/pull/1767) [`2de84ea`](https://github.com/hey-api/openapi-ts/commit/2de84ea3dbd2cba50150808a872aea8242c33014) Thanks [@Schroedi](https://github.com/Schroedi)! - fix: handle nested dates in transformers ## 0.64.9 ### Patch Changes - [#1774](https://github.com/hey-api/openapi-ts/pull/1774) [`c0b36b9`](https://github.com/hey-api/openapi-ts/commit/c0b36b95645d484034c3af145c5554867568979b) Thanks [@mrlubos](https://github.com/mrlubos)! - docs: announce Hey API platform ## 0.64.8 ### Patch Changes - [#1764](https://github.com/hey-api/openapi-ts/pull/1764) [`b3ecac3`](https://github.com/hey-api/openapi-ts/commit/b3ecac31d49a269ab400db4dbb84a22f1047e19a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: reduce minimum Node.js 22 version to 22.10.0 ## 0.64.7 ### Patch Changes - [#1755](https://github.com/hey-api/openapi-ts/pull/1755) [`82f7c14`](https://github.com/hey-api/openapi-ts/commit/82f7c1425dd903b75d15cf532b88580d180f281a) Thanks [@Matsuuu](https://github.com/Matsuuu)! - fix: Wrap the GET request in watch mode with try-catch to prevent crashes on no-head watch targets ## 0.64.6 ### Patch Changes - [#1748](https://github.com/hey-api/openapi-ts/pull/1748) [`7326d25`](https://github.com/hey-api/openapi-ts/commit/7326d2550ae3336fd8f754f8d4a25f1a40c13a2b) Thanks [@Matsuuu](https://github.com/Matsuuu)! - fix: Wrap HEAD request in a try-catch to prevent watch mode crashes on server reloads ## 0.64.5 ### Patch Changes - [#1728](https://github.com/hey-api/openapi-ts/pull/1728) [`cc8dabb`](https://github.com/hey-api/openapi-ts/commit/cc8dabbf1cb94879bb08fe66ecb04c4d0801e9cc) Thanks [@georgesmith46](https://github.com/georgesmith46)! - fix: correctly generate zod regex expressions when using patterns ## 0.64.4 ### Patch Changes - [#1710](https://github.com/hey-api/openapi-ts/pull/1710) [`4afdaa1`](https://github.com/hey-api/openapi-ts/commit/4afdaa1247b0bf0629817a51c29ca25840569b77) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use relative path to custom config file if provided when resolving relative paths ## 0.64.3 ### Patch Changes - [#1701](https://github.com/hey-api/openapi-ts/pull/1701) [`e86629b`](https://github.com/hey-api/openapi-ts/commit/e86629bfa9ae2a47131d3a9a240a6aa2a4f67911) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly type default value for Nuxt client ## 0.64.2 ### Patch Changes - [#1697](https://github.com/hey-api/openapi-ts/pull/1697) [`dec3fed`](https://github.com/hey-api/openapi-ts/commit/dec3fedb5f51aad4711fec15a006c525cb0bf7d8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add exportFromIndex option to all plugins - [#1699](https://github.com/hey-api/openapi-ts/pull/1699) [`8ff188f`](https://github.com/hey-api/openapi-ts/commit/8ff188fb269cf46321538dbe846e1b9ae3b8de42) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow passing arbitrary values to SDK functions via `meta` field - [#1687](https://github.com/hey-api/openapi-ts/pull/1687) [`04c7cea`](https://github.com/hey-api/openapi-ts/commit/04c7ceac940a81cbed6a4070d9244aa5052ba4a2) Thanks [@hunshcn](https://github.com/hunshcn)! - sanitize "+" in uri to avoid plus in function name ## 0.64.1 ### Patch Changes - [#1668](https://github.com/hey-api/openapi-ts/pull/1668) [`7a03341`](https://github.com/hey-api/openapi-ts/commit/7a03341301d9d56ae93b4e4e3bd1ca469444f886) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: watch mode handles servers not exposing HEAD method for spec - [#1668](https://github.com/hey-api/openapi-ts/pull/1668) [`7a03341`](https://github.com/hey-api/openapi-ts/commit/7a03341301d9d56ae93b4e4e3bd1ca469444f886) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add watch.timeout option ## 0.64.0 ### Minor Changes - [#1661](https://github.com/hey-api/openapi-ts/pull/1661) [`ccefe43`](https://github.com/hey-api/openapi-ts/commit/ccefe434ee83f1202769547ce128e1c134dee25f) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: added `client.baseUrl` option ### Added `client.baseUrl` option You can use this option to configure the default base URL for the generated client. By default, we will attempt to resolve the first defined server or infer the base URL from the input path. If you'd like to preserve the previous behavior, set `baseUrl` to `false`. ```js export default { input: "path/to/openapi.json", output: "src/client", plugins: [ { baseUrl: false, // [!code ++] name: "@hey-api/client-fetch", }, ], }; ``` - [#1661](https://github.com/hey-api/openapi-ts/pull/1661) [`bb6d46a`](https://github.com/hey-api/openapi-ts/commit/bb6d46ae119ce4e7e3a2ab3fded74ac4fb4cdff2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make createConfig, CreateClientConfig, and Config accept ClientOptions generic ### Added `ClientOptions` interface The `Config` interface now accepts an optional generic extending `ClientOptions` instead of `boolean` type `ThrowOnError`. ```ts type Foo = Config; // [!code --] type Foo = Config<{ throwOnError: false }>; // [!code ++] ``` ## 0.63.2 ### Patch Changes - [#1651](https://github.com/hey-api/openapi-ts/pull/1651) [`df350f3`](https://github.com/hey-api/openapi-ts/commit/df350f31dae957d063010ba46c5008ae831b3a32) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: lower Node version requirements ## 0.63.1 ### Patch Changes - [#1637](https://github.com/hey-api/openapi-ts/pull/1637) [`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update keywords in package.json - [#1637](https://github.com/hey-api/openapi-ts/pull/1637) [`2dc380e`](https://github.com/hey-api/openapi-ts/commit/2dc380eabc17c723654beb04ecd7bce6d33d3b49) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add Next.js client - [#1646](https://github.com/hey-api/openapi-ts/pull/1646) [`2cbffeb`](https://github.com/hey-api/openapi-ts/commit/2cbffeb2cdd6c6143cd68cac68369584879dda31) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support required client in SDK using sdk.client = false - [#1648](https://github.com/hey-api/openapi-ts/pull/1648) [`66a9e45`](https://github.com/hey-api/openapi-ts/commit/66a9e4517d2306da8c60750dc3380e6774a7177b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for openIdConnect auth flow ## 0.63.0 ### Minor Changes - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: move clients to plugins ### Client plugins Clients are now plugins generating their own `client.gen.ts` file. There's no migration needed if you're using CLI. If you're using the configuration file, move `client` options to `plugins`. ```js export default { client: "@hey-api/client-fetch", // [!code --] input: "path/to/openapi.json", output: "src/client", plugins: ["@hey-api/client-fetch"], // [!code ++] }; ``` ### Patch Changes - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: move sdk.throwOnError option to client.throwOnError ### Moved `sdk.throwOnError` option This SDK configuration option has been moved to the client plugins where applicable. Not every client can be configured to throw on error, so it didn't make sense to expose the option when it didn't have any effect. ```js export default { input: "path/to/openapi.json", output: "src/client", plugins: [ { name: "@hey-api/client-fetch", throwOnError: true, // [!code ++] }, { name: "@hey-api/sdk", throwOnError: true, // [!code --] }, ], }; ``` - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: sdks import client from client.gen.ts instead of defining it inside the file ### Added `client.gen.ts` file The internal `client` instance previously located in `sdk.gen.ts` is now defined in `client.gen.ts`. If you're importing it in your code, update the import module. ```js import { client } from "client/sdk.gen"; // [!code --] import { client } from "client/client.gen"; // [!code ++] ``` - [#1626](https://github.com/hey-api/openapi-ts/pull/1626) [`8eba19d`](https://github.com/hey-api/openapi-ts/commit/8eba19d4092fc0903572ab9fdadf0b4c26928ba2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: throw if inferred plugin not found ## 0.62.3 ### Patch Changes - [#1600](https://github.com/hey-api/openapi-ts/pull/1600) [`0432418`](https://github.com/hey-api/openapi-ts/commit/0432418d72c94ef94865f8216ed2f723ad5191f9) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: bundle clients from compiled index file - [#1594](https://github.com/hey-api/openapi-ts/pull/1594) [`bc66cde`](https://github.com/hey-api/openapi-ts/commit/bc66cde1ebe0e2df08c8d04b3ddc9504e4952cf3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate correct response for text/plain content type - [#1596](https://github.com/hey-api/openapi-ts/pull/1596) [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not use a body serializer on text/plain sdks - [#1602](https://github.com/hey-api/openapi-ts/pull/1602) [`194f941`](https://github.com/hey-api/openapi-ts/commit/194f94110545f2cae07bde13b863cd0cb5284d8a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support all oauth2 flows in sdk auth - [#1596](https://github.com/hey-api/openapi-ts/pull/1596) [`4784727`](https://github.com/hey-api/openapi-ts/commit/47847276e8bc854045044dd414382080270dd779) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add null to valid bodySerializer types ## 0.62.2 ### Patch Changes - [#1519](https://github.com/hey-api/openapi-ts/pull/1519) [`14d3c4c`](https://github.com/hey-api/openapi-ts/commit/14d3c4ce0393d543e2d3aaebbfcf8f0cf32483b0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for Nuxt client ## 0.62.1 ### Patch Changes - [#1574](https://github.com/hey-api/openapi-ts/pull/1574) [`51bf7fc`](https://github.com/hey-api/openapi-ts/commit/51bf7fc88cb6e9ab392106b85f900a75540e524f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate bigint type instead of BigInt - [#1572](https://github.com/hey-api/openapi-ts/pull/1572) [`0e4882a`](https://github.com/hey-api/openapi-ts/commit/0e4882ae3b0dc048a2d9a2a0b5c39fbdeed6de8d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add ability to skip generating index file with output.indexFile ## 0.62.0 ### Minor Changes - [#1568](https://github.com/hey-api/openapi-ts/pull/1568) [`465410c`](https://github.com/hey-api/openapi-ts/commit/465410c201eb19e737e3143ad53a146e95f80107) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: change the default parser ### Patch Changes - [#1566](https://github.com/hey-api/openapi-ts/pull/1566) [`39d558a`](https://github.com/hey-api/openapi-ts/commit/39d558afc6af97fe8de1a6471b9d1f172ec2960a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: spread sdk options at the end to allow overriding generated values ## 0.61.3 ### Patch Changes - [#1552](https://github.com/hey-api/openapi-ts/pull/1552) [`ceb8bd7`](https://github.com/hey-api/openapi-ts/commit/ceb8bd74207566871e9f179cb28b2d8c440ef2c8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use z.coerce before calling z.bigint ## 0.61.2 ### Patch Changes - [#1543](https://github.com/hey-api/openapi-ts/pull/1543) [`7a2d6dc`](https://github.com/hey-api/openapi-ts/commit/7a2d6dcd6e30411178ac5c78db3f1dbbcc8d6b27) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: send GET request only on first spec fetch ## 0.61.1 ### Patch Changes - [#1530](https://github.com/hey-api/openapi-ts/pull/1530) [`67b7295`](https://github.com/hey-api/openapi-ts/commit/67b72959be499ff59f5f68bfdaa7e5568f5de02f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: detect pagination in composite schemas with null type - [#1535](https://github.com/hey-api/openapi-ts/pull/1535) [`d4cfa05`](https://github.com/hey-api/openapi-ts/commit/d4cfa05ed425d57f79b28efe76e6a33f1e892ec5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle primitive constants in Zod and types ## 0.61.0 ### Minor Changes - [#1520](https://github.com/hey-api/openapi-ts/pull/1520) [`b3c23ba`](https://github.com/hey-api/openapi-ts/commit/b3c23ba99c361bdca3ab9c44017b6e5c044f40a7) Thanks [@chriswiggins](https://github.com/chriswiggins)! - Add support for HTTP Bearer Authentication Scheme - [#1525](https://github.com/hey-api/openapi-ts/pull/1525) [`7b7313e`](https://github.com/hey-api/openapi-ts/commit/7b7313eeaf9a749fb81465546bc4e4bdce31d5ab) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add OpenAPI 2.0 support to experimental parser - [#1511](https://github.com/hey-api/openapi-ts/pull/1511) [`4e8064d`](https://github.com/hey-api/openapi-ts/commit/4e8064d9a589e14b42d2b1a329e2436f242884da) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add watch mode ## Watch Mode ::: warning Watch mode currently supports only remote files via URL. ::: If your schema changes frequently, you may want to automatically regenerate the output during development. To watch your input file for changes, enable `watch` mode in your configuration or pass the `--watch` flag to the CLI. ### Config ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", watch: true, }; ``` ### CLI ```sh npx @hey-api/openapi-ts \ -c @hey-api/client-fetch \ -i path/to/openapi.json \ -o src/client \ -w ``` - **BREAKING**: please update `@hey-api/client-*` packages to the latest version feat: add support for basic http auth ### Patch Changes - [#1529](https://github.com/hey-api/openapi-ts/pull/1529) [`ccc0bbc`](https://github.com/hey-api/openapi-ts/commit/ccc0bbcbdeace22bbd8e92caadebdca81e61e393) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for long integers - [#1512](https://github.com/hey-api/openapi-ts/pull/1512) [`dd0e0a2`](https://github.com/hey-api/openapi-ts/commit/dd0e0a266153e34448fbc3db6b0f864f75483280) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add `sdk.throwOnError` option - [#1525](https://github.com/hey-api/openapi-ts/pull/1525) [`7b7313e`](https://github.com/hey-api/openapi-ts/commit/7b7313eeaf9a749fb81465546bc4e4bdce31d5ab) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: preserve leading separators in enum keys ## 0.60.1 ### Patch Changes - [#1468](https://github.com/hey-api/openapi-ts/pull/1468) [`20d7497`](https://github.com/hey-api/openapi-ts/commit/20d7497acb6c046f6a4206c2d8137414e17b2263) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle indexed access checks - [#1469](https://github.com/hey-api/openapi-ts/pull/1469) [`a7608c2`](https://github.com/hey-api/openapi-ts/commit/a7608c27ced3419dee228f4b0cd96479b3dc2c04) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: zod: generate patterns and improve plain schemas - [#1471](https://github.com/hey-api/openapi-ts/pull/1471) [`f86d293`](https://github.com/hey-api/openapi-ts/commit/f86d293f18f133ef6dd2f4864d037611b81edd26) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add links to the experimental parser callouts - [#1462](https://github.com/hey-api/openapi-ts/pull/1462) [`893d6ef`](https://github.com/hey-api/openapi-ts/commit/893d6ef5677d17b96174f505937f6da686abb2bc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update types for custom plugins so defineConfig does not throw - [#1464](https://github.com/hey-api/openapi-ts/pull/1464) [`787d59c`](https://github.com/hey-api/openapi-ts/commit/787d59c307549f5faf9f83314a8e9692bb01eb5d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export IR types - [#1467](https://github.com/hey-api/openapi-ts/pull/1467) [`3a3f8d7`](https://github.com/hey-api/openapi-ts/commit/3a3f8d7ea4c993d4372e4bc52f6d9525bf1e45b6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export utils - [#1457](https://github.com/hey-api/openapi-ts/pull/1457) [`bc03c37`](https://github.com/hey-api/openapi-ts/commit/bc03c373f4df61d8d715dc13badba2a6c5a3a450) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow plugins to explicitly declare whether they should be re-exported from the index file ## 0.60.0 ### Minor Changes - [#1430](https://github.com/hey-api/openapi-ts/pull/1430) [`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: require sdk.transformer to use generated transformers ### Added `sdk.transformer` option When generating SDKs, you now have to specify `transformer` in order to modify response data. By default, adding `@hey-api/transformers` to your plugins will only produce additional output. To preserve the previous functionality, set `sdk.transformer` to `true`. ```js import { defaultPlugins } from "@hey-api/openapi-ts"; export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", plugins: [ ...defaultPlugins, { dates: true, name: "@hey-api/transformers", }, { name: "@hey-api/sdk", transformer: true, // [!code ++] }, ], }; ``` - [#1447](https://github.com/hey-api/openapi-ts/pull/1447) [`200821b`](https://github.com/hey-api/openapi-ts/commit/200821b3ceea8ffca7656fe3f6e2ef98b7110a2a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: revert license to MIT ### Patch Changes - [#1430](https://github.com/hey-api/openapi-ts/pull/1430) [`9cec9e8`](https://github.com/hey-api/openapi-ts/commit/9cec9e8582c12a8c041b922d9587e16f6f19782a) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: Zod plugin generates response schemas ## 0.59.2 ### Patch Changes - [#1420](https://github.com/hey-api/openapi-ts/pull/1420) [`8010dbb`](https://github.com/hey-api/openapi-ts/commit/8010dbb1ab8b91d1d49d5cf16276183764a63ff3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate querySerializer options for Axios client - [#1419](https://github.com/hey-api/openapi-ts/pull/1419) [`4555796`](https://github.com/hey-api/openapi-ts/commit/4555796df3a33fb3fdf7d7417f7d1f3b22d89bcf) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: infer responseType in SDKs for axios client - [#1409](https://github.com/hey-api/openapi-ts/pull/1409) [`646064d`](https://github.com/hey-api/openapi-ts/commit/646064d1aecea988d2b4df73bd24b2ee83394ae0) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: support oauth2 and apiKey security schemes - [#1416](https://github.com/hey-api/openapi-ts/pull/1416) [`2a605b7`](https://github.com/hey-api/openapi-ts/commit/2a605b7e43655b3100e302e10b9979fbbad6cdfe) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: zod plugin handles recursive schemas ## 0.59.1 ### Patch Changes - [#1398](https://github.com/hey-api/openapi-ts/pull/1398) [`a88e7d9`](https://github.com/hey-api/openapi-ts/commit/a88e7d9f8a313c641cf651256a710d0610b95b5d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: prefix restricted identifier names with underscore - [#1394](https://github.com/hey-api/openapi-ts/pull/1394) [`ec48d32`](https://github.com/hey-api/openapi-ts/commit/ec48d323d80de8e6a47ce7ecd732288f0a47e17a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: disallow additional query parameters in experimental parser output ## 0.59.0 ### Minor Changes - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`7c4335d`](https://github.com/hey-api/openapi-ts/commit/7c4335d12782c73b5b242e7d5786ec8778857d1d) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add `logs.level` option ### Added `logs.level` option You can now configure different log levels. As part of this feature, we had to introduce a breaking change by moving the `debug` option to `logs.level`. This will affect you if you're calling `@hey-api/openapi-ts` from Node.js (not CLI) or using the configuration file. ```js export default { client: "@hey-api/client-fetch", debug: true, // [!code --] input: "path/to/openapi.json", logs: { level: "debug", // [!code ++] }, output: "src/client", }; ``` - [#1389](https://github.com/hey-api/openapi-ts/pull/1389) [`f4c98ec`](https://github.com/hey-api/openapi-ts/commit/f4c98ec429ee989ae1c76328f4d42d44f14cb52e) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: remove `@hey-api/schemas` from default plugins ### Updated default `plugins` `@hey-api/schemas` has been removed from the default plugins. To continue using it, add it to your plugins array. ```js import { defaultPlugins } from "@hey-api/openapi-ts"; export default { client: "@hey-api/client-fetch", experimentalParser: true, input: "path/to/openapi.json", output: "src/client", plugins: [ ...defaultPlugins, "@hey-api/schemas", // [!code ++] ], }; ``` ### Patch Changes - [#1382](https://github.com/hey-api/openapi-ts/pull/1382) [`3580c1e`](https://github.com/hey-api/openapi-ts/commit/3580c1eec4640d235a1e0f78bf76581e532aaf8b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly resolve required properties in nested allOf composition - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`7c4335d`](https://github.com/hey-api/openapi-ts/commit/7c4335d12782c73b5b242e7d5786ec8778857d1d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add `--silent` or `-s` CLI option for silent log level - [#1382](https://github.com/hey-api/openapi-ts/pull/1382) [`3580c1e`](https://github.com/hey-api/openapi-ts/commit/3580c1eec4640d235a1e0f78bf76581e532aaf8b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: transformers handle allOf composition in experimental parser - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`0def82c`](https://github.com/hey-api/openapi-ts/commit/0def82c91d1be936702690b8cf5a21775974d946) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add `logs` configuration option to customize log directory - [#1390](https://github.com/hey-api/openapi-ts/pull/1390) [`8388c47`](https://github.com/hey-api/openapi-ts/commit/8388c4720dbb657899d5e30bd8d59c19583cad98) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow arbitrary object properties when additionalProperties is undefined - [#1387](https://github.com/hey-api/openapi-ts/pull/1387) [`7c4335d`](https://github.com/hey-api/openapi-ts/commit/7c4335d12782c73b5b242e7d5786ec8778857d1d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support `DEBUG` environment variable ## 0.58.0 ### Minor Changes - [#1353](https://github.com/hey-api/openapi-ts/pull/1353) [`efd3e54`](https://github.com/hey-api/openapi-ts/commit/efd3e5444d208ea0c8dda7573f26bb04c31cc372) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add typescript.identifierCase option ### Added `typescript.identifierCase` option **This change affects only the experimental parser.** By default, the generated TypeScript interfaces will follow the PascalCase naming convention. In the previous versions, we tried to preserve the original name as much as possible. To keep the previous behavior, set `typescript.identifierCase` to `preserve`. ```js export default { client: "@hey-api/client-fetch", experimentalParser: true, input: "path/to/openapi.json", output: "src/client", plugins: [ // ...other plugins { identifierCase: "preserve", // [!code ++] name: "@hey-api/typescript", }, ], }; ``` - [#1360](https://github.com/hey-api/openapi-ts/pull/1360) [`5f6ddd7`](https://github.com/hey-api/openapi-ts/commit/5f6ddd796f0ce77bcca55fd13981f2a8481aecd3) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: remove schemas and transformers re-exports from index.ts ### Removed `schemas.gen.ts` re-export `index.ts` will no longer re-export `schemas.gen.ts` to reduce the chance of producing broken output. Please update your code to import from `schemas.gen.ts` directly. ```js import { mySchema } from "client"; // [!code --] import { mySchema } from "client/schemas.gen"; // [!code ++] ``` ### Removed `transformers.gen.ts` re-export `index.ts` will no longer re-export `transformers.gen.ts` to reduce the chance of producing broken output. Please update your code to import from `transformers.gen.ts` directly. ```js import { myTransformer } from "client"; // [!code --] import { myTransformer } from "client/transformers.gen"; // [!code ++] ``` - [#1360](https://github.com/hey-api/openapi-ts/pull/1360) [`5f6ddd7`](https://github.com/hey-api/openapi-ts/commit/5f6ddd796f0ce77bcca55fd13981f2a8481aecd3) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add output.clean option ### Added `output.clean` option By default, the `output.path` folder will be emptied on every run. To preserve the previous behavior, set `output.clean` to `false`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: { clean: false, // [!code ++] path: "src/client", }, }; ``` - [#1362](https://github.com/hey-api/openapi-ts/pull/1362) [`3bf7169`](https://github.com/hey-api/openapi-ts/commit/3bf7169b620946d99c17cf5398d7a818d0099f94) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add typescript.enumsCase option ### Patch Changes - [#1361](https://github.com/hey-api/openapi-ts/pull/1361) [`a23c25e`](https://github.com/hey-api/openapi-ts/commit/a23c25ea1b5ca8bf421302bf93690168df3473cb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add before and after to pagination keywords - [#1368](https://github.com/hey-api/openapi-ts/pull/1368) [`cca2290`](https://github.com/hey-api/openapi-ts/commit/cca2290aeaab0b9807c928d73dbfc1e4bacadc4d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export Plugin API namespace - [#1369](https://github.com/hey-api/openapi-ts/pull/1369) [`11163f0`](https://github.com/hey-api/openapi-ts/commit/11163f0d6885633078126849c04c0646e7d19255) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: TanStack Query plugin handles conflict with internal function name in experimental parser ## 0.57.1 ### Patch Changes - [#1335](https://github.com/hey-api/openapi-ts/pull/1335) [`bb9a848`](https://github.com/hey-api/openapi-ts/commit/bb9a84869dc911861f3b12f725a470b8fd6b67fe) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: transformers correctly handle an array - [#1332](https://github.com/hey-api/openapi-ts/pull/1332) [`25b598b`](https://github.com/hey-api/openapi-ts/commit/25b598bcecd1dd3eb3da6b7c7f24f4adb0170114) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve camelcase with abbreviated plurals - [#1333](https://github.com/hey-api/openapi-ts/pull/1333) [`734a62d`](https://github.com/hey-api/openapi-ts/commit/734a62dd8d594b8266964fe16766a481d37eb7df) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser generates url inside data types - [#1336](https://github.com/hey-api/openapi-ts/pull/1336) [`6857da8`](https://github.com/hey-api/openapi-ts/commit/6857da8a7f23829a89115b2237aaac9a71a38dfb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser transforms anyOf date and null - [#1330](https://github.com/hey-api/openapi-ts/pull/1330) [`3d68587`](https://github.com/hey-api/openapi-ts/commit/3d6858748c94d6e33fd4dae7ddbf6cb70d21aaee) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser handles empty string and null enum values in JavaScript mode - [#1340](https://github.com/hey-api/openapi-ts/pull/1340) [`c8511e0`](https://github.com/hey-api/openapi-ts/commit/c8511e0d84dd408407bf764fb0bae4938b70dacb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: experimental parser exports reusable request bodies ## 0.57.0 ### Minor Changes - [#1324](https://github.com/hey-api/openapi-ts/pull/1324) [`4e62378`](https://github.com/hey-api/openapi-ts/commit/4e62378352d8306580293ee4aeef43756d245f85) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: rename Hey API plugins ### Renamed `@hey-api/services` plugin This plugin has been renamed to `@hey-api/sdk`. ### Changed `sdk.output` value To align with the updated name, the `@hey-api/sdk` plugin will generate an `sdk.gen.ts` file. This will result in a breaking change if you're importing from `services.gen.ts`. Please update your imports to reflect this change. ```js import { client } from "client/services.gen"; // [!code --] import { client } from "client/sdk.gen"; // [!code ++] ``` ### Renamed `@hey-api/types` plugin This plugin has been renamed to `@hey-api/typescript`. - [#1327](https://github.com/hey-api/openapi-ts/pull/1327) [`62e37d5`](https://github.com/hey-api/openapi-ts/commit/62e37d51e9d829e11d08a494060c1e808ce2e3f3) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add typescript.exportInlineEnums option ### Added `typescript.exportInlineEnums` option By default, inline enums (enums not defined as reusable components in the input file) will be generated only as inlined union types. You can set `exportInlineEnums` to `true` to treat inline enums as reusable components. When `true`, the exported enums will follow the style defined in `enums`. This is a breaking change since in the previous versions, inline enums were always treated as reusable components. To preserve your current output, set `exportInlineEnums` to `true`. This feature works only with the experimental parser. ```js export default { client: "@hey-api/client-fetch", experimentalParser: true, input: "path/to/openapi.json", output: "src/client", plugins: [ // ...other plugins { exportInlineEnums: true, // [!code ++] name: "@hey-api/typescript", }, ], }; ``` ### Patch Changes - [#1326](https://github.com/hey-api/openapi-ts/pull/1326) [`01c3d69`](https://github.com/hey-api/openapi-ts/commit/01c3d69e4c97262cd6dda5061f0a76f3b4fda31a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve generated enum keys in experimental parser ## 0.56.3 ### Patch Changes - [#1319](https://github.com/hey-api/openapi-ts/pull/1319) [`af76a77`](https://github.com/hey-api/openapi-ts/commit/af76a7705c585fcfae0c72872f358936f7d19d56) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: Zod plugin handles value constraints and defaults ## 0.56.2 ### Patch Changes - [#1316](https://github.com/hey-api/openapi-ts/pull/1316) [`a79fac8`](https://github.com/hey-api/openapi-ts/commit/a79fac8919ed29eec7195cbd441ffa38b559d63c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add input.exclude option - [#1316](https://github.com/hey-api/openapi-ts/pull/1316) [`a79fac8`](https://github.com/hey-api/openapi-ts/commit/a79fac8919ed29eec7195cbd441ffa38b559d63c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make Zod plugin available in plugins options ## 0.56.1 ### Patch Changes - [#1309](https://github.com/hey-api/openapi-ts/pull/1309) [`785480b`](https://github.com/hey-api/openapi-ts/commit/785480b2d5f96a681dfc1f7f0fb626f744bb221f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: gracefully handle invalid schema type in experimental parser ## 0.56.0 ### Minor Changes - [#1286](https://github.com/hey-api/openapi-ts/pull/1286) [`5514de4`](https://github.com/hey-api/openapi-ts/commit/5514de46a8c913ddc40f07d0142c80266e9837cd) Thanks [@jacobinu](https://github.com/jacobinu)! - feat: add `fastify` plugin ### Patch Changes - [#1286](https://github.com/hey-api/openapi-ts/pull/1286) [`cebf327`](https://github.com/hey-api/openapi-ts/commit/cebf327046c801b375846bae6b07561b8ad1bdd6) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: export a map of error and response types by status code - [#1286](https://github.com/hey-api/openapi-ts/pull/1286) [`8a15a35`](https://github.com/hey-api/openapi-ts/commit/8a15a35e86ff22eca85dc218bc1793315b934556) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: deprecate types.tree option - [#1305](https://github.com/hey-api/openapi-ts/pull/1305) [`a3698a7`](https://github.com/hey-api/openapi-ts/commit/a3698a7f1680d7dfb913c6253f8685ebbdd132ca) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle file-like content media type without explicit schema ## 0.55.3 ### Patch Changes - [#1283](https://github.com/hey-api/openapi-ts/pull/1283) [`781d1a4`](https://github.com/hey-api/openapi-ts/commit/781d1a40d10ce380f1ca2cb2bc7aca7d3b169bc6) Thanks [@hougesen](https://github.com/hougesen)! - feat: add support for oxlint as linter ## 0.55.2 ### Patch Changes - [#1253](https://github.com/hey-api/openapi-ts/pull/1253) [`01dee3d`](https://github.com/hey-api/openapi-ts/commit/01dee3df879232939e43355231147b3d910fb482) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update sponsorship links - [#1266](https://github.com/hey-api/openapi-ts/pull/1266) [`d60d260`](https://github.com/hey-api/openapi-ts/commit/d60d260342ff3013c2e228151e9b897224eb89cc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly generate array when items are a oneOf array with length 1 - [#1265](https://github.com/hey-api/openapi-ts/pull/1265) [`691cdc2`](https://github.com/hey-api/openapi-ts/commit/691cdc28b6ad5bc1a38e1ae9eb134a2b41d4ead8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle non-exploded array query parameters - [#1267](https://github.com/hey-api/openapi-ts/pull/1267) [`ff3aa4a`](https://github.com/hey-api/openapi-ts/commit/ff3aa4ac58068671d2b9eedbd7528eb4f9969386) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle discriminators in experimental parser ## 0.55.1 ### Patch Changes - [#1248](https://github.com/hey-api/openapi-ts/pull/1248) [`61cd848`](https://github.com/hey-api/openapi-ts/commit/61cd848262b20580fb185d023c28aa54754bf19c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle nullable enums in experimental parser - [#1251](https://github.com/hey-api/openapi-ts/pull/1251) [`07800d4`](https://github.com/hey-api/openapi-ts/commit/07800d4fbb849614ed2c23b8acc9c82f1ef74598) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for custom plugins - [#1250](https://github.com/hey-api/openapi-ts/pull/1250) [`9e07675`](https://github.com/hey-api/openapi-ts/commit/9e07675802c75b8f5105dd104bb7736aeb83ece6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: render void for empty response status codes in experimental parser ## 0.55.0 ### Minor Changes - [#1241](https://github.com/hey-api/openapi-ts/pull/1241) [`41cee41`](https://github.com/hey-api/openapi-ts/commit/41cee417055c50de6170e6fdeae65bd6e643d19c) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add input.include option ### Patch Changes - [#1239](https://github.com/hey-api/openapi-ts/pull/1239) [`319a28a`](https://github.com/hey-api/openapi-ts/commit/319a28af29541d7f61cca82389e1d486204f321f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle pagination with basic refs ## 0.54.4 ### Patch Changes - [#1237](https://github.com/hey-api/openapi-ts/pull/1237) [`63ccc07`](https://github.com/hey-api/openapi-ts/commit/63ccc0775e24a096bc46ac7ff29b99b694aad621) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: forbid any body, path, or query parameters if not defined in spec - [#1235](https://github.com/hey-api/openapi-ts/pull/1235) [`7a1a419`](https://github.com/hey-api/openapi-ts/commit/7a1a419f07d5ad39e07265771b30d49a4b754a88) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle additionalProperties: boolean in experimental parser - [#1233](https://github.com/hey-api/openapi-ts/pull/1233) [`08baa77`](https://github.com/hey-api/openapi-ts/commit/08baa77afdc5e2c49d4789b20673e949951ab0b2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update schemas plugin to handle experimental 3.0.x parser This release adds an experimental parser for OpenAPI versions 3.0.x. In the future, this will become the default parser. If you're using OpenAPI 3.0 or newer, we encourage you to try it out today. You can enable the experimental parser by setting the `experimentalParser` boolean flag to `true` in your configuration file or CLI. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", experimentalParser: true, }; ``` ```sh npx @hey-api/openapi-ts -i path/to/openapi.json -o src/client -c @hey-api/client-fetch -e ``` The generated output should not structurally change, despite few things being generated in a different order. In fact, the output should be cleaner! That's the immediate side effect you should notice. If that's not true, please leave feedback in [GitHub issues](https://github.com/hey-api/openapi-ts/issues). Hey API parser marks an important milestone towards v1 of `@hey-api/openapi-ts`. More features will be added to the parser in the future and the original parser from `openapi-typescript-codegen` will be deprecated and used only for generating legacy clients. If you'd like to work with the parser more closely (e.g. to generate code not natively supported by this package), feel free to reach out with any feedback or suggestions. Happy parsing! 🎉 ## 0.54.3 ### Patch Changes - [#1230](https://github.com/hey-api/openapi-ts/pull/1230) [`3e65ae0`](https://github.com/hey-api/openapi-ts/commit/3e65ae06bcd2823482cf012909388c7630e18229) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add OpenAPI 3.0.x experimental parser This release adds an experimental parser for OpenAPI versions 3.0.x. In the future, this will become the default parser. If you're using OpenAPI 3.0 or newer, we encourage you to try it out today. You can enable the experimental parser by setting the `experimentalParser` boolean flag to `true` in your configuration file or CLI. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", experimentalParser: true, }; ``` ```sh npx @hey-api/openapi-ts -i path/to/openapi.json -o src/client -c @hey-api/client-fetch -e ``` The generated output should not structurally change, despite few things being generated in a different order. In fact, the output should be cleaner! That's the immediate side effect you should notice. If that's not true, please leave feedback in [GitHub issues](https://github.com/hey-api/openapi-ts/issues). Hey API parser marks an important milestone towards v1 of `@hey-api/openapi-ts`. More features will be added to the parser in the future and the original parser from `openapi-typescript-codegen` will be deprecated and used only for generating legacy clients. If you'd like to work with the parser more closely (e.g. to generate code not natively supported by this package), feel free to reach out with any feedback or suggestions. Happy parsing! 🎉 ## 0.54.2 ### Patch Changes - [#1222](https://github.com/hey-api/openapi-ts/pull/1222) [`ceb4363`](https://github.com/hey-api/openapi-ts/commit/ceb4363d52893ebe947e21aac402b868ff2820d4) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add support for @tanstack/angular-query-experimental package ## 0.54.1 ### Patch Changes - [#1211](https://github.com/hey-api/openapi-ts/pull/1211) [`c8a3e3d`](https://github.com/hey-api/openapi-ts/commit/c8a3e3d7e59692698b7cf45182ca92494fc4af96) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: ignore name option when not used with legacy clients to avoid producing broken output - [#1209](https://github.com/hey-api/openapi-ts/pull/1209) [`3a80b9f`](https://github.com/hey-api/openapi-ts/commit/3a80b9fd009c8229d69f3f349acbfb19b7549a94) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add support for OpenAPI 3.1.1 to experimental parser ## 0.54.0 ### Minor Changes - [#1201](https://github.com/hey-api/openapi-ts/pull/1201) [`972a93a`](https://github.com/hey-api/openapi-ts/commit/972a93a91a945cc9ead73c08bb0fa9ee120433ba) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: make plugins first-class citizens This release makes plugins first-class citizens. In order to achieve that, the following breaking changes were introduced. ### Removed CLI options The `--types`, `--schemas`, and `--services` CLI options have been removed. You can list which plugins you'd like to use explicitly by passing a list of plugins as `--plugins ` ### Removed `*.export` option Previously, you could explicitly disable export of certain artifacts using the `*.export` option or its shorthand variant. These were both removed. You can now disable export of specific artifacts by manually defining an array of `plugins` and excluding the unwanted plugin. ::: code-group ```js [shorthand] export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", schemas: false, // [!code --] plugins: ["@hey-api/types", "@hey-api/services"], // [!code ++] }; ``` ```js [*.export] export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", schemas: { export: false, // [!code --] }, plugins: ["@hey-api/types", "@hey-api/services"], // [!code ++] }; ``` ::: ### Renamed `schemas.name` option Each plugin definition contains a `name` field. This was conflicting with the `schemas.name` option. As a result, it has been renamed to `nameBuilder`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", schemas: { name: (name) => `${name}Schema`, // [!code --] }, plugins: [ // ...other plugins { nameBuilder: (name) => `${name}Schema`, // [!code ++] name: "@hey-api/schemas", }, ], }; ``` ### Removed `services.include` shorthand option Previously, you could use a string value as a shorthand for the `services.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", services: "^MySchema", // [!code --] plugins: [ // ...other plugins { include: "^MySchema", // [!code ++] name: "@hey-api/services", }, ], }; ``` ### Renamed `services.name` option Each plugin definition contains a `name` field. This was conflicting with the `services.name` option. As a result, it has been renamed to `serviceNameBuilder`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", services: { name: "{{name}}Service", // [!code --] }, plugins: [ // ...other plugins { serviceNameBuilder: "{{name}}Service", // [!code ++] name: "@hey-api/services", }, ], }; ``` ### Renamed `types.dates` option Previously, you could set `types.dates` to a boolean or a string value, depending on whether you wanted to transform only type strings into dates, or runtime code too. Many people found these options confusing, so they have been simplified to a boolean and extracted into a separate `@hey-api/transformers` plugin. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", types: { dates: "types+transform", // [!code --] }, plugins: [ // ...other plugins { dates: true, // [!code ++] name: "@hey-api/transformers", }, ], }; ``` ### Removed `types.include` shorthand option Previously, you could use a string value as a shorthand for the `types.include` configuration option. You can now achieve the same result using the `include` option. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", types: "^MySchema", // [!code --] plugins: [ // ...other plugins { include: "^MySchema", // [!code ++] name: "@hey-api/types", }, ], }; ``` ### Renamed `types.name` option Each plugin definition contains a `name` field. This was conflicting with the `types.name` option. As a result, it has been renamed to `style`. ```js export default { client: "@hey-api/client-fetch", input: "path/to/openapi.json", output: "src/client", types: { name: "PascalCase", // [!code --] }, plugins: [ // ...other plugins { name: "@hey-api/types", style: "PascalCase", // [!code ++] }, ], }; ``` ## 0.53.12 ### Patch Changes - [#1195](https://github.com/hey-api/openapi-ts/pull/1195) [`753643f`](https://github.com/hey-api/openapi-ts/commit/753643fae74d4248df8dc5fe9dda5f28a1dabdf1) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: TanStack Query plugin using missing import for infinite query - [#1194](https://github.com/hey-api/openapi-ts/pull/1194) [`c38deaf`](https://github.com/hey-api/openapi-ts/commit/c38deaf02b606b92edd9c316b1444b6b6c12916d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: pass TanStack query signal to client call ## 0.53.11 ### Patch Changes - [#1151](https://github.com/hey-api/openapi-ts/pull/1151) [`587791d`](https://github.com/hey-api/openapi-ts/commit/587791dfede0167fbed229281467e4c4875936f5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update website domain, add license documentation ## 0.53.10 ### Patch Changes - [#1145](https://github.com/hey-api/openapi-ts/pull/1145) [`a0a5551`](https://github.com/hey-api/openapi-ts/commit/a0a55510d30a1a8dea0ade4908b5b13d51b5f9e6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update license field in package.json to match the license, revert client packages license to MIT ## 0.53.9 ### Patch Changes - [#1137](https://github.com/hey-api/openapi-ts/pull/1137) [`f4566c2`](https://github.com/hey-api/openapi-ts/commit/f4566c2bcd67f45f069bfa6220d3c710177f28cc) Thanks [@BierDav](https://github.com/BierDav)! - Add support for passing mutation specific options to `Mutation(options)` ## 0.53.8 ### Patch Changes - [#1123](https://github.com/hey-api/openapi-ts/pull/1123) [`032338c`](https://github.com/hey-api/openapi-ts/commit/032338c47506ccfd567bbbf915398942c8394bc2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use correct relative path to bundled client when imported from nested module ## 0.53.7 ### Patch Changes - [#1113](https://github.com/hey-api/openapi-ts/pull/1113) [`dc696e0`](https://github.com/hey-api/openapi-ts/commit/dc696e0b4500dba5ceb4c772110b123bd2f71b40) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: skip nested properties in oneOf and anyOf compositions - [#1115](https://github.com/hey-api/openapi-ts/pull/1115) [`5f077dd`](https://github.com/hey-api/openapi-ts/commit/5f077dd8d144bbfe71d8775bad5fe7ddda2315d6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: abstract page params logic in TanStack Query plugin ## 0.53.6 ### Patch Changes - [#1104](https://github.com/hey-api/openapi-ts/pull/1104) [`a1eada1`](https://github.com/hey-api/openapi-ts/commit/a1eada1896046f0de1710682635efc59434a1e2c) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export spec-compliant OpenAPI 3.1 interface - [#1108](https://github.com/hey-api/openapi-ts/pull/1108) [`7677924`](https://github.com/hey-api/openapi-ts/commit/76779246534391deca5a371df2c7dc76e9d2eb73) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle multiple form-data parameters in Swagger 2.0 ## 0.53.5 ### Patch Changes - [#1096](https://github.com/hey-api/openapi-ts/pull/1096) [`b6e350a`](https://github.com/hey-api/openapi-ts/commit/b6e350a9cc2d82ac4496b7d57ec8b58978c951c2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make TanStack Query plugin work with class-based services - [#1095](https://github.com/hey-api/openapi-ts/pull/1095) [`11ee53f`](https://github.com/hey-api/openapi-ts/commit/11ee53f4f519643ae7e3f0997ce4fe9b6cb050a8) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: avoid printing duplicate null nodes - [#1094](https://github.com/hey-api/openapi-ts/pull/1094) [`713ccd5`](https://github.com/hey-api/openapi-ts/commit/713ccd5e5e250a14cacf96fd1dffad252cc4cc6a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: attach TanStack Query infinite page params only if they exist ## 0.53.4 ### Patch Changes - [#1087](https://github.com/hey-api/openapi-ts/pull/1087) [`b528236`](https://github.com/hey-api/openapi-ts/commit/b528236b626d12d4ac03b98b8abecc425291c5e5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: import handlebars instead of runtime - [#1086](https://github.com/hey-api/openapi-ts/pull/1086) [`0bc1ebe`](https://github.com/hey-api/openapi-ts/commit/0bc1ebe318399d01296777746ce0bccc83c0e83d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support dynamic require in child_process ## 0.53.3 ### Patch Changes - [#1075](https://github.com/hey-api/openapi-ts/pull/1075) [`11a276a`](https://github.com/hey-api/openapi-ts/commit/11a276a1e35dde0735363e892d8142016fd87eec) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: properly handle dual publishing and type generation ## 0.53.2 ### Patch Changes - [#1060](https://github.com/hey-api/openapi-ts/pull/1060) [`8d66c08`](https://github.com/hey-api/openapi-ts/commit/8d66c085cf81e0e166c3e172ce319d5e2d4002bf) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle colon in operation path - [#1065](https://github.com/hey-api/openapi-ts/pull/1065) [`a756987`](https://github.com/hey-api/openapi-ts/commit/a756987ad396fd7e68cc5eff63f6615bffef3782) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow overriding generated headers from options - [#1068](https://github.com/hey-api/openapi-ts/pull/1068) [`a48be86`](https://github.com/hey-api/openapi-ts/commit/a48be8660f6d1d84fdf25a3952587fb963482e8a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export Operation interface - [#1067](https://github.com/hey-api/openapi-ts/pull/1067) [`5a52da1`](https://github.com/hey-api/openapi-ts/commit/5a52da1425abef9f4fef58ef077dbd05545e25a2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle named object property with no nested properties - [#1066](https://github.com/hey-api/openapi-ts/pull/1066) [`e8a38ae`](https://github.com/hey-api/openapi-ts/commit/e8a38ae4e3f021a105d18764ef3252db7efa9aa0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: transform any-of nullable dates ## 0.53.1 ### Patch Changes - [#1050](https://github.com/hey-api/openapi-ts/pull/1050) [`6922b5a`](https://github.com/hey-api/openapi-ts/commit/6922b5a3ebe67190d2034ea79674706a5e80e818) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: throw error on invalid client value ## 0.53.0 ### Minor Changes - [#1008](https://github.com/hey-api/openapi-ts/pull/1008) [`dc4a40d`](https://github.com/hey-api/openapi-ts/commit/dc4a40d517853e4cf5be532f5bf4874c84c924be) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: rename legacy clients with 'legacy/' prefix - [#1009](https://github.com/hey-api/openapi-ts/pull/1009) [`c6b044d`](https://github.com/hey-api/openapi-ts/commit/c6b044d0bc9dc54cb0eb58d23438f4e1d050cb38) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: change schemas name pattern, add schemas.name option ### Patch Changes - [#989](https://github.com/hey-api/openapi-ts/pull/989) [`bc78a42`](https://github.com/hey-api/openapi-ts/commit/bc78a421eafed1920102b796842e227cacda6ef0) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: make UserConfig interface instead of type - [#1010](https://github.com/hey-api/openapi-ts/pull/1010) [`b6e58c6`](https://github.com/hey-api/openapi-ts/commit/b6e58c64d1b71897533a85d1738cd7ce7ede178d) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: set query key base url from supplied client if provided ## 0.52.11 ### Patch Changes - [#981](https://github.com/hey-api/openapi-ts/pull/981) [`afd8c43`](https://github.com/hey-api/openapi-ts/commit/afd8c4386fb7b2f86a54e73c9471945bdfad22ea) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: export query key functions from TanStack Query plugin ## 0.52.10 ### Patch Changes - [#973](https://github.com/hey-api/openapi-ts/pull/973) [`8f7a14f`](https://github.com/hey-api/openapi-ts/commit/8f7a14f570e2d17053f1e612f6e045df774916f1) Thanks [@jacobinu](https://github.com/jacobinu)! - fix: handle tree-shakeable angular client case ## 0.52.9 ### Patch Changes - [#948](https://github.com/hey-api/openapi-ts/pull/948) [`ebfd6ee`](https://github.com/hey-api/openapi-ts/commit/ebfd6eec434d7b84883a8f9058f31948fb1a40f2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle schemas with generics from C# - [#949](https://github.com/hey-api/openapi-ts/pull/949) [`16f8956`](https://github.com/hey-api/openapi-ts/commit/16f89566a7affeb09a6b928c43cfa2733e8b9adc) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: rename infinite key in query key to \_infinite - [#946](https://github.com/hey-api/openapi-ts/pull/946) [`f873fa6`](https://github.com/hey-api/openapi-ts/commit/f873fa67befe60b2fd8f63bc2c8b73437591f686) Thanks [@mrlubos](https://github.com/mrlubos)! - chore: warn on duplicate operation ID - [#947](https://github.com/hey-api/openapi-ts/pull/947) [`7f0fefe`](https://github.com/hey-api/openapi-ts/commit/7f0fefec92b25ce18ed0d1c6a6edf1adbc7d4481) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly use parentheses around composed schemas - [#944](https://github.com/hey-api/openapi-ts/pull/944) [`2f7cc89`](https://github.com/hey-api/openapi-ts/commit/2f7cc8986c0644b41cc6a5526ddf52ebff880c79) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly handle integer type in additional properties ## 0.52.8 ### Patch Changes - [#932](https://github.com/hey-api/openapi-ts/pull/932) [`cdf01e8`](https://github.com/hey-api/openapi-ts/commit/cdf01e8cc0dc63213465b9e8fe33b80443d36f55) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: cherry pick keys in mutation page param type ## 0.52.7 ### Patch Changes - [#929](https://github.com/hey-api/openapi-ts/pull/929) [`b56c81c`](https://github.com/hey-api/openapi-ts/commit/b56c81ca67a2d069b33430c3139e2135a299b309) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle various issues with additionalProperties definitions - [#927](https://github.com/hey-api/openapi-ts/pull/927) [`65f151d`](https://github.com/hey-api/openapi-ts/commit/65f151dc0004ce817bc370486495bdd281439e55) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: update TanStack Query key to contain base URL - [#927](https://github.com/hey-api/openapi-ts/pull/927) [`65f151d`](https://github.com/hey-api/openapi-ts/commit/65f151dc0004ce817bc370486495bdd281439e55) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: change TanStack Query mutation helpers to functions for consistent API ## 0.52.6 ### Patch Changes - [#920](https://github.com/hey-api/openapi-ts/pull/920) [`4ff2404`](https://github.com/hey-api/openapi-ts/commit/4ff24049457b7d0d5333c3704f488f1f45dd0c5b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: add preview version of TanStack Query plugin ## 0.52.5 ### Patch Changes - [#910](https://github.com/hey-api/openapi-ts/pull/910) [`428dcad`](https://github.com/hey-api/openapi-ts/commit/428dcad06eba3ab14876c28092a6df81fcde7dbe) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: throw if prerequisite checks are not met - [#907](https://github.com/hey-api/openapi-ts/pull/907) [`a2a1ab8`](https://github.com/hey-api/openapi-ts/commit/a2a1ab8bd78c2cbbdcb7adb2ba3815250843dbe7) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly transform string to pascalcase when referenced inside schema - [#908](https://github.com/hey-api/openapi-ts/pull/908) [`225b640`](https://github.com/hey-api/openapi-ts/commit/225b640b5ac628cb7ba3b7afb39ff271a0608055) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not generate types tree by default if services are enabled as it is unused ## 0.52.4 ### Patch Changes - [#895](https://github.com/hey-api/openapi-ts/pull/895) [`44de8d8`](https://github.com/hey-api/openapi-ts/commit/44de8d89556b3abf48acc4e23c9b9c198059c757) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: define ThrowOnError generic as the last argument ## 0.52.3 ### Patch Changes - [#884](https://github.com/hey-api/openapi-ts/pull/884) [`62a39e6`](https://github.com/hey-api/openapi-ts/commit/62a39e63f645bce0801779fb6b90531401748e86) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate ThrowOnError generic for class-based client methods ## 0.52.2 ### Patch Changes - [#881](https://github.com/hey-api/openapi-ts/pull/881) [`a9ddfe6`](https://github.com/hey-api/openapi-ts/commit/a9ddfe6c4487fe5debd04a194ee6c6b6c611dc6b) Thanks [@hougesen](https://github.com/hougesen)! - fix: check if key is schema property before removing ## 0.52.1 ### Patch Changes - [#855](https://github.com/hey-api/openapi-ts/pull/855) [`7ac6274`](https://github.com/hey-api/openapi-ts/commit/7ac627463a15fa6be2c9d103b25200355df6b166) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: define multiple errors type as union instead of intersection - [#853](https://github.com/hey-api/openapi-ts/pull/853) [`6ab387d`](https://github.com/hey-api/openapi-ts/commit/6ab387d3440ec5ec524e7f198aedfa6734431d76) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: remove Content-Type header with multipart/form-data content type - [#861](https://github.com/hey-api/openapi-ts/pull/861) [`21ccf90`](https://github.com/hey-api/openapi-ts/commit/21ccf90b864590c211fbfa3de5c687dd3c48f897) Thanks [@qqilihq](https://github.com/qqilihq)! - fix: Additional properties key - [#869](https://github.com/hey-api/openapi-ts/pull/869) [`42d8a41`](https://github.com/hey-api/openapi-ts/commit/42d8a4151bace7b70af60a1abe46b7550ddad686) Thanks [@SamuelGuillemet](https://github.com/SamuelGuillemet)! - fix: add conditionnal generation for service related types ## 0.52.0 ### Minor Changes - [#835](https://github.com/hey-api/openapi-ts/pull/835) [`7ab277b`](https://github.com/hey-api/openapi-ts/commit/7ab277b22467fe268719af817aee701d6be3e828) Thanks [@LeeChSien](https://github.com/LeeChSien)! - feat: add namespace supporting for enums ### Patch Changes - [#830](https://github.com/hey-api/openapi-ts/pull/830) [`babf11a`](https://github.com/hey-api/openapi-ts/commit/babf11ae082af642ac71cfee9c523cc976132a50) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate internal client for services when using standalone package ## 0.51.0 ### Minor Changes - [#828](https://github.com/hey-api/openapi-ts/pull/828) [`82a4696`](https://github.com/hey-api/openapi-ts/commit/82a4696b0b209ea2d9147f47f213479e61aed3d7) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: make `client` config option required ### Patch Changes - [#823](https://github.com/hey-api/openapi-ts/pull/823) [`23c9dcd`](https://github.com/hey-api/openapi-ts/commit/23c9dcd5de19de62d745cc539674c815b2588cd2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: correctly process body parameter for OpenAPI 2.0 specs - [#827](https://github.com/hey-api/openapi-ts/pull/827) [`8d81c06`](https://github.com/hey-api/openapi-ts/commit/8d81c0605dbf4b4d19ec1c2dc51a93f8a2aca5b2) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: do not ignore api-version param in standalone clients ## 0.50.2 ### Patch Changes - [#818](https://github.com/hey-api/openapi-ts/pull/818) [`85d123c`](https://github.com/hey-api/openapi-ts/commit/85d123c9160f4ecb4c48e8a2ead54abf604dd21b) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle fully illegal schema names ## 0.50.1 ### Patch Changes - [#807](https://github.com/hey-api/openapi-ts/pull/807) [`ef249ba`](https://github.com/hey-api/openapi-ts/commit/ef249ba5bd04dbfb0e0a497caaa021f9c7de6949) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate types only for filtered services - [#807](https://github.com/hey-api/openapi-ts/pull/807) [`ef249ba`](https://github.com/hey-api/openapi-ts/commit/ef249ba5bd04dbfb0e0a497caaa021f9c7de6949) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow any key/value pair in object types with empty properties object ## 0.50.0 ### Minor Changes - [#790](https://github.com/hey-api/openapi-ts/pull/790) [`68c3921`](https://github.com/hey-api/openapi-ts/commit/68c3921fd6e9a5db41ebd9f06e4f3ef6e64ab051) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: allow bundling standalone clients with `client.bundle = true` ## 0.49.0 ### Minor Changes - [#787](https://github.com/hey-api/openapi-ts/pull/787) [`327c5fb`](https://github.com/hey-api/openapi-ts/commit/327c5fb629f0c7b9c727da87b6bc287b8e98bcd5) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: allow filtering service endpoints with `services.filter` ### Patch Changes - [#784](https://github.com/hey-api/openapi-ts/pull/784) [`f12dccf`](https://github.com/hey-api/openapi-ts/commit/f12dccf0ae3a05badb5783354bcd093f18f3ab74) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: suffix illegal service names - [#786](https://github.com/hey-api/openapi-ts/pull/786) [`20759e2`](https://github.com/hey-api/openapi-ts/commit/20759e2cc52d78974fc0f78f581e9d9cb2d21ca5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle references to schemas with illegal names - [#788](https://github.com/hey-api/openapi-ts/pull/788) [`ecd94f2`](https://github.com/hey-api/openapi-ts/commit/ecd94f2adab1dbe10e7a9c310d1fb6d1f170d332) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle application/x-www-form-urlencoded content in request body ## 0.48.3 ### Patch Changes - [#781](https://github.com/hey-api/openapi-ts/pull/781) [`df3b799`](https://github.com/hey-api/openapi-ts/commit/df3b79996d47a69e4f2fdad93cea18ae1a01c419) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use methodNameBuilder when asClass is false - [#782](https://github.com/hey-api/openapi-ts/pull/782) [`edfd2bd`](https://github.com/hey-api/openapi-ts/commit/edfd2bdbb64f6682ded16f6da30f88f1c113bbe0) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow not generating types tree with types.tree = false ## 0.48.2 ### Patch Changes - [#746](https://github.com/hey-api/openapi-ts/pull/746) [`0448823`](https://github.com/hey-api/openapi-ts/commit/044882399d56d1532c7125df2e69cfb3b5fb4f34) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle formData parameters in generated types - [#742](https://github.com/hey-api/openapi-ts/pull/742) [`efc30f4`](https://github.com/hey-api/openapi-ts/commit/efc30f4a2327b165b62f8467c68351a8bf94ffe5) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: ignore services.asClass setting for named clients - [#744](https://github.com/hey-api/openapi-ts/pull/744) [`1e9edde`](https://github.com/hey-api/openapi-ts/commit/1e9edde54abd8978405f91b821c99b97f067d566) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve default response type detection - [#745](https://github.com/hey-api/openapi-ts/pull/745) [`342772a`](https://github.com/hey-api/openapi-ts/commit/342772a560378c6718d25c29871eeab9a72c62a6) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle properties in one-of composition ## 0.48.1 ### Patch Changes - [#734](https://github.com/hey-api/openapi-ts/pull/734) [`1f52b26`](https://github.com/hey-api/openapi-ts/commit/1f52b260807531edb2c14003473ea4907007ecdb) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: generate service types when types are enabled, even if services are disabled - [#737](https://github.com/hey-api/openapi-ts/pull/737) [`0537fe8`](https://github.com/hey-api/openapi-ts/commit/0537fe8682a93cc95d7637d643db4b9780318ea1) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: support custom config file path - [#736](https://github.com/hey-api/openapi-ts/pull/736) [`8410046`](https://github.com/hey-api/openapi-ts/commit/8410046c45d25db48ba940a0c6c7a7cda9e86b6a) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle async response transformers ## 0.48.0 ### Minor Changes - [#696](https://github.com/hey-api/openapi-ts/pull/696) [`917405f`](https://github.com/hey-api/openapi-ts/commit/917405fcdcb2e978df693eb51720afa6fcf914e2) Thanks [@anchan828](https://github.com/anchan828)! - feat: pass the Operation object to methodNameBuilder ### Patch Changes - [#708](https://github.com/hey-api/openapi-ts/pull/708) [`36cf95d`](https://github.com/hey-api/openapi-ts/commit/36cf95d319b175149d3b3ecc382b8d739186e658) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: make getHeaders() accept generic - [#712](https://github.com/hey-api/openapi-ts/pull/712) [`6a5b96b`](https://github.com/hey-api/openapi-ts/commit/6a5b96b59e4248f2acaf5422be262edde97427dd) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle void responses in transformers ## 0.47.2 ### Patch Changes - [#701](https://github.com/hey-api/openapi-ts/pull/701) [`1081bbf`](https://github.com/hey-api/openapi-ts/commit/1081bbf5082450c18547dac4737ecc0e312cdd0e) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add initial implementation of prefixItems ## 0.47.1 ### Patch Changes - [#690](https://github.com/hey-api/openapi-ts/pull/690) [`1017ace`](https://github.com/hey-api/openapi-ts/commit/1017acee80630d84a08bd8f0087c8fb0de270f1a) Thanks [@Nick-Lucas](https://github.com/Nick-Lucas)! - Fix an issue where transforms for endpoints with array returns were not generated correctly ## 0.47.0 ### Minor Changes - [#685](https://github.com/hey-api/openapi-ts/pull/685) [`8ca3e5e`](https://github.com/hey-api/openapi-ts/commit/8ca3e5e2990bc07ce0bac902245d08b67b6621e8) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: add initial support for response transformers (string -> Date) - [#663](https://github.com/hey-api/openapi-ts/pull/663) [`e01c612`](https://github.com/hey-api/openapi-ts/commit/e01c61213e266afad5e3b159682b05957aac6534) Thanks [@Stono](https://github.com/Stono)! - Add support for customizing method names with `services.methodNameBuilder()` ## 0.46.3 ### Patch Changes - [#594](https://github.com/hey-api/openapi-ts/pull/594) [`9878381`](https://github.com/hey-api/openapi-ts/commit/98783811e0c90705ddac2cc5e54c524aae634865) Thanks [@SimenB](https://github.com/SimenB)! - Add explicit type annotations to `Interceptors` This allows the generated code to work with TypeScript 5.5's new `isolatedDeclarations` configuration. - [#635](https://github.com/hey-api/openapi-ts/pull/635) [`0b09940`](https://github.com/hey-api/openapi-ts/commit/0b0994050dbcb6c17e8b78ca1c77738fc8e0d498) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: handle 1XX response status codes - [#636](https://github.com/hey-api/openapi-ts/pull/636) [`498f459`](https://github.com/hey-api/openapi-ts/commit/498f45979b91bf93b319413c60492af94a08df48) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: improve default response status code classification ## 0.46.2 ### Patch Changes - fix: do not transform property names for standalone clients ([#616](https://github.com/hey-api/openapi-ts/pull/616)) ## 0.46.1 ### Patch Changes - fix: handle application/json content type in parameter definitions ([#614](https://github.com/hey-api/openapi-ts/pull/614)) ## 0.46.0 ### Minor Changes - feat: tree-shakeable services ([#602](https://github.com/hey-api/openapi-ts/pull/602)) ## 0.45.1 ### Patch Changes - fix: use generated types in request object instead of inlined duplicated params ([#582](https://github.com/hey-api/openapi-ts/pull/582)) ## 0.45.0 ### Minor Changes - feat: remove client inference ([#569](https://github.com/hey-api/openapi-ts/pull/569)) ### Patch Changes - fix: deduplicate inlined enums ([#573](https://github.com/hey-api/openapi-ts/pull/573)) - fix: generate correct optional key in types when using positional arguments (useOptions: false) ([#572](https://github.com/hey-api/openapi-ts/pull/572)) ## 0.44.0 ### Minor Changes - feat: move format and lint config options to output object ([#546](https://github.com/hey-api/openapi-ts/pull/546)) ### Patch Changes - fix: comment position in JavaScript enums ([#544](https://github.com/hey-api/openapi-ts/pull/544)) - fix: export inlined enums from components ([#563](https://github.com/hey-api/openapi-ts/pull/563)) - fix: remove unused enums option from CLI ([#565](https://github.com/hey-api/openapi-ts/pull/565)) - fix: Support typescript in peerDependencies ([#551](https://github.com/hey-api/openapi-ts/pull/551)) ## 0.43.2 ### Patch Changes - fix: deduplicate exported data and response types ([#538](https://github.com/hey-api/openapi-ts/pull/538)) ## 0.43.1 ### Patch Changes - fix: use optional chaining in bin catch block ([#528](https://github.com/hey-api/openapi-ts/pull/528)) - fix: broken encoding ([#532](https://github.com/hey-api/openapi-ts/pull/532)) - fix(parser): handle type array ([#533](https://github.com/hey-api/openapi-ts/pull/533)) ## 0.43.0 ### Minor Changes - feat: remove enum postfix, use typescript enums in types when generated, export enums from types.gen.ts ([#498](https://github.com/hey-api/openapi-ts/pull/498)) ### Patch Changes - fix: negative numbers in numeric enums ([#470](https://github.com/hey-api/openapi-ts/pull/470)) - fix: escape keys in schemas starting with digit but containing non-digit characters ([#502](https://github.com/hey-api/openapi-ts/pull/502)) - fix: issue causing code to not generate (t.filter is not a function) ([#507](https://github.com/hey-api/openapi-ts/pull/507)) - fix: handle additional properties union ([#499](https://github.com/hey-api/openapi-ts/pull/499)) - fix: do not export inline enums ([#508](https://github.com/hey-api/openapi-ts/pull/508)) - fix: prefix parameter type exports to avoid conflicts ([#501](https://github.com/hey-api/openapi-ts/pull/501)) - fix: export operation data and response types ([#500](https://github.com/hey-api/openapi-ts/pull/500)) - fix: handle cases where packages are installed globally ([#471](https://github.com/hey-api/openapi-ts/pull/471)) - fix: handle cases where package.json does not exist ([#471](https://github.com/hey-api/openapi-ts/pull/471)) ## 0.42.1 ### Patch Changes - fix: properly set formData and body when using options ([#461](https://github.com/hey-api/openapi-ts/pull/461)) ## 0.42.0 ### Minor Changes - change: config option `lint: true` has changed to `lint: 'eslint'` ([#455](https://github.com/hey-api/openapi-ts/pull/455)) - change: disable formatting with prettier by default ([#457](https://github.com/hey-api/openapi-ts/pull/457)) - feat: add support for biomejs as a formatter ([#455](https://github.com/hey-api/openapi-ts/pull/455)) - feat: move operationId config option to services object ([#441](https://github.com/hey-api/openapi-ts/pull/441)) - feat: add operation error type mappings ([#442](https://github.com/hey-api/openapi-ts/pull/442)) - feat: add support for biomejs as a linter ([#455](https://github.com/hey-api/openapi-ts/pull/455)) - change: config option `format: true` has changed to `format: 'prettier'` ([#455](https://github.com/hey-api/openapi-ts/pull/455)) ### Patch Changes - fix: do not destructure data when using use options ([#450](https://github.com/hey-api/openapi-ts/pull/450)) - feat: automatically handle dates in query string ([#443](https://github.com/hey-api/openapi-ts/pull/443)) - fix: only remove core directory when export core is true ([#449](https://github.com/hey-api/openapi-ts/pull/449)) - fix: add jsdoc comments with use options ([#439](https://github.com/hey-api/openapi-ts/pull/439)) ## 0.41.0 ### Minor Changes - feat: add form type option for schemas ([#433](https://github.com/hey-api/openapi-ts/pull/433)) - feat: replace useDateType with option in types object ([#435](https://github.com/hey-api/openapi-ts/pull/435)) - feat: replace serviceResponse with option in services object ([#434](https://github.com/hey-api/openapi-ts/pull/434)) - feat: replace postfixServices with configuration object ([#430](https://github.com/hey-api/openapi-ts/pull/430)) ### Patch Changes - fix: properly escape backticks in template literals ([#431](https://github.com/hey-api/openapi-ts/pull/431)) - fix: transform names of referenced types ([#422](https://github.com/hey-api/openapi-ts/pull/422)) - fix: use config interceptors passed to constructor when using named client ([#432](https://github.com/hey-api/openapi-ts/pull/432)) - fix: properly escape expressions in template literals ([#431](https://github.com/hey-api/openapi-ts/pull/431)) - fix: do not export common properties as schemas ([#424](https://github.com/hey-api/openapi-ts/pull/424)) ## 0.40.2 ### Patch Changes - fix: unhandled SyntaxKind unknown when specification has numeric enums ([#417](https://github.com/hey-api/openapi-ts/pull/417)) ## 0.40.1 ### Patch Changes - fix: revert to generating commonjs for esm and commonjs support ([#409](https://github.com/hey-api/openapi-ts/pull/409)) ## 0.40.0 ### Minor Changes - feat: allow choosing naming convention for types ([#402](https://github.com/hey-api/openapi-ts/pull/402)) ### Patch Changes - fix: rename exportModels to types ([#402](https://github.com/hey-api/openapi-ts/pull/402)) - fix: rename models.gen.ts to types.gen.ts ([#399](https://github.com/hey-api/openapi-ts/pull/399)) - fix: export enums from index.ts ([#399](https://github.com/hey-api/openapi-ts/pull/399)) ## 0.39.0 ### Minor Changes - feat: rename generated files ([#363](https://github.com/hey-api/openapi-ts/pull/363)) - feat: add JSON-LD to content parsing ([#390](https://github.com/hey-api/openapi-ts/pull/390)) - fix: generate enums into their own file ([#358](https://github.com/hey-api/openapi-ts/pull/358)) ### Patch Changes - fix: remove file if no contents to write to it ([#373](https://github.com/hey-api/openapi-ts/pull/373)) - fix: eslint properly fixes output ([#375](https://github.com/hey-api/openapi-ts/pull/375)) - fix: invalid typescript Record generated with circular dependencies ([#374](https://github.com/hey-api/openapi-ts/pull/374)) - fix: prefer unknown type over any ([#392](https://github.com/hey-api/openapi-ts/pull/392)) - fix: only delete generated files instead of whole output directory ([#362](https://github.com/hey-api/openapi-ts/pull/362)) - fix: handle decoding models with `%` in description ([#360](https://github.com/hey-api/openapi-ts/pull/360)) - fix: throw error when typescript is missing ([#366](https://github.com/hey-api/openapi-ts/pull/366)) ## 0.38.1 ### Patch Changes - fix: inconsistent indentation in models file when not using `format: true` ([#349](https://github.com/hey-api/openapi-ts/pull/349)) - fix: output path no longer required to be within cwd ([#353](https://github.com/hey-api/openapi-ts/pull/353)) ## 0.38.0 ### Minor Changes - fix: rename write to dryRun and invert value ([#326](https://github.com/hey-api/openapi-ts/pull/326)) ### Patch Changes - fix: generate constant size array types properly ([#345](https://github.com/hey-api/openapi-ts/pull/345)) - fix: support x-enumNames for custom enum names ([#334](https://github.com/hey-api/openapi-ts/pull/334)) - fix: export service types from single namespace ([#341](https://github.com/hey-api/openapi-ts/pull/341)) - fix: generate models with proper indentation when formatting is false ([#340](https://github.com/hey-api/openapi-ts/pull/340)) - fix: log errors to file ([#329](https://github.com/hey-api/openapi-ts/pull/329)) - fix: cleanup some styling issues when generating client without formatting ([#330](https://github.com/hey-api/openapi-ts/pull/330)) ## 0.37.3 ### Patch Changes - fix: do not ignore additionalProperties when object with properties object ([#323](https://github.com/hey-api/openapi-ts/pull/323)) ## 0.37.2 ### Patch Changes - fix: escape schema names ([#317](https://github.com/hey-api/openapi-ts/pull/317)) - fix: escape backticks in strings starting with backtick ([#315](https://github.com/hey-api/openapi-ts/pull/315)) ## 0.37.1 ### Patch Changes - fix: ensure strings with both single/double quotes and backticks are escaped properly ([#310](https://github.com/hey-api/openapi-ts/pull/310)) ([#310](https://github.com/hey-api/openapi-ts/pull/310)) ## 0.37.0 ### Minor Changes - remove: `generics` as valid option for serviceResponse ([#299](https://github.com/hey-api/openapi-ts/pull/299)) ### Patch Changes - fix: escape dollar sign in operation names ([#307](https://github.com/hey-api/openapi-ts/pull/307)) ## 0.36.2 ### Patch Changes - fix: move service types into models file ([#292](https://github.com/hey-api/openapi-ts/pull/292)) ## 0.36.1 ### Patch Changes - fix: do not throw when failing to decode URI ([#296](https://github.com/hey-api/openapi-ts/pull/296)) ## 0.36.0 ### Minor Changes - feat: export schemas directly from OpenAPI specification (ie. support exporting JSON schemas draft 2020-12 ([#285](https://github.com/hey-api/openapi-ts/pull/285)) ### Patch Changes - fix(config): rename exportSchemas to schemas ([#288](https://github.com/hey-api/openapi-ts/pull/288)) ## 0.35.0 ### Minor Changes - fix(config): remove postfixModels option ([#266](https://github.com/hey-api/openapi-ts/pull/266)) - fix(client): do not send default params ([#267](https://github.com/hey-api/openapi-ts/pull/267)) ### Patch Changes - fix(api): use TypeScript Compiler API to create schemas ([#271](https://github.com/hey-api/openapi-ts/pull/271)) - fix(client): export APIResult when using serviceResponse as 'response' ([#283](https://github.com/hey-api/openapi-ts/pull/283)) - fix(parser): use only isRequired to determine if field is required ([#264](https://github.com/hey-api/openapi-ts/pull/264)) ## 0.34.5 ### Patch Changes - fix(client): access service data type in namespace properly ([#258](https://github.com/hey-api/openapi-ts/pull/258)) ## 0.34.4 ### Patch Changes - fix(client): namespace service data types ([#246](https://github.com/hey-api/openapi-ts/pull/246)) ## 0.34.3 ### Patch Changes - fix(docs): link to docs hosted on vercel ([#244](https://github.com/hey-api/openapi-ts/pull/244)) ## 0.34.2 ### Patch Changes - docs(readme): update broken contributing link ([#236](https://github.com/hey-api/openapi-ts/pull/236)) - fix(config): support ts config files and `defineConfig` syntax ([`0c92222ab74bb7d2391d49587760db9ea9228d5a`](https://github.com/hey-api/openapi-ts/commit/0c92222ab74bb7d2391d49587760db9ea9228d5a)) ## 0.34.1 ### Patch Changes - fix(docs): ensure README is shown on NPMJS ([#229](https://github.com/hey-api/openapi-ts/pull/229)) ## 0.34.0 ### Minor Changes - feat(client): generate all services in single `services.ts` file ([#215](https://github.com/hey-api/openapi-ts/pull/215)) - feat(schema): add support for default values ([#197](https://github.com/hey-api/openapi-ts/pull/197)) - feat(schema): add array of enum values for enums ([#197](https://github.com/hey-api/openapi-ts/pull/197)) ### Patch Changes - fix(axios): use builtin form data to ensure blob form data works in node environment ([#211](https://github.com/hey-api/openapi-ts/pull/211)) - fix(enum): append index number on duplicate name ([#220](https://github.com/hey-api/openapi-ts/pull/220)) ## 0.33.2 ### Patch Changes - fix(axios): properly type content-type headers assignment ([#206](https://github.com/hey-api/openapi-ts/pull/206)) ## 0.33.1 ### Patch Changes - fix(axios): set content type to multipart/form-data when using form data ([#204](https://github.com/hey-api/openapi-ts/pull/204)) ## 0.33.0 ### Minor Changes - feat(fetch): detect form data repsonses properly ([#195](https://github.com/hey-api/openapi-ts/pull/195)) - feat(fetch): add application/octet-stream, application/pdf, and application/zip as binary response types ([#195](https://github.com/hey-api/openapi-ts/pull/195)) ### Patch Changes - fix(client): do not create or export empty files ([#200](https://github.com/hey-api/openapi-ts/pull/200)) - client(angular/fetch/xhr): detect all application/json or +json as JSON ([#195](https://github.com/hey-api/openapi-ts/pull/195)) ## 0.32.1 ### Patch Changes - fix(schema): allow minimums/maximums to be 0 ([#194](https://github.com/hey-api/openapi-ts/pull/194)) - fix(axios): let axios handle serializing form data ([#192](https://github.com/hey-api/openapi-ts/pull/192)) ## 0.32.0 ### Minor Changes - Support all HTTP error codes ([#188](https://github.com/hey-api/openapi-ts/pull/188)) - Use File or Blob type for binary types ([#186](https://github.com/hey-api/openapi-ts/pull/186)) - Check value instanceof Blob when using isBlob ([#186](https://github.com/hey-api/openapi-ts/pull/186)) ### Patch Changes - fix(cli): properly handle booleans ([#190](https://github.com/hey-api/openapi-ts/pull/190)) - Attempt to use body type as content type when sending Blob in node client ([#185](https://github.com/hey-api/openapi-ts/pull/185)) - fix(api): add experimental flag ([#191](https://github.com/hey-api/openapi-ts/pull/191)) ## 0.31.1 ### Patch Changes - merge enums and useLegacyEnums into one option ([#178](https://github.com/hey-api/openapi-ts/pull/178)) - use FormData from node-fetch in node client ([#173](https://github.com/hey-api/openapi-ts/pull/173)) ## 0.31.0 ### Minor Changes - Import all required models for a service in one import ([#172](https://github.com/hey-api/openapi-ts/pull/172)) - generate all models in single `models.ts` file ([#168](https://github.com/hey-api/openapi-ts/pull/168)) - generate all schemas in single `schemas.ts` file ([#168](https://github.com/hey-api/openapi-ts/pull/168)) ### Patch Changes - fix async response interceptors when using angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) - fix deprecation warning on `throwError` in Angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) - Do not create or export CancelablePromise when using Angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) - Fix issue causing type error when targeting lower than ES2015 ([#171](https://github.com/hey-api/openapi-ts/pull/171)) - fix various warnings in generated client code ([#164](https://github.com/hey-api/openapi-ts/pull/164)) - fix providing interceptors in Angular client ([#167](https://github.com/hey-api/openapi-ts/pull/167)) ## 0.30.0 ### Minor Changes - add support for interceptors ([#153](https://github.com/hey-api/openapi-ts/pull/153)) ## 0.29.2 ### Patch Changes - Fix export types as type only when using useLegacyEnums ([#160](https://github.com/hey-api/openapi-ts/pull/160)) ## 0.29.1 ### Patch Changes - Properly export enums when using useLegacyEnums ([#158](https://github.com/hey-api/openapi-ts/pull/158)) ## 0.29.0 ### Minor Changes - Add useLegacyEnums options to generate TypeScript enums ([#147](https://github.com/hey-api/openapi-ts/pull/147)) ## 0.28.0 ### Minor Changes - Add `index.ts` file to models, schemas, and services ([#137](https://github.com/hey-api/openapi-ts/pull/137)) ## 0.27.39 ### Patch Changes - Warn users about missing dependencies used in the generated client ([#124](https://github.com/hey-api/openapi-ts/pull/124)) - Use AbortController in Axios client instead of deprecated CancelToken ([#124](https://github.com/hey-api/openapi-ts/pull/124)) ## 0.27.38 ### Minor Changes - Make useOptions default to true ## 0.27.37 ### Minor Changes - Fix import error in generated Node client - Update package dependencies - Use engine-strict in .npmrc ## 0.27.36 ### Minor Changes - Handle falsy values in header - Export schemas by default ## 0.27.35 ### Minor Changes - Update all project dependencies - Discard only null or undefined in query string ## 0.27.34 ### Minor Changes - Add flag for linting generated code (default: false) - Add flag for formatting generated code (default: true) ## 0.27.33 ### Minor Changes - Auto format with Eslint if available - Add types for programmatic API ## 0.27.32 ### Minor Changes - Rename Config type to UserConfig - Pass arguments in correct order in Angular client ## 0.27.31 ### Minor Changes - Add support for openapi-ts.config.js file - Use built-in flat map ## 0.27.30 ### Minor Changes - Prefer unknown instead of any in generated client ## 0.27.29 ### Minor Changes - Rename openapi command to openapi-ts - Add basic support for response that are Blobs ## 0.27.28 ### Minor Changes - Generate enums as JavaScript objects - Use shorthand object properties in service calls ## 0.27.27 ### Minor Changes - Handle cases where a project does not have dependencies when checking to run Prettier ## 0.27.26 ### Minor Changes - Skip global parameters if they are duplicates of path parameters - remove option to indent code ## 0.27.25 ### Minor Changes - Correctly set content-type header, even when body is falsy ## 0.27.24 ### Minor Changes - Remove union types flag (this is now default) ## 0.27.23 ### Minor Changes - Support printing exact arrays ## 0.27.22 ### Minor Changes - Add option to specify custom base path - Fix spacing in cancelable promise ## 0.27.21 ### Minor Changes - Add explicit flags for generics ## 0.27.20 ### Minor Changes - Do not require type to be set for object properties ## 0.27.19 ### Minor Changes - Do not insert generics into custom client ## 0.27.18 ### Minor Changes - Support returning raw result object - Allow passing config ## 0.27.17 ### Minor Changes - Generate nullable interface when isNullable is true ## 0.27.16 ### Minor Changes - Generate types for services when useOptions is true ## 0.27.15 ### Minor Changes - Fix wrong path on Windows ## 0.27.14 ### Minor Changes - Change imports to match project style ## 0.27.13 ### Minor Changes - Support printing Date instead of string for date-time formats in models ## 0.27.12 ### Minor Changes - Escape enum name when exported ## 0.27.11 ### Minor Changes - Fix typo in template header ## 0.27.10 ### Minor Changes - Escape newlines when outputting pattern string value in schemas ## 0.27.9 ### Minor Changes - Start passing options object instead of positional parameters - Handle composition of any-of and properties - Allow ignoring operation ID when generating operation names - Propagate useVersionId to Swagger V2 parser - Change --ingoreOperationId to --useOperationId ## 0.27.8 ### Minor Changes - Support non-ascii (unicode) characters in service name, operation name, and parameter name ## 0.27.7 ### Minor Changes - Bump dependencies ## 0.27.6 ### Minor Changes - Allow overriding request body name with x-body-name key ## 0.27.5 ### Minor Changes - Type additional properties with properties - Parse array items only if parent definition has type ## 0.27.4 ### Minor Changes - Bump dependencies ## 0.27.3 ### Minor Changes - Support autoformat option flag - Handle more cases of any-of - Support regexp to select models to export - Return optional success response on 204 status code - Fix nested any-of - Add const support ## 0.27.0 ### Minor Changes - Reverted `@apidevtools/json-schema-ref-parser` to version 10.1.0 ## 0.26.0 ### Minor Changes - Upgraded dependencies ## 0.25.0 ### Minor Changes - Upgraded dependencies - Allow usage of a custom axios instance - Added message in generated files ## 0.24.0 ### Minor Changes - Upgraded dependencies - Fixed issue with Cancelable promise - Fixed issue with escaping reserved keywords in schema names - Added `--postfixModels` option ## 0.23.0 ### Minor Changes - Upgraded dependencies - Added blank line at the end of generated files - Added support for Node.js v12 - Added `request` property inside `ApiError` - Added support for `@depricated` inside models and operations ## 0.22.0 ### Minor Changes - Upgraded dependencies - Fixed issue with `null` value inside comments for OpenAPI v2 enums - Fixed issue with compatibility for latest version of Axios (0.27.x) - Removed deprecated enum model generation ## 0.21.0 ### Minor Changes - Return `undefined` to match `noImplicitReturns` rule - Made `BaseHttpRequest` class abstract - Removed private fields using `#` inside `CancelablePromise` - Removed unneeded import `AbortController` from `node-fetch` client - Filter out wrong enum values ## 0.20.1 ### Patch Changes - Support enums with single quotes in names for V2 ## 0.20.0 ### Minor Changes - Updated dependencies - Support enums with single quotes in names for V3 - Generating better names when `operationId` is not given (breaking change) - Fixed issue where `x-enum` flags where breaking due to non-string values ## 0.19.0 ### Minor Changes - Support for Angular client with `--name` option - Added test cases for Angular client ## 0.18.2 ### Patch Changes - Updated dependencies - Fixed type definition - Added test cases for CLI commands - Added test cases for query parsing ## 0.18.1 ### Patch Changes - Escaping error description - Made `Client.request` and `BaseHttpRequest.config` props public ## 0.18.0 ### Minor Changes - Angular client generation! - Updated documentation with more examples and better descriptions ## 0.17.0 ### Minor Changes - Shorthand notation for properties passed through constructor - Simplified creation of headers - Prepare codebase for Angular client ## 0.16.2 ### Patch Changes - Removed dependency on `URLSearchParams` to support browser and node without any additional imports ## 0.16.1 ### Patch Changes - Correct export inside `index.ts` when giving a custom name ## 0.16.0 ### Minor Changes - Added option to set the indentation (spaces and tabs) - Added option to export separate client file that allows usage for multiple backends - Decoupled OpenAPI object from requests - Updated dependencies ## 0.15.0 ### Minor Changes - Added change log and releases on GitHub ## 0.14.0 ### Minor Changes - Added missing `postfix` options to typedef - Updated escaping of comments and descriptions - Better handling of services without tags - Updated dependencies ================================================ FILE: packages/openapi-ts/LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/openapi-ts/README.md ================================================
    Hey API presents openapi-ts

    OpenAPI TypeScript

    “OpenAPI codegen that just works.”
    — Guillermo Rauch, CEO of Vercel

    DevTrends badge for @hey-api/openapi-ts DevTrends badge for @hey-api/openapi-ts CI status GitHub stars MIT License

    Demo  •  Manual  •  Issues  •  Contribute

    ## About The OpenAPI to TypeScript code generator used by Vercel, OpenCode, and PayPal. Generate production-ready SDKs, Zod schemas, TanStack Query hooks, or choose from 20+ other plugins. Part of the Hey API ecosystem. ## Features - production-ready code that compiles - runs in any Node.js 20+ environment - accepts any OpenAPI specification - core plugins for SDKs, types, and schemas - HTTP clients for Fetch API, Angular, Axios, Next.js, Nuxt, and more - 20+ plugins to reduce third-party boilerplate - highly customizable via plugins - [sync with Hey API Registry](https://heyapi.dev/openapi-ts/integrations) for spec management ## Contributing Want to see your code in products used by millions? Start with our [Contributing](https://heyapi.dev/openapi-ts/community/contributing) guide and release your first feature. ## Sponsors Hey API is sponsor-funded. If you rely on Hey API in production, consider becoming a [sponsor](https://github.com/sponsors/hey-api) to accelerate the roadmap.

    Gold

    Stainless logo
    Best-in-class developer interfaces for your API.
    stainless.com

    Opencode logo
    The open source coding agent.
    opencode.ai

    Mintlify logo
    The intelligent knowledge platform.
    mintlify.com

    Silver

    Scalar logo
    scalar.com
    FastAPI logo
    fastapi.tiangolo.com

    Bronze

    Kinde logo Cella logo
    ## Quick Start The fastest way to use `@hey-api/openapi-ts` is via npx ```sh npx @hey-api/openapi-ts -i hey-api/backend -o src/client ``` Congratulations on creating your first client! 🎉 You can learn more about the generated files on the [Output](https://heyapi.dev/openapi-ts/output) page. ## Installation You can download `@hey-api/openapi-ts` from npm using your favorite package manager. #### npm ```sh npm install @hey-api/openapi-ts -D -E ``` #### pnpm ```sh pnpm add @hey-api/openapi-ts -D -E ``` #### yarn ```sh yarn add @hey-api/openapi-ts -D -E ``` #### bun ```sh bun add @hey-api/openapi-ts -D -E ``` ### Versioning This package is in [initial development](https://semver.org/#spec-item-4). Please pin an exact version so you can safely upgrade when you're ready. We publish [migration notes](https://heyapi.dev/openapi-ts/migrating) for every breaking release. You might not be impacted by a breaking change if you don't use the affected features. ## Usage ### CLI Most people run `@hey-api/openapi-ts` via CLI. To do that, add a script to your `package.json` file which will make `openapi-ts` executable through script. ```json "scripts": { "openapi-ts": "openapi-ts" } ``` The above script can be executed by running `npm run openapi-ts` or equivalent command in other package managers. Next, we will create a [configuration](https://heyapi.dev/openapi-ts/configuration) file and move our options from Quick Start to it. ### Node.js You can also generate output programmatically by calling `createClient()` in a JavaScript/TypeScript file. #### `script.ts` ```ts import { createClient } from '@hey-api/openapi-ts'; createClient({ input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }); ``` ## Configuration `@hey-api/openapi-ts` supports loading configuration from any file inside your project root folder supported by [jiti loader](https://github.com/unjs/c12?tab=readme-ov-file#-features). Below are the most common file formats. #### `openapi-ts.config.ts` ```js import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }); ``` #### `openapi-ts.config.cjs` ```js /** @type {import('@hey-api/openapi-ts').UserConfig} */ module.exports = { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` #### `openapi-ts.config.mjs` ```js /** @type {import('@hey-api/openapi-ts').UserConfig} */ export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', }; ``` Alternatively, you can use `openapi-ts.config.js` and configure the export statement depending on your project setup. ### Input You must set the input so we can load your OpenAPI specification. It can be a path or URL, object containing a path or URL, or an object representing an OpenAPI specification. Hey API supports all valid OpenAPI versions and file formats. > If you use an HTTPS URL with a self-signed certificate in development, you will need to set [`NODE_TLS_REJECT_UNAUTHORIZED=0`](https://github.com/hey-api/openapi-ts/issues/276#issuecomment-2043143501) in your environment. ### Output You must set the output so we know where to generate your files. It can be a path to the destination folder or an object containing the destination folder path and optional settings. > You should treat the output folder as a dependency. Do not directly modify its contents as your changes might be erased when you run `@hey-api/openapi-ts` again. ## Parser We parse your input before making it available to plugins. While configuring the parser is optional, it's the perfect place to modify or validate your input if needed. ## Plugins Plugins are responsible for generating artifacts from your input. By default, Hey API will generate TypeScript interfaces and SDK from your OpenAPI specification. You can add, remove, or customize any of the plugins. In fact, we highly encourage you to do so! ### Client Clients are responsible for sending the actual HTTP requests. Using clients is not required, but you must add a client to `plugins` if you're generating SDKs (we default to Fetch). ### Native Clients - [`@hey-api/client-fetch`](https://heyapi.dev/openapi-ts/clients/fetch) - [`@hey-api/client-angular`](https://heyapi.dev/openapi-ts/clients/angular) - [`@hey-api/client-axios`](https://heyapi.dev/openapi-ts/clients/axios) - [`@hey-api/client-ky`](https://heyapi.dev/openapi-ts/clients/ky) - [`@hey-api/client-next`](https://heyapi.dev/openapi-ts/clients/next-js) - [`@hey-api/client-nuxt`](https://heyapi.dev/openapi-ts/clients/nuxt) - [`@hey-api/client-ofetch`](https://heyapi.dev/openapi-ts/clients/ofetch) ### Planned Clients The following clients are planned but not in development yet. You can help us prioritize them by voting on [GitHub](https://github.com/hey-api/openapi-ts/labels/RSVP%20%F0%9F%91%8D%F0%9F%91%8E). - [`@hey-api/client-effect`](https://heyapi.dev/openapi-ts/clients/effect) Don't see your client? [Build your own](https://heyapi.dev/openapi-ts/clients/custom) or let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ### Native Plugins These plugins help reduce boilerplate associated with third-party dependencies. Hey API natively supports the most popular packages. Please open an issue on [GitHub](https://github.com/hey-api/openapi-ts/issues) if you'd like us to support your favorite package. - [`@angular/common`](https://heyapi.dev/openapi-ts/plugins/angular) - [`@hey-api/schemas`](https://heyapi.dev/openapi-ts/output/json-schema) - [`@hey-api/sdk`](https://heyapi.dev/openapi-ts/output/sdk) - [`@hey-api/transformers`](https://heyapi.dev/openapi-ts/transformers) - [`@hey-api/typescript`](https://heyapi.dev/openapi-ts/output/typescript) - [`@pinia/colada`](https://heyapi.dev/openapi-ts/plugins/pinia-colada) - [`@tanstack/angular-query-experimental`](https://heyapi.dev/openapi-ts/plugins/tanstack-query) - [`@tanstack/preact-query`](https://heyapi.dev/openapi-ts/plugins/tanstack-query) - [`@tanstack/react-query`](https://heyapi.dev/openapi-ts/plugins/tanstack-query) - [`@tanstack/solid-query`](https://heyapi.dev/openapi-ts/plugins/tanstack-query) - [`@tanstack/svelte-query`](https://heyapi.dev/openapi-ts/plugins/tanstack-query) - [`@tanstack/vue-query`](https://heyapi.dev/openapi-ts/plugins/tanstack-query) - [`fastify`](https://heyapi.dev/openapi-ts/plugins/fastify) - [`nestjs`](https://heyapi.dev/openapi-ts/plugins/nest) - [`valibot`](https://heyapi.dev/openapi-ts/plugins/valibot) - [`zod`](https://heyapi.dev/openapi-ts/plugins/zod) ### Planned Plugins The following plugins are planned but not in development yet. You can help us prioritize them by voting on [GitHub](https://github.com/hey-api/openapi-ts/labels/RSVP%20%F0%9F%91%8D%F0%9F%91%8E). - [Adonis](https://heyapi.dev/openapi-ts/plugins/adonis) - [Ajv](https://heyapi.dev/openapi-ts/plugins/ajv) - [Arktype](https://heyapi.dev/openapi-ts/plugins/arktype) - [Chance](https://heyapi.dev/openapi-ts/plugins/chance) - [Elysia](https://heyapi.dev/openapi-ts/plugins/elysia) - [Express](https://heyapi.dev/openapi-ts/plugins/express) - [Faker](https://heyapi.dev/openapi-ts/plugins/faker) - [Falso](https://heyapi.dev/openapi-ts/plugins/falso) - [Hono](https://heyapi.dev/openapi-ts/plugins/hono) - [Joi](https://heyapi.dev/openapi-ts/plugins/joi) - [Koa](https://heyapi.dev/openapi-ts/plugins/koa) - [MSW](https://heyapi.dev/openapi-ts/plugins/msw) - [Nock](https://heyapi.dev/openapi-ts/plugins/nock) - [Superstruct](https://heyapi.dev/openapi-ts/plugins/superstruct) - [Supertest](https://heyapi.dev/openapi-ts/plugins/supertest) - [SWR](https://heyapi.dev/openapi-ts/plugins/swr) - [TypeBox](https://heyapi.dev/openapi-ts/plugins/typebox) - [Yup](https://heyapi.dev/openapi-ts/plugins/yup) - [Zustand](https://heyapi.dev/openapi-ts/plugins/zustand) Don't see your plugin? [Build your own](https://heyapi.dev/openapi-ts/plugins/custom) or let us know your interest by [opening an issue](https://github.com/hey-api/openapi-ts/issues). ## Migrating You can learn more on the [Migrating](https://heyapi.dev/openapi-ts/migrating) page. ## License Released under the [MIT License](https://github.com/hey-api/openapi-ts/blob/main/LICENSE.md). ================================================ FILE: packages/openapi-ts/bin/run.cmd ================================================ @echo off node "%~dp0\run.js" %* ================================================ FILE: packages/openapi-ts/bin/run.js ================================================ #!/usr/bin/env node import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const target = path.join(__dirname, '..', 'dist', 'run.mjs'); if (!fs.existsSync(target)) { console.error('openapi-ts not built (expect dist/run.mjs)'); process.exit(1); } const res = spawnSync(process.execPath, [target, ...process.argv.slice(2)], { stdio: 'inherit', }); process.exit(res.status ?? 0); ================================================ FILE: packages/openapi-ts/package.json ================================================ { "name": "@hey-api/openapi-ts", "version": "0.94.4", "description": "🌀 OpenAPI to TypeScript codegen. Production-ready SDKs, Zod schemas, TanStack Query hooks, and 20+ plugins. Used by Vercel, OpenCode, and PayPal.", "keywords": [ "angular", "axios", "codegen", "fetch", "generator", "http", "javascript", "json", "next", "next.js", "node", "nuxt", "ofetch", "openapi", "rest", "swagger", "typescript", "xhr", "yaml" ], "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "bin": { "openapi-ts": "./bin/run.js" }, "files": [ "bin", "dist", "LICENSE.md", "README.md" ], "type": "module", "main": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "types": "./dist/index.d.mts", "import": "./dist/index.mjs" }, "./internal": { "types": "./dist/internal.d.mts", "import": "./dist/internal.mjs" }, "./package.json": "./package.json" }, "scripts": { "build": "tsdown && pnpm check-exports", "check-exports": "attw --pack . --profile esm-only --ignore-rules cjs-resolves-to-esm", "dev": "tsdown --watch", "prepublishOnly": "pnpm build", "typecheck": "tsgo --noEmit" }, "dependencies": { "@hey-api/codegen-core": "workspace:*", "@hey-api/json-schema-ref-parser": "workspace:*", "@hey-api/shared": "workspace:*", "@hey-api/types": "workspace:*", "ansi-colors": "4.1.3", "color-support": "1.1.3", "commander": "14.0.3", "get-tsconfig": "4.13.6" }, "devDependencies": { "@angular/common": "21.1.2", "@angular/compiler": "21.1.2", "@angular/compiler-cli": "21.1.2", "@angular/core": "21.1.2", "@angular/platform-browser": "21.1.2", "@angular/platform-browser-dynamic": "21.1.2", "@angular/router": "21.1.2", "axios": "1.13.4", "eslint": "9.39.1", "ky": "1.14.3", "nuxt": "3.14.1592", "ofetch": "1.5.1", "rxjs": "7.8.2", "typescript": "5.9.3", "vue": "3.5.25", "yaml": "2.8.2", "zone.js": "0.16.0" }, "peerDependencies": { "typescript": ">=5.5.3 || 6.0.1-rc" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts/src/__tests__/cli.test.ts ================================================ import type { Mock } from 'vitest'; import { runCli } from '../cli'; import { createClient } from '../index'; vi.mock('../index', () => { const result: Awaited> = []; return { createClient: vi.fn().mockResolvedValue(result), }; }); const spyExit = vi.spyOn(process, 'exit').mockImplementation(() => ({}) as never); const spy = createClient as Mock; describe('cli', () => { beforeEach(() => { spy.mockClear(); spyExit.mockClear(); }); it('with default options', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1])]; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({}); }); it('with minimal options', async () => { const originalArgv = process.argv.slice(); try { process.argv = [ String(process.argv[0]), String(process.argv[1]), '--input', 'foo.json', '--output', 'bar', ]; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({ input: ['foo.json'], output: ['bar'], }); }); it('with no plugins', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1]), '--plugins']; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({}); }); it('with plugins', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1]), '--plugins', 'foo']; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({ plugins: ['foo'], }); }); it('with client plugin', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1]), '--client', 'foo']; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({ plugins: ['foo'], }); }); describe('logs', () => { it('debug', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1]), '--debug']; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({ logs: { level: 'debug', }, }); }); it('silent', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1]), '--silent']; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({ logs: { level: 'silent', }, }); }); it('no log file', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1]), '--no-log-file']; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({ logs: { file: false, }, }); }); }); it('with all options', async () => { const originalArgv = process.argv.slice(); try { process.argv = [ String(process.argv[0]), String(process.argv[1]), '--client', 'foo', '--dry-run', 'true', '--file', 'bar', '--input', 'baz', '--logs', 'qux', '--output', 'quux', '--plugins', '--watch', ]; await runCli(); } finally { process.argv = originalArgv; } expect(spy).toHaveBeenCalledWith({ configFile: 'bar', dryRun: true, input: ['baz'], logs: { path: 'qux', }, output: ['quux'], plugins: ['foo'], watch: true, }); }); it('exits when not in watch mode', async () => { const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1])]; await runCli(); } finally { process.argv = originalArgv; } expect(spyExit).toHaveBeenCalledWith(0); }); it('does not exit in watch mode', async () => { spy.mockResolvedValueOnce([ { config: { input: [{ watch: { enabled: true } }] }, }, ]); const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1])]; await runCli(); } finally { process.argv = originalArgv; } expect(spyExit).not.toHaveBeenCalled(); }); it('exits with error code on error', async () => { spy.mockRejectedValueOnce('Some error'); const originalArgv = process.argv.slice(); try { process.argv = [String(process.argv[0]), String(process.argv[1])]; await runCli(); } finally { process.argv = originalArgv; } expect(spyExit).toHaveBeenCalledWith(1); }); }); ================================================ FILE: packages/openapi-ts/src/__tests__/index.test.ts ================================================ import { createClient } from '../index'; type Config = Parameters[0]; describe('createClient', () => { it('handles deep path $ref without errors', async () => { // This test verifies that deep path refs like // #/components/schemas/Foo/properties/bar/items are inlined // instead of being treated as symbol references (which would fail) const config: Config = { dryRun: true, input: { components: { schemas: { Bar: { properties: { nested: { // Deep path ref - should be inlined, not treated as symbol $ref: '#/components/schemas/Foo/properties/items/items', }, }, type: 'object', }, Foo: { properties: { items: { items: { properties: { name: { type: 'string' }, }, type: 'object', }, type: 'array', }, }, type: 'object', }, }, }, info: { title: 'deep-ref-test', version: '1.0.0' }, openapi: '3.1.0', }, logs: { level: 'silent', }, output: 'output', plugins: ['@hey-api/typescript'], }; // Should not throw "Symbol finalName has not been resolved yet" error const results = await createClient(config); expect(results).toHaveLength(1); }); it('handles deep path $ref in OpenAPI 3.0.x without errors', async () => { const config: Config = { dryRun: true, input: { components: { schemas: { Bar: { properties: { nested: { $ref: '#/components/schemas/Foo/properties/items/items', }, }, type: 'object', }, Foo: { properties: { items: { items: { properties: { name: { type: 'string' }, }, type: 'object', }, type: 'array', }, }, type: 'object', }, }, }, info: { title: 'deep-ref-test', version: '1.0.0' }, openapi: '3.0.0', paths: {}, }, logs: { level: 'silent', }, output: 'output', plugins: ['@hey-api/typescript'], }; const results = await createClient(config); expect(results).toHaveLength(1); }); it('handles deep path $ref in OpenAPI 2.0 (Swagger) without errors', async () => { const config: Config = { dryRun: true, input: { definitions: { Bar: { properties: { nested: { $ref: '#/definitions/Foo/properties/items/items', }, }, type: 'object', }, Foo: { properties: { items: { items: { properties: { name: { type: 'string' }, }, type: 'object', }, type: 'array', }, }, type: 'object', }, }, info: { title: 'deep-ref-test', version: '1.0.0' }, paths: {}, swagger: '2.0', }, logs: { level: 'silent', }, output: 'output', plugins: ['@hey-api/typescript'], }; const results = await createClient(config); expect(results).toHaveLength(1); }); it('1 config, 1 input, 1 output', async () => { const config: Config = { dryRun: true, input: { info: { title: 'foo', version: '1.0.0' }, openapi: '3.0.0', }, logs: { level: 'silent', }, output: 'output', plugins: ['@hey-api/typescript'], }; const results = await createClient(config); expect(results).toHaveLength(1); }); it('1 config, 2 inputs, 1 output', async () => { const config: Config = { dryRun: true, input: [ { info: { title: 'foo', version: '1.0.0' }, openapi: '3.0.0', }, { info: { title: 'bar', version: '1.0.0' }, openapi: '3.0.0', paths: {}, }, ], logs: { level: 'silent', }, output: 'output', plugins: ['@hey-api/typescript'], }; const results = await createClient(config); expect(results).toHaveLength(1); }); it('1 config, 2 inputs, 2 outputs', async () => { const config: Config = { dryRun: true, input: [ { info: { title: 'foo', version: '1.0.0' }, openapi: '3.0.0', }, { info: { title: 'bar', version: '1.0.0' }, openapi: '3.0.0', paths: {}, }, ], logs: { level: 'silent', }, output: ['output', 'output2'], plugins: ['@hey-api/typescript'], }; const results = await createClient(config); expect(results).toHaveLength(2); }); it('2 configs, 1 input, 1 output', async () => { const config: Config = [ { dryRun: true, input: { info: { title: 'foo', version: '1.0.0' }, openapi: '3.0.0', }, logs: { level: 'silent', }, output: 'output', plugins: ['@hey-api/typescript'], }, { dryRun: true, input: { info: { title: 'bar', version: '1.0.0' }, openapi: '3.0.0', }, logs: { level: 'silent', }, output: 'output2', plugins: ['@hey-api/typescript'], }, ]; const results = await createClient(config); expect(results).toHaveLength(2); }); it('2 configs, 2 inputs, 2 outputs', async () => { const config: Config = [ { dryRun: true, input: [ { info: { title: 'foo', version: '1.0.0' }, openapi: '3.0.0', }, { info: { title: 'bar', version: '1.0.0' }, openapi: '3.0.0', paths: {}, }, ], logs: { level: 'silent', }, output: ['output', 'output2'], plugins: ['@hey-api/typescript'], }, { dryRun: true, input: [ { info: { title: 'baz', version: '1.0.0' }, openapi: '3.0.0', }, { info: { title: 'qux', version: '1.0.0' }, openapi: '3.0.0', paths: {}, }, ], logs: { level: 'silent', }, output: ['output3', 'output4'], plugins: ['@hey-api/typescript'], }, ]; const results = await createClient(config); expect(results).toHaveLength(4); }); it('executes @angular/common HttpRequest builder path', async () => { const results = await createClient({ dryRun: true, input: { info: { title: 'angular-common-test', version: '1.0.0' }, openapi: '3.1.0', paths: { '/pets': { get: { operationId: 'listPets', responses: { 200: { content: { 'application/json': { schema: { items: { type: 'string' }, type: 'array', }, }, }, description: 'ok', }, }, }, }, }, }, logs: { level: 'silent' }, output: 'out', plugins: [ '@hey-api/typescript', '@hey-api/sdk', '@angular/common', '@hey-api/client-angular', ], }); expect(results.length).toBeGreaterThanOrEqual(1); }); }); ================================================ FILE: packages/openapi-ts/src/__tests__/interactive.test.ts ================================================ import { detectInteractiveSession, Logger, mergeConfigs } from '@hey-api/codegen-core'; import { resolveJobs } from '../config/init'; describe('interactive config', () => { it('should use detectInteractiveSession when not provided', async () => { const result = await resolveJobs({ logger: new Logger(), userConfigs: [ { input: 'test.json', output: './test', }, ], }); // In test environment, TTY is typically not available, so it should be false expect(result.jobs[0]?.config.interactive).toBe(false); }); it('should respect user config when set to true', async () => { const result = await resolveJobs({ logger: new Logger(), userConfigs: [ { input: 'test.json', interactive: true, output: './test', }, ], }); expect(result.jobs[0]?.config.interactive).toBe(true); }); it('should respect user config when set to false', async () => { const result = await resolveJobs({ logger: new Logger(), userConfigs: [ { input: 'test.json', interactive: false, output: './test', }, ], }); expect(result.jobs[0]?.config.interactive).toBe(false); }); it('should allow file config to set interactive when CLI does not provide it', () => { // This simulates what happens when: // 1. User has a config file with interactive: false // 2. CLI doesn't provide interactive (undefined) // 3. The bug was: bin script would set interactive = isInteractive (true in TTY) const fileConfig = { input: 'test.json', interactive: false, output: './test', }; // CLI config without interactive (correct behavior after fix) const cliConfigWithoutInteractive = { input: 'test.json', output: './test', }; // CLI config with interactive set to true (simulating the bug) const cliConfigWithInteractiveBug = { input: 'test.json', interactive: true, output: './test', // Bug: bin script was setting this even when user didn't provide it }; // After fix: file config's interactive should be preserved const mergedCorrect = mergeConfigs>( fileConfig, cliConfigWithoutInteractive, ); expect(mergedCorrect.interactive).toBe(false); // Before fix: CLI's auto-detected interactive would override file config const mergedWithBug = mergeConfigs(fileConfig, cliConfigWithInteractiveBug); expect(mergedWithBug.interactive).toBe(true); // This was the bug - it overrode the file config }); }); describe('detectInteractiveSession', () => { const originalEnv = process.env; const originalStdin = process.stdin; const originalStdout = process.stdout; afterEach(() => { process.env = originalEnv; Object.defineProperty(process, 'stdin', { value: originalStdin }); Object.defineProperty(process, 'stdout', { value: originalStdout }); }); it('should return false when CI environment variable is set', () => { process.env = { ...originalEnv, CI: 'true' }; Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true, }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true, }); expect(detectInteractiveSession()).toBe(false); }); it('should return false when NO_INTERACTIVE environment variable is set', () => { process.env = { ...originalEnv, NO_INTERACTIVE: '1' }; Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true, }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true, }); expect(detectInteractiveSession()).toBe(false); }); it('should return false when NO_INTERACTION environment variable is set', () => { process.env = { ...originalEnv, NO_INTERACTION: '1' }; Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true, }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true, }); expect(detectInteractiveSession()).toBe(false); }); it('should return false when stdin is not TTY', () => { process.env = { ...originalEnv }; delete process.env.CI; delete process.env.NO_INTERACTIVE; delete process.env.NO_INTERACTION; Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false, }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true, }); expect(detectInteractiveSession()).toBe(false); }); it('should return false when stdout is not TTY', () => { process.env = { ...originalEnv }; delete process.env.CI; delete process.env.NO_INTERACTIVE; delete process.env.NO_INTERACTION; Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true, }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: false, }); expect(detectInteractiveSession()).toBe(false); }); it('should return true when TTY is available and no blocking env vars are set', () => { process.env = { ...originalEnv }; delete process.env.CI; delete process.env.NO_INTERACTIVE; delete process.env.NO_INTERACTION; Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true, }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true, }); expect(detectInteractiveSession()).toBe(true); }); }); ================================================ FILE: packages/openapi-ts/src/__tests__/internal.test.ts ================================================ describe('internal entry index', () => { it('should be exported', async () => { const internal = await import('../internal'); expect(internal.getSpec).toBeDefined(); expect(internal.initConfigs).toBeDefined(); expect(internal.parseOpenApiSpec).toBeDefined(); }); }); ================================================ FILE: packages/openapi-ts/src/cli/adapter.ts ================================================ import type { ToArray } from '@hey-api/types'; import type { UserConfig } from '../config/types'; import type { CliOptions } from './schema'; export function cliToConfig(cli: CliOptions): Partial { const config: Partial = {}; if (cli.input) config.input = cli.input; if (cli.output) config.output = cli.output; if (cli.file) config.configFile = cli.file; if (cli.dryRun !== undefined) config.dryRun = cli.dryRun; const plugins: ToArray = []; if (cli.plugins instanceof Array && cli.plugins.length > 0) { plugins.push(...cli.plugins); } if (cli.client) plugins.push(cli.client); if (plugins.length > 0) config.plugins = plugins; if (cli.debug || cli.silent || cli.logs || cli.logFile === false) { config.logs = { ...(cli.logs && { path: cli.logs }), ...(cli.debug && { level: 'debug' as const }), ...(cli.silent && { level: 'silent' as const }), ...(cli.logFile === false && { file: false }), }; } if (cli.watch !== undefined) { if (typeof cli.watch === 'string') { config.watch = Number.parseInt(cli.watch, 10); } else { config.watch = cli.watch; } } return config; } ================================================ FILE: packages/openapi-ts/src/cli/index.ts ================================================ import { isEnvironment } from '@hey-api/shared'; import { Command, CommanderError } from 'commander'; import pkg from '../../package.json'; import { createClient } from '../index'; import { cliToConfig } from './adapter'; const binName = Object.keys(pkg.bin)[0]!; const program = new Command() .name(binName) .description('Generate TypeScript code from OpenAPI specifications') .version(isEnvironment('development') ? '[DEVELOPMENT]' : pkg.version); program .option('-i, --input ', 'OpenAPI specification (path, URL, or string)') .option('-o, --output ', 'Output folder(s)') .option('-c, --client ', 'HTTP client to generate') .option('-p, --plugins [names...]', 'Plugins to use') .option('-f, --file ', 'Path to config file') .option('-d, --debug', 'Enable debug logging') .option('-s, --silent', 'Suppress all output') .option('-l, --logs ', 'Logs folder path') .option('--no-log-file', 'Disable log file output') .option('--dry-run', 'Skip writing files') .option('-w, --watch [interval]', 'Watch for changes') .action(async (options) => { const config = cliToConfig(options); const context = await createClient(config as Parameters[0]); const hasActiveWatch = context[0]?.config.input.some((input) => input.watch?.enabled); if (!hasActiveWatch) { process.exit(0); } }); export async function runCli(): Promise { try { await program.parseAsync(process.argv); } catch (error) { if (error instanceof CommanderError && 'code' in error) { if (error.code === 'commander.optionMissingArgument') { console.error(`\nMissing required argument. Run '${binName} --help' for usage.\n`); } else if (error.code === 'commander.unknownOption') { console.error(`\nUnknown option. Run '${binName} --help' for available options.\n`); } process.exit(error.exitCode); } console.error('Unexpected error:', error); process.exit(1); } } ================================================ FILE: packages/openapi-ts/src/cli/schema.ts ================================================ import type { PluginNames } from '@hey-api/shared'; import type { MaybeArray } from '@hey-api/types'; import type { PluginClientNames } from '../plugins/types'; export interface CliOptions { client?: PluginClientNames; debug?: boolean; dryRun?: boolean; file?: string; input?: MaybeArray; logFile?: boolean; logs?: string; output?: MaybeArray; plugins?: ReadonlyArray; silent?: boolean; watch?: boolean | string; } ================================================ FILE: packages/openapi-ts/src/config/expand.ts ================================================ import { getInput } from '@hey-api/shared'; import colors from 'ansi-colors'; import type { UserConfig } from './types'; export interface Job { config: UserConfig; index: number; } export function expandToJobs(configs: ReadonlyArray): ReadonlyArray { const jobs: Array = []; let jobIndex = 0; for (const config of configs) { const inputs = getInput(config); const outputs = config.output instanceof Array ? config.output : [config.output]; if (outputs.length === 1) { jobs.push({ config: { ...config, input: inputs, output: outputs[0]!, // output array with single item }, index: jobIndex++, }); } else if (outputs.length > 1 && inputs.length !== outputs.length) { // Warn and create job per output (all with same inputs) console.warn( `⚙️ ${colors.yellow('Warning:')} You provided ${colors.cyan(String(inputs.length))} ${colors.cyan(inputs.length === 1 ? 'input' : 'inputs')} and ${colors.yellow(String(outputs.length))} ${colors.yellow('outputs')}. This will produce identical output in multiple locations. You likely want to provide a single output or the same number of outputs as inputs.`, ); for (const output of outputs) { jobs.push({ config: { ...config, input: inputs, output }, index: jobIndex++, }); } } else if (outputs.length > 1) { // Pair inputs with outputs by index outputs.forEach((output, index) => { jobs.push({ config: { ...config, input: inputs[index]!, output }, index: jobIndex++, }); }); } } return jobs; } ================================================ FILE: packages/openapi-ts/src/config/init.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { loadConfigFile } from '@hey-api/codegen-core'; import { expandToJobs } from './expand'; import { getProjectDependencies } from './packages'; import type { ResolvedJob } from './resolve'; import { resolveConfig } from './resolve'; import type { UserConfig } from './types'; import { validateJobs } from './validate'; export type Configs = { dependencies: Record; jobs: ReadonlyArray; /** * @deprecated Use `jobs` instead. */ results: ReadonlyArray; }; /** * @internal */ export async function resolveJobs({ logger, userConfigs, }: { logger: Logger; userConfigs: ReadonlyArray; }): Promise { const configs: Array = []; let dependencies: Record = {}; const eventLoad = logger.timeEvent('load'); for (const userConfig of userConfigs) { let configFile: string | undefined; if (userConfig.configFile) { const parts = userConfig.configFile.split('.'); configFile = parts.slice(0, parts.length - 1).join('.'); } const loaded = await loadConfigFile({ configFile, logger, name: 'openapi-ts', userConfig, }); if (!Object.keys(dependencies).length) { // TODO: handle dependencies for multiple configs properly? dependencies = getProjectDependencies(loaded.foundConfig ? loaded.configFile : undefined); } configs.push(...loaded.configs); } eventLoad.timeEnd(); const eventBuild = logger.timeEvent('build'); const jobs = validateJobs(expandToJobs(configs)); const resolvedJobs = jobs.map((validated) => resolveConfig(validated, dependencies)); eventBuild.timeEnd(); return { dependencies, jobs: resolvedJobs, results: resolvedJobs, }; } ================================================ FILE: packages/openapi-ts/src/config/output/__tests__/config.test.ts ================================================ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { getOutput } from '../config'; describe('getOutput', () => { let tmpDir: string; beforeEach(() => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openapi-ts-test-')); }); afterEach(() => { if (fs.existsSync(tmpDir)) { fs.rmSync(tmpDir, { force: true, recursive: true }); } }); describe('module resolution detection', () => { it('should set module.extension when moduleResolution is NodeNext', () => { const tsconfigPath = path.join(tmpDir, 'tsconfig.json'); fs.writeFileSync( tsconfigPath, JSON.stringify({ compilerOptions: { moduleResolution: 'nodenext', }, }), ); const output = getOutput({ output: { path: tmpDir, tsConfigPath: tsconfigPath, }, }); expect(output.module.extension).toBe('.js'); }); it('should set module.extension when moduleResolution is Node16', () => { const tsconfigPath = path.join(tmpDir, 'tsconfig.json'); fs.writeFileSync( tsconfigPath, JSON.stringify({ compilerOptions: { moduleResolution: 'node16', }, }), ); const output = getOutput({ output: { path: tmpDir, tsConfigPath: tsconfigPath, }, }); expect(output.module.extension).toBe('.js'); }); it('should set module.extension when module is NodeNext (implicit moduleResolution)', () => { const tsconfigPath = path.join(tmpDir, 'tsconfig.json'); fs.writeFileSync( tsconfigPath, JSON.stringify({ compilerOptions: { module: 'nodenext', }, }), ); const output = getOutput({ output: { path: tmpDir, tsConfigPath: tsconfigPath, }, }); expect(output.module.extension).toBe('.js'); }); it('should set module.extension when module is Node16 (implicit moduleResolution)', () => { const tsconfigPath = path.join(tmpDir, 'tsconfig.json'); fs.writeFileSync( tsconfigPath, JSON.stringify({ compilerOptions: { module: 'node16', }, }), ); const output = getOutput({ output: { path: tmpDir, tsConfigPath: tsconfigPath, }, }); expect(output.module.extension).toBe('.js'); }); it('should not set module.extension for other module types', () => { const tsconfigPath = path.join(tmpDir, 'tsconfig.json'); fs.writeFileSync( tsconfigPath, JSON.stringify({ compilerOptions: { module: 'esnext', }, }), ); const output = getOutput({ output: { path: tmpDir, tsConfigPath: tsconfigPath, }, }); expect(output.module.extension).toBeUndefined(); }); it('should not override explicit module.extension setting', () => { const tsconfigPath = path.join(tmpDir, 'tsconfig.json'); fs.writeFileSync( tsconfigPath, JSON.stringify({ compilerOptions: { module: 'nodenext', }, }), ); const output = getOutput({ output: { module: { extension: '.ts', }, path: tmpDir, tsConfigPath: tsconfigPath, }, }); expect(output.module.extension).toBe('.ts'); }); it('should work when both module and moduleResolution are set', () => { const tsconfigPath = path.join(tmpDir, 'tsconfig.json'); fs.writeFileSync( tsconfigPath, JSON.stringify({ compilerOptions: { module: 'nodenext', moduleResolution: 'nodenext', }, }), ); const output = getOutput({ output: { path: tmpDir, tsConfigPath: tsconfigPath, }, }); expect(output.module.extension).toBe('.js'); }); it('should handle missing tsconfig gracefully', () => { const output = getOutput({ output: { path: tmpDir, }, }); expect(output.module.extension).toBeUndefined(); }); }); }); ================================================ FILE: packages/openapi-ts/src/config/output/config.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { log } from '@hey-api/codegen-core'; import type { PostProcessor, UserPostProcessor } from '@hey-api/shared'; import { findTsConfigPath, resolveSource, valueToObject } from '@hey-api/shared'; import type { MaybeArray } from '@hey-api/types'; import type { TsConfigJsonResolved } from 'get-tsconfig'; import { parseTsconfig } from 'get-tsconfig'; import { postProcessors } from './postprocess'; import type { Output, UserOutput } from './types'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export function getOutput(userConfig: { output: MaybeArray }): Output { if (userConfig.output instanceof Array) { throw new Error( 'Unexpected array of outputs in user configuration. This should have been expanded already.', ); } const userOutput = typeof userConfig.output === 'string' ? { path: userConfig.output } : (userConfig.output ?? {}); const legacyPostProcess = resolveLegacyPostProcess(userOutput); const output = valueToObject({ defaultValue: { clean: true, entryFile: true, fileName: { case: 'preserve', name: '{{name}}', suffix: '.gen', }, format: null, lint: null, module: {}, path: '', postProcess: [], preferExportAll: false, }, mappers: { object: (fields, defaultValue) => ({ ...fields, fileName: valueToObject({ defaultValue: { ...(defaultValue.fileName as Extract< typeof defaultValue.fileName, Record >), }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: fields.fileName, }), module: valueToObject({ defaultValue: { extension: fields.importFileExtension, resolve: fields.resolveModuleName, }, mappers: { object: (moduleFields) => ({ ...moduleFields, extension: fields.importFileExtension ?? moduleFields.extension, resolve: fields.resolveModuleName ?? moduleFields.resolve, }), }, value: fields.module, }), }), }, value: userOutput, }) as Output; output.tsConfig = loadTsConfig(findTsConfigPath(__dirname, output.tsConfigPath)); if ( output.module.extension === undefined && (output.tsConfig?.compilerOptions?.moduleResolution === 'nodenext' || output.tsConfig?.compilerOptions?.moduleResolution === 'NodeNext' || output.tsConfig?.compilerOptions?.moduleResolution === 'node16' || output.tsConfig?.compilerOptions?.moduleResolution === 'Node16' || output.tsConfig?.compilerOptions?.module === 'nodenext' || output.tsConfig?.compilerOptions?.module === 'NodeNext' || output.tsConfig?.compilerOptions?.module === 'node16' || output.tsConfig?.compilerOptions?.module === 'Node16') ) { output.module.extension = '.js'; } if (output.module.extension && !output.module.extension.startsWith('.')) { output.module.extension = `.${output.module.extension}`; } output.postProcess = normalizePostProcess(userOutput.postProcess ?? legacyPostProcess); output.source = resolveSource(output); return output; } function resolveLegacyPostProcess(config: Partial): ReadonlyArray { const result: Array = []; if (config.lint !== undefined) { let processor: PostProcessor | undefined; let preset: keyof typeof postProcessors | undefined; if (config.lint) { preset = config.lint === 'biome' ? 'biome:lint' : config.lint; processor = postProcessors[preset]; if (processor) result.push(processor); } log.warnDeprecated({ context: 'output', field: 'lint', replacement: `postProcess: [${processor && preset ? `'${preset}'` : ''}]`, }); } if (config.format !== undefined) { let processor: PostProcessor | undefined; let preset: keyof typeof postProcessors | undefined; if (config.format) { preset = config.format === 'biome' ? 'biome:format' : config.format; processor = postProcessors[preset]; if (processor) result.push(processor); } log.warnDeprecated({ context: 'output', field: 'format', replacement: `postProcess: [${processor && preset ? `'${preset}'` : ''}]`, }); } return result; } function normalizePostProcess(input: UserOutput['postProcess']): ReadonlyArray { if (!input) return []; return input.map((item) => { if (typeof item === 'string') { const preset = postProcessors[item]; if (!preset) { throw new Error(`Unknown post-processor preset: "${item}"`); } return preset; } return { name: item.name ?? item.command, ...item, }; }); } function loadTsConfig(configPath: string | null): TsConfigJsonResolved | null { if (!configPath) { return null; } try { return parseTsconfig(configPath); } catch { throw new Error(`Couldn't read tsconfig from path: ${configPath}`); } } ================================================ FILE: packages/openapi-ts/src/config/output/postprocess.ts ================================================ import type { PostProcessor } from '@hey-api/shared'; /** * @deprecated Use `PostProcessorPreset` instead. */ export type Formatters = 'biome' | 'prettier'; /** * @deprecated Use `PostProcessorPreset` instead. */ export type Linters = 'biome' | 'eslint' | 'oxlint'; export const postProcessors = { 'biome:format': { args: ['format', '--write', '{{path}}'], command: 'biome', name: 'Biome (Format)', }, 'biome:lint': { args: ['lint', '--apply', '{{path}}'], command: 'biome', name: 'Biome (Lint)', }, eslint: { args: ['{{path}}', '--fix'], command: 'eslint', name: 'ESLint', }, oxfmt: { args: ['{{path}}'], command: 'oxfmt', name: 'Oxfmt', }, oxlint: { args: ['--fix', '{{path}}'], command: 'oxlint', name: 'Oxlint', }, prettier: { args: ['--ignore-unknown', '{{path}}', '--write', '--ignore-path', './.prettierignore'], command: 'prettier', name: 'Prettier', }, } as const satisfies Record; export type PostProcessorPreset = keyof typeof postProcessors; ================================================ FILE: packages/openapi-ts/src/config/output/types.ts ================================================ import type { BaseOutput, BaseUserOutput, UserPostProcessor } from '@hey-api/shared'; import type { AnyString } from '@hey-api/types'; import type { TsConfigJsonResolved } from 'get-tsconfig'; import type { Formatters, Linters, PostProcessorPreset } from './postprocess'; export type UserOutput = BaseUserOutput<'.js' | '.ts'> & { /** * Which formatter to use to process output folder? * * @default null * @deprecated Use `postProcess` instead. */ format?: Formatters | null; /** * If specified, this will be the file extension used when importing * other modules. By default, we don't add a file extension and let the * runtime resolve it. If you're using moduleResolution `nodenext` or * `node16`, we default to `.js`. * * @default undefined * @deprecated Use `module.extension` instead. */ importFileExtension?: '.js' | '.ts' | AnyString | null; /** * Which linter to use to process output folder? * * @default null * @deprecated Use `postProcess` instead. */ lint?: Linters | null; /** * Post-processing commands to run on the output folder, executed in order. * * Use preset strings for common tools, or provide custom configurations. * * @example ['biome:lint', 'prettier'] * @example [{ command: 'dprint', args: ['fmt', '{{path}}'] }] * @example ['eslint', { command: 'prettier', args: ['{{path}}', '--write'] }] * * @default [] */ postProcess?: ReadonlyArray; /** * Whether `export * from 'module'` should be used when possible * instead of named exports. * * @default false */ preferExportAll?: boolean; /** * Relative or absolute path to the tsconfig file we should use to * generate the output. If a path to tsconfig file is not provided, we * attempt to find one starting from the location of the * `@hey-api/openapi-ts` configuration file and traversing up. * * @default undefined */ tsConfigPath?: AnyString | null; }; export type Output = BaseOutput<'.js' | '.ts'> & { /** * Which formatter to use to process output folder? */ format: Formatters | null; /** * Which linter to use to process output folder? */ lint: Linters | null; /** * Whether `export * from 'module'` should be used when possible * instead of named exports. */ preferExportAll: boolean; /** * The parsed TypeScript configuration used to generate the output. * If no `tsconfig` file path was provided or found, this will be `null`. */ tsConfig: TsConfigJsonResolved | null; /** * Relative or absolute path to the tsconfig file we should use to * generate the output. If a path to tsconfig file is not provided, we * attempt to find one starting from the location of the * `@hey-api/openapi-ts` configuration file and traversing up. */ tsConfigPath: AnyString | null | undefined; }; ================================================ FILE: packages/openapi-ts/src/config/packages.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; /** * Finds and reads the project's package.json file by searching upwards from the config file location, * or from process.cwd() if no config file is provided. * This ensures we get the correct dependencies even in monorepo setups. * * @param configFilePath - The path to the configuration file (e.g., openapi-ts.config.ts) * @returns An object containing all project dependencies (dependencies, devDependencies, peerDependencies, optionalDependencies) */ export const getProjectDependencies = (configFilePath?: string): Record => { let currentDir = configFilePath ? path.dirname(configFilePath) : process.cwd(); while (currentDir !== path.dirname(currentDir)) { const packageJsonPath = path.join(currentDir, 'package.json'); if (fs.existsSync(packageJsonPath)) { try { const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); return { ...packageJson.dependencies, ...packageJson.devDependencies, ...packageJson.peerDependencies, ...packageJson.optionalDependencies, }; } catch { // Silently ignore JSON parsing errors and continue searching } } const parentDir = path.dirname(currentDir); if (parentDir === currentDir) { break; } currentDir = parentDir; } return {}; }; ================================================ FILE: packages/openapi-ts/src/config/plugins.ts ================================================ import type { AnyPluginName, PluginContext, PluginNames } from '@hey-api/shared'; import { dependencyFactory, valueToObject } from '@hey-api/shared'; import { defaultPluginConfigs } from '../plugins/config'; import type { Config, UserConfig } from './types'; /** * Default plugins used to generate artifacts if plugins aren't specified. */ export const defaultPlugins = [ '@hey-api/typescript', '@hey-api/sdk', ] as const satisfies ReadonlyArray; function getPluginsConfig({ dependencies, userPlugins, userPluginsConfig, }: { dependencies: Record; userPlugins: ReadonlyArray; userPluginsConfig: Config['plugins']; }): Pick { const circularReferenceTracker = new Set(); const pluginOrder = new Set(); const plugins: Config['plugins'] = {}; const dfs = (name: AnyPluginName) => { if (circularReferenceTracker.has(name)) { throw new Error(`Circular reference detected at '${name}'`); } if (pluginOrder.has(name)) { return; } circularReferenceTracker.add(name); const defaultPlugin = defaultPluginConfigs[name as PluginNames]; const userPlugin = userPluginsConfig[name as PluginNames]; if (!defaultPlugin && !userPlugin) { throw new Error( `unknown plugin dependency "${name}" - do you need to register a custom plugin with this name?`, ); } const plugin = { ...defaultPlugin, ...userPlugin, config: { ...defaultPlugin?.config, ...userPlugin?.config, }, dependencies: new Set([ ...(defaultPlugin?.dependencies || []), ...(userPlugin?.dependencies || []), ]), }; if (plugin.resolveConfig) { const context: PluginContext = { package: dependencyFactory(dependencies), pluginByTag: (tag, props = {}) => { const { defaultPlugin, errorMessage } = props; for (const userPlugin of userPlugins) { const defaultConfig = defaultPluginConfigs[userPlugin as PluginNames] || userPluginsConfig[userPlugin as PluginNames]; if (defaultConfig && defaultConfig.tags?.includes(tag) && userPlugin !== name) { return userPlugin as any; } } if (defaultPlugin) { const defaultConfig = defaultPluginConfigs[defaultPlugin as PluginNames] || userPluginsConfig[defaultPlugin as PluginNames]; if (defaultConfig && defaultConfig.tags?.includes(tag) && defaultPlugin !== name) { return defaultPlugin; } } throw new Error(errorMessage || `missing plugin - no plugin with tag "${tag}" found`); }, valueToObject, }; // @ts-expect-error plugin.resolveConfig(plugin, context); } for (const dependency of plugin.dependencies) { dfs(dependency); } circularReferenceTracker.delete(name); pluginOrder.add(name); // @ts-expect-error plugins[name] = plugin; }; for (const name of userPlugins) { dfs(name); } return { pluginOrder: Array.from(pluginOrder) as ReadonlyArray, plugins, }; } function isPluginClient(plugin: Required['plugins'][number]): boolean { if (typeof plugin === 'string') { return plugin.startsWith('@hey-api/client'); } return ( plugin.name.startsWith('@hey-api/client') || // @ts-expect-error (plugin.tags && plugin.tags.includes('client')) ); } export function getPlugins({ dependencies, userConfig, }: { dependencies: Record; userConfig: UserConfig; }): Pick { const userPluginsConfig: Config['plugins'] = {}; let definedPlugins: UserConfig['plugins'] = defaultPlugins; if (userConfig.plugins) { userConfig.plugins = userConfig.plugins.filter( (plugin) => (typeof plugin === 'string' && plugin) || (typeof plugin !== 'string' && plugin.name), ); if (userConfig.plugins.length === 1 && isPluginClient(userConfig.plugins[0]!)) { definedPlugins = [...defaultPlugins, ...userConfig.plugins]; } else { definedPlugins = userConfig.plugins; } } const userPlugins = definedPlugins .map((plugin) => { if (typeof plugin === 'string') { return plugin; } const pluginName = plugin.name; if (pluginName) { // @ts-expect-error if (plugin.handler) { // @ts-expect-error userPluginsConfig[pluginName] = plugin; } else { // @ts-expect-error userPluginsConfig[pluginName] = { config: { ...plugin }, }; // @ts-expect-error delete userPluginsConfig[pluginName]!.config.name; } } return pluginName; }) .filter(Boolean); return getPluginsConfig({ dependencies, userPlugins, userPluginsConfig }); } ================================================ FILE: packages/openapi-ts/src/config/resolve.ts ================================================ import path from 'node:path'; import { detectInteractiveSession } from '@hey-api/codegen-core'; import { ConfigError, getInput, getLogs, getParser } from '@hey-api/shared'; import colors from 'ansi-colors'; import { getOutput } from './output/config'; import { getPlugins } from './plugins'; import type { Config } from './types'; import type { ValidationResult } from './validate'; export type ResolvedJob = { config: Config; errors: Array; index: number; }; export function resolveConfig( validated: ValidationResult, dependencies: Record, ): ResolvedJob { const logs = getLogs(validated.job.config.logs); const input = getInput(validated.job.config); const output = getOutput(validated.job.config); const parser = getParser(validated.job.config); output.path = path.resolve(process.cwd(), output.path); let plugins: Pick; try { plugins = getPlugins({ dependencies, userConfig: validated.job.config }); } catch (error) { if (error instanceof ConfigError) { validated.errors.push(error); } plugins = { pluginOrder: [], plugins: {}, }; } const config: Config = { configFile: validated.job.config.configFile ?? '', dryRun: validated.job.config.dryRun ?? false, input, interactive: validated.job.config.interactive ?? detectInteractiveSession(), logs, output, parser, pluginOrder: plugins.pluginOrder, plugins: plugins.plugins, }; if (logs.level === 'debug') { const jobPrefix = colors.gray(`[Job ${validated.job.index}] `); console.warn(`${jobPrefix}${colors.cyan('config:')}`, config); } return { config, errors: validated.errors, index: validated.job.index, }; } ================================================ FILE: packages/openapi-ts/src/config/types.ts ================================================ import type { BaseConfig, BaseUserConfig, Plugin, PluginConfigMap, PluginNames, } from '@hey-api/shared'; import type { Output, UserOutput } from './output/types'; export type UserConfig = BaseUserConfig & { /** * Plugins generate artifacts from `input`. By default, we generate SDK * functions and TypeScript interfaces. If you manually define `plugins`, * you need to include the default plugins if you wish to use them. * * @default ['@hey-api/typescript', '@hey-api/sdk'] */ plugins?: ReadonlyArray< | PluginNames | { [K in PluginNames]: PluginConfigMap[K]['config'] & { name: K; }; }[PluginNames] >; }; export type Config = BaseConfig & { pluginOrder: ReadonlyArray; plugins: { [K in PluginNames]?: Plugin.Config; }; }; ================================================ FILE: packages/openapi-ts/src/config/utils.ts ================================================ import type { Context, PluginInstance } from '@hey-api/shared'; import type { Config } from './types'; export function getTypedConfig( plugin: Pick | Pick, ): Config { if ('context' in plugin) { return plugin.context.config as Config; } return plugin.config as Config; } ================================================ FILE: packages/openapi-ts/src/config/validate.ts ================================================ import { ConfigError, getInput } from '@hey-api/shared'; import type { Job } from './expand'; import { getOutput } from './output/config'; export type ValidationResult = { errors: Array; job: Job; }; export function validateJobs(jobs: ReadonlyArray): ReadonlyArray { return jobs.map((job) => { const errors: Array = []; const { config } = job; const inputs = getInput(config); if (!inputs.length) { errors.push( new ConfigError( 'missing input - which OpenAPI specification should we use to generate your output?', ), ); } const output = getOutput(config); if (!output.path) { errors.push(new ConfigError('missing output - where should we generate your output?')); } return { errors, job }; }); } ================================================ FILE: packages/openapi-ts/src/createClient.ts ================================================ import path from 'node:path'; import { type Logger, Project } from '@hey-api/codegen-core'; import { $RefParser } from '@hey-api/json-schema-ref-parser'; import { applyNaming, buildGraph, compileInputPath, Context, getSpec, type Input, logInputPaths, type OpenApi, parseOpenApiSpec, patchOpenApiSpec, postprocessOutput, type WatchValues, } from '@hey-api/shared'; import colors from 'ansi-colors'; import { postProcessors } from './config/output/postprocess'; import type { Config } from './config/types'; import { generateOutput } from './generate/output'; import { TypeScriptRenderer } from './ts-dsl'; export async function createClient({ config, dependencies, jobIndex, logger, watches: _watches, }: { config: Config; dependencies: Record; jobIndex: number; logger: Logger; /** * Always undefined on the first run, defined on subsequent runs. */ watches?: ReadonlyArray; }): Promise { const watches: ReadonlyArray = _watches || Array.from({ length: config.input.length }, () => ({ headers: new Headers(), })); const inputPaths = config.input.map((input) => compileInputPath(input)); // on first run, print the message as soon as possible if (config.logs.level !== 'silent' && !_watches) { logInputPaths(inputPaths, jobIndex); } const getSpecData = async (input: Input, index: number) => { const eventSpec = logger.timeEvent('spec'); const { arrayBuffer, error, resolvedInput, response } = await getSpec({ fetchOptions: input.fetch, inputPath: inputPaths[index]!.path, timeout: input.watch.timeout, watch: watches[index]!, }); eventSpec.timeEnd(); // throw on first run if there's an error to preserve user experience // if in watch mode, subsequent errors won't throw to gracefully handle // cases where server might be reloading if (error && !_watches) { const text = await response.text().catch(() => ''); throw new Error( `Request failed with status ${response.status}: ${text || response.statusText}`, ); } return { arrayBuffer, resolvedInput }; }; const specData = ( await Promise.all(config.input.map((input, index) => getSpecData(input, index))) ).filter((data) => data.arrayBuffer || data.resolvedInput); let context: Context | undefined; if (specData.length) { const refParser = new $RefParser(); const data = specData.length > 1 ? await refParser.bundleMany({ arrayBuffer: specData.map((data) => data.arrayBuffer!), pathOrUrlOrSchemas: [], resolvedInputs: specData.map((data) => data.resolvedInput!), }) : await refParser.bundle({ arrayBuffer: specData[0]!.arrayBuffer, pathOrUrlOrSchema: undefined, resolvedInput: specData[0]!.resolvedInput!, }); // on subsequent runs in watch mode, print the message only if we know we're // generating the output if (config.logs.level !== 'silent' && _watches) { console.clear(); logInputPaths(inputPaths, jobIndex); } const eventInputPatch = logger.timeEvent('input.patch'); await patchOpenApiSpec({ patchOptions: config.parser.patch, spec: data }); eventInputPatch.timeEnd(); const eventParser = logger.timeEvent('parser'); const header = config.output.header; // TODO: allow overriding via config const project = new Project({ defaultFileName: 'index', fileName: (base) => { const name = applyNaming(base, config.output.fileName); const { suffix } = config.output.fileName; if (!suffix) { return name; } return name === 'index' || name.endsWith(suffix) ? name : `${name}${suffix}`; }, nameConflictResolvers: config.output.nameConflictResolver ? { typescript: config.output.nameConflictResolver, } : undefined, renderers: [ new TypeScriptRenderer({ header: (ctx) => { const defaultValue = ['// This file is auto-generated by @hey-api/openapi-ts']; const result = typeof header === 'function' ? header({ ...ctx, defaultValue }) : header; return result === undefined ? defaultValue : result; }, module: config.output.module, preferExportAll: config.output.preferExportAll, }), ], root: config.output.path, }); context = new Context({ config, dependencies, logger, project, spec: data as OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X, }); parseOpenApiSpec(context); context.graph = buildGraph(context.ir, logger).graph; eventParser.timeEnd(); const eventGenerator = logger.timeEvent('generator'); await generateOutput(context); eventGenerator.timeEnd(); const eventPostprocess = logger.timeEvent('postprocess'); if (!config.dryRun) { const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `); postprocessOutput(config.output, postProcessors, jobPrefix); if (config.logs.level !== 'silent') { const outputPath = process.env.INIT_CWD ? `./${path.relative(process.env.INIT_CWD, config.output.path)}` : config.output.path; console.log( `${jobPrefix}${colors.green('✅ Done!')} Your output is in ${colors.cyanBright(outputPath)}`, ); } } eventPostprocess.timeEnd(); } const watchedInput = config.input.find( (input, index) => input.watch.enabled && typeof inputPaths[index]!.path === 'string', ); if (watchedInput) { setTimeout(() => { createClient({ config, dependencies, jobIndex, logger, watches, }); }, watchedInput.watch.interval); } return context; } ================================================ FILE: packages/openapi-ts/src/generate/client.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { IProject } from '@hey-api/codegen-core'; import type { BaseOutput, DefinePlugin, OutputHeader } from '@hey-api/shared'; import { ensureDirSync, isEnvironment, outputHeaderToPrefix } from '@hey-api/shared'; import type { Config } from '../config/types'; import type { Client } from '../plugins/@hey-api/client-core/types'; import { getClientPlugin } from '../plugins/@hey-api/client-core/utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); /** * Returns paths to client bundle files based on execution context */ function getClientBundlePaths(pluginName: string): { clientPath: string; corePath: string; } { const clientName = pluginName.slice('@hey-api/client-'.length); if (isEnvironment('development')) { // Dev: source bundle folders at src/plugins/@hey-api/{client}/bundle const pluginsDir = path.resolve(__dirname, '..', 'plugins', '@hey-api'); return { clientPath: path.resolve(pluginsDir, `client-${clientName}`, 'bundle'), corePath: path.resolve(pluginsDir, 'client-core', 'bundle'), }; } // Prod: copied to dist/clients/{clientName} return { clientPath: path.resolve(__dirname, 'clients', clientName), corePath: path.resolve(__dirname, 'clients', 'core'), }; } /** * Returns absolute path to the client folder. This is hard-coded for now. */ export function clientFolderAbsolutePath(config: Config): string { const client = getClientPlugin(config); if ('bundle' in client.config && client.config.bundle) { // not proud of this one const renamed: Map | undefined = // @ts-expect-error config._FRAGILE_CLIENT_BUNDLE_RENAMED; return path.resolve(config.output.path, 'client', `${renamed?.get('index') ?? 'index'}.ts`); } return client.name; } /** * Recursively copies files and directories. * This is a PnP-compatible alternative to fs.cpSync that works with Yarn PnP's * virtualized filesystem. */ function copyRecursivePnP(src: string, dest: string): void { const stat = fs.statSync(src); if (stat.isDirectory()) { if (!fs.existsSync(dest)) { fs.mkdirSync(dest, { recursive: true }); } const files = fs.readdirSync(src); for (const file of files) { copyRecursivePnP(path.join(src, file), path.join(dest, file)); } } else { const content = fs.readFileSync(src); fs.writeFileSync(dest, content); } } function renameFile({ filePath, project, renamed, }: { filePath: string; project: IProject; renamed: Map; }): void { const extension = path.extname(filePath); const name = path.basename(filePath, extension); const renamedName = project.fileName?.(name) || name; if (renamedName !== name) { const outputPath = path.dirname(filePath); fs.renameSync(filePath, path.resolve(outputPath, `${renamedName}${extension}`)); renamed.set(name, renamedName); } } function replaceImports({ filePath, header, module, renamed, }: Pick & { filePath: string; header?: string; renamed: Map; }): void { let content = fs.readFileSync(filePath, 'utf8'); // Dev mode: rewrite source bundle imports to match output structure if (isEnvironment('development')) { // ../../client-core/bundle/foo -> ../core/foo content = content.replace(/from\s+['"]\.\.\/\.\.\/client-core\/bundle\//g, "from '../core/"); // ../../client-core/bundle' (index import) content = content.replace(/from\s+['"]\.\.\/\.\.\/client-core\/bundle['"]/g, "from '../core'"); } content = content.replace(/from\s+['"](\.\.?\/[^'"]*?)['"]/g, (match, importPath) => { const importIndex = match.indexOf(importPath); const extension = path.extname(importPath); const fileName = path.basename(importPath, extension); const importDir = path.dirname(importPath); const replacedName = (renamed.get(fileName) ?? fileName) + (module.extension ? module.extension : extension); const replacedMatch = match.slice(0, importIndex) + [importDir, replacedName].filter(Boolean).join('/') + match.slice(importIndex + importPath.length); return replacedMatch; }); const fileHeader = header ?? ''; content = `${fileHeader}${content}`; fs.writeFileSync(filePath, content, 'utf8'); } /** * Creates a `client` folder containing the same modules as the client package. */ export function generateClientBundle({ header, module, outputPath, plugin, project, }: Pick & { header?: OutputHeader; outputPath: string; plugin: DefinePlugin['Config']; project: IProject; }): Map | undefined { const renamed = new Map(); const headerPrefix = outputHeaderToPrefix({ defaultValue: ['// This file is auto-generated by @hey-api/openapi-ts'], header, project, }); // copy Hey API clients to output const isHeyApiClientPlugin = plugin.name.startsWith('@hey-api/client-'); if (isHeyApiClientPlugin) { const { clientPath, corePath } = getClientBundlePaths(plugin.name); // copy client core const coreOutputPath = path.resolve(outputPath, 'core'); ensureDirSync(coreOutputPath); copyRecursivePnP(corePath, coreOutputPath); // copy client bundle const clientOutputPath = path.resolve(outputPath, 'client'); ensureDirSync(clientOutputPath); copyRecursivePnP(clientPath, clientOutputPath); if (project) { const copiedCoreFiles = fs.readdirSync(coreOutputPath); for (const file of copiedCoreFiles) { renameFile({ filePath: path.resolve(coreOutputPath, file), project, renamed, }); } const copiedClientFiles = fs.readdirSync(clientOutputPath); for (const file of copiedClientFiles) { renameFile({ filePath: path.resolve(clientOutputPath, file), project, renamed, }); } } const coreFiles = fs.readdirSync(coreOutputPath); for (const file of coreFiles) { replaceImports({ filePath: path.resolve(coreOutputPath, file), header: headerPrefix, module, renamed, }); } const clientFiles = fs.readdirSync(clientOutputPath); for (const file of clientFiles) { replaceImports({ filePath: path.resolve(clientOutputPath, file), header: headerPrefix, module, renamed, }); } return renamed; } const clientSrcPath = path.isAbsolute(plugin.name) ? path.dirname(plugin.name) : undefined; // copy custom local client to output if (clientSrcPath) { const dirPath = path.resolve(outputPath, 'client'); ensureDirSync(dirPath); copyRecursivePnP(clientSrcPath, dirPath); return; } // copy third-party client to output const clientModulePath = path.normalize(require.resolve(plugin.name)); const clientModulePathComponents = clientModulePath.split(path.sep); const clientDistPath = clientModulePathComponents .slice(0, clientModulePathComponents.indexOf('dist') + 1) .join(path.sep); const indexJsFile = clientModulePathComponents[clientModulePathComponents.length - 1]; const distFiles = [indexJsFile!, 'index.d.mts', 'index.d.cts']; const dirPath = path.resolve(outputPath, 'client'); ensureDirSync(dirPath); for (const file of distFiles) { fs.copyFileSync(path.resolve(clientDistPath, file), path.resolve(dirPath, file)); } return; } ================================================ FILE: packages/openapi-ts/src/generate/output.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import type { Context } from '@hey-api/shared'; import { IntentContext } from '@hey-api/shared'; import { getTypedConfig } from '../config/utils'; import { getClientPlugin } from '../plugins/@hey-api/client-core/utils'; import { generateClientBundle } from './client'; export async function generateOutput(context: Context): Promise { const outputPath = path.resolve(context.config.output.path); if (context.config.output.clean) { if (fs.existsSync(outputPath)) { fs.rmSync(outputPath, { force: true, recursive: true }); } } const config = getTypedConfig(context); const client = getClientPlugin(config); if ('bundle' in client.config && client.config.bundle && !config.dryRun) { // not proud of this one // @ts-expect-error config._FRAGILE_CLIENT_BUNDLE_RENAMED = generateClientBundle({ header: config.output.header, module: config.output.module, outputPath, // @ts-expect-error plugin: client, project: context.gen, }); } for (const plugin of context.registerPlugins()) { await plugin.run(); } context.gen.plan(); const ctx = new IntentContext(context.spec); for (const intent of context.intents) { await intent.run(ctx); } for (const file of context.gen.render()) { const filePath = path.resolve(outputPath, file.path); const dir = path.dirname(filePath); if (!context.config.dryRun) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(filePath, file.content, { encoding: 'utf8' }); } } const { source } = context.config.output; if (source.enabled) { const sourcePath = source.path === null ? undefined : path.resolve(outputPath, source.path); if (!context.config.dryRun && sourcePath && sourcePath !== outputPath) { fs.mkdirSync(sourcePath, { recursive: true }); } const serialized = await source.serialize(context.spec); // TODO: handle yaml (convert before writing) if (!context.config.dryRun && sourcePath) { fs.writeFileSync( path.resolve(sourcePath, `${source.fileName}.${source.extension}`), serialized, { encoding: 'utf8' }, ); } if (source.callback) { await source.callback(serialized); } } } ================================================ FILE: packages/openapi-ts/src/generate.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { Logger } from '@hey-api/codegen-core'; import type { Context } from '@hey-api/shared'; import { checkNodeVersion, ConfigValidationError, getLogs, JobError, logCrashReport, openGitHubIssueWithCrashReport, printCliIntro, printCrashReport, shouldReportCrash, } from '@hey-api/shared'; import type { LazyOrAsync, MaybeArray } from '@hey-api/types'; import type { Configs } from './config/init'; import { resolveJobs } from './config/init'; import type { UserConfig } from './config/types'; import { createClient as pCreateClient } from './createClient'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); /** * Generate a client from the provided configuration. * * @param userConfig User provided {@link UserConfig} configuration(s). */ export async function createClient( userConfig?: LazyOrAsync>, logger = new Logger(), ): Promise> { const resolvedConfig = typeof userConfig === 'function' ? await userConfig() : userConfig; const userConfigs = resolvedConfig ? resolvedConfig instanceof Array ? resolvedConfig : [resolvedConfig] : []; let rawLogs = userConfigs.find((config) => getLogs(config.logs).level !== 'silent')?.logs; if (typeof rawLogs === 'string') { rawLogs = getLogs(rawLogs); } let jobs: Configs['jobs'] = []; try { checkNodeVersion(); const eventCreateClient = logger.timeEvent('createClient'); const eventConfig = logger.timeEvent('config'); const resolved = await resolveJobs({ logger, userConfigs }); const dependencies = resolved.dependencies; jobs = resolved.jobs; const printIntro = jobs.some((job) => job.config.logs.level !== 'silent'); if (printIntro) printCliIntro(__dirname); eventConfig.timeEnd(); const configErrors = jobs.flatMap((job) => job.errors.map((error) => ({ error, jobIndex: job.index })), ); if (configErrors.length > 0) { throw new ConfigValidationError(configErrors); } const outputs = await Promise.all( jobs.map(async (job) => { try { return await pCreateClient({ config: job.config, dependencies, jobIndex: job.index, logger, }); } catch (error) { if (error instanceof Error) { throw new JobError('', { error, jobIndex: job.index, }); } } }), ); const contexts = outputs.filter((ctx): ctx is Context => ctx !== undefined); eventCreateClient.timeEnd(); logger.report(jobs.some((job) => job.config.logs.level === 'debug')); return contexts; } catch (error) { const logs = jobs.find((job) => job.config.logs.level !== 'silent')?.config.logs ?? jobs[0]?.config.logs ?? rawLogs; const dryRun = jobs.some((job) => job.config.dryRun) ?? userConfigs.some((config) => config.dryRun) ?? false; const logPath = logs?.file && !dryRun ? logCrashReport(error, logs.path ?? '') : undefined; if (!logs || logs.level !== 'silent') { printCrashReport({ error, logPath }); const isInteractive = jobs.some((job) => job.config.interactive) ?? userConfigs.some((config) => config.interactive) ?? false; if (await shouldReportCrash({ error, isInteractive })) { await openGitHubIssueWithCrashReport(error, __dirname); } } throw error; } } ================================================ FILE: packages/openapi-ts/src/index.ts ================================================ /* eslint-disable @typescript-eslint/no-namespace */ // OVERRIDES // hard-coded here because build process doesn't pick up overrides from separate files import '@hey-api/codegen-core'; import '@hey-api/shared'; declare module '@hey-api/codegen-core' { interface ProjectRenderMeta { /** * If specified, this will be the file extension used when importing * other modules. By default, we don't add a file extension and let the * runtime resolve it. * * @default null */ importFileExtension?: AnyString | null; } interface SymbolMeta { category?: | 'client' | 'external' | 'hook' | 'schema' | 'sdk' | 'transform' | 'type' | 'utility' | AnyString; /** * Path to the resource this symbol represents. */ path?: ReadonlyArray; /** * Name of the plugin that registered this symbol. */ pluginName?: string; resource?: 'client' | 'definition' | 'operation' | 'webhook' | AnyString; resourceId?: string; role?: 'data' | 'error' | 'errors' | 'options' | 'response' | 'responses' | AnyString; /** * Tags associated with this symbol. */ tags?: ReadonlyArray; tool?: | 'angular' | 'arktype' | 'fastify' | 'json-schema' | 'sdk' | 'typescript' | 'valibot' | 'zod' | AnyString; variant?: 'container' | AnyString; } } declare module '@hey-api/shared' { interface PluginConfigMap { '@angular/common': Plugins.AngularCommon.Types['Types']; '@faker-js/faker': Plugins.FakerJsFaker.Types['Types']; '@hey-api/client-angular': Plugins.HeyApiClientAngular.Types['Types']; '@hey-api/client-axios': Plugins.HeyApiClientAxios.Types['Types']; '@hey-api/client-fetch': Plugins.HeyApiClientFetch.Types['Types']; '@hey-api/client-ky': Plugins.HeyApiClientKy.Types['Types']; '@hey-api/client-next': Plugins.HeyApiClientNext.Types['Types']; '@hey-api/client-nuxt': Plugins.HeyApiClientNuxt.Types['Types']; '@hey-api/client-ofetch': Plugins.HeyApiClientOfetch.Types['Types']; '@hey-api/schemas': Plugins.HeyApiSchemas.Types['Types']; '@hey-api/sdk': Plugins.HeyApiSdk.Types['Types']; '@hey-api/transformers': Plugins.HeyApiTransformers.Types['Types']; '@hey-api/typescript': Plugins.HeyApiTypeScript.Types['Types']; '@pinia/colada': Plugins.PiniaColada.Types['Types']; '@tanstack/angular-query-experimental': Plugins.TanStackAngularQuery.Types['Types']; '@tanstack/preact-query': Plugins.TanStackPreactQuery.Types['Types']; '@tanstack/react-query': Plugins.TanStackReactQuery.Types['Types']; '@tanstack/solid-query': Plugins.TanStackSolidQuery.Types['Types']; '@tanstack/svelte-query': Plugins.TanStackSvelteQuery.Types['Types']; '@tanstack/vue-query': Plugins.TanStackVueQuery.Types['Types']; arktype: Plugins.Arktype.Types['Types']; fastify: Plugins.Fastify.Types['Types']; nestjs: Plugins.NestJs.Types['Types']; orpc: Plugins.Orpc.Types['Types']; swr: Plugins.Swr.Types['Types']; valibot: Plugins.Valibot.Types['Types']; zod: Plugins.Zod.Types['Types']; } interface PluginInstanceTypes { Node: TsDsl; } } // END OVERRIDES import type { AnyString, LazyOrAsync, MaybeArray } from '@hey-api/types'; import colors from 'ansi-colors'; // @ts-expect-error import colorSupport from 'color-support'; import type { UserConfig } from './config/types'; import type { AngularCommonPlugin } from './plugins/@angular/common'; import type { FakerJsFakerPlugin, FakerJsFakerResolvers } from './plugins/@faker-js/faker'; import type { AngularClient as AngularClientImp, HeyApiClientAngularPlugin, } from './plugins/@hey-api/client-angular'; import type { AxiosClient as AxiosClientImp, HeyApiClientAxiosPlugin, } from './plugins/@hey-api/client-axios'; import type { FetchClient as FetchClientImp, HeyApiClientFetchPlugin, } from './plugins/@hey-api/client-fetch'; import type { HeyApiClientKyPlugin, KyClient as KyClientImp } from './plugins/@hey-api/client-ky'; import type { HeyApiClientNextPlugin, NextClient as NextClientImp, } from './plugins/@hey-api/client-next'; import type { HeyApiClientNuxtPlugin, NuxtClient as NuxtClientImp, } from './plugins/@hey-api/client-nuxt'; import type { HeyApiClientOfetchPlugin, OfetchClient as OfetchClientImp, } from './plugins/@hey-api/client-ofetch'; import type { HeyApiSchemasPlugin } from './plugins/@hey-api/schemas'; import type { HeyApiSdkPlugin } from './plugins/@hey-api/sdk'; import type { HeyApiTransformersPlugin } from './plugins/@hey-api/transformers'; import type { HeyApiTypeScriptPlugin, HeyApiTypeScriptResolvers, } from './plugins/@hey-api/typescript'; import type { PiniaColadaPlugin } from './plugins/@pinia/colada'; import type { TanStackAngularQueryPlugin } from './plugins/@tanstack/angular-query-experimental'; import type { TanStackPreactQueryPlugin } from './plugins/@tanstack/preact-query'; import type { TanStackReactQueryPlugin } from './plugins/@tanstack/react-query'; import type { TanStackSolidQueryPlugin } from './plugins/@tanstack/solid-query'; import type { TanStackSvelteQueryPlugin } from './plugins/@tanstack/svelte-query'; import type { TanStackVueQueryPlugin } from './plugins/@tanstack/vue-query'; import type { ArktypePlugin } from './plugins/arktype'; import type { FastifyPlugin } from './plugins/fastify'; import type { NestJsPlugin } from './plugins/nestjs'; import type { OrpcPlugin } from './plugins/orpc'; import type { SwrPlugin } from './plugins/swr'; import type { ValibotPlugin, ValibotResolvers } from './plugins/valibot'; import type { ZodPlugin, ZodResolvers } from './plugins/zod'; import type { TsDsl } from './ts-dsl'; colors.enabled = colorSupport().hasBasic; export { createClient } from './generate'; /** * Type helper for configuration object, returns {@link MaybeArray} object(s) */ export function defineConfig( config: LazyOrAsync>, ): Promise>; export function defineConfig(config: LazyOrAsync): Promise; export async function defineConfig>( config: LazyOrAsync, ): Promise { return typeof config === 'function' ? await config() : config; } export { defaultPlugins } from './config/plugins'; export type { UserConfig } from './config/types'; export { clientDefaultConfig, clientDefaultMeta } from './plugins/@hey-api/client-core/config'; export { clientPluginHandler } from './plugins/@hey-api/client-core/plugin'; export type { Client } from './plugins/@hey-api/client-core/types'; export type { ExpressionTransformer, TypeTransformer } from './plugins/@hey-api/transformers/types'; export * from './ts-dsl'; export { Logger } from '@hey-api/codegen-core'; export type { DefinePlugin, IR, OpenApi, OpenApiMetaObject, OpenApiOperationObject, OpenApiParameterObject, OpenApiRequestBodyObject, OpenApiResponseObject, OpenApiSchemaObject, Plugin, } from '@hey-api/shared'; export { defaultPaginationKeywords, definePluginConfig, OperationPath, OperationStrategy, utils, } from '@hey-api/shared'; export namespace Plugins { export namespace AngularCommon { export type Types = AngularCommonPlugin; } export namespace Arktype { export type Types = ArktypePlugin; } export namespace FakerJsFaker { export type Types = FakerJsFakerPlugin; export type Resolvers = Required['~resolvers']; } export namespace Fastify { export type Types = FastifyPlugin; } export namespace HeyApiClientAngular { export type Client = AngularClientImp; export type Types = HeyApiClientAngularPlugin; } export namespace HeyApiClientAxios { export type Client = AxiosClientImp; export type Types = HeyApiClientAxiosPlugin; } export namespace HeyApiClientFetch { export type Client = FetchClientImp; export type Types = HeyApiClientFetchPlugin; } export namespace HeyApiClientKy { export type Client = KyClientImp; export type Types = HeyApiClientKyPlugin; } export namespace HeyApiClientNext { export type Client = NextClientImp; export type Types = HeyApiClientNextPlugin; } export namespace HeyApiClientNuxt { export type Client = NuxtClientImp; export type Types = HeyApiClientNuxtPlugin; } export namespace HeyApiClientOfetch { export type Client = OfetchClientImp; export type Types = HeyApiClientOfetchPlugin; } export namespace HeyApiSchemas { export type Types = HeyApiSchemasPlugin; } export namespace HeyApiSdk { export type Types = HeyApiSdkPlugin; } export namespace HeyApiTransformers { export type Types = HeyApiTransformersPlugin; } export namespace HeyApiTypeScript { export type Resolvers = Required['~resolvers']; export type Types = HeyApiTypeScriptPlugin; } export namespace NestJs { export type Types = NestJsPlugin; } export namespace Orpc { export type Types = OrpcPlugin; } export namespace PiniaColada { export type Types = PiniaColadaPlugin; } export namespace Swr { export type Types = SwrPlugin; } export namespace TanStackAngularQuery { export type Types = TanStackAngularQueryPlugin; } export namespace TanStackPreactQuery { export type Types = TanStackPreactQueryPlugin; } export namespace TanStackReactQuery { export type Types = TanStackReactQueryPlugin; } export namespace TanStackSolidQuery { export type Types = TanStackSolidQueryPlugin; } export namespace TanStackSvelteQuery { export type Types = TanStackSvelteQueryPlugin; } export namespace TanStackVueQuery { export type Types = TanStackVueQueryPlugin; } export namespace Valibot { export type Resolvers = Required['~resolvers']; export type Types = ValibotPlugin; } export namespace Zod { export type Resolvers = Required['~resolvers']; export type Types = ZodPlugin; } } // DEPRECATED /** @deprecated Use `Plugins.HeyApiClientAngular.Client` instead. */ export type AngularClient = AngularClientImp; /** @deprecated Use `Plugins.HeyApiClientAxios.Client` instead. */ export type AxiosClient = AxiosClientImp; /** @deprecated Use `Plugins.HeyApiClientFetch.Client` instead. */ export type FetchClient = FetchClientImp; /** @deprecated Use `Plugins.HeyApiClientKy.Client` instead. */ export type KyClient = KyClientImp; /** @deprecated Use `Plugins.HeyApiClientNext.Client` instead. */ export type NextClient = NextClientImp; /** @deprecated Use `Plugins.HeyApiClientNuxt.Client` instead. */ export type NuxtClient = NuxtClientImp; /** @deprecated Use `Plugins.HeyApiClientOfetch.Client` instead. */ export type OfetchClient = OfetchClientImp; ================================================ FILE: packages/openapi-ts/src/internal.ts ================================================ export { resolveJobs as initConfigs } from './config/init'; export { getSpec, parseOpenApiSpec } from '@hey-api/shared'; ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { resolveHttpRequests } from './httpRequests'; import { resolveHttpResources } from './httpResources'; import { handler } from './plugin'; import type { AngularCommonPlugin } from './types'; export const defaultConfig: AngularCommonPlugin['Config'] = { config: { comments: true, includeInEntry: false, }, dependencies: ['@hey-api/client-angular', '@hey-api/sdk'], handler, name: '@angular/common', resolveConfig: (plugin, context) => { plugin.config.httpRequests = resolveHttpRequests(plugin.config, context); plugin.config.httpResources = resolveHttpResources(plugin.config, context); }, }; /** * Type helper for `@angular/common` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpRequests/config.ts ================================================ import type { PluginContext } from '@hey-api/shared'; import type { UserConfig } from '../types'; import type { HttpRequestsConfig, UserHttpRequestsConfig } from './types'; type Config = Omit; export function resolveHttpRequests(config: Config, context: PluginContext): HttpRequestsConfig { let input = config.httpRequests; if (typeof input === 'string' || typeof input === 'function') { input = { strategy: input }; } else if (typeof input === 'boolean' || !input) { input = { enabled: Boolean(input) }; } const strategy = input.strategy ?? 'flat'; return context.valueToObject({ defaultValue: { container: 'class', enabled: true, methods: 'instance', nesting: 'operationId', nestingDelimiters: /[./]/, strategy, strategyDefaultTag: 'default', }, mappers: { object(value) { value.containerName = context.valueToObject({ defaultValue: strategy === 'single' ? { casing: 'PascalCase', name: 'HttpRequests' } : { casing: 'PascalCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.containerName, }); value.methodName = context.valueToObject({ defaultValue: strategy === 'flat' ? { casing: 'camelCase', name: '{{name}}Request' } : { casing: 'camelCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.methodName, }); value.segmentName = context.valueToObject({ defaultValue: { casing: 'PascalCase', name: '{{name}}Requests' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.segmentName, }); return value; }, }, value: input as UserHttpRequestsConfig, }) as HttpRequestsConfig; } ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpRequests/index.ts ================================================ export { resolveHttpRequests } from './config'; export { resolveHttpRequestsStrategy } from './resolve'; export type { HttpRequestsConfig, UserHttpRequestsConfig } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpRequests/resolve.ts ================================================ import type { OperationPathStrategy, OperationStructureStrategy } from '@hey-api/shared'; import { OperationPath, OperationStrategy } from '@hey-api/shared'; import type { AngularCommonPlugin } from '../types'; function resolvePath(plugin: AngularCommonPlugin['Instance']): OperationPathStrategy { if (plugin.config.httpRequests.nesting === 'id') { return OperationPath.id(); } if (plugin.config.httpRequests.nesting === 'operationId') { return OperationPath.fromOperationId({ delimiters: plugin.config.httpRequests.nestingDelimiters, fallback: OperationPath.id(), }); } return plugin.config.httpRequests.nesting; } export function resolveHttpRequestsStrategy( plugin: AngularCommonPlugin['Instance'], ): OperationStructureStrategy { if (plugin.config.httpRequests.strategy === 'flat') { return OperationStrategy.flat({ path: (operation) => [resolvePath(plugin)(operation).join('.')], }); } if (plugin.config.httpRequests.strategy === 'single') { const root = plugin.config.httpRequests.containerName; return OperationStrategy.single({ path: resolvePath(plugin), root: typeof root.name === 'string' ? root.name : (root.name?.('') ?? ''), }); } if (plugin.config.httpRequests.strategy === 'byTags') { return OperationStrategy.byTags({ fallback: plugin.config.httpRequests.strategyDefaultTag, path: resolvePath(plugin), }); } return plugin.config.httpRequests.strategy; } ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpRequests/types.ts ================================================ import type { FeatureToggle, NamingConfig, NamingRule, OperationPathStrategy, OperationsStrategy, } from '@hey-api/shared'; export interface UserHttpRequestsConfig { /** * Type of container for grouped operations. * * Ignored when `strategy` is `'flat'`. * * - `'class'` - Class with methods * * @default 'class' */ container?: 'class'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'Sdk' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'MyApi' * * @example * // Transform tag names with suffix * containerName: '{{name}}Service' * * @example * // With casing * containerName: { name: '{{name}}Service', case: 'PascalCase' } */ containerName?: NamingRule; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Customize method/function names. * * Applied to the final segment of the path (the method name). */ methodName?: NamingRule; /** * How methods are attached to class containers. * * Only applies when `container` is `'class'`. * * - `'instance'` - Instance methods, requires `new ClassName(config)` * * @default 'instance' */ methods?: 'instance'; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control * * @default 'operationId' */ nesting?: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. * * @default /[./]/ */ nestingDelimiters?: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the method name). */ segmentName?: NamingRule; /** * Grouping strategy. * * - `'flat'` - Standalone functions, no grouping * - `'byTags'` - One container per operation tag * - `'single'` - All operations in one container * - Custom function for full control * * @default 'flat' */ strategy?: OperationsStrategy; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. * * @default 'default' */ strategyDefaultTag?: string; } export type HttpRequestsConfig = FeatureToggle & { /** * Type of container for grouped operations. * * Ignored when `strategy` is `'flat'`. * * - `'class'` - Class with methods */ container: 'class'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'Sdk' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'MyApi' * * @example * // Transform tag names with suffix * containerName: '{{name}}Service' * * @example * // With casing * containerName: { name: '{{name}}Service', case: 'PascalCase' } */ containerName: NamingConfig; /** * Customize method/function names. * * Applied to the final segment of the path (the method name). */ methodName: NamingConfig; /** * How methods are attached to class containers. * * Only applies when `container` is `'class'`. * * - `'instance'` - Instance methods, requires `new ClassName(config)` */ methods: 'instance'; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control */ nesting: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. */ nestingDelimiters: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the method name). */ segmentName: NamingConfig; /** * Grouping strategy. * * - `'flat'` - Standalone functions, no grouping * - `'byTags'` - One container per operation tag * - `'single'` - All operations in one container * - Custom function for full control */ strategy: OperationsStrategy; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. */ strategyDefaultTag: string; }; ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpResources/config.ts ================================================ import type { PluginContext } from '@hey-api/shared'; import type { UserConfig } from '../types'; import type { HttpResourcesConfig, UserHttpResourcesConfig } from './types'; type Config = Omit; export function resolveHttpResources(config: Config, context: PluginContext): HttpResourcesConfig { let input = config.httpResources; if (typeof input === 'string' || typeof input === 'function') { input = { strategy: input }; } else if (typeof input === 'boolean' || !input) { input = { enabled: Boolean(input) }; } const strategy = input.strategy ?? 'flat'; return context.valueToObject({ defaultValue: { container: 'class', enabled: true, methods: 'instance', nesting: 'operationId', nestingDelimiters: /[./]/, strategy, strategyDefaultTag: 'default', }, mappers: { object(value) { value.containerName = context.valueToObject({ defaultValue: strategy === 'single' ? { casing: 'PascalCase', name: 'HttpResources' } : { casing: 'PascalCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.containerName, }); value.methodName = context.valueToObject({ defaultValue: strategy === 'flat' ? { casing: 'camelCase', name: '{{name}}Resource' } : { casing: 'camelCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.methodName, }); value.segmentName = context.valueToObject({ defaultValue: { casing: 'PascalCase', name: '{{name}}Resources' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.segmentName, }); return value; }, }, value: input as UserHttpResourcesConfig, }) as HttpResourcesConfig; } ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpResources/index.ts ================================================ export { resolveHttpResources } from './config'; export { resolveHttpResourcesStrategy } from './resolve'; export type { HttpResourcesConfig, UserHttpResourcesConfig } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpResources/resolve.ts ================================================ import type { OperationPathStrategy, OperationStructureStrategy } from '@hey-api/shared'; import { OperationPath, OperationStrategy } from '@hey-api/shared'; import type { AngularCommonPlugin } from '../types'; function resolvePath(plugin: AngularCommonPlugin['Instance']): OperationPathStrategy { if (plugin.config.httpResources.nesting === 'id') { return OperationPath.id(); } if (plugin.config.httpResources.nesting === 'operationId') { return OperationPath.fromOperationId({ delimiters: plugin.config.httpResources.nestingDelimiters, fallback: OperationPath.id(), }); } return plugin.config.httpResources.nesting; } export function resolveHttpResourcesStrategy( plugin: AngularCommonPlugin['Instance'], ): OperationStructureStrategy { if (plugin.config.httpResources.strategy === 'flat') { return OperationStrategy.flat({ path: (operation) => [resolvePath(plugin)(operation).join('.')], }); } if (plugin.config.httpResources.strategy === 'single') { const root = plugin.config.httpResources.containerName; return OperationStrategy.single({ path: resolvePath(plugin), root: typeof root.name === 'string' ? root.name : (root.name?.('') ?? ''), }); } if (plugin.config.httpResources.strategy === 'byTags') { return OperationStrategy.byTags({ fallback: plugin.config.httpResources.strategyDefaultTag, path: resolvePath(plugin), }); } return plugin.config.httpResources.strategy; } ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/httpResources/types.ts ================================================ import type { FeatureToggle, NamingConfig, NamingRule, OperationPathStrategy, OperationsStrategy, } from '@hey-api/shared'; export interface UserHttpResourcesConfig { /** * Type of container for grouped operations. * * Ignored when `strategy` is `'flat'`. * * - `'class'` - Class with methods * * @default 'class' */ container?: 'class'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'Sdk' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'MyApi' * * @example * // Transform tag names with suffix * containerName: '{{name}}Service' * * @example * // With casing * containerName: { name: '{{name}}Service', case: 'PascalCase' } */ containerName?: NamingRule; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Customize method/function names. * * Applied to the final segment of the path (the method name). */ methodName?: NamingRule; /** * How methods are attached to class containers. * * Only applies when `container` is `'class'`. * * - `'instance'` - Instance methods, requires `new ClassName(config)` * * @default 'instance' */ methods?: 'instance'; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control * * @default 'operationId' */ nesting?: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. * * @default /[./]/ */ nestingDelimiters?: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the method name). */ segmentName?: NamingRule; /** * Grouping strategy. * * - `'flat'` - Standalone functions, no grouping * - `'byTags'` - One container per operation tag * - `'single'` - All operations in one container * - Custom function for full control * * @default 'flat' */ strategy?: OperationsStrategy; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. * * @default 'default' */ strategyDefaultTag?: string; } export type HttpResourcesConfig = FeatureToggle & { /** * Type of container for grouped operations. * * Ignored when `strategy` is `'flat'`. * * - `'class'` - Class with methods */ container: 'class'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'Sdk' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'MyApi' * * @example * // Transform tag names with suffix * containerName: '{{name}}Service' * * @example * // With casing * containerName: { name: '{{name}}Service', case: 'PascalCase' } */ containerName: NamingConfig; /** * Customize method/function names. * * Applied to the final segment of the path (the method name). */ methodName: NamingConfig; /** * How methods are attached to class containers. * * Only applies when `container` is `'class'`. * * - `'instance'` - Instance methods, requires `new ClassName(config)` */ methods: 'instance'; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control */ nesting: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. */ nestingDelimiters: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the method name). */ segmentName: NamingConfig; /** * Grouping strategy. * * - `'flat'` - Standalone functions, no grouping * - `'byTags'` - One container per operation tag * - `'single'` - All operations in one container * - Custom function for full control */ strategy: OperationsStrategy; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. */ strategyDefaultTag: string; }; ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { AngularCommonPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/plugin.ts ================================================ import { StructureModel } from '@hey-api/codegen-core'; import type { $ } from '../../../ts-dsl'; import { resolveHttpRequestsStrategy } from './httpRequests'; import { resolveHttpResourcesStrategy } from './httpResources'; import type { OperationItem } from './shared/node'; import { createHttpRequestShell, createHttpResourceShell, source, toHttpRequestNode, toHttpResourceNode, } from './shared/node'; import type { AngularCommonPlugin } from './types'; export const handler: AngularCommonPlugin['Handler'] = ({ plugin }) => { plugin.symbol('HttpRequest', { external: '@angular/common/http', kind: 'type', meta: { category: 'external', resource: '@angular/common/http.HttpRequest', }, }); plugin.symbol('inject', { external: '@angular/core', meta: { category: 'external', resource: '@angular/core.inject', }, }); plugin.symbol('Injectable', { external: '@angular/core', meta: { category: 'external', resource: '@angular/core.Injectable', }, }); plugin.symbol('httpResource', { external: '@angular/common/http', meta: { category: 'external', resource: '@angular/common/http.httpResource', }, }); const httpRequestStructure = new StructureModel(); const httpResourceStructure = new StructureModel(); if (plugin.config.httpRequests.enabled) { const shell = createHttpRequestShell(plugin); const strategy = resolveHttpRequestsStrategy(plugin); plugin.forEach( 'operation', ({ operation }) => { httpRequestStructure.insert({ data: { operation, } satisfies OperationItem, locations: strategy(operation).map((path) => ({ path, shell })), source, }); }, { order: 'declarations' }, ); } if (plugin.config.httpResources.enabled) { const shell = createHttpResourceShell(plugin); const strategy = resolveHttpResourcesStrategy(plugin); plugin.forEach( 'operation', ({ operation }) => { httpResourceStructure.insert({ data: { operation, } satisfies OperationItem, locations: strategy(operation).map((path) => ({ path, shell })), source, }); }, { order: 'declarations' }, ); } const allDependencies: Array> = []; const allNodes: Array> = []; for (const node of httpRequestStructure.walk()) { const { dependencies, nodes } = toHttpRequestNode(node, plugin); allDependencies.push(...(dependencies ?? [])); allNodes.push(...nodes); } for (const node of httpResourceStructure.walk()) { const { dependencies, nodes } = toHttpResourceNode(node, plugin); allDependencies.push(...(dependencies ?? [])); allNodes.push(...nodes); } const uniqueDependencies = new Map>(); for (const dep of allDependencies) { if (dep.symbol) uniqueDependencies.set(dep.symbol.id, dep); } for (const dep of uniqueDependencies.values()) { plugin.node(dep); } for (const node of allNodes) { plugin.node(node); } }; ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/shared/node.ts ================================================ import type { StructureItem, StructureNode, StructureShell, Symbol, SymbolMeta, } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { applyNaming, toCase } from '@hey-api/shared'; import { getTypedConfig } from '../../../../config/utils'; import { getClientPlugin } from '../../../../plugins/@hey-api/client-core/utils'; import { createOperationComment, isOperationOptionsRequired, } from '../../../../plugins/shared/utils/operation'; import { $ } from '../../../../ts-dsl'; import type { AngularCommonPlugin } from '../types'; export interface OperationItem { operation: IR.OperationObject; } export const source = globalThis.Symbol('@angular/common'); function attachComment>(args: { node: T; operation: IR.OperationObject; plugin: AngularCommonPlugin['Instance']; }): T { const { node, operation, plugin } = args; return node.$if(plugin.config.comments && createOperationComment(operation), (n, v) => n.doc(v), ) as T; } function createHttpRequestFnMeta(operation: IR.OperationObject): SymbolMeta { return { category: 'utility', resource: 'operation', resourceId: operation.id, role: 'request', tool: 'angular', }; } function createHttpRequestShellMeta(node: StructureNode): SymbolMeta { return { category: 'utility', resource: 'shell', resourceId: node.getPath().join('.'), role: 'request', tool: 'angular', }; } function createHttpResourceFnMeta(operation: IR.OperationObject): SymbolMeta { return { category: 'utility', resource: 'operation', resourceId: operation.id, role: 'resource', tool: 'angular', }; } function createHttpResourceShellMeta(node: StructureNode): SymbolMeta { return { category: 'utility', resource: 'shell', resourceId: node.getPath().join('.'), role: 'resource', tool: 'angular', }; } function createHttpRequestFnSymbol( plugin: AngularCommonPlugin['Instance'], item: StructureItem & { data: OperationItem }, ): Symbol { const { operation } = item.data; const name = item.location[item.location.length - 1]!; return plugin.symbol(applyNaming(name, plugin.config.httpRequests.methodName), { meta: createHttpRequestFnMeta(operation), }); } function createHttpResourceFnSymbol( plugin: AngularCommonPlugin['Instance'], item: StructureItem & { data: OperationItem }, ): Symbol { const { operation } = item.data; const name = item.location[item.location.length - 1]!; return plugin.symbol(applyNaming(name, plugin.config.httpResources.methodName), { meta: createHttpResourceFnMeta(operation), }); } function childToHttpRequestNode( resource: StructureNode, plugin: AngularCommonPlugin['Instance'], ): ReadonlyArray> { const refChild = plugin.referenceSymbol(createHttpRequestShellMeta(resource)); const memberNameStr = toCase(refChild.name, 'camelCase'); const memberName = plugin.symbol(memberNameStr); const privateName = plugin.symbol(`_${memberNameStr}`); return [ $.field(privateName, (f) => f.private().optional().type(refChild)), $.getter(memberName, (g) => g .returns(refChild) .do($('this').attr(privateName).nullishAssign($.new(refChild).args()).return()), ), ]; } function childToHttpResourceNode( resource: StructureNode, plugin: AngularCommonPlugin['Instance'], ): ReadonlyArray> { const refChild = plugin.referenceSymbol(createHttpResourceShellMeta(resource)); const memberNameStr = toCase(refChild.name, 'camelCase'); const memberName = plugin.symbol(memberNameStr); const privateName = plugin.symbol(`_${memberNameStr}`); return [ $.field(privateName, (f) => f.private().optional().type(refChild)), $.getter(memberName, (g) => g .returns(refChild) .do($('this').attr(privateName).nullishAssign($.new(refChild).args()).return()), ), ]; } export function createHttpRequestShell(plugin: AngularCommonPlugin['Instance']): StructureShell { const client = getClientPlugin(getTypedConfig(plugin)); const isAngularClient = client.name === '@hey-api/client-angular'; const symbolInjectable = plugin.external('@angular/core.Injectable'); return { define: (node) => { const symbol = plugin.symbol( applyNaming( node.name, node.isRoot ? plugin.config.httpRequests.containerName : plugin.config.httpRequests.segmentName, ), { meta: createHttpRequestShellMeta(node), }, ); const c = $.class(symbol) .export() .$if(isAngularClient && node.isRoot, (c) => c.decorator(symbolInjectable, $.object().prop('providedIn', $.literal('root'))), ); return { dependencies: [], node: c }; }, }; } export function createHttpResourceShell(plugin: AngularCommonPlugin['Instance']): StructureShell { const client = getClientPlugin(getTypedConfig(plugin)); const isAngularClient = client.name === '@hey-api/client-angular'; const symbolInjectable = plugin.external('@angular/core.Injectable'); return { define: (node) => { const symbol = plugin.symbol( applyNaming( node.name, node.isRoot ? plugin.config.httpResources.containerName : plugin.config.httpResources.segmentName, ), { meta: createHttpResourceShellMeta(node), }, ); const c = $.class(symbol) .export() .$if(isAngularClient && node.isRoot, (c) => c.decorator(symbolInjectable, $.object().prop('providedIn', $.literal('root'))), ); return { dependencies: [], node: c }; }, }; } function implementHttpRequestFn>(args: { node: T; operation: IR.OperationObject; plugin: AngularCommonPlugin['Instance']; }): T { const { node, operation, plugin } = args; const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, operation, }); const symbolHttpRequest = plugin.external('@angular/common/http.HttpRequest'); const symbolClient = plugin.getSymbol({ category: 'client' }); const symbolOptions = plugin.referenceSymbol({ category: 'type', resource: 'client-options', tool: 'sdk', }); const symbolDataType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'typescript', }); const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', }); return node .param('options', (p) => p.required(isRequiredOptions).type( $.type(symbolOptions) .generic(symbolDataType ?? 'unknown') .generic('ThrowOnError'), ), ) .generic('ThrowOnError', (g) => g.extends('boolean').default(false)) .returns($.type(symbolHttpRequest).generic(symbolResponseType ?? 'unknown')) .do( $.return( $('options') .attr('client') .optional() .$if(symbolClient, (c, s) => c.coalesce(s)) .attr('requestOptions') .call( $.object() .prop('responseStyle', $.literal('data')) .prop('method', $.literal(operation.method.toUpperCase())) .prop('url', $.literal(operation.path)) .spread('options'), ) .generic(symbolResponseType ?? 'unknown') .generic('ThrowOnError'), ), ) as T; } function implementHttpResourceFn>(args: { node: T; operation: IR.OperationObject; plugin: AngularCommonPlugin['Instance']; }): T { const { node, operation, plugin } = args; const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, operation, }); const symbolHttpResource = plugin.external('@angular/common/http.httpResource'); const symbolInject = plugin.external('@angular/core.inject'); const symbolOptions = plugin.referenceSymbol({ category: 'type', resource: 'client-options', tool: 'sdk', }); const symbolDataType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'typescript', }); const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', }); return node .param('options', (p) => p.required(isRequiredOptions).type( $.type.func().returns( $.type.or( $.type(symbolOptions) .generic(symbolDataType ?? 'unknown') .generic('ThrowOnError'), $.type('undefined'), ), ), ), ) .generic('ThrowOnError', (g) => g.extends('boolean').default(false)) .do( $.return( $(symbolHttpResource) .call( $.func().do( $.const('opts').assign( $.ternary('options').do($('options').call()).otherwise($.id('undefined')), ), $.return( $.ternary('opts') .do( $.lazy((ctx) => ctx .access(plugin.referenceSymbol(createHttpRequestFnMeta(operation)), { transform: (node, index) => index === 0 ? node['~dsl'] === 'ClassTsDsl' ? $(symbolInject).call($(node.name)) : $(node.name) : node, }) .call('opts'), ), ) .otherwise($.id('undefined')), ), ), ) .generic(symbolResponseType ?? 'unknown'), ), ) as T; } export function toHttpRequestNode( model: StructureNode, plugin: AngularCommonPlugin['Instance'], ): { dependencies?: Array>; nodes: ReadonlyArray>; } { if (model.virtual) { const nodes: Array> = []; for (const item of model.itemsFrom(source)) { const { operation } = item.data; let node = $.const(createHttpRequestFnSymbol(plugin, item)) .export() .assign( implementHttpRequestFn({ node: $.func(), operation, plugin, }), ); node = attachComment({ node, operation, plugin }); nodes.push(node); } return { nodes }; } if (!model.shell) { return { nodes: [] }; } const nodes: Array> = []; const shell = model.shell.define(model); const node = shell.node as ReturnType; let index = 0; for (const item of model.itemsFrom(source)) { const { operation } = item.data; if (index > 0 || node.hasBody) node.newline(); node.do( implementHttpRequestFn({ node: $.method(createHttpRequestFnSymbol(plugin, item), (m) => attachComment({ node: m, operation, plugin, }).public(), ), operation, plugin, }), ); index += 1; } for (const child of model.children.values()) { if (node.hasBody) node.newline(); node.do(...childToHttpRequestNode(child, plugin)); } nodes.push(node); return { dependencies: shell.dependencies as Array>, nodes, }; } export function toHttpResourceNode( model: StructureNode, plugin: AngularCommonPlugin['Instance'], ): { dependencies?: Array>; nodes: ReadonlyArray>; } { if (model.virtual) { const nodes: Array> = []; for (const item of model.itemsFrom(source)) { const { operation } = item.data; let node = $.const(createHttpResourceFnSymbol(plugin, item)) .export() .assign( implementHttpResourceFn({ node: $.func(), operation, plugin, }), ); node = attachComment({ node, operation, plugin }); nodes.push(node); } return { nodes }; } if (!model.shell) { return { nodes: [] }; } const nodes: Array> = []; const shell = model.shell.define(model); const node = shell.node as ReturnType; let index = 0; for (const item of model.itemsFrom(source)) { const { operation } = item.data; if (index > 0 || node.hasBody) node.newline(); node.do( implementHttpResourceFn({ node: $.method(createHttpResourceFnSymbol(plugin, item), (m) => attachComment({ node: m, operation, plugin, }).public(), ), operation, plugin, }), ); index += 1; } for (const child of model.children.values()) { if (node.hasBody) node.newline(); node.do(...childToHttpResourceNode(child, plugin)); } nodes.push(node); return { dependencies: shell.dependencies as Array>, nodes, }; } ================================================ FILE: packages/openapi-ts/src/plugins/@angular/common/types.ts ================================================ import type { DefinePlugin, OperationsStrategy, Plugin } from '@hey-api/shared'; import type { HttpRequestsConfig, UserHttpRequestsConfig } from './httpRequests'; import type { HttpResourcesConfig, UserHttpResourcesConfig } from './httpResources'; export type UserConfig = Plugin.Name<'@angular/common'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Options for generating HTTP Request instances. * * @default 'flat' */ httpRequests?: boolean | OperationsStrategy | UserHttpRequestsConfig; /** * Options for generating HTTP resource APIs. * * @default 'flat' */ httpResources?: boolean | OperationsStrategy | UserHttpResourcesConfig; }; export type Config = Plugin.Name<'@angular/common'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Options for generating HTTP Request instances. */ httpRequests: HttpRequestsConfig; /** * Options for generating HTTP resource APIs. */ httpResources: HttpResourcesConfig; }; export type AngularCommonPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@faker-js/faker/api.ts ================================================ import type { IR } from '@hey-api/shared'; import type { $ } from '../../../ts-dsl'; type Expression = ReturnType; export type IApi = { /** * Generate a Faker expression for a schema. * * Returns an expression that produces a valid instance when executed. * Use when you need one-off generation without referencing shared artifacts. * * @example * ```ts * { * name: faker.person.fullName(), * email: faker.internet.email() * } * ``` */ toNode(schema: IR.SchemaObject): Expression; /** * Get a reference to a generated Faker expression for a schema. * * Returns a call expression referencing the shared artifact. * If the artifact doesn't exist, it will be created. * * @example * // Returns: fakeUser() */ toNodeRef(schema: IR.SchemaObject): Expression; }; export class Api implements IApi { // eslint-disable-next-line @typescript-eslint/no-unused-vars toNode(_schema: IR.SchemaObject): Expression { return undefined as any; } // eslint-disable-next-line @typescript-eslint/no-unused-vars toNodeRef(_schema: IR.SchemaObject): Expression { return undefined as any; } } ================================================ FILE: packages/openapi-ts/src/plugins/@faker-js/faker/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { Api } from './api'; // import { handler } from './plugin'; import type { FakerJsFakerPlugin } from './types'; export const defaultConfig: FakerJsFakerPlugin['Config'] = { api: new Api(), config: { case: 'camelCase', includeInEntry: false, }, // handler, handler: () => {}, name: '@faker-js/faker', resolveConfig: (plugin, context) => { plugin.config.definitions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'v{{name}}', }, mappers, value: plugin.config.definitions, }); }, tags: ['mocker'], }; /** * Type helper for Faker plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@faker-js/faker/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { FakerJsFakerResolvers } from './resolvers/types'; export type { FakerJsFakerPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@faker-js/faker/resolvers/types.ts ================================================ // TODO: later import type { Symbol } from '@hey-api/codegen-core'; import type { Plugin, SchemaWithType } from '@hey-api/shared'; import type { $, DollarTsDsl } from '../../../../ts-dsl'; import type { FakerJsFakerPlugin } from '../types'; type Expression = ReturnType; export type FakerJsFakerResolvers = Plugin.Resolvers<{ array?: (ctx: ArrayResolverContext) => Expression | undefined; number?: (ctx: NumberResolverContext) => Expression | undefined; object?: (ctx: ObjectResolverContext) => Expression | undefined; string?: (ctx: StringResolverContext) => Expression | undefined; }>; interface BaseContext extends DollarTsDsl { plugin: FakerJsFakerPlugin['Instance']; symbols: { faker: Symbol; }; } export interface ArrayResolverContext extends BaseContext { nodes: { items: (ctx: ArrayResolverContext) => Expression; length: (ctx: ArrayResolverContext) => Expression | undefined; }; schema: SchemaWithType<'array'>; } export interface NumberResolverContext extends BaseContext { nodes: { base: (ctx: NumberResolverContext) => Expression; max: (ctx: NumberResolverContext) => Expression | undefined; min: (ctx: NumberResolverContext) => Expression | undefined; }; schema: SchemaWithType<'integer' | 'number'>; } export interface ObjectResolverContext extends BaseContext { nodes: { properties: (ctx: ObjectResolverContext) => Expression; }; schema: SchemaWithType<'object'>; } export interface StringResolverContext extends BaseContext { nodes: { base: (ctx: StringResolverContext) => Expression; format: (ctx: StringResolverContext) => Expression | undefined; pattern: (ctx: StringResolverContext) => Expression | undefined; }; schema: SchemaWithType<'string'>; } ================================================ FILE: packages/openapi-ts/src/plugins/@faker-js/faker/types.ts ================================================ import type { Casing, FeatureToggle, NameTransformer, NamingOptions } from '@hey-api/shared'; import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { IApi } from './api'; export type UserConfig = Plugin.Name<'@faker-js/faker'> & Plugin.Hooks & Plugin.UserExports & { // Resolvers & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for reusable schema definitions. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object */ definitions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'fake{{name}}' */ name?: NameTransformer; }; /** * Faker locale for generated data. * * @default 'en' */ locale?: string; /** * Seed for deterministic output. When set, Faker will produce * the same values across runs. */ seed?: number; }; export type Config = Plugin.Name<'@faker-js/faker'> & Plugin.Hooks & Plugin.Exports & { // Resolvers & { /** * Casing convention for generated names. */ case: Casing; /** * Configuration for reusable schema definitions. */ definitions: NamingOptions & FeatureToggle; /** * Faker locale for generated data. */ locale: string; /** * Seed for deterministic output. When set, Faker will produce * the same values across runs. */ seed?: number; }; export type FakerJsFakerPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/__tests__/client.test.ts ================================================ import type { HttpClient } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; import { createClient } from '../bundle/client'; describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, { options: { query: { bar: [], foo: [], }, url: '/', }, url: '/', }, { options: { query: { bar: [], foo: ['abc', 'def'], }, url: '/', }, url: '/?foo=abc&foo=def', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); it('uses baseUrl from client config by default', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ url: '/foo' })).toBe('https://example.com/foo'); }); it('allows overriding baseUrl from client config', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ baseUrl: 'https://other.com', url: '/foo' })).toBe( 'https://other.com/foo', ); }); }); describe('unserialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); afterEach(() => { vi.restoreAllMocks(); }); const scenarios = [{ body: 0 }, { body: false }, { body: 'test string' }, { body: '' }]; it.each(scenarios)('handles plain text body with $body value', async ({ body }) => { const spy = vi.spyOn(HttpHeaders.prototype, 'delete'); const request = client.requestOptions({ body, bodySerializer: null, httpClient: vi.fn() as Partial as HttpClient, url: '/test', }); expect(request).toMatchObject( expect.objectContaining({ body, }), ); expect(spy).toHaveBeenCalledTimes(0); }); }); describe('requestOptions serialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); afterEach(() => { vi.restoreAllMocks(); }); const scenarios = [ { body: '', expectBodyValue: false, expectDeleteHeader: 1, serializedBody: '', }, { body: 0, expectBodyValue: true, expectDeleteHeader: 0, serializedBody: 0, }, { body: false, expectBodyValue: true, expectDeleteHeader: 0, serializedBody: false, }, { body: {}, expectBodyValue: true, expectDeleteHeader: 0, serializedBody: '{"key":"value"}', }, ]; it.each(scenarios)( 'handles $serializedBody serializedBody value', async ({ body, expectBodyValue, expectDeleteHeader, serializedBody }) => { const spy = vi.spyOn(HttpHeaders.prototype, 'delete'); const request = client.requestOptions({ body, bodySerializer: () => serializedBody, httpClient: vi.fn() as Partial as HttpClient, url: '/test', }); expect(request).toMatchObject( expect.objectContaining({ body: expectBodyValue ? serializedBody : null, }), ); expect(spy).toHaveBeenCalledTimes(expectDeleteHeader); }, ); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/__tests__/utils.test.ts ================================================ import { HttpHeaders } from '@angular/common/http'; import type { Auth } from '../../client-core/bundle/auth'; import type { Client } from '../bundle/types'; import { buildUrl, getParseAs, setAuthParams } from '../bundle/utils'; describe('buildUrl', () => { const scenarios: Array<{ options: Parameters[0]; url: string; }> = [ { options: { path: { id: new Date('2025-01-01T00:00:00.000Z'), }, url: '/foo/{id}', }, url: '/foo/2025-01-01T00:00:00.000Z', }, ]; it.each(scenarios)('builds $url', async ({ options, url }) => { expect(buildUrl(options)).toEqual(url); }); }); describe('getParseAs', () => { const scenarios: Array<{ content: Parameters[0]; parseAs: ReturnType; }> = [ { content: null, parseAs: 'stream', }, { content: 'application/json', parseAs: 'json', }, { content: 'application/ld+json', parseAs: 'json', }, { content: 'application/ld+json;charset=utf-8', parseAs: 'json', }, { content: 'application/ld+json; charset=utf-8', parseAs: 'json', }, { content: 'multipart/form-data', parseAs: 'formData', }, { content: 'application/*', parseAs: 'blob', }, { content: 'audio/*', parseAs: 'blob', }, { content: 'image/*', parseAs: 'blob', }, { content: 'video/*', parseAs: 'blob', }, { content: 'text/*', parseAs: 'text', }, { content: 'unsupported', parseAs: undefined, }, ]; it.each(scenarios)('detects $content as $parseAs', async ({ content, parseAs }) => { expect(getParseAs(content)).toEqual(parseAs); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new HttpHeaders(); const query: Record = {}; const options = { auth, headers, query, security: [ { name: 'baz', scheme: 'bearer' as const, type: 'http' as const, }, ], }; await setAuthParams(options); expect(auth).toHaveBeenCalled(); expect(options.headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new HttpHeaders(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new HttpHeaders(); const query: Record = {}; const options = { auth, headers, query, security: [ { type: 'http' as const, }, ], }; await setAuthParams(options); expect(auth).toHaveBeenCalled(); expect(options.headers.get('Authorization')).toBe('foo'); expect(query).toEqual({}); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new HttpHeaders(); const query: Record = {}; const options = { auth, headers, query, security: [ { name: 'baz', scheme: 'bearer' as const, type: 'http' as const, }, { in: 'query' as const, name: 'baz', scheme: 'bearer' as const, type: 'http' as const, }, ], }; await setAuthParams(options); expect(auth).toHaveBeenCalled(); expect(options.headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers = new HttpHeaders(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets an API key in a cookie', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new HttpHeaders(); const query: Record = {}; const options = { auth, headers, query, security: [ { in: 'cookie' as const, name: 'baz', type: 'apiKey' as const, }, ], }; await setAuthParams(options); expect(auth).toHaveBeenCalled(); expect(options.headers.get('Cookie')).toBe('baz=foo'); expect(query).toEqual({}); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/bundle/client.ts ================================================ import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../../client-core/bundle/serverSentEvents'; import type { HttpMethod } from '../../client-core/bundle/types'; import { getValidRequestBody } from '../../client-core/bundle/utils'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/bundle/index.ts ================================================ export type { Auth } from '../../client-core/bundle/auth'; export type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../../client-core/bundle/bodySerializer'; export { buildClientParams } from '../../client-core/bundle/params'; export { serializeQueryKeyValue } from '../../client-core/bundle/queryKeySerializer'; export { createClient } from './client'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types'; export { createConfig, mergeHeaders } from './utils'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/bundle/types.ts ================================================ import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../../client-core/bundle/auth'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../../client-core/bundle/serverSentEvents'; import type { Client as CoreClient, Config as CoreConfig } from '../../client-core/bundle/types'; import type { Middleware } from './utils'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/bundle/utils.ts ================================================ import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../../client-core/bundle/auth'; import type { QuerySerializer, QuerySerializerOptions, } from '../../client-core/bundle/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../../client-core/bundle/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta, } from '../../../plugins/@hey-api/client-core/config'; import { clientPluginHandler } from '../../../plugins/@hey-api/client-core/plugin'; import type { HeyApiClientAngularPlugin } from './types'; export const defaultConfig: HeyApiClientAngularPlugin['Config'] = { ...clientDefaultMeta, config: { ...clientDefaultConfig, throwOnError: false, }, handler: clientPluginHandler as unknown as HeyApiClientAngularPlugin['Handler'], name: '@hey-api/client-angular', }; /** * Type helper for `@hey-api/client-angular` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/index.ts ================================================ export type { Client as AngularClient } from './bundle/types'; export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientAngularPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-angular/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { Client } from '../../../plugins/@hey-api/client-core/types'; export type UserConfig = Plugin.Name<'@hey-api/client-angular'> & Client.Config & { /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: boolean; }; export type HeyApiClientAngularPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/__tests__/client.test.ts ================================================ import type { AxiosInstance } from 'axios'; import axios from 'axios'; import { createClient } from '../bundle/client'; describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); it('uses baseURL from client config by default', () => { const clientWithBase = createClient({ baseURL: 'https://example.com' }); expect(clientWithBase.buildUrl({ url: '/foo' })).toBe('https://example.com/foo'); }); it('allows overriding baseURL from client config', () => { const clientWithBase = createClient({ baseURL: 'https://example.com' }); expect(clientWithBase.buildUrl({ baseURL: 'https://other.com', url: '/foo' })).toBe( 'https://other.com/foo', ); }); }); describe('AxiosInstance', () => { it('should create an AxiosInstance if no axios option passed', () => { const client = createClient({ baseURL: 'test-url' }); expect(client.instance).toBeDefined(); expect(client.instance.defaults).toBeDefined(); expect(client.instance.defaults.baseURL).toBe('test-url'); }); it('should use the provided AxiosStatic if axios option passed', () => { axios.defaults.baseURL = 'test-url'; const client = createClient({ axios }); expect(client.instance).toBeDefined(); expect(client.instance.defaults).toBeDefined(); expect(client.instance.defaults.baseURL).toBe('test-url'); }); it('should use the provided AxiosInstance if axios option is passed', () => { const axiosInstance = axios.create({ baseURL: 'test-url' }); axiosInstance.interceptors.request.use((config) => config); const client = createClient({ axios: axiosInstance }); expect(client.instance).toBe(axiosInstance); expect(client.instance.defaults.baseURL).toBe('test-url'); expect((client.instance.interceptors.request as any).handlers.length).toBe(1); }); }); describe('unserialized request body handling', () => { const client = createClient({ baseURL: 'https://example.com' }); const scenarios = [{ body: 0 }, { body: false }, { body: 'test string' }, { body: '' }]; it.each(scenarios)('handles plain text body with $body value', async ({ body }) => { const mockAxios = vi.fn(); await client.post({ axios: mockAxios as Partial as AxiosInstance, body, bodySerializer: null, headers: { 'Content-Type': 'text/plain', }, url: '/test', }); expect(mockAxios).toHaveBeenCalledWith( expect.objectContaining({ data: body, }), ); }); }); describe('serialized request body handling', () => { const client = createClient({ baseURL: 'https://example.com' }); const scenarios = [ { body: '', expectBodyValue: false, serializedBody: '', }, { body: 0, expectBodyValue: true, serializedBody: 0, }, { body: false, expectBodyValue: true, serializedBody: false, }, { body: {}, expectBodyValue: true, serializedBody: '{"key":"value"}', }, ]; it.each(scenarios)( 'handles $serializedBody serializedBody value', async ({ body, expectBodyValue, serializedBody }) => { const mockAxios = vi.fn(); await client.post({ axios: mockAxios as Partial as AxiosInstance, body, bodySerializer: () => serializedBody, headers: { 'Content-Type': 'application/json', }, url: '/test', }); expect(mockAxios).toHaveBeenCalledWith( expect.objectContaining({ data: expectBodyValue ? serializedBody : null, }), ); }, ); }); describe('calling axios instance', () => { it.each([ { description: 'with absolute baseURL', expectedURL: 'https://api.example.com/users', instanceBaseURL: 'https://api.example.com', optionsURL: '/users', }, { description: 'without baseURL', expectedURL: '/users', instanceBaseURL: undefined, optionsURL: '/users', }, { description: 'with relative baseURL', expectedURL: '/some-base-url/users', instanceBaseURL: '/some-base-url', optionsURL: '/users', }, ])( 'should call the axios instance with correct baseURL and url $description configured via createClient', async ({ expectedURL, instanceBaseURL, optionsURL }) => { const client = createClient({ baseURL: instanceBaseURL }); const mockAxios = vi.fn().mockResolvedValue({ data: { ok: true } }); const options = { axios: mockAxios as Partial as AxiosInstance, headers: {}, url: optionsURL, }; await client.get(options); expect(mockAxios).toHaveBeenCalledWith( expect.objectContaining({ baseURL: '', url: expectedURL, }), ); }, ); it.each([ { description: 'with absolute baseURL', expectedURL: 'https://api.example.com/some-base-url/users', optionsBaseURL: 'https://api.example.com/some-base-url', optionsURL: '/users', }, { description: 'with relative baseURL', expectedURL: '/some-base-url/users', optionsBaseURL: '/some-base-url', optionsURL: '/users', }, ])( 'should call the axios instance with correct url $description configured via request options', async ({ expectedURL, optionsBaseURL, optionsURL }) => { const client = createClient({ baseURL: 'base-url-that-will-be-overridden', }); const mockAxios = vi.fn().mockResolvedValue({ data: { ok: true } }); const options = { axios: mockAxios as Partial as AxiosInstance, baseURL: optionsBaseURL, headers: {}, url: optionsURL, }; await client.get(options); expect(mockAxios).toHaveBeenCalledWith( expect.objectContaining({ baseURL: '', url: expectedURL, }), ); }, ); it('should call the axios instance with correct url when baseURL configured via axios defaults', async () => { const client = createClient(); const mockAxios = vi.fn().mockResolvedValue({ data: { ok: true }, }) as Partial as AxiosInstance; mockAxios.defaults = { baseURL: '/some-base-url', headers: {} as any }; const options = { axios: mockAxios, headers: {}, url: '/users', }; await client.get(options); expect(mockAxios).toHaveBeenCalledWith( expect.objectContaining({ baseURL: '', url: '/some-base-url/users', }), ); }); it('should prefer passed baseUrl over configs', async () => { const client = createClient({ baseURL: 'base-url-from-config-1' }); const mockAxios = vi.fn().mockResolvedValue({ data: { ok: true }, }) as Partial as AxiosInstance; mockAxios.defaults = { baseURL: 'base-url-from-config-2', headers: {} as any, }; const options = { axios: mockAxios, baseURL: '/some-base-url', headers: {}, url: '/users', }; await client.get(options); expect(mockAxios).toHaveBeenCalledWith( expect.objectContaining({ baseURL: '', url: '/some-base-url/users', }), ); }); }); // TODO: remove this after confirmation describe('confirming axios behaviour for constructing URLs', () => { it('resolves relative URLs against baseURL', async () => { const client = axios.create({ baseURL: 'https://api.example.com', }); const config = client.getUri({ url: '/users' }); expect(config).toBe('https://api.example.com/users'); }); it('resolves relative URLs against relative baseURL', async () => { const client = axios.create({ baseURL: '/example', }); const config = client.getUri({ url: '/users' }); expect(config).toBe('/example/users'); }); it('does not prepend baseURL when url is absolute', async () => { const client = axios.create({ baseURL: 'https://api.example.com', }); const config = client.getUri({ url: 'https://other.com/users' }); expect(config).toBe('https://other.com/users'); }); it('does not prepend baseURL when overriding baseURL with empty string', async () => { const client = axios.create({ baseURL: 'https://api.example.com', }); const config = client.getUri({ baseURL: '', url: '/users' }); expect(config).toBe('/users'); }); it('does prepend baseURL when overriding baseURL with undefined', async () => { const client = axios.create({ baseURL: 'https://api.example.com', }); const config = client.getUri({ baseURL: undefined, url: '/users' }); expect(config).toBe('https://api.example.com/users'); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/__tests__/utils-buildUrl.test.ts ================================================ import type { QuerySerializer } from '../../client-core/bundle/bodySerializer'; describe('buildUrl', () => { afterEach(() => { vi.resetAllMocks(); vi.resetModules(); }); it.each([ { description: 'with query params', expectedUrl: '/some-url?param1=some-query-param', inputOptions: { baseUrl: 'some-base-url', path: { param1: 'some-path-param' }, query: { param1: 'some-query-param' }, querySerializer: (() => 'param1=some-query-param') as QuerySerializer, url: '/some-url', }, }, { description: 'without query params', expectedUrl: '/some-url', inputOptions: { baseURL: 'some-base-url', path: { param1: 'some-path-param' }, query: undefined, querySerializer: (() => '') as QuerySerializer, url: '/some-url', }, }, ])('passes correct parameters to getUrl $description', async ({ expectedUrl, inputOptions }) => { const getUrlMock = vi.fn().mockReturnValue(expectedUrl); vi.doMock('../../client-core/bundle/utils', async () => ({ getUrl: getUrlMock, })); const { buildUrl } = await import('../bundle/utils'); const builtUrl = buildUrl(inputOptions); expect(builtUrl).toBe(expectedUrl); expect(getUrlMock).toHaveBeenCalledExactlyOnceWith({ baseUrl: inputOptions.baseURL, path: inputOptions.path, query: inputOptions.query, querySerializer: inputOptions.querySerializer, url: inputOptions.url, }); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/__tests__/utils.test.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import { axiosHeadersKeywords, mergeHeaders, setAuthParams } from '../bundle/utils'; describe('mergeHeaders', () => { it.each(axiosHeadersKeywords)('handles "%s" Axios special keyword', (keyword) => { const headers = mergeHeaders( { foo: 'foo', }, { [keyword]: { foo: 'foo', }, }, ); expect(headers).toEqual({ foo: 'foo', [keyword]: { foo: 'foo', }, }); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers: Record = {}; const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.baz).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers: Record = {}; const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.baz).toBeUndefined(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers: Record = {}; const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.Authorization).toBe('foo'); expect(query).toEqual({}); }); it('sets an API key in a cookie', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers: Record = {}; const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'cookie', name: 'baz', type: 'apiKey', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.Cookie).toBe('baz=foo'); expect(query).toEqual({}); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers: Record = {}; const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.baz).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers: Record = {}; const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.baz).toBeUndefined(); expect(query.baz).toBe('Bearer foo'); }); it('sets only one specific header', async () => { const auth = vi.fn(({ name }: Auth) => { if (name === 'baz') { return 'foo'; } return 'buz'; }); const headers: Record = {}; const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { name: 'fiz', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers['baz']).toBe('Bearer foo'); expect(headers['fiz']).toBe('buz'); expect(Object.keys(query).length).toBe(0); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/bundle/client.ts ================================================ import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../../client-core/bundle/serverSentEvents'; import type { HttpMethod } from '../../client-core/bundle/types'; import { getValidRequestBody } from '../../client-core/bundle/utils'; import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/bundle/index.ts ================================================ export type { Auth } from '../../client-core/bundle/auth'; export type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../../client-core/bundle/bodySerializer'; export { buildClientParams } from '../../client-core/bundle/params'; export { serializeQueryKeyValue } from '../../client-core/bundle/queryKeySerializer'; export { createClient } from './client'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/bundle/types.ts ================================================ import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../../client-core/bundle/auth'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../../client-core/bundle/serverSentEvents'; import type { Client as CoreClient, Config as CoreConfig } from '../../client-core/bundle/types'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/bundle/utils.ts ================================================ import { getAuthToken } from '../../client-core/bundle/auth'; import type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../../client-core/bundle/pathSerializer'; import { getUrl } from '../../client-core/bundle/utils'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta, } from '../../../plugins/@hey-api/client-core/config'; import { clientPluginHandler } from '../../../plugins/@hey-api/client-core/plugin'; import type { HeyApiClientAxiosPlugin } from './types'; export const defaultConfig: HeyApiClientAxiosPlugin['Config'] = { ...clientDefaultMeta, config: { ...clientDefaultConfig, throwOnError: false, }, handler: clientPluginHandler as unknown as HeyApiClientAxiosPlugin['Handler'], name: '@hey-api/client-axios', }; /** * Type helper for `@hey-api/client-axios` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/index.ts ================================================ export type { Client as AxiosClient } from './bundle/types'; export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientAxiosPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-axios/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { Client } from '../../../plugins/@hey-api/client-core/types'; export type UserConfig = Plugin.Name<'@hey-api/client-axios'> & Client.Config & { /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: boolean; }; export type HeyApiClientAxiosPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/__tests__/auth.test.ts ================================================ import { getAuthToken } from '../bundle/auth'; describe('getAuthToken', () => { it('returns bearer token', async () => { const auth = vi.fn().mockReturnValue('foo'); const token = await getAuthToken( { scheme: 'bearer', type: 'http', }, auth, ); expect(auth).toHaveBeenCalled(); expect(token).toBe('Bearer foo'); }); it('returns basic token', async () => { const auth = vi.fn().mockReturnValue('foo:bar'); const token = await getAuthToken( { scheme: 'basic', type: 'http', }, auth, ); expect(auth).toHaveBeenCalled(); expect(token).toBe(`Basic ${btoa('foo:bar')}`); }); it('returns raw token', async () => { const auth = vi.fn().mockReturnValue('foo'); const token = await getAuthToken( { type: 'http', }, auth, ); expect(auth).toHaveBeenCalled(); expect(token).toBe('foo'); }); it('returns nothing when auth function is undefined', async () => { const token = await getAuthToken( { type: 'http', }, undefined, ); expect(token).toBeUndefined(); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/__tests__/bodySerializer.test.ts ================================================ import { formDataBodySerializer } from '../bundle/bodySerializer'; describe('formDataBodySerializer', () => { it('serializes number', () => { const body = { a: 1 }; const formData = formDataBodySerializer.bodySerializer(body); expect(formData.get('a')).toBe('1'); }); it('serializes string', () => { const body = { a: 'foo' }; const formData = formDataBodySerializer.bodySerializer(body); expect(formData.get('a')).toBe('foo'); }); it('serializes date', () => { const body = { a: new Date('2025-01-01T00:00:00.000Z') }; const formData = formDataBodySerializer.bodySerializer(body); expect(formData.get('a')).toBe('2025-01-01T00:00:00.000Z'); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/__tests__/params.test.ts ================================================ import type { FieldsConfig } from '../bundle/params'; import { buildClientParams } from '../bundle/params'; describe('buildClientParams', () => { const scenarios: ReadonlyArray<{ args: ReadonlyArray; config: FieldsConfig; description: string; params: Record; }> = [ { args: [1, 2, 3, 4], config: [ { in: 'path', key: 'foo', }, { in: 'query', key: 'bar', }, { in: 'headers', key: 'baz', }, { in: 'body', key: 'qux', }, ], description: 'positional arguments', params: { body: { qux: 4, }, headers: { baz: 3, }, path: { foo: 1, }, query: { bar: 2, }, }, }, { args: [ { bar: 2, baz: 3, foo: 1, qux: 4, }, ], config: [ { args: [ { in: 'path', key: 'foo', }, { in: 'query', key: 'bar', }, { in: 'headers', key: 'baz', }, { in: 'body', key: 'qux', }, ], }, ], description: 'flat arguments', params: { body: { qux: 4, }, headers: { baz: 3, }, path: { foo: 1, }, query: { bar: 2, }, }, }, { args: [ 1, 2, { baz: 3, qux: 4, }, ], config: [ { in: 'path', key: 'foo', }, { in: 'query', key: 'bar', }, { args: [ { in: 'headers', key: 'baz', }, { in: 'body', key: 'qux', }, ], }, ], description: 'mixed arguments', params: { body: { qux: 4, }, headers: { baz: 3, }, path: { foo: 1, }, query: { bar: 2, }, }, }, { args: [1, 2, 3, 4], config: [ { in: 'path', key: 'foo', map: 'f_o_o', }, { in: 'query', key: 'bar', map: 'b_a_r', }, { in: 'headers', key: 'baz', map: 'b_a_z', }, { in: 'body', key: 'qux', map: 'q_u_x', }, ], description: 'positional mapped arguments', params: { body: { q_u_x: 4, }, headers: { b_a_z: 3, }, path: { f_o_o: 1, }, query: { b_a_r: 2, }, }, }, { args: [ { bar: 2, baz: 3, foo: 1, qux: 4, }, ], config: [ { args: [ { in: 'path', key: 'foo', map: 'f_o_o', }, { in: 'query', key: 'bar', map: 'b_a_r', }, { in: 'headers', key: 'baz', map: 'b_a_z', }, { in: 'body', key: 'qux', map: 'q_u_x', }, ], }, ], description: 'flat mapped arguments', params: { body: { q_u_x: 4, }, headers: { b_a_z: 3, }, path: { f_o_o: 1, }, query: { b_a_r: 2, }, }, }, { args: [1], config: [ { in: 'body', }, ], description: 'positional primitive body', params: { body: 1, }, }, { args: [ { foo: 1, }, ], config: [ { key: 'foo', map: 'body', }, ], description: 'alias flat body', params: { body: 1, }, }, { args: [ { bar: 2, baz: 3, foo: 1, qux: 4, }, ], config: [ { in: 'body', }, ], description: 'positional complex body', params: { body: { bar: 2, baz: 3, foo: 1, qux: 4, }, }, }, { args: [ { $body_qux: 4, $headers_baz: 3, $path_foo: 1, $query_bar: 2, }, ], config: [ { allowExtra: {}, }, ], description: 'namespace extra arguments', params: { body: { qux: 4, }, headers: { baz: 3, }, path: { foo: 1, }, query: { bar: 2, }, }, }, { args: [ { bar: 2, baz: 3, foo: 1, qux: 4, }, ], config: [ { allowExtra: { query: true, }, }, ], description: 'slot extra arguments', params: { query: { bar: 2, baz: 3, foo: 1, qux: 4, }, }, }, { args: [], config: [], description: 'strip empty slots', params: {}, }, { args: [[]], config: [ { in: 'body', }, ], description: 'empty array body', params: { body: [], }, }, ]; it.each(scenarios)('$description', async ({ args, config, params }) => { expect(buildClientParams(args, config)).toEqual(params); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/__tests__/queryKeySerializer.test.ts ================================================ import { queryKeyJsonReplacer, serializeQueryKeyValue, stringifyToJsonValue, } from '../bundle/queryKeySerializer'; describe('query key helpers', () => { describe('queryKeyJsonReplacer', () => { it('converts bigint to string', () => { expect(queryKeyJsonReplacer('value', 1n)).toBe('1'); }); it('converts Date to ISO string', () => { const date = new Date('2025-01-01T12:34:56.000Z'); expect(queryKeyJsonReplacer('value', date)).toBe(date.toISOString()); }); it('drops unsupported values', () => { expect(queryKeyJsonReplacer('value', undefined)).toBeUndefined(); expect(queryKeyJsonReplacer('value', () => {})).toBeUndefined(); expect(queryKeyJsonReplacer('value', Symbol('s'))).toBeUndefined(); }); }); describe('stringifyToJsonValue', () => { it('produces JSON-safe structures', () => { const input = { a: 1n, b: new Date('2025-01-02T00:00:00.000Z'), c: () => {}, d: undefined, }; expect(stringifyToJsonValue(input)).toEqual({ a: '1', b: '2025-01-02T00:00:00.000Z', }); }); it('returns undefined when value cannot be stringified', () => { const circular: { self?: unknown } = {}; circular.self = circular; expect(stringifyToJsonValue(circular)).toBeUndefined(); }); }); describe('serializeQueryKeyValue', () => { it('handles primitives and null', () => { expect(serializeQueryKeyValue(null)).toBeNull(); expect(serializeQueryKeyValue('')).toBe(''); expect(serializeQueryKeyValue(0)).toBe(0); expect(serializeQueryKeyValue(false)).toBe(false); }); it('converts special primitives', () => { expect(serializeQueryKeyValue(1n)).toBe('1'); const date = new Date('2025-03-04T05:06:07.000Z'); expect(serializeQueryKeyValue(date)).toBe(date.toISOString()); }); it('normalizes arrays', () => { const date = new Date('2025-03-04T05:06:07.000Z'); expect(serializeQueryKeyValue([1n, date, undefined, () => {}, 'ok'])).toEqual([ '1', date.toISOString(), null, null, 'ok', ]); }); it('normalizes plain objects', () => { const result = serializeQueryKeyValue({ a: 1, b: 1n, c: new Date('2025-06-07T08:09:10.000Z'), d: undefined, e: () => {}, }); expect(result).toEqual({ a: 1, b: '1', c: '2025-06-07T08:09:10.000Z', }); }); it('supports objects with null prototype', () => { const value = Object.assign(Object.create(null), { a: 1 }); expect(serializeQueryKeyValue(value)).toEqual({ a: 1 }); }); it('serializes URLSearchParams as JSON object', () => { const params = new URLSearchParams(); params.append('a', '1'); params.append('a', '2'); params.append('b', 'foo'); expect(serializeQueryKeyValue(params)).toEqual({ a: ['1', '2'], b: 'foo', }); }); it('rejects unsupported structures', () => { expect(serializeQueryKeyValue(new Map())).toBeUndefined(); expect(serializeQueryKeyValue(new Set())).toBeUndefined(); expect(serializeQueryKeyValue(new (class Example {})())).toBeUndefined(); }); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/__tests__/serverSentEvents.test.ts ================================================ import { createSseClient } from '../bundle/serverSentEvents'; function makeStream(chunks: string[]) { let index = 0; return new ReadableStream({ pull(controller) { if (index < chunks.length) { controller.enqueue(new TextEncoder().encode(chunks[index])); index++; } else { controller.close(); } }, }); } function toRequest(input: RequestInfo, init?: RequestInit): Request { if (input instanceof Request) { const url = input.url.startsWith('http') ? input.url : `http://localhost${input.url}`; return new Request(url, input); } const url = input.startsWith('http') ? input : `http://localhost${input}`; return new Request(url, init); } describe('createSseClient', () => { let fetchMock: any; beforeEach(() => { fetchMock = vi.fn(); global.fetch = fetchMock; }); afterEach(() => { vi.restoreAllMocks(); }); it('yields parsed JSON events', async () => { fetchMock.mockResolvedValue({ body: makeStream(['id: 1\nevent: test\ndata: {"foo":"bar"}\n\n']), ok: true, }); const onEvent = vi.fn(); const { stream } = createSseClient({ onSseEvent: onEvent, url: 'http://localhost/sse', }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([{ foo: 'bar' }]); expect(onEvent).toHaveBeenCalledWith({ data: { foo: 'bar' }, event: 'test', id: '1', retry: 3000, }); }); it('falls back to raw string if not valid JSON', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: hello\n\n']), ok: true, }); const { stream } = createSseClient({ url: 'http://localhost/sse' }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual(['hello']); }); it('calls onSseError when response not ok', async () => { fetchMock.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error', text: async () => 'fail', }); const onError = vi.fn(); const controller = new AbortController(); const { stream } = createSseClient({ onSseError: onError, signal: controller.signal, sseDefaultRetryDelay: 0, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const promise = iter.next().catch(() => {}); controller.abort(); await promise; expect(onError).toHaveBeenCalled(); const error = onError.mock.calls[0]![0]; expect(error).toBeInstanceOf(Error); expect((error as Error).message).toContain('SSE failed'); }); it('respects retry from server', async () => { fetchMock.mockResolvedValue({ body: makeStream(['retry: 1234\ndata: "x"\n\n']), ok: true, }); const onEvent = vi.fn(); const { stream } = createSseClient({ onSseEvent: onEvent, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); await iter.return?.(); expect(onEvent).toHaveBeenCalledWith({ data: 'x', event: undefined, id: undefined, retry: 1234, }); }); it('yields multiple events in one stream', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: 1\n\n', 'data: 2\n\n', 'data: 3\n\n']), ok: true, }); const { stream } = createSseClient({ url: 'http://localhost/sse' }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([1, 2, 3]); }); it('handles partial chunks correctly', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: par', 'tial\n\n']), ok: true, }); const { stream } = createSseClient({ url: 'http://localhost/sse' }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual(['partial']); }); it('sets Last-Event-ID header on reconnect', async () => { let headersSeen: string | null | undefined; fetchMock.mockImplementation(async (input: RequestInfo, init?: RequestInit) => { const req = toRequest(input, init); headersSeen = req.headers.get('Last-Event-ID'); return { body: makeStream(['data: a\n\n']), ok: true, }; }); const onEvent = vi.fn(); const { stream } = createSseClient({ onSseEvent: onEvent, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); await iter.return?.(); // simulate next fetch after reconnect await fetchMock('http://localhost/sse', { headers: new Headers({ 'Last-Event-ID': '1' }), }); expect(headersSeen).toBe('1'); }); it('stops cleanly when aborted', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: stop\n\n']), ok: true, }); const controller = new AbortController(); const { stream } = createSseClient({ signal: controller.signal, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const first = await iter.next(); expect(first).toEqual({ done: false, value: 'stop' }); controller.abort(); const second = await iter.next(); expect(second).toEqual({ done: true, value: undefined }); }); it('handles mixed JSON and raw string events', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: {"foo":1}\n\n', 'data: bar\n\n', 'data: {"baz":2}\n\n']), ok: true, }); const { stream } = createSseClient({ url: 'http://localhost/sse' }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([{ foo: 1 }, 'bar', { baz: 2 }]); }); it('passes custom headers', async () => { let headersSeen: string | null | undefined; fetchMock.mockImplementation(async (input: RequestInfo, init?: RequestInit) => { const req = toRequest(input, init); headersSeen = req.headers.get('X-Custom'); return { body: makeStream([]), ok: true, }; }); const { stream } = createSseClient({ headers: { 'X-Custom': 'abc' }, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); await iter.return?.(); expect(headersSeen).toBe('abc'); }); it('handles chunked JSON across multiple SSE messages', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: {"foo":', '"bar"}\n\n']), ok: true, }); const { stream } = createSseClient({ url: 'http://localhost/sse' }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([{ foo: 'bar' }]); }); it('handles empty stream', async () => { fetchMock.mockResolvedValue({ body: makeStream([]), ok: true }); const { stream } = createSseClient({ url: 'http://localhost/sse' }); const iter = stream[Symbol.asyncIterator](); const first = await iter.next(); expect(first).toEqual({ done: true, value: undefined }); }); it('respects retryDelay on rapid reconnects', async () => { let attempt = 0; fetchMock.mockImplementation(async () => { attempt++; if (attempt < 2) throw new Error('fail'); return { body: makeStream(['data: ok\n\n']), ok: true, }; }); const onError = vi.fn(); const { stream } = createSseClient({ onSseError: onError, sseDefaultRetryDelay: 0, url: 'http://localhost/sse', }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(onError).toHaveBeenCalled(); expect(result).toEqual(['ok']); }); it('ignores invalid retry values', async () => { fetchMock.mockResolvedValue({ body: makeStream(['retry: not-a-number\ndata: x\n\n']), ok: true, }); const onEvent = vi.fn(); const { stream } = createSseClient({ onSseEvent: onEvent, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const ev = await iter.next(); expect(ev.value).toBe('x'); expect(onEvent.mock.calls[0]![0].retry).toBe(3000); // default }); it('handles events with no data lines gracefully', async () => { fetchMock.mockResolvedValue({ body: makeStream(['event: noop\nid: 1\n\n']), ok: true, }); const onEvent = vi.fn(); const { stream } = createSseClient({ onSseEvent: onEvent, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const ev = await iter.next(); expect(ev.done).toBe(true); expect(onEvent).toHaveBeenCalledWith({ data: undefined, event: 'noop', id: '1', retry: 3000, }); }); it('yields raw string on JSON parse error without calling onSseError', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: {"foo": unquoted}\n\n']), ok: true, }); const onEvent = vi.fn(); const onError = vi.fn(); const { stream } = createSseClient({ onSseError: onError, onSseEvent: onEvent, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const ev = await iter.next(); expect(ev.value).toBe('{"foo": unquoted}'); expect(onError).not.toHaveBeenCalled(); }); it('handles multiple aborts without throwing', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: a\n\n']), ok: true, }); const controller = new AbortController(); const { stream } = createSseClient({ signal: controller.signal, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); controller.abort(); await expect(iter.next()).resolves.toEqual({ done: true, value: undefined, }); controller.abort(); await expect(iter.next()).resolves.toEqual({ done: true, value: undefined, }); }); it('stops immediately if signal is already aborted', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: a\n\n']), ok: true, }); const controller = new AbortController(); controller.abort(); const { stream } = createSseClient({ signal: controller.signal, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const ev = await iter.next(); expect(ev).toEqual({ done: true, value: undefined }); }); it('respects custom HTTP method', async () => { let methodSeen: string | undefined; fetchMock.mockImplementation(async (input: RequestInfo, init?: RequestInit) => { const req = toRequest(input, init); methodSeen = req.method; return { body: makeStream(['data: ok\n\n']), ok: true, }; }); const { stream } = createSseClient({ method: 'POST', url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); await iter.return?.(); expect(methodSeen).toBe('POST'); }); it('respects external AbortSignal', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: x\n\n']), ok: true, }); const controller = new AbortController(); const { stream } = createSseClient({ signal: controller.signal, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const first = await iter.next(); expect(first.value).toBe('x'); controller.abort(); const second = await iter.next(); expect(second.done).toBe(true); }); it('ignores empty data but updates lastEventId', async () => { let lastEventId: string | undefined; fetchMock.mockImplementation(async () => ({ body: makeStream(['id: 99\ndata:\n\n']), ok: true, })); const { stream } = createSseClient({ onSseEvent: (ev) => { lastEventId = ev.id; }, url: 'http://localhost/sse', }); stream[Symbol.asyncIterator](); // pull all events until done // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _ of stream) { /* noop */ } expect(lastEventId).toBe('99'); }); it('stops retrying after sseMaxRetryAttempts is reached', async () => { let attempt = 0; fetchMock.mockImplementation(async () => { attempt++; throw new Error('fail'); }); const onError = vi.fn(); const { stream } = createSseClient({ onSseError: onError, sseDefaultRetryDelay: 0, sseMaxRetryAttempts: 2, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const result = await iter.next(); expect(result.done).toBe(true); expect(onError).toHaveBeenCalledTimes(2); // once per failed attempt expect(attempt).toBe(2); }); it('applies exponential backoff between retries', async () => { let attempt = 0; fetchMock.mockImplementation(() => { attempt++; if (attempt < 3) throw new Error('fail'); return Promise.resolve({ body: makeStream(['data: ok\n\n']), ok: true, }); }); const onError = vi.fn(); const { stream } = createSseClient({ onSseError: onError, sseDefaultRetryDelay: 10, // Inject a fake sleep that resolves instantly sseSleepFn: async () => {}, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const ev = await iter.next(); expect(ev.value).toBe('ok'); expect(onError).toHaveBeenCalledTimes(2); expect(attempt).toBe(3); }); it('does not retry when sseMaxRetryAttempts is 0', async () => { let attempt = 0; fetchMock.mockImplementation(async () => { attempt++; throw new Error('fail'); }); const onError = vi.fn(); const { stream } = createSseClient({ onSseError: onError, sseMaxRetryAttempts: 0, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); const result = await iter.next(); expect(result.done).toBe(true); expect(onError).toHaveBeenCalledTimes(1); expect(attempt).toBe(1); }); it('calls responseValidator before yielding JSON', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: {"foo": "bar"}\n\n']), ok: true, }); const validator = vi.fn(async (data) => { if (!('foo' in (data as any))) throw new Error('Missing foo'); }); const { stream } = createSseClient({ responseValidator: validator, url: 'http://localhost/sse', }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([{ foo: 'bar' }]); expect(validator).toHaveBeenCalledTimes(1); }); it('calls responseTransformer before yielding JSON', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: {"num": 2}\n\n']), ok: true, }); const transformer = vi.fn(async (data) => ({ doubled: (data as any).num * 2, })); const { stream } = createSseClient({ responseTransformer: transformer, url: 'http://localhost/sse', }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([{ doubled: 4 }]); expect(transformer).toHaveBeenCalledTimes(1); }); it('validator error triggers onSseError and retry', async () => { let attempt = 0; fetchMock.mockImplementation(async () => { attempt++; return { body: makeStream(['data: {"foo": "bar"}\n\n']), ok: true, }; }); const validator = vi.fn(async () => { throw new Error('invalid'); }); const onError = vi.fn(); const { stream } = createSseClient({ onSseError: onError, responseValidator: validator, sseDefaultRetryDelay: 0, sseMaxRetryAttempts: 1, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next().catch(() => {}); expect(onError).toHaveBeenCalledTimes(1); expect(attempt).toBe(1); }); it('skips validator/transformer for non-JSON events', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: rawstring\n\n']), ok: true, }); const validator = vi.fn(); const transformer = vi.fn(); const { stream } = createSseClient({ responseTransformer: transformer, responseValidator: validator, url: 'http://localhost/sse', }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual(['rawstring']); expect(validator).not.toHaveBeenCalled(); expect(transformer).not.toHaveBeenCalled(); }); it('handles CRLF line endings', async () => { fetchMock.mockResolvedValue({ body: makeStream(['id: 1\r\nevent: test\r\ndata: {"foo":"bar"}\r\n\r\n']), ok: true, }); const onEvent = vi.fn(); const { stream } = createSseClient({ onSseEvent: onEvent, url: 'http://localhost/sse', }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([{ foo: 'bar' }]); expect(onEvent).toHaveBeenCalledWith({ data: { foo: 'bar' }, event: 'test', id: '1', retry: 3000, }); }); it('handles CR-only line endings', async () => { fetchMock.mockResolvedValue({ body: makeStream(['id: 2\revent: test\rdata: {"baz":"qux"}\r\r']), ok: true, }); const onEvent = vi.fn(); const { stream } = createSseClient({ onSseEvent: onEvent, url: 'http://localhost/sse', }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([{ baz: 'qux' }]); expect(onEvent).toHaveBeenCalledWith({ data: { baz: 'qux' }, event: 'test', id: '2', retry: 3000, }); }); it('handles mixed line endings in a single stream', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: 1\n\n', 'data: 2\r\n\r\n', 'data: 3\r\r']), ok: true, }); const { stream } = createSseClient({ url: 'http://localhost/sse' }); const result: any[] = []; for await (const ev of stream) result.push(ev); expect(result).toEqual([1, 2, 3]); }); }); describe('serialized request body handling', () => { let fetchMock: any; beforeEach(() => { fetchMock = vi.fn(); global.fetch = fetchMock; }); afterEach(() => { vi.restoreAllMocks(); }); it('sends serialized JSON body in SSE request', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: ok\n\n']), ok: true, }); const jsonBody = { key: 'value' }; const serializedBody = JSON.stringify(jsonBody); const { stream } = createSseClient({ body: jsonBody as any, method: 'POST', serializedBody, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); await iter.return?.(); expect(fetchMock).toHaveBeenCalled(); const request = fetchMock.mock.calls[0]![0]; expect(request).toBeInstanceOf(Request); await expect(request.text()).resolves.toBe(serializedBody); }); it('handles empty string serializedBody', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: ok\n\n']), ok: true, }); const { stream } = createSseClient({ body: '' as any, method: 'POST', serializedBody: '', url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); await iter.return?.(); expect(fetchMock).toHaveBeenCalled(); const request = fetchMock.mock.calls[0]![0]; expect(request).toBeInstanceOf(Request); await expect(request.text()).resolves.toBe(''); }); it('provides serialized body to onRequest hook', async () => { fetchMock.mockResolvedValue({ body: makeStream(['data: ok\n\n']), ok: true, }); const jsonBody = { key: 'value' }; const serializedBody = JSON.stringify(jsonBody); const onRequest = vi.fn(async (url: string, init: RequestInit) => { expect(init.body).toBe(serializedBody); return toRequest(url, init); }); const { stream } = createSseClient({ body: jsonBody as any, method: 'POST', onRequest, serializedBody, url: 'http://localhost/sse', }); const iter = stream[Symbol.asyncIterator](); await iter.next(); await iter.return?.(); expect(onRequest).toHaveBeenCalledWith( 'http://localhost/sse', expect.objectContaining({ body: serializedBody, method: 'POST', }), ); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/__tests__/utils.test.ts ================================================ import { getValidRequestBody } from '../../client-core/bundle/utils'; describe('getValidRequestBody', () => { const noBodySerializer = [ { body: '' }, { body: 0 }, { body: false }, { body: 'test string' }, { body: null }, { body: undefined }, ].map(({ body }) => ({ expectedBody: body, options: { body, bodySerializer: null, serializedBody: 'ignore' }, })); const hasBodySerializer = [ { body: '', expectedBody: null }, { body: 0, expectedBody: 0 }, { body: false, expectedBody: false }, { body: '{"key":"value"}', expectedBody: '{"key":"value"}' }, { body: null, expectedBody: null }, { body: undefined, expectedBody: undefined }, ].map(({ body, expectedBody }) => ({ expectedBody, options: { body, bodySerializer: () => {} }, })); const hasBodySerializerAndSerializedBodyProperty = [ { body: '', expectedBody: null, serializedBody: '' }, { body: 0, expectedBody: 0, serializedBody: 0 }, { body: false, expectedBody: false, serializedBody: false }, { body: {}, expectedBody: '{"key":"value"}', serializedBody: '{"key":"value"}', }, { body: null, expectedBody: 'foo', serializedBody: 'foo' }, { body: undefined, expectedBody: undefined, serializedBody: undefined }, ].map(({ body, expectedBody, serializedBody }) => ({ expectedBody, options: { body, bodySerializer: () => {}, serializedBody }, })); it.each(noBodySerializer)( 'returns $expectedBody when unserialized body value is $options.body', ({ expectedBody, options }) => { expect(getValidRequestBody(options)).toBe(expectedBody); }, ); it.each(hasBodySerializer)( 'evaluates body and returns $expectedBody when serialized value is $options.body', ({ expectedBody, options }) => { expect(getValidRequestBody(options)).toBe(expectedBody); }, ); it.each(hasBodySerializerAndSerializedBodyProperty)( 'evaluates serializedBody and returns $expectedBody when value is $options.serializedBody', ({ expectedBody, options }) => { expect(getValidRequestBody(options)).toBe(expectedBody); }, ); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/queryKeySerializer.ts ================================================ /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/serverSentEvents.ts ================================================ import type { Config } from './types'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/bundle/utils.ts ================================================ import type { BodySerializer, QuerySerializer } from './bodySerializer'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/client.ts ================================================ import { parseUrl } from '@hey-api/shared'; import { getTypedConfig } from '../../../config/utils'; import { clientFolderAbsolutePath } from '../../../generate/client'; import { $ } from '../../../ts-dsl'; import type { PluginHandler } from './types'; import { getClientBaseUrlKey } from './utils'; const resolveBaseUrlString = ({ plugin }: Parameters[0]): string | undefined => { const { baseUrl } = plugin.config; if (baseUrl === false) { return; } if (typeof baseUrl === 'string') { return baseUrl; } const { servers } = plugin.context.ir; if (!servers) { return; } return servers[typeof baseUrl === 'number' ? baseUrl : 0]?.url; }; export const createClient: PluginHandler = ({ plugin }) => { const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin)); const symbolCreateClient = plugin.symbol('createClient', { external: clientModule, }); const symbolCreateConfig = plugin.symbol('createConfig', { external: clientModule, }); const symbolClientOptions = plugin.referenceSymbol({ category: 'type', resource: 'client', role: 'options', }); const { runtimeConfigPath } = plugin.config; const symbolCreateClientConfig = runtimeConfigPath ? plugin.symbol('createClientConfig', { external: runtimeConfigPath, }) : undefined; const defaultVals = $.object(); const resolvedBaseUrl = resolveBaseUrlString({ plugin: plugin as any, }); if (resolvedBaseUrl) { const url = parseUrl(resolvedBaseUrl); if (url.protocol && url.host && !resolvedBaseUrl.includes('{')) { defaultVals.prop(getClientBaseUrlKey(getTypedConfig(plugin)), $.literal(resolvedBaseUrl)); } else if (resolvedBaseUrl !== '/' && resolvedBaseUrl.startsWith('/')) { const baseUrl = resolvedBaseUrl.endsWith('/') ? resolvedBaseUrl.slice(0, -1) : resolvedBaseUrl; defaultVals.prop(getClientBaseUrlKey(getTypedConfig(plugin)), $.literal(baseUrl)); } } if ('throwOnError' in plugin.config && plugin.config.throwOnError) { defaultVals.prop('throwOnError', $.literal(true)); } const createConfigParameters = [ $(symbolCreateConfig) .call(defaultVals.hasProps() ? defaultVals : undefined) .generic(symbolClientOptions), ]; const symbolClient = plugin.symbol('client', { meta: { category: 'client', }, }); const statement = $.const(symbolClient) .export() .assign( $(symbolCreateClient).$if( symbolCreateClientConfig, (c, s) => c.call($(s).call(...createConfigParameters)), (c) => c.call(...createConfigParameters), ), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/config.ts ================================================ export const clientDefaultConfig = { baseUrl: true, bundle: true, includeInEntry: false, } as const; export const clientDefaultMeta = { dependencies: ['@hey-api/typescript'], tags: ['client'], } as const; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/createClientConfig.ts ================================================ import { getTypedConfig } from '../../../config/utils'; import { clientFolderAbsolutePath } from '../../../generate/client'; import { $ } from '../../../ts-dsl'; import type { PluginHandler } from './types'; export const createClientConfigType = ({ plugin }: Parameters[0]) => { const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin)); const symbolClientOptions = plugin.referenceSymbol({ category: 'type', resource: 'client', role: 'options', }); const symbolConfig = plugin.symbol('Config', { external: clientModule, kind: 'type', }); const symbolDefaultClientOptions = plugin.symbol('ClientOptions', { external: clientModule, kind: 'type', }); const symbolCreateClientConfig = plugin.symbol('CreateClientConfig'); const typeCreateClientConfig = $.type .alias(symbolCreateClientConfig) .export() .doc([ 'The `createClientConfig()` function will be called on client initialization', "and the returned object will become the client's initial configuration.", '', 'You may want to initialize your client this way instead of calling', "`setConfig()`. This is useful for example if you're using Next.js", 'to ensure your client always has the correct values.', ]) .generic('T', (g) => g.extends(symbolDefaultClientOptions).default(symbolClientOptions)) .type( $.type .func() .param('override', (p) => p .optional() .type($.type(symbolConfig).generic($.type.and(symbolDefaultClientOptions, 'T'))), ) .returns( $.type(symbolConfig).generic( $.type.and($.type('Required').generic(symbolDefaultClientOptions), 'T'), ), ), ); plugin.node(typeCreateClientConfig); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/plugin.ts ================================================ import { createClient } from './client'; import { createClientConfigType } from './createClientConfig'; import type { PluginHandler } from './types'; export const clientPluginHandler = ({ plugin }: Parameters[0]) => { createClientConfigType({ plugin }); createClient({ plugin }); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/types.ts ================================================ /* eslint-disable @typescript-eslint/no-namespace */ import type { Plugin } from '@hey-api/shared'; import type { HeyApiClientAngularPlugin } from '../../../plugins/@hey-api/client-angular'; import type { HeyApiClientAxiosPlugin } from '../../../plugins/@hey-api/client-axios'; import type { HeyApiClientFetchPlugin } from '../../../plugins/@hey-api/client-fetch'; import type { HeyApiClientNextPlugin } from '../../../plugins/@hey-api/client-next'; import type { HeyApiClientNuxtPlugin } from '../../../plugins/@hey-api/client-nuxt'; import type { HeyApiClientOfetchPlugin } from '../../../plugins/@hey-api/client-ofetch'; export interface PluginHandler { (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; } /** * Public Client API. */ export namespace Client { export type Config = Plugin.Hooks & Plugin.UserExports & { /** * Set a default base URL when creating the client? You can set `baseUrl` * to a string which will be used as the base URL. If your input defines * server(s), you can set `baseUrl` to a number to pick a specific server * to use as the base URL. You can disable setting the base URL by setting * `baseUrl` to `false`. By default, `baseUrl` is `true` and it will try to * use the first defined server value. If there's none, we won't set a * base URL. * * If the matched URL contains template literals, it will be ignored. * * @default true */ baseUrl?: string | number | boolean; /** * Bundle the client module? When `true`, the client module will be copied * from the client plugin and bundled with the generated output. * * @default true */ bundle?: boolean; /** * Relative path to the runtime configuration file. This file must export * a `createClientConfig()` function. The `createClientConfig()` function * will be called on client initialization and the returned object will * become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ runtimeConfigPath?: string; /** * Should the type helper for base URL allow only values matching the * server(s) defined in the input? By default, `strictBaseUrl` is `false` * which will provide type hints and allow you to pass any string. * * Note that setting `strictBaseUrl` to `true` can produce an invalid * build if you specify `baseUrl` which doesn't conform to the type helper. * * @default false */ strictBaseUrl?: boolean; }; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-core/utils.ts ================================================ import type { Config } from '../../../config/types'; import type { PluginClientNames } from '../../types'; export function getClientBaseUrlKey(config: Config) { const client = getClientPlugin(config); if (client.name === '@hey-api/client-axios' || client.name === '@hey-api/client-nuxt') { return 'baseURL'; } return 'baseUrl'; } export function getClientPlugin( config: Config, ): Config['plugins'][PluginClientNames] & { name: PluginClientNames } { for (const name of config.pluginOrder) { const plugin = config.plugins[name]; if (plugin?.tags?.includes('client')) { return plugin as Config['plugins'][PluginClientNames] & { name: PluginClientNames; }; } } return { config: { // @ts-expect-error name: '', }, // @ts-expect-error name: '', }; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/__tests__/client.test.ts ================================================ import type { ResolvedRequestOptions } from '../bundle'; import { createClient } from '../bundle/client'; type MockFetch = ((...args: any[]) => any) & { preconnect?: any; }; describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, { options: { query: { bar: [], foo: [], }, url: '/', }, url: '/', }, { options: { query: { bar: [], foo: ['abc', 'def'], }, url: '/', }, url: '/?foo=abc&foo=def', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); it('uses baseUrl from client config by default', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ url: '/foo' })).toBe('https://example.com/foo'); }); it('allows overriding baseUrl from client config', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ baseUrl: 'https://other.com', url: '/foo' })).toBe( 'https://other.com/foo', ); }); }); describe('zero-length body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('returns empty Blob for zero-length application/octet-stream response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/octet-stream', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toBeInstanceOf(Blob); expect((result.data as Blob).size).toBe(0); }); it('returns empty ArrayBuffer for zero-length response with arrayBuffer parseAs', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', parseAs: 'arrayBuffer', url: '/test', }); expect(result.data).toBeInstanceOf(ArrayBuffer); expect((result.data as ArrayBuffer).byteLength).toBe(0); }); it('returns empty string for zero-length text response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'text/plain', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toBe(''); }); it('returns empty object for zero-length JSON response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty FormData for zero-length multipart/form-data response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'multipart/form-data', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toBeInstanceOf(FormData); expect([...(result.data as FormData).entries()]).toHaveLength(0); }); it('returns stream body for zero-length stream response', async () => { const mockBody = new ReadableStream(); const mockResponse = new Response(mockBody, { headers: { 'Content-Length': '0', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', parseAs: 'stream', url: '/test', }); expect(result.data).toBe(mockBody); }); it('handles non-zero content correctly for comparison', async () => { const blobContent = new Blob(['test data']); const mockResponse = new Response(blobContent, { headers: { 'Content-Type': 'application/octet-stream', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toBeInstanceOf(Blob); expect((result.data as Blob).size).toBeGreaterThan(0); }); it('returns empty object for empty JSON response without Content-Length header (status 200)', async () => { // Simulates a server returning an empty body with status 200 and no Content-Length header // This is the scenario described in the issue where response.json() throws const mockResponse = new Response('', { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty object for empty response without Content-Length header and no Content-Type (defaults to JSON)', async () => { // Tests the auto-detection behavior when no Content-Type is provided const mockResponse = new Response('', { status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); // When parseAs is 'auto' and no Content-Type header exists, it should handle empty body gracefully expect(result.data).toBeDefined(); }); }); describe('unserialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: 0, textValue: '0' }, { body: false, textValue: 'false' }, { body: 'test string', textValue: 'test string' }, { body: '', textValue: '' }, ]; it.each(scenarios)('handles plain text body with $body value', async ({ body, textValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValueOnce(mockResponse); const result = await client.post({ body, bodySerializer: null, fetch: mockFetch, headers: { 'Content-Type': 'text/plain', }, url: '/test', }); expect(mockFetch).toHaveBeenCalledWith( expect.objectContaining({ body: expect.any(ReadableStream), }), ); await expect(result.request.text()).resolves.toEqual(textValue); expect(result.request.headers.get('Content-Type')).toEqual('text/plain'); }); }); describe('serialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: '', expectBodyValue: false, expectContentHeader: false, serializedBody: '', textValue: '', }, { body: 0, expectBodyValue: true, expectContentHeader: true, serializedBody: 0, textValue: '0', }, { body: false, expectBodyValue: true, expectContentHeader: true, serializedBody: false, textValue: 'false', }, { body: {}, expectBodyValue: true, expectContentHeader: true, serializedBody: '{"key":"value"}', textValue: '{"key":"value"}', }, ]; it.each(scenarios)( 'handles $serializedBody serializedBody value', async ({ body, expectBodyValue, expectContentHeader, serializedBody, textValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValueOnce(mockResponse); const result = await client.post({ body, bodySerializer: () => serializedBody, fetch: mockFetch, headers: { 'Content-Type': 'application/json', }, url: '/test', }); expect(mockFetch).toHaveBeenCalledWith( expect.objectContaining({ body: expectBodyValue ? expect.any(ReadableStream) : null, }), ); await expect(result.request.text()).resolves.toEqual(textValue); expect(result.request.headers.get('Content-Type')).toEqual( expectContentHeader ? 'application/json' : null, ); }, ); }); describe('request interceptor', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: 'test string', bodySerializer: null, contentType: 'text/plain', expectedSerializedValue: undefined, expectedValue: async (request: Request) => await request.text(), }, { body: { key: 'value' }, bodySerializer: (body: unknown) => JSON.stringify(body), contentType: 'application/json', expectedSerializedValue: '{"key":"value"}', expectedValue: async (request: Request) => await request.json(), }, ]; it.each(scenarios)( 'exposes $contentType serialized and raw body values', async ({ body, bodySerializer, contentType, expectedSerializedValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValueOnce(mockResponse); const mockRequestInterceptor = vi .fn() .mockImplementation((request: Request, options: ResolvedRequestOptions) => { expect(options.serializedBody).toBe(expectedSerializedValue); expect(options.body).toBe(body); return request; }); const interceptorId = client.interceptors.request.use(mockRequestInterceptor); await client.post({ body, bodySerializer, fetch: mockFetch, headers: { 'Content-Type': contentType, }, url: '/test', }); expect(mockRequestInterceptor).toHaveBeenCalledOnce(); client.interceptors.request.eject(interceptorId); }, ); }); describe('error interceptor for fetch exceptions', () => { it('intercepts AbortError when fetch is aborted', async () => { const client = createClient({ baseUrl: 'https://example.com' }); const abortError = new DOMException('The operation was aborted', 'AbortError'); const mockFetch: MockFetch = vi.fn().mockRejectedValue(abortError); const mockErrorInterceptor = vi.fn().mockImplementation((error) => { expect(error).toBe(abortError); return { message: 'Request was aborted', type: 'abort' }; }); const interceptorId = client.interceptors.error.use(mockErrorInterceptor); const result = await client.get({ fetch: mockFetch, url: '/test', }); expect(mockErrorInterceptor).toHaveBeenCalledOnce(); expect(result.error).toEqual({ message: 'Request was aborted', type: 'abort', }); client.interceptors.error.eject(interceptorId); }); it('intercepts network errors', async () => { const client = createClient({ baseUrl: 'https://example.com' }); const networkError = new TypeError('Failed to fetch'); const mockFetch: MockFetch = vi.fn().mockRejectedValue(networkError); const mockErrorInterceptor = vi.fn().mockImplementation((error) => { expect(error).toBe(networkError); return { message: 'Network error occurred', type: 'network' }; }); const interceptorId = client.interceptors.error.use(mockErrorInterceptor); const result = await client.get({ fetch: mockFetch, url: '/test', }); expect(mockErrorInterceptor).toHaveBeenCalledOnce(); expect(result.error).toEqual({ message: 'Network error occurred', type: 'network', }); client.interceptors.error.eject(interceptorId); }); it('throws AbortError when throwOnError is true', async () => { const client = createClient({ baseUrl: 'https://example.com' }); const abortError = new DOMException('The operation was aborted', 'AbortError'); const mockFetch: MockFetch = vi.fn().mockRejectedValue(abortError); const mockErrorInterceptor = vi.fn().mockImplementation(() => ({ message: 'Request was aborted', type: 'abort', })); const interceptorId = client.interceptors.error.use(mockErrorInterceptor); await expect( client.get({ fetch: mockFetch, throwOnError: true, url: '/test', }), ).rejects.toEqual({ message: 'Request was aborted', type: 'abort' }); expect(mockErrorInterceptor).toHaveBeenCalledOnce(); client.interceptors.error.eject(interceptorId); }); it('handles fetch exceptions without error interceptor', async () => { const client = createClient({ baseUrl: 'https://example.com' }); const abortError = new DOMException('The operation was aborted', 'AbortError'); const mockFetch: MockFetch = vi.fn().mockRejectedValue(abortError); const result = await client.get({ fetch: mockFetch, url: '/test', }); expect(result.error).toBe(abortError); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/__tests__/utils.test.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import type { Client } from '../bundle/types'; import { buildUrl, getParseAs, setAuthParams } from '../bundle/utils'; describe('buildUrl', () => { const scenarios: Array<{ options: Parameters[0]; url: string; }> = [ { options: { path: { id: new Date('2025-01-01T00:00:00.000Z'), }, url: '/foo/{id}', }, url: '/foo/2025-01-01T00:00:00.000Z', }, ]; it.each(scenarios)('builds $url', async ({ options, url }) => { expect(buildUrl(options)).toEqual(url); }); }); describe('getParseAs', () => { const scenarios: Array<{ content: Parameters[0]; parseAs: ReturnType; }> = [ { content: null, parseAs: 'stream', }, { content: 'application/json', parseAs: 'json', }, { content: 'application/ld+json', parseAs: 'json', }, { content: 'application/ld+json;charset=utf-8', parseAs: 'json', }, { content: 'application/ld+json; charset=utf-8', parseAs: 'json', }, { content: 'multipart/form-data', parseAs: 'formData', }, { content: 'application/*', parseAs: 'blob', }, { content: 'audio/*', parseAs: 'blob', }, { content: 'image/*', parseAs: 'blob', }, { content: 'video/*', parseAs: 'blob', }, { content: 'text/*', parseAs: 'text', }, { content: 'unsupported', parseAs: undefined, }, ]; it.each(scenarios)('detects $content as $parseAs', async ({ content, parseAs }) => { expect(getParseAs(content)).toEqual(parseAs); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Authorization')).toBe('foo'); expect(query).toEqual({}); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets an API key in a cookie', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'cookie', name: 'baz', type: 'apiKey', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Cookie')).toBe('baz=foo'); expect(query).toEqual({}); }); it('sets only one specific header', async () => { const auth = vi.fn(({ name }: Auth) => { if (name === 'baz') { return 'foo'; } return 'buz'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { name: 'fiz', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(headers.get('fiz')).toBe('buz'); expect(Object.keys(query).length).toBe(0); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/bundle/client.ts ================================================ import { createSseClient } from '../../client-core/bundle/serverSentEvents'; import type { HttpMethod } from '../../client-core/bundle/types'; import { getValidRequestBody } from '../../client-core/bundle/utils'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/bundle/index.ts ================================================ export type { Auth } from '../../client-core/bundle/auth'; export type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../../client-core/bundle/bodySerializer'; export { buildClientParams } from '../../client-core/bundle/params'; export { serializeQueryKeyValue } from '../../client-core/bundle/queryKeySerializer'; export { createClient } from './client'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types'; export { createConfig, mergeHeaders } from './utils'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/bundle/types.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../../client-core/bundle/serverSentEvents'; import type { Client as CoreClient, Config as CoreConfig } from '../../client-core/bundle/types'; import type { Middleware } from './utils'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/bundle/utils.ts ================================================ import { getAuthToken } from '../../client-core/bundle/auth'; import type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; import { jsonBodySerializer } from '../../client-core/bundle/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../../client-core/bundle/pathSerializer'; import { getUrl } from '../../client-core/bundle/utils'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta, } from '../../../plugins/@hey-api/client-core/config'; import { clientPluginHandler } from '../../../plugins/@hey-api/client-core/plugin'; import type { HeyApiClientFetchPlugin } from './types'; export const defaultConfig: HeyApiClientFetchPlugin['Config'] = { ...clientDefaultMeta, config: { ...clientDefaultConfig, throwOnError: false, }, handler: clientPluginHandler as unknown as HeyApiClientFetchPlugin['Handler'], name: '@hey-api/client-fetch', }; /** * Type helper for `@hey-api/client-fetch` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/index.ts ================================================ export type { Client as FetchClient } from './bundle/types'; export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientFetchPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-fetch/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { Client } from '../../../plugins/@hey-api/client-core/types'; export type UserConfig = Plugin.Name<'@hey-api/client-fetch'> & Client.Config & { /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: boolean; }; export type HeyApiClientFetchPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/__tests__/client.test.ts ================================================ import type { KyInstance } from 'ky'; import { HTTPError } from 'ky'; import type { ResolvedRequestOptions } from '../bundle'; import { createClient } from '../bundle/client'; describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, { options: { query: { bar: [], foo: [], }, url: '/', }, url: '/', }, { options: { query: { bar: [], foo: ['abc', 'def'], }, url: '/', }, url: '/?foo=abc&foo=def', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); it('uses baseUrl from client config by default', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ url: '/foo' })).toBe('https://example.com/foo'); }); it('allows overriding baseUrl from client config', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ baseUrl: 'https://other.com', url: '/foo' })).toBe( 'https://other.com/foo', ); }); }); describe('zero-length body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('returns empty Blob for zero-length application/octet-stream response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/octet-stream', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', url: '/test', }); expect(result.data).toBeInstanceOf(Blob); expect((result.data as Blob).size).toBe(0); }); it('returns empty ArrayBuffer for zero-length response with arrayBuffer parseAs', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', parseAs: 'arrayBuffer', url: '/test', }); expect(result.data).toBeInstanceOf(ArrayBuffer); expect((result.data as ArrayBuffer).byteLength).toBe(0); }); it('returns empty string for zero-length text response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'text/plain', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', url: '/test', }); expect(result.data).toBe(''); }); it('returns empty object for zero-length JSON response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty FormData for zero-length multipart/form-data response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'multipart/form-data', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', url: '/test', }); expect(result.data).toBeInstanceOf(FormData); expect([...(result.data as FormData).entries()]).toHaveLength(0); }); it('returns stream body for zero-length stream response', async () => { const mockBody = new ReadableStream(); const mockResponse = new Response(mockBody, { headers: { 'Content-Length': '0', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', parseAs: 'stream', url: '/test', }); expect(result.data).toBe(mockBody); }); it('handles non-zero content correctly for comparison', async () => { const blobContent = new Blob(['test data']); const mockResponse = new Response(blobContent, { headers: { 'Content-Type': 'application/octet-stream', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', url: '/test', }); expect(result.data).toBeInstanceOf(Blob); expect((result.data as Blob).size).toBeGreaterThan(0); }); it('returns empty object for empty JSON response without Content-Length header (status 200)', async () => { // Simulates a server returning an empty body with status 200 and no Content-Length header // This is the scenario described in the issue where response.json() throws const mockResponse = new Response('', { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty object for empty response without Content-Length header and no Content-Type (defaults to JSON)', async () => { // Tests the auto-detection behavior when no Content-Type is provided const mockResponse = new Response('', { status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ ky: mockKy as Partial as KyInstance, method: 'GET', url: '/test', }); // When parseAs is 'auto' and no Content-Type header exists, it should handle empty body gracefully expect(result.data).toBeDefined(); }); }); describe('unserialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: 0, textValue: '0' }, { body: false, textValue: 'false' }, { body: 'test string', textValue: 'test string' }, { body: '', textValue: '' }, ]; it.each(scenarios)('handles plain text body with $body value', async ({ body, textValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValueOnce(mockResponse); const result = await client.post({ body, bodySerializer: null, headers: { 'Content-Type': 'text/plain', }, ky: mockKy as Partial as KyInstance, url: '/test', }); expect(mockKy).toHaveBeenCalledWith( expect.objectContaining({ body: expect.any(ReadableStream), }), expect.any(Object), ); await expect(result.request.text()).resolves.toEqual(textValue); expect(result.request.headers.get('Content-Type')).toEqual('text/plain'); }); }); describe('serialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: '', expectBodyValue: false, expectContentHeader: false, serializedBody: '', textValue: '', }, { body: 0, expectBodyValue: true, expectContentHeader: true, serializedBody: 0, textValue: '0', }, { body: false, expectBodyValue: true, expectContentHeader: true, serializedBody: false, textValue: 'false', }, { body: {}, expectBodyValue: true, expectContentHeader: true, serializedBody: '{"key":"value"}', textValue: '{"key":"value"}', }, ]; it.each(scenarios)( 'handles $serializedBody serializedBody value', async ({ body, expectBodyValue, expectContentHeader, serializedBody, textValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValueOnce(mockResponse); const result = await client.post({ body, bodySerializer: () => serializedBody, headers: { 'Content-Type': 'application/json', }, ky: mockKy as Partial as KyInstance, url: '/test', }); expect(mockKy).toHaveBeenCalledWith( expect.objectContaining({ body: expectBodyValue ? expect.any(ReadableStream) : null, }), expect.any(Object), ); await expect(result.request.text()).resolves.toEqual(textValue); expect(result.request.headers.get('Content-Type')).toEqual( expectContentHeader ? 'application/json' : null, ); }, ); }); describe('request interceptor', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: 'test string', bodySerializer: null, contentType: 'text/plain', expectedSerializedValue: undefined, expectedValue: async (request: Request) => await request.text(), }, { body: { key: 'value' }, bodySerializer: (body: unknown) => JSON.stringify(body), contentType: 'application/json', expectedSerializedValue: '{"key":"value"}', expectedValue: async (request: Request) => await request.json(), }, ]; it.each(scenarios)( 'exposes $contentType serialized and raw body values', async ({ body, bodySerializer, contentType, expectedSerializedValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValueOnce(mockResponse); const mockRequestInterceptor = vi .fn() .mockImplementation((request: Request, options: ResolvedRequestOptions) => { expect(options.serializedBody).toBe(expectedSerializedValue); expect(options.body).toBe(body); return request; }); const interceptorId = client.interceptors.request.use(mockRequestInterceptor); await client.post({ body, bodySerializer, headers: { 'Content-Type': contentType, }, ky: mockKy as Partial as KyInstance, url: '/test', }); expect(mockRequestInterceptor).toHaveBeenCalledOnce(); client.interceptors.request.eject(interceptorId); }, ); }); describe('response interceptor', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('allows response transformation', async () => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const mockResponseInterceptor = vi.fn().mockImplementation((response: Response) => { expect(response).toBe(mockResponse); return response; }); const interceptorId = client.interceptors.response.use(mockResponseInterceptor); await client.get({ ky: mockKy as Partial as KyInstance, url: '/test', }); expect(mockResponseInterceptor).toHaveBeenCalledOnce(); client.interceptors.response.eject(interceptorId); }); }); describe('error handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('handles HTTP errors with throwOnError: false', async () => { const errorResponse = new Response(JSON.stringify({ message: 'Not found' }), { headers: { 'Content-Type': 'application/json', }, status: 404, }); const mockKy = vi.fn().mockRejectedValue( new HTTPError(errorResponse, new Request('https://example.com/test'), { method: 'GET', } as any), ); const result = await client.get({ ky: mockKy as Partial as KyInstance, throwOnError: false, url: '/test', }); expect(result.error).toEqual({ message: 'Not found' }); expect(result.response.status).toBe(404); }); it('throws HTTP errors with throwOnError: true', async () => { const errorResponse = new Response(JSON.stringify({ message: 'Not found' }), { headers: { 'Content-Type': 'application/json', }, status: 404, }); const mockKy = vi.fn().mockRejectedValue( new HTTPError(errorResponse, new Request('https://example.com/test'), { method: 'GET', } as any), ); await expect( client.get({ ky: mockKy as Partial as KyInstance, throwOnError: true, url: '/test', }), ).rejects.toEqual({ message: 'Not found' }); }); it('handles text error responses', async () => { const errorResponse = new Response('Internal Server Error', { status: 500, }); const mockKy = vi.fn().mockRejectedValue( new HTTPError(errorResponse, new Request('https://example.com/test'), { method: 'GET', } as any), ); const result = await client.get({ ky: mockKy as Partial as KyInstance, throwOnError: false, url: '/test', }); expect(result.error).toBe('Internal Server Error'); expect(result.response.status).toBe(500); }); }); describe('error interceptor', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('allows error transformation', async () => { const errorResponse = new Response(JSON.stringify({ message: 'Not found' }), { headers: { 'Content-Type': 'application/json', }, status: 404, }); const mockKy = vi.fn().mockRejectedValue( new HTTPError(errorResponse, new Request('https://example.com/test'), { method: 'GET', } as any), ); const mockErrorInterceptor = vi .fn() .mockImplementation((error: any) => ({ transformed: true, ...error })); const interceptorId = client.interceptors.error.use(mockErrorInterceptor); const result = await client.get({ ky: mockKy as Partial as KyInstance, throwOnError: false, url: '/test', }); expect(mockErrorInterceptor).toHaveBeenCalledOnce(); expect(result.error).toEqual({ message: 'Not found', transformed: true }); client.interceptors.error.eject(interceptorId); }); }); describe('retry configuration', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('passes retry configuration to ky', async () => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); await client.get({ ky: mockKy as Partial as KyInstance, retry: { limit: 3, methods: ['get', 'post'], statusCodes: [408, 429, 500], }, url: '/test', }); expect(mockKy).toHaveBeenCalledWith( expect.any(Request), expect.objectContaining({ retry: { limit: 3, methods: ['get', 'post'], statusCodes: [408, 429, 500], }, }), ); }); }); describe('responseStyle configuration', () => { const client = createClient({ baseUrl: 'https://example.com', responseStyle: 'data', }); it('returns only data when responseStyle is "data"', async () => { const mockResponse = new Response(JSON.stringify({ result: 'success' }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockKy = vi.fn().mockResolvedValue(mockResponse); const result = await client.get({ ky: mockKy as Partial as KyInstance, url: '/test', }); expect(result).toEqual({ result: 'success' }); expect(result).not.toHaveProperty('response'); expect(result).not.toHaveProperty('request'); }); it('returns undefined for errors when responseStyle is "data"', async () => { const errorResponse = new Response(JSON.stringify({ message: 'Not found' }), { headers: { 'Content-Type': 'application/json', }, status: 404, }); const mockKy = vi.fn().mockRejectedValue( new HTTPError(errorResponse, new Request('https://example.com/test'), { method: 'GET', } as any), ); const result = await client.get({ ky: mockKy as Partial as KyInstance, throwOnError: false, url: '/test', }); expect(result).toBeUndefined(); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/__tests__/utils.test.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import type { Client } from '../bundle/types'; import { buildUrl, getParseAs, setAuthParams } from '../bundle/utils'; describe('buildUrl', () => { const scenarios: Array<{ options: Parameters[0]; url: string; }> = [ { options: { path: { id: new Date('2025-01-01T00:00:00.000Z'), }, url: '/foo/{id}', }, url: '/foo/2025-01-01T00:00:00.000Z', }, ]; it.each(scenarios)('builds $url', async ({ options, url }) => { expect(buildUrl(options)).toEqual(url); }); }); describe('getParseAs', () => { const scenarios: Array<{ content: Parameters[0]; parseAs: ReturnType; }> = [ { content: null, parseAs: 'stream', }, { content: 'application/json', parseAs: 'json', }, { content: 'application/ld+json', parseAs: 'json', }, { content: 'application/ld+json;charset=utf-8', parseAs: 'json', }, { content: 'application/ld+json; charset=utf-8', parseAs: 'json', }, { content: 'multipart/form-data', parseAs: 'formData', }, { content: 'application/*', parseAs: 'blob', }, { content: 'audio/*', parseAs: 'blob', }, { content: 'image/*', parseAs: 'blob', }, { content: 'video/*', parseAs: 'blob', }, { content: 'text/*', parseAs: 'text', }, { content: 'unsupported', parseAs: undefined, }, ]; it.each(scenarios)('detects $content as $parseAs', async ({ content, parseAs }) => { expect(getParseAs(content)).toEqual(parseAs); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Authorization')).toBe('foo'); expect(query).toEqual({}); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets an API key in a cookie', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'cookie', name: 'baz', type: 'apiKey', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Cookie')).toBe('baz=foo'); expect(query).toEqual({}); }); it('sets only one specific header', async () => { const auth = vi.fn(({ name }: Auth) => { if (name === 'baz') { return 'foo'; } return 'buz'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { name: 'fiz', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(headers.get('fiz')).toBe('buz'); expect(Object.keys(query).length).toBe(0); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/bundle/client.ts ================================================ import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../../client-core/bundle/serverSentEvents'; import type { HttpMethod } from '../../client-core/bundle/types'; import { getValidRequestBody } from '../../client-core/bundle/utils'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types'; import type { Middleware } from './utils'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/bundle/index.ts ================================================ export type { Auth } from '../../client-core/bundle/auth'; export type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../../client-core/bundle/bodySerializer'; export { buildClientParams } from '../../client-core/bundle/params'; export { serializeQueryKeyValue } from '../../client-core/bundle/queryKeySerializer'; export { createClient } from './client'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types'; export { createConfig, mergeHeaders } from './utils'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/bundle/types.ts ================================================ import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../../client-core/bundle/auth'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../../client-core/bundle/serverSentEvents'; import type { Client as CoreClient, Config as CoreConfig } from '../../client-core/bundle/types'; import type { Middleware } from './utils'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/bundle/utils.ts ================================================ import { getAuthToken } from '../../client-core/bundle/auth'; import type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; import { jsonBodySerializer } from '../../client-core/bundle/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../../client-core/bundle/pathSerializer'; import { getUrl } from '../../client-core/bundle/utils'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta, } from '../../../plugins/@hey-api/client-core/config'; import { clientPluginHandler } from '../../../plugins/@hey-api/client-core/plugin'; import type { HeyApiClientKyPlugin } from './types'; export const defaultConfig: HeyApiClientKyPlugin['Config'] = { ...clientDefaultMeta, config: { ...clientDefaultConfig, throwOnError: false, }, handler: clientPluginHandler as unknown as HeyApiClientKyPlugin['Handler'], name: '@hey-api/client-ky', }; /** * Type helper for `@hey-api/client-ky` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/index.ts ================================================ export type { Client as KyClient } from './bundle/types'; export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientKyPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ky/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { Client } from '../../../plugins/@hey-api/client-core/types'; export type UserConfig = Plugin.Name<'@hey-api/client-ky'> & Client.Config & { /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: boolean; }; export type HeyApiClientKyPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/__tests__/client.test.ts ================================================ import { createClient } from '../bundle/client'; import type { ResolvedRequestOptions } from '../bundle/types'; type MockFetch = ((...args: any[]) => any) & { preconnect?: any; }; describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); it('uses baseUrl from client config by default', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ url: '/foo' })).toBe('https://example.com/foo'); }); it('allows overriding baseUrl from client config', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ baseUrl: 'https://other.com', url: '/foo' })).toBe( 'https://other.com/foo', ); }); }); describe('zero-length body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('returns empty object for zero-length JSON response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty object for empty JSON response without Content-Length header (status 200)', async () => { // Simulates a server returning an empty body with status 200 and no Content-Length header // This is the scenario described in the issue where response.json() throws const mockResponse = new Response('', { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty object for empty response without Content-Length header and no Content-Type (defaults to JSON)', async () => { // Tests the auto-detection behavior when no Content-Type is provided const mockResponse = new Response('', { status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValue(mockResponse); const result = await client.request({ fetch: mockFetch, method: 'GET', url: '/test', }); // When parseAs is 'auto' and no Content-Type header exists, it should handle empty body gracefully expect(result.data).toBeDefined(); }); }); describe('unserialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [{ body: 0 }, { body: false }, { body: 'test string' }, { body: '' }]; it.each(scenarios)('handles plain text body with $body value', async ({ body }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValueOnce(mockResponse); const headers = new Headers({ 'Content-Type': 'text/plain' }); await client.post({ body, bodySerializer: null, fetch: mockFetch, headers: { 'Content-Type': 'text/plain', }, url: '/test', }); expect(mockFetch).toHaveBeenCalledExactlyOnceWith( expect.any(String), expect.objectContaining({ body, headers, }), ); }); }); describe('serialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: '', expectBodyValue: false, expectContentHeader: false, serializedBody: '', }, { body: 0, expectBodyValue: true, expectContentHeader: true, serializedBody: 0, }, { body: false, expectBodyValue: true, expectContentHeader: true, serializedBody: false, }, { body: {}, expectBodyValue: true, expectContentHeader: true, serializedBody: '{"key":"value"}', }, ]; it.each(scenarios)( 'handles $serializedBody serializedBody value', async ({ body, expectBodyValue, expectContentHeader, serializedBody }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValueOnce(mockResponse); const headers = new Headers({ 'Content-Type': 'application/json' }); await client.post({ body, bodySerializer: () => serializedBody, fetch: mockFetch, headers: { 'Content-Type': 'application/json', }, url: '/test', }); expect(mockFetch).toHaveBeenCalledExactlyOnceWith( expect.any(String), expect.objectContaining({ body: expectBodyValue ? serializedBody : null, headers: expectContentHeader ? headers : new Headers(), }), ); }, ); }); describe('request interceptor', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: 'test string', bodySerializer: null, contentType: 'text/plain', expectedSerializedValue: undefined, expectedValue: 'test string', }, { body: { key: 'value' }, bodySerializer: (body: unknown) => JSON.stringify(body), contentType: 'application/json', expectedSerializedValue: '{"key":"value"}', expectedValue: '{"key":"value"}', }, ]; it.each(scenarios)( 'exposes $contentType serialized and raw body in interceptor', async ({ body, bodySerializer, contentType, expectedSerializedValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockFetch: MockFetch = vi.fn().mockResolvedValueOnce(mockResponse); const mockRequestInterceptor = vi .fn() .mockImplementation((options: ResolvedRequestOptions) => { expect(options.serializedBody).toBe(expectedSerializedValue); expect(options.body).toBe(body); return options; }); const interceptorId = client.interceptors.request.use(mockRequestInterceptor); await client.post({ body, bodySerializer, fetch: mockFetch, headers: { 'Content-Type': contentType, }, url: '/test', }); expect(mockRequestInterceptor).toHaveBeenCalledOnce(); client.interceptors.request.eject(interceptorId); }, ); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/__tests__/utils.test.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import { getParseAs, setAuthParams } from '../bundle/utils'; describe('getParseAs', () => { const scenarios: Array<{ content: Parameters[0]; parseAs: ReturnType; }> = [ { content: null, parseAs: 'stream', }, { content: 'application/json', parseAs: 'json', }, { content: 'application/ld+json', parseAs: 'json', }, { content: 'application/ld+json;charset=utf-8', parseAs: 'json', }, { content: 'application/ld+json; charset=utf-8', parseAs: 'json', }, { content: 'multipart/form-data', parseAs: 'formData', }, { content: 'application/*', parseAs: 'blob', }, { content: 'audio/*', parseAs: 'blob', }, { content: 'image/*', parseAs: 'blob', }, { content: 'video/*', parseAs: 'blob', }, { content: 'text/*', parseAs: 'text', }, { content: 'unsupported', parseAs: undefined, }, ]; it.each(scenarios)('detects $content as $parseAs', async ({ content, parseAs }) => { expect(getParseAs(content)).toEqual(parseAs); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Authorization')).toBe('foo'); expect(query).toEqual({}); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets an API key in a cookie', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'cookie', name: 'baz', type: 'apiKey', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Cookie')).toBe('baz=foo'); expect(query).toEqual({}); }); it('sets only one specific header', async () => { const auth = vi.fn(({ name }: Auth) => { if (name === 'baz') { return 'foo'; } return 'buz'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { name: 'fiz', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(headers.get('fiz')).toBe('buz'); expect(Object.keys(query).length).toBe(0); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/bundle/client.ts ================================================ import { createSseClient } from '../../client-core/bundle/serverSentEvents'; import type { HttpMethod } from '../../client-core/bundle/types'; import { getValidRequestBody } from '../../client-core/bundle/utils'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/bundle/index.ts ================================================ export type { Auth } from '../../client-core/bundle/auth'; export type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../../client-core/bundle/bodySerializer'; export { buildClientParams } from '../../client-core/bundle/params'; export { serializeQueryKeyValue } from '../../client-core/bundle/queryKeySerializer'; export { createClient } from './client'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/bundle/types.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../../client-core/bundle/serverSentEvents'; import type { Client as CoreClient, Config as CoreConfig } from '../../client-core/bundle/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/bundle/utils.ts ================================================ import { getAuthToken } from '../../client-core/bundle/auth'; import type { QuerySerializer, QuerySerializerOptions, } from '../../client-core/bundle/bodySerializer'; import { jsonBodySerializer } from '../../client-core/bundle/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../../client-core/bundle/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta, } from '../../../plugins/@hey-api/client-core/config'; import { clientPluginHandler } from '../../../plugins/@hey-api/client-core/plugin'; import type { HeyApiClientNextPlugin } from './types'; export const defaultConfig: HeyApiClientNextPlugin['Config'] = { ...clientDefaultMeta, config: { ...clientDefaultConfig, throwOnError: false, }, handler: clientPluginHandler as unknown as HeyApiClientNextPlugin['Handler'], name: '@hey-api/client-next', }; /** * Type helper for `@hey-api/client-next` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/index.ts ================================================ export type { Client as NextClient } from './bundle/types'; export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientNextPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-next/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { Client } from '../../../plugins/@hey-api/client-core/types'; export type UserConfig = Plugin.Name<'@hey-api/client-next'> & Client.Config & { /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: boolean; }; export type HeyApiClientNextPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/__tests__/client.test.ts ================================================ // Mock $fetch global (Nuxt auto-import) const $fetchMock = vi.fn(); vi.stubGlobal('$fetch', $fetchMock); // Mock Nuxt composables with realistic return values vi.mock('nuxt/app', () => ({ useAsyncData: vi.fn(() => ({ data: { value: null }, error: { value: null }, pending: { value: false }, refresh: vi.fn(), })), useFetch: vi.fn(() => ({ data: { value: null }, error: { value: null }, pending: { value: false }, refresh: vi.fn(), })), useLazyAsyncData: vi.fn(() => ({ data: { value: null }, error: { value: null }, pending: { value: false }, refresh: vi.fn(), })), useLazyFetch: vi.fn(() => ({ data: { value: null }, error: { value: null }, pending: { value: false }, refresh: vi.fn(), })), })); import { useFetch } from 'nuxt/app'; import { computed, ref } from 'vue'; import { createClient } from '../bundle/client'; describe('useFetch with computed body', () => { it('does not throw when body is a ComputedRef', () => { const client = createClient(); const page = ref(1); const body = computed(() => ({ page: page.value, pageSize: 10 })); expect(() => { client.post({ body, composable: 'useFetch', url: '/test', }); }).not.toThrow(); }); it('serializes ComputedRef body correctly on initial call', () => { const client = createClient(); const body = computed(() => ({ page: 1, search: 'hello' })); client.post({ body, composable: 'useFetch', url: '/test', }); // useFetch should be called with the serialized body as a ref expect(useFetch).toHaveBeenCalled(); const callArgs = vi.mocked(useFetch).mock.calls.at(-1)!; const opts = callArgs[1] as Record; // body should be a ref containing the JSON-serialized value expect((opts.body as { value: unknown }).value).toBe('{"page":1,"search":"hello"}'); }); it('does not throw when body is a plain Ref', () => { const client = createClient(); const body = ref({ page: 1, pageSize: 10 }); expect(() => { client.post({ body, composable: 'useFetch', url: '/test', }); }).not.toThrow(); }); }); describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); it('uses baseURL from client config by default', () => { const clientWithBase = createClient({ baseURL: 'https://example.com' }); expect(clientWithBase.buildUrl({ url: '/foo' })).toBe('https://example.com/foo'); }); it('allows overriding baseURL from client config', () => { const clientWithBase = createClient({ baseURL: 'https://example.com' }); expect(clientWithBase.buildUrl({ baseURL: 'https://other.com', url: '/foo' })).toBe( 'https://other.com/foo', ); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/__tests__/utils.test.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import { mergeInterceptors, setAuthParams, unwrapRefs } from '../bundle/utils'; describe('unwrapRefs', () => { it('returns Blob as-is', () => { const blob = new Blob(['test content'], { type: 'text/plain' }); const result = unwrapRefs(blob); expect(result).toBe(blob); }); it('preserves Blob in object', () => { const blob = new Blob(['test content'], { type: 'application/json' }); const input = { file: blob, name: 'test' }; const result = unwrapRefs(input); expect(result.file).toBe(blob); expect(result.name).toBe('test'); }); it('preserves Blob in array', () => { const blob = new Blob(['test content'], { type: 'image/png' }); const input = [blob, 'text']; const result = unwrapRefs(input); expect(result[0]).toBe(blob); expect(result[1]).toBe('text'); }); it('preserves File (extends Blob) as-is', () => { const file = new File(['test content'], 'test.txt', { type: 'text/plain' }); const result = unwrapRefs(file); expect(result).toBe(file); }); it('returns AbortSignal as-is', () => { const controller = new AbortController(); const result = unwrapRefs(controller.signal); expect(result).toBe(controller.signal); }); it('preserves AbortSignal in object', () => { const controller = new AbortController(); const input = { signal: controller.signal, url: '/test' }; const result = unwrapRefs(input); expect(result.signal).toBe(controller.signal); expect(result.signal instanceof AbortSignal).toBe(true); expect(result.url).toBe('/test'); }); it('returns FormData as-is', () => { const formData = new FormData(); formData.append('key', 'value'); const result = unwrapRefs(formData); expect(result).toBe(formData); }); it('preserves FormData in object', () => { const formData = new FormData(); formData.append('key', 'value'); const input = { body: formData, url: '/upload' }; const result = unwrapRefs(input); expect(result.body).toBe(formData); expect(result.body instanceof FormData).toBe(true); }); it('returns ReadableStream as-is', () => { const stream = new ReadableStream(); const result = unwrapRefs(stream); expect(result).toBe(stream); }); }); describe('mergeInterceptors', () => { it('handles no arguments', () => { const result = mergeInterceptors(); expect(result).toEqual([]); }); it('handles interceptor function', () => { const foo = () => {}; const result = mergeInterceptors(foo); expect(result).toEqual([foo]); }); it('handles interceptors array', () => { const foo = [() => {}]; const result = mergeInterceptors(foo); expect(result).toEqual([foo[0]]); }); it('handles interceptors array and function', () => { const foo = [() => {}, () => {}]; const bar = () => {}; const result = mergeInterceptors(foo, bar); expect(result).toEqual([foo[0], foo[1], bar]); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Authorization')).toBe('foo'); expect(query).toEqual({}); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets only one specific header', async () => { const auth = vi.fn(({ name }: Auth) => { if (name === 'baz') { return 'foo'; } return 'buz'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { name: 'fiz', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(headers.get('fiz')).toBe('buz'); expect(Object.keys(query).length).toBe(0); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/bundle/client.ts ================================================ import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../../client-core/bundle/serverSentEvents'; import type { HttpMethod } from '../../client-core/bundle/types'; import { getValidRequestBody } from '../../client-core/bundle/utils'; import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/bundle/index.ts ================================================ export type { Auth } from '../../client-core/bundle/auth'; export type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../../client-core/bundle/bodySerializer'; export { buildClientParams } from '../../client-core/bundle/params'; export { serializeQueryKeyValue } from '../../client-core/bundle/queryKeySerializer'; export { createClient } from './client'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/bundle/types.ts ================================================ import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../../client-core/bundle/auth'; import type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../../client-core/bundle/serverSentEvents'; import type { Client as CoreClient, Config as CoreConfig } from '../../client-core/bundle/types'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/bundle/utils.ts ================================================ import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../../client-core/bundle/auth'; import type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; import { jsonBodySerializer } from '../../client-core/bundle/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../../client-core/bundle/pathSerializer'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta, } from '../../../plugins/@hey-api/client-core/config'; import { clientPluginHandler } from '../../../plugins/@hey-api/client-core/plugin'; import type { HeyApiClientNuxtPlugin } from './types'; export const defaultConfig: HeyApiClientNuxtPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as unknown as HeyApiClientNuxtPlugin['Handler'], name: '@hey-api/client-nuxt', }; /** * Type helper for `@hey-api/client-nuxt` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/index.ts ================================================ export type { Client as NuxtClient } from './bundle/types'; export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientNuxtPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-nuxt/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { Client } from '../../../plugins/@hey-api/client-core/types'; export type UserConfig = Plugin.Name<'@hey-api/client-nuxt'> & Client.Config; export type HeyApiClientNuxtPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/__tests__/client.test.ts ================================================ import { createClient } from '../bundle/client'; import type { ResolvedRequestOptions } from '../bundle/types'; type MockOfetch = ((...args: any[]) => any) & { raw?: any; }; const makeMockOfetch = (response: Response): MockOfetch => { const fn: any = vi.fn(); fn.raw = vi.fn().mockResolvedValue(response); return fn as MockOfetch; }; describe('buildUrl', () => { const client = createClient(); const scenarios: { options: Parameters[0]; url: string; }[] = [ { options: { url: '', }, url: '/', }, { options: { url: '/foo', }, url: '/foo', }, { options: { path: { fooId: 1, }, url: '/foo/{fooId}', }, url: '/foo/1', }, { options: { path: { fooId: 1, }, query: { bar: 'baz', }, url: '/foo/{fooId}', }, url: '/foo/1?bar=baz', }, { options: { query: { bar: [], foo: [], }, url: '/', }, url: '/', }, { options: { query: { bar: [], foo: ['abc', 'def'], }, url: '/', }, url: '/?foo=abc&foo=def', }, ]; it.each(scenarios)('returns $url', ({ options, url }) => { expect(client.buildUrl(options)).toBe(url); }); it('uses baseUrl from client config by default', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ url: '/foo' })).toBe('https://example.com/foo'); }); it('allows overriding baseUrl from client config', () => { const clientWithBase = createClient({ baseUrl: 'https://example.com' }); expect(clientWithBase.buildUrl({ baseUrl: 'https://other.com', url: '/foo' })).toBe( 'https://other.com/foo', ); }); }); describe('zero-length body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('returns empty Blob for zero-length application/octet-stream response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/octet-stream', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.request({ method: 'GET', ofetch: mockOfetch as any, url: '/test', }); expect(result.data).toBeInstanceOf(Blob); expect((result.data as Blob).size).toBe(0); }); it('returns empty ArrayBuffer for zero-length response with arrayBuffer parseAs', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.request({ method: 'GET', ofetch: mockOfetch as any, parseAs: 'arrayBuffer', url: '/test', }); expect(result.data).toBeInstanceOf(ArrayBuffer); expect((result.data as ArrayBuffer).byteLength).toBe(0); }); it('returns empty string for zero-length text response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'text/plain', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.request({ method: 'GET', ofetch: mockOfetch as any, url: '/test', }); expect(result.data).toBe(''); }); it('returns empty object for zero-length JSON response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'application/json', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.request({ method: 'GET', ofetch: mockOfetch as any, url: '/test', }); expect(result.data).toEqual({}); }); it('returns empty FormData for zero-length multipart/form-data response', async () => { const mockResponse = new Response(null, { headers: { 'Content-Length': '0', 'Content-Type': 'multipart/form-data', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.request({ method: 'GET', ofetch: mockOfetch as any, url: '/test', }); expect(result.data).toBeInstanceOf(FormData); expect([...(result.data as FormData).entries()]).toHaveLength(0); }); it('returns stream body for zero-length stream response', async () => { const mockBody = new ReadableStream(); const mockResponse = new Response(mockBody, { headers: { 'Content-Length': '0', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.request({ method: 'GET', ofetch: mockOfetch as any, parseAs: 'stream', url: '/test', }); expect(result.data).toBe(mockBody); }); it('handles non-zero content correctly for comparison', async () => { const blobContent = new Blob(['test data']); const mockResponse = new Response(blobContent, { headers: { 'Content-Type': 'application/octet-stream', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.request({ method: 'GET', ofetch: mockOfetch as any, url: '/test', }); expect(result.data).toBeInstanceOf(Blob); expect((result.data as Blob).size).toBeGreaterThan(0); }); }); describe('unserialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: 0, textValue: '0' }, { body: false, textValue: 'false' }, { body: 'test string', textValue: 'test string' }, { body: '', textValue: '' }, ]; it.each(scenarios)('handles plain text body with $body value', async ({ body, textValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.post({ body, bodySerializer: null, headers: { 'Content-Type': 'text/plain', }, ofetch: mockOfetch as any, url: '/test', }); await expect(result.request.text()).resolves.toEqual(textValue); expect(result.request.headers.get('Content-Type')).toEqual('text/plain'); }); }); describe('serialized request body handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: '', expectBodyValue: null, expectContentHeader: false, serializedBody: '', textValue: '', }, { body: 0, expectBodyValue: 0, expectContentHeader: true, serializedBody: 0, textValue: '0', }, { body: false, expectBodyValue: false, expectContentHeader: true, serializedBody: false, textValue: 'false', }, { body: {}, expectBodyValue: '{"key":"value"}', expectContentHeader: true, serializedBody: '{"key":"value"}', textValue: '{"key":"value"}', }, ]; it.each(scenarios)( 'handles $serializedBody serializedBody value', async ({ body, expectBodyValue, expectContentHeader, serializedBody, textValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const result = await client.post({ body, bodySerializer: () => serializedBody, headers: { 'Content-Type': 'application/json', }, ofetch: mockOfetch as any, url: '/test', }); // Ensure request captures serialized text value await expect(result.request.text()).resolves.toEqual(textValue); expect(result.request.headers.get('Content-Type')).toEqual( expectContentHeader ? 'application/json' : null, ); // Ensure ofetch.raw received the expected body const call = (mockOfetch.raw as any).mock.calls[0]; const opts = call[1]; expect(opts.body).toEqual(expectBodyValue); }, ); }); describe('request interceptor', () => { const client = createClient({ baseUrl: 'https://example.com' }); const scenarios = [ { body: 'test string', bodySerializer: null, contentType: 'text/plain', expectedSerializedValue: undefined, }, { body: { key: 'value' }, bodySerializer: (body: unknown) => JSON.stringify(body), contentType: 'application/json', expectedSerializedValue: '{"key":"value"}', }, ]; it.each(scenarios)( 'exposes $contentType serialized and raw body values', async ({ body, bodySerializer, contentType, expectedSerializedValue }) => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const mockRequestInterceptor = vi .fn() .mockImplementation((request: Request, options: ResolvedRequestOptions) => { expect(options.serializedBody).toBe(expectedSerializedValue); expect(options.body).toBe(body); return request; }); const interceptorId = client.interceptors.request.use(mockRequestInterceptor); await client.post({ body, bodySerializer, headers: { 'Content-Type': contentType, }, ofetch: mockOfetch as any, url: '/test', }); expect(mockRequestInterceptor).toHaveBeenCalledOnce(); client.interceptors.request.eject(interceptorId); }, ); }); describe('FormData boundary handling', () => { const client = createClient({ baseUrl: 'https://example.com' }); it('should not include Content-Type header for FormData body to avoid boundary mismatch', async () => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const formData = new FormData(); formData.append('field1', 'value1'); formData.append('field2', 'value2'); await client.post({ body: formData, bodySerializer: null, ofetch: mockOfetch as any, url: '/upload', }); // Verify that ofetch.raw was called expect(mockOfetch.raw).toHaveBeenCalledOnce(); // Get the options passed to ofetch.raw const call = (mockOfetch.raw as any).mock.calls[0]; const opts = call[1]; // Verify that FormData is passed as body expect(opts.body).toBeInstanceOf(FormData); // Verify that Content-Type header is NOT set (so ofetch can set its own boundary) expect(opts.headers.get('Content-Type')).toBeNull(); }); it('should preserve Content-Type header for non-FormData bodies', async () => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); await client.post({ body: { test: 'data' }, ofetch: mockOfetch as any, url: '/api', }); // Verify that ofetch.raw was called expect(mockOfetch.raw).toHaveBeenCalledOnce(); // Get the options passed to ofetch.raw const call = (mockOfetch.raw as any).mock.calls[0]; const opts = call[1]; // Verify that Content-Type header IS set for JSON expect(opts.headers.get('Content-Type')).toBe('application/json'); }); it('should handle FormData with interceptors correctly', async () => { const mockResponse = new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json', }, status: 200, }); const mockOfetch = makeMockOfetch(mockResponse); const formData = new FormData(); formData.append('field1', 'value1'); const mockRequestInterceptor = vi.fn().mockImplementation((request: Request) => { // Interceptor can modify headers but we should still remove Content-Type for FormData request.headers.set('X-Custom-Header', 'custom-value'); return request; }); const interceptorId = client.interceptors.request.use(mockRequestInterceptor); await client.post({ body: formData, bodySerializer: null, ofetch: mockOfetch as any, url: '/upload', }); expect(mockRequestInterceptor).toHaveBeenCalledOnce(); // Get the options passed to ofetch.raw const call = (mockOfetch.raw as any).mock.calls[0]; const opts = call[1]; // Verify that Content-Type is NOT set even after interceptor expect(opts.headers.get('Content-Type')).toBeNull(); // Verify that custom header from interceptor IS preserved expect(opts.headers.get('X-Custom-Header')).toBe('custom-value'); client.interceptors.request.eject(interceptorId); }); }); // Note: дополнительные проверки поведения ofetch (responseType/responseStyle/retry) // не дублируем, чтобы набор тестов оставался сопоставим с другими клиентами. ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/__tests__/utils.test.ts ================================================ import type { Auth } from '../../client-core/bundle/auth'; import type { ResolvedRequestOptions } from '../bundle/types'; import { buildOfetchOptions, mergeHeaders, setAuthParams } from '../bundle/utils'; describe('mergeHeaders', () => { it('merges plain objects into Headers', () => { const headers = mergeHeaders( { baz: 'qux', foo: 'bar', }, { baz: 'override', }, ); expect(headers).toBeInstanceOf(Headers); expect(headers.get('foo')).toBe('bar'); expect(headers.get('baz')).toBe('override'); }); }); describe('setAuthParams', () => { it('sets bearer token in headers', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(Object.keys(query).length).toBe(0); }); it('sets access token in query', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets Authorization header when `in` and `name` are undefined', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Authorization')).toBe('foo'); expect(Object.keys(query).length).toBe(0); }); it('sets an API key in a cookie', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { in: 'cookie', name: 'baz', type: 'apiKey', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('Cookie')).toContain('baz=foo'); expect(Object.keys(query).length).toBe(0); }); it('sets first scheme only', async () => { const auth = vi.fn().mockReturnValue('foo'); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(query.baz).toBeUndefined(); }); it('sets first scheme with token', async () => { const auth = vi.fn().mockImplementation((auth: Auth) => { if (auth.type === 'apiKey') { return; } return 'foo'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', type: 'apiKey', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBeNull(); expect(query.baz).toBe('Bearer foo'); }); it('sets only one specific header', async () => { const auth = vi.fn(({ name }: Auth) => { if (name === 'baz') { return 'foo'; } return 'buz'; }); const headers = new Headers(); const query: Record = {}; await setAuthParams({ auth, headers, query, security: [ { name: 'baz', scheme: 'bearer', type: 'http', }, { name: 'fiz', type: 'http', }, { in: 'query', name: 'baz', scheme: 'bearer', type: 'http', }, ], }); expect(auth).toHaveBeenCalled(); expect(headers.get('baz')).toBe('Bearer foo'); expect(headers.get('fiz')).toBe('buz'); expect(Object.keys(query).length).toBe(0); }); }); describe('buildOfetchOptions', () => { it('passes through credentials property when provided', () => { const opts: ResolvedRequestOptions = { baseUrl: 'https://api.example.com', credentials: 'include' as const, headers: new Headers({ 'Content-Type': 'application/json' }), method: 'GET', url: '/test', }; const result = buildOfetchOptions(opts, null, undefined); expect(result.credentials).toBe('include'); }); it('passes through undefined credentials when not provided', () => { const opts: ResolvedRequestOptions = { baseUrl: 'https://api.example.com', headers: new Headers({ 'Content-Type': 'application/json' }), method: 'GET', url: '/test', }; const result = buildOfetchOptions(opts, null, undefined); expect(result.credentials).toBeUndefined(); }); it('passes through different credential values', () => { const testCases: Array = ['omit', 'same-origin', 'include']; testCases.forEach((credentialValue) => { const opts: ResolvedRequestOptions = { baseUrl: 'https://api.example.com', credentials: credentialValue, headers: new Headers({ 'Content-Type': 'application/json' }), method: 'GET', url: '/test', }; const result = buildOfetchOptions(opts, null, undefined); expect(result.credentials).toBe(credentialValue); }); }); }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/bundle/client.ts ================================================ import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../../client-core/bundle/serverSentEvents'; import type { HttpMethod } from '../../client-core/bundle/types'; import { getValidRequestBody } from '../../client-core/bundle/utils'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/bundle/index.ts ================================================ export type { Auth } from '../../client-core/bundle/auth'; export type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../../client-core/bundle/bodySerializer'; export { buildClientParams } from '../../client-core/bundle/params'; export { serializeQueryKeyValue } from '../../client-core/bundle/queryKeySerializer'; export { createClient } from './client'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types'; export { createConfig, mergeHeaders } from './utils'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/bundle/types.ts ================================================ import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../../client-core/bundle/auth'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../../client-core/bundle/serverSentEvents'; import type { Client as CoreClient, Config as CoreConfig } from '../../client-core/bundle/types'; import type { Middleware } from './utils'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/bundle/utils.ts ================================================ import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../../client-core/bundle/auth'; import type { QuerySerializerOptions } from '../../client-core/bundle/bodySerializer'; import { jsonBodySerializer } from '../../client-core/bundle/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../../client-core/bundle/pathSerializer'; import { getUrl } from '../../client-core/bundle/utils'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { clientDefaultConfig, clientDefaultMeta, } from '../../../plugins/@hey-api/client-core/config'; import { clientPluginHandler } from '../../../plugins/@hey-api/client-core/plugin'; import type { HeyApiClientOfetchPlugin } from './types'; export const defaultConfig: HeyApiClientOfetchPlugin['Config'] = { ...clientDefaultMeta, config: { ...clientDefaultConfig, throwOnError: false, }, handler: clientPluginHandler, name: '@hey-api/client-ofetch', }; /** * Type helper for `@hey-api/client-ofetch` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/index.ts ================================================ export type { Client as OfetchClient } from './bundle/types'; export { defaultConfig, defineConfig } from './config'; export type { HeyApiClientOfetchPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/client-ofetch/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { Client } from '../../../plugins/@hey-api/client-core/types'; export type UserConfig = Plugin.Name<'@hey-api/client-ofetch'> & Client.Config & { /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: boolean; }; export type HeyApiClientOfetchPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/schemas/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { handler } from './plugin'; import type { HeyApiSchemasPlugin } from './types'; export const defaultConfig: HeyApiSchemasPlugin['Config'] = { config: { includeInEntry: false, nameBuilder: (name) => `${name}Schema`, type: 'json', }, handler, name: '@hey-api/schemas', }; /** * Type helper for `@hey-api/schemas` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/schemas/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { HeyApiSchemasPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/schemas/plugin.ts ================================================ import type { Context, OpenApi, OpenApiV2_0_XTypes, OpenApiV3_0_XTypes, OpenApiV3_1_XTypes, } from '@hey-api/shared'; import { satisfies } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import type { HeyApiSchemasPlugin } from './types'; const stripSchema = ({ plugin, schema, }: { plugin: HeyApiSchemasPlugin['Instance']; schema: | OpenApiV2_0_XTypes['SchemaObject'] | OpenApiV3_0_XTypes['SchemaObject'] | OpenApiV3_1_XTypes['SchemaObject']; }) => { if (plugin.config.type === 'form') { if (schema.description) { delete schema.description; } if (schema['x-enum-descriptions']) { delete schema['x-enum-descriptions']; } if (schema['x-enum-varnames']) { delete schema['x-enum-varnames']; } if (schema['x-enumNames']) { delete schema['x-enumNames']; } if (schema.title) { delete schema.title; } } }; const schemaToJsonSchemaDraft_04 = ({ context, plugin, schema: _schema, }: { context: Context; plugin: HeyApiSchemasPlugin['Instance']; schema: OpenApiV2_0_XTypes['SchemaObject']; }): OpenApiV2_0_XTypes['SchemaObject'] => { if (Array.isArray(_schema)) { return _schema.map((item) => schemaToJsonSchemaDraft_04({ context, plugin, schema: item, }), ) as unknown as OpenApiV2_0_XTypes['SchemaObject']; } const schema = structuredClone(_schema); if (schema.$ref) { // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` schema.$ref = decodeURI(schema.$ref); return schema; } stripSchema({ plugin, schema }); if (schema.additionalProperties && typeof schema.additionalProperties !== 'boolean') { schema.additionalProperties = schemaToJsonSchemaDraft_04({ context, plugin, schema: schema.additionalProperties, }); } if (schema.allOf) { schema.allOf = schema.allOf.map((item) => schemaToJsonSchemaDraft_04({ context, plugin, schema: item, }), ); } if (schema.items) { schema.items = schemaToJsonSchemaDraft_04({ context, plugin, schema: schema.items as OpenApiV2_0_XTypes['SchemaObject'], }); } if (schema.properties) { for (const name in schema.properties) { const property = schema.properties[name]!; if (typeof property !== 'boolean') { schema.properties[name] = schemaToJsonSchemaDraft_04({ context, plugin, schema: property, }); } } } return schema; }; const schemaToJsonSchemaDraft_05 = ({ context, plugin, schema: _schema, }: { context: Context; plugin: HeyApiSchemasPlugin['Instance']; schema: OpenApiV3_0_XTypes['SchemaObject'] | OpenApiV3_0_XTypes['ReferenceObject']; }): OpenApiV3_0_XTypes['SchemaObject'] | OpenApiV3_0_XTypes['ReferenceObject'] => { if (Array.isArray(_schema)) { return _schema.map((item) => schemaToJsonSchemaDraft_05({ context, plugin, schema: item, }), ) as unknown as OpenApiV3_0_XTypes['SchemaObject'] | OpenApiV3_0_XTypes['ReferenceObject']; } const schema = structuredClone(_schema); if ('$ref' in schema) { // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` schema.$ref = decodeURI(schema.$ref); return schema; } stripSchema({ plugin, schema }); if (schema.additionalProperties && typeof schema.additionalProperties !== 'boolean') { schema.additionalProperties = schemaToJsonSchemaDraft_05({ context, plugin, schema: schema.additionalProperties, }); } if (schema.allOf) { schema.allOf = schema.allOf.map((item) => schemaToJsonSchemaDraft_05({ context, plugin, schema: item, }), ); } if (schema.anyOf) { schema.anyOf = schema.anyOf.map((item) => schemaToJsonSchemaDraft_05({ context, plugin, schema: item, }), ); } if (schema.items) { schema.items = schemaToJsonSchemaDraft_05({ context, plugin, schema: schema.items, }); } if (schema.oneOf) { schema.oneOf = schema.oneOf.map((item) => schemaToJsonSchemaDraft_05({ context, plugin, schema: item, }), ); } if (schema.properties) { for (const name in schema.properties) { const property = schema.properties[name]!; if (typeof property !== 'boolean') { schema.properties[name] = schemaToJsonSchemaDraft_05({ context, plugin, schema: property, }); } } } return schema; }; const schemaToJsonSchema2020_12 = ({ context, plugin, schema: _schema, }: { context: Context; plugin: HeyApiSchemasPlugin['Instance']; schema: OpenApiV3_1_XTypes['SchemaObject']; }): OpenApiV3_1_XTypes['SchemaObject'] => { if (Array.isArray(_schema)) { return _schema.map((item) => schemaToJsonSchema2020_12({ context, plugin, schema: item, }), ) as unknown as OpenApiV3_1_XTypes['SchemaObject']; } const schema = structuredClone(_schema); stripSchema({ plugin, schema }); if (schema.$ref) { // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` schema.$ref = decodeURI(schema.$ref); } if (schema.additionalProperties && typeof schema.additionalProperties !== 'boolean') { schema.additionalProperties = schemaToJsonSchema2020_12({ context, plugin, schema: schema.additionalProperties, }); } if (schema.allOf) { schema.allOf = schema.allOf.map((item) => schemaToJsonSchema2020_12({ context, plugin, schema: item, }), ); } if (schema.anyOf) { schema.anyOf = schema.anyOf.map((item) => schemaToJsonSchema2020_12({ context, plugin, schema: item, }), ); } if (schema.items) { schema.items = schemaToJsonSchema2020_12({ context, plugin, schema: schema.items, }); } if (schema.oneOf) { schema.oneOf = schema.oneOf.map((item) => schemaToJsonSchema2020_12({ context, plugin, schema: item, }), ); } if (schema.prefixItems) { schema.prefixItems = schema.prefixItems.map((item) => schemaToJsonSchema2020_12({ context, plugin, schema: item, }), ); } if (schema.properties) { for (const name in schema.properties) { const property = schema.properties[name]!; if (typeof property !== 'boolean') { schema.properties[name] = schemaToJsonSchema2020_12({ context, plugin, schema: property, }); } } } return schema; }; const schemaName = ({ name, plugin, schema, }: { name: string; plugin: HeyApiSchemasPlugin['Instance']; schema: | OpenApiV2_0_XTypes['SchemaObject'] | OpenApiV3_0_XTypes['ReferenceObject'] | OpenApiV3_0_XTypes['SchemaObject'] | OpenApiV3_1_XTypes['SchemaObject']; }): string => { let customName = ''; if (plugin.config.nameBuilder) { if (typeof plugin.config.nameBuilder === 'function') { customName = plugin.config.nameBuilder(name, schema); } else { customName = plugin.config.nameBuilder.replace('{{name}}', name); } } if (!customName) { customName = `${name}Schema`; } return customName; }; const schemasV2_0_X = ({ context, plugin, }: { context: Context; plugin: HeyApiSchemasPlugin['Instance']; }) => { if (!context.spec.definitions) { return; } for (const name in context.spec.definitions) { const schema = context.spec.definitions[name]!; const symbol = plugin.symbol(schemaName({ name, plugin, schema }), { meta: { category: 'schema', resource: 'definition', resourceId: name, tool: 'json-schema', }, }); const obj = schemaToJsonSchemaDraft_04({ context, plugin, schema, }); const statement = $.const(symbol) .export() .assign( $( $.fromValue(obj, { layout: 'pretty', }), ).as('const'), ); plugin.node(statement); } }; const schemasV3_0_X = ({ context, plugin, }: { context: Context; plugin: HeyApiSchemasPlugin['Instance']; }) => { if (!context.spec.components) { return; } for (const name in context.spec.components.schemas) { const schema = context.spec.components.schemas[name]!; const symbol = plugin.symbol(schemaName({ name, plugin, schema }), { meta: { category: 'schema', resource: 'definition', resourceId: name, tool: 'json-schema', }, }); const obj = schemaToJsonSchemaDraft_05({ context, plugin, schema, }); const statement = $.const(symbol) .export() .assign( $( $.fromValue(obj, { layout: 'pretty', }), ).as('const'), ); plugin.node(statement); } }; const schemasV3_1_X = ({ context, plugin, }: { context: Context; plugin: HeyApiSchemasPlugin['Instance']; }) => { if (!context.spec.components) { return; } for (const name in context.spec.components.schemas) { const schema = context.spec.components.schemas[name]!; const symbol = plugin.symbol(schemaName({ name, plugin, schema }), { meta: { category: 'schema', resource: 'definition', resourceId: name, tool: 'json-schema', }, }); const obj = schemaToJsonSchema2020_12({ context, plugin, schema, }); const statement = $.const(symbol) .export() .assign( $( $.fromValue(obj, { layout: 'pretty', }), ).as('const'), ); plugin.node(statement); } }; export const handler: HeyApiSchemasPlugin['Handler'] = ({ plugin }) => { if ('swagger' in plugin.context.spec) { schemasV2_0_X({ context: plugin.context as Context, plugin, }); return; } if (satisfies(plugin.context.spec.openapi, '>=3.0.0 <3.1.0')) { schemasV3_0_X({ context: plugin.context as Context, plugin, }); return; } if (satisfies(plugin.context.spec.openapi, '>=3.1.0')) { schemasV3_1_X({ context: plugin.context as Context, plugin, }); return; } throw new Error('Unsupported OpenAPI specification'); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/schemas/types.ts ================================================ import type { DefinePlugin, OpenApiV2_0_XTypes, OpenApiV3_0_XTypes, OpenApiV3_1_XTypes, Plugin, } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@hey-api/schemas'> & Plugin.Hooks & Plugin.UserExports & { /** * Customise the schema name. By default, `{{name}}Schema` is used. `name` is a * valid JavaScript/TypeScript identifier, e.g. if your schema name is * "Foo-Bar", `name` value would be "FooBar". * * @default '{{name}}Schema' */ nameBuilder?: | string | (( name: string, schema: | OpenApiV2_0_XTypes['SchemaObject'] | OpenApiV3_0_XTypes['ReferenceObject'] | OpenApiV3_0_XTypes['SchemaObject'] | OpenApiV3_1_XTypes['SchemaObject'], ) => string); /** * Choose schema type to generate. Select 'form' if you don't want * descriptions to reduce bundle size and you plan to use schemas * for form validation * * @default 'json' */ type?: 'form' | 'json'; }; export type HeyApiSchemasPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/config.ts ================================================ import { log } from '@hey-api/codegen-core'; import { definePluginConfig } from '@hey-api/shared'; import { resolveExamples } from './examples'; import { resolveOperations } from './operations'; import { handler } from './plugin'; import type { HeyApiSdkPlugin } from './types'; const transformerInferWarn = 'You set `transformer: true` but no transformer plugin was found in your plugins. Add a transformer plugin like `@hey-api/transformers` to enable this feature. The transformer option has been disabled.'; const validatorInferWarn = 'You set `validator: true` but no validator plugin was found in your plugins. Add a validator plugin like `zod` to enable this feature. The validator option has been disabled.'; export const defaultConfig: HeyApiSdkPlugin['Config'] = { config: { auth: true, client: true, comments: true, includeInEntry: true, paramsStructure: 'grouped', responseStyle: 'fields', transformer: false, validator: false, // Deprecated - kept for backward compatibility // eslint-disable-next-line sort-keys-fix/sort-keys-fix response: 'body', }, dependencies: ['@hey-api/typescript'], handler, name: '@hey-api/sdk', resolveConfig: (plugin, context) => { if (plugin.config.client) { if (typeof plugin.config.client === 'boolean') { plugin.config.client = context.pluginByTag('client', { defaultPlugin: '@hey-api/client-fetch', }); } plugin.dependencies.add(plugin.config.client!); } else { plugin.config.client = false; } if (plugin.config.transformer) { if (typeof plugin.config.transformer === 'boolean') { try { plugin.config.transformer = context.pluginByTag('transformer'); plugin.dependencies.add(plugin.config.transformer!); } catch { log.warn(transformerInferWarn); plugin.config.transformer = false; } } else { plugin.dependencies.add(plugin.config.transformer); } } else { plugin.config.transformer = false; } if (typeof plugin.config.validator !== 'object') { plugin.config.validator = { request: plugin.config.validator, response: plugin.config.validator, }; } if (plugin.config.validator.request) { if (typeof plugin.config.validator.request === 'boolean') { try { plugin.config.validator.request = context.pluginByTag('validator'); plugin.dependencies.add(plugin.config.validator.request!); } catch { log.warn(validatorInferWarn); plugin.config.validator.request = false; } } else { plugin.dependencies.add(plugin.config.validator.request); } } else { plugin.config.validator.request = false; } if (plugin.config.validator.response) { if (typeof plugin.config.validator.response === 'boolean') { try { plugin.config.validator.response = context.pluginByTag('validator'); plugin.dependencies.add(plugin.config.validator.response!); } catch { log.warn(validatorInferWarn); plugin.config.validator.response = false; } } else { plugin.dependencies.add(plugin.config.validator.response); } } else { plugin.config.validator.response = false; } plugin.config.examples = resolveExamples(plugin.config, context); plugin.config.operations = resolveOperations(plugin.config, context); }, }; /** * Type helper for `@hey-api/sdk` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/examples/config.ts ================================================ import type { PluginContext } from '@hey-api/shared'; import type { UserConfig } from '../types'; import type { ExamplesConfig } from './types'; type Config = Omit; export function resolveExamples(config: Config, context: PluginContext): ExamplesConfig { return context.valueToObject({ defaultValue: { enabled: Boolean(config.examples), language: 'JavaScript', }, mappers: { boolean: (enabled) => ({ enabled }), }, value: config.examples, }) as ExamplesConfig; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/examples/index.ts ================================================ export { resolveExamples } from './config'; export type { ExamplesConfig, UserExamplesConfig } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/examples/types.ts ================================================ import type { FeatureToggle, IR, LinguistLanguages } from '@hey-api/shared'; import type { MaybeFunc } from '@hey-api/types'; import type { CallArgs, DollarTsDsl, ExampleOptions } from '../../../../ts-dsl'; export type UserExamplesConfig = Omit & { /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * The programming language for the generated examples. * * This is used to display the language label in code blocks in * documentation UIs. * * @default 'JavaScript' */ language?: LinguistLanguages; /** * Example request payload. */ payload?: MaybeFunc< (operation: IR.OperationObject, ctx: DollarTsDsl) => CallArgs | CallArgs[number] >; /** * Transform the generated example string. * * @param example The generated example string. * @param operation The operation the example was generated for. * @returns The final example string. */ transform?: (example: string, operation: IR.OperationObject) => string; }; export type ExamplesConfig = Omit & FeatureToggle & { /** * The programming language for the generated examples. * * This is used to display the language label in code blocks in * documentation UIs. */ language: LinguistLanguages; /** * Example request payload. */ payload?: MaybeFunc< (operation: IR.OperationObject, ctx: DollarTsDsl) => CallArgs | CallArgs[number] >; /** * Transform the generated example string. * * @param example The generated example string. * @param operation The operation the example was generated for. * @returns The final example string. */ transform?: (example: string, operation: IR.OperationObject) => string; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { HeyApiSdkPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/operations/config.ts ================================================ import { log } from '@hey-api/codegen-core'; import type { PluginContext } from '@hey-api/shared'; import type { UserConfig } from '../types'; import type { OperationsConfig, UserOperationsConfig } from './types'; type Config = Omit; export function resolveOperations(config: Config, context: PluginContext): OperationsConfig { if (config.asClass !== undefined) { log.warnDeprecated({ context: '@hey-api/sdk', field: 'asClass', replacement: ['operations: { strategy: "byTags" }', 'operations: { strategy: "single" }'], }); } if (config.classNameBuilder !== undefined) { log.warnDeprecated({ context: '@hey-api/sdk', field: 'classNameBuilder', replacement: 'operations: { containerName: "..." }', }); } if (config.classStructure !== undefined) { log.warnDeprecated({ context: '@hey-api/sdk', field: 'classStructure', replacement: ['operations: { nesting: "operationId" }', 'operations: { nesting: "id" }'], }); } if (config.instance !== undefined) { log.warnDeprecated({ context: '@hey-api/sdk', field: 'instance', replacement: `operations: { strategy: "single", containerName: "${config.instance || 'Name'}", methods: "instance" }`, }); } if (config.methodNameBuilder !== undefined) { log.warnDeprecated({ context: '@hey-api/sdk', field: 'methodNameBuilder', replacement: 'operations: { methodName: "..." }', }); } if (config.operationId !== undefined) { log.warnDeprecated({ context: '@hey-api/sdk', field: 'operationId', replacement: ['operations: { nesting: "operationId" }', 'operations: { nesting: "id" }'], }); } const legacy = mapLegacyToConfig(config); return normalizeConfig(config.operations, legacy, context); } function normalizeConfig( input: Config['operations'], legacy: Partial, context: PluginContext, ): OperationsConfig { if (!input || typeof input === 'string' || typeof input === 'function') { input = { strategy: input }; } const strategy = legacy.strategy ?? input.strategy ?? 'flat'; const methods: OperationsConfig['methods'] = strategy === 'single' ? 'instance' : 'static'; return context.valueToObject({ defaultValue: { container: 'class', methods, nesting: 'operationId', nestingDelimiters: /[./]/, strategy, strategyDefaultTag: 'default', }, mappers: { object(value) { value.containerName = context.valueToObject({ defaultValue: strategy === 'single' ? { casing: 'PascalCase', name: 'Sdk' } : { casing: 'PascalCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.containerName, }); value.methodName = context.valueToObject({ defaultValue: { casing: 'camelCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.methodName, }); value.segmentName = context.valueToObject({ defaultValue: { casing: 'PascalCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.segmentName, }); return value; }, }, value: { ...legacy, ...input, } as UserOperationsConfig, }) as OperationsConfig; } function mapLegacyToConfig(config: Config): Partial { let strategy: OperationsConfig['strategy'] | undefined; if (config.instance) { strategy = 'single'; } else if (config.asClass) { strategy = 'byTags'; } else if (config.instance === false || config.asClass === false) { strategy = 'flat'; } let containerName: OperationsConfig['containerName'] | undefined; let segmentName: OperationsConfig['segmentName'] | undefined; if (config.instance) { let name = typeof config.instance === 'string' ? config.instance : 'Sdk'; segmentName = { casing: 'PascalCase' }; if (config.classNameBuilder) { segmentName.name = config.classNameBuilder; if (typeof config.classNameBuilder === 'string') { name = config.classNameBuilder.replace('{{name}}', name); } else { name = config.classNameBuilder(name); } } containerName = { casing: 'PascalCase', name }; } else if (config.classNameBuilder) { containerName = { casing: 'PascalCase', name: config.classNameBuilder, }; segmentName = { ...containerName }; } else if (config.asClass) { containerName = { casing: 'PascalCase' }; segmentName = { ...containerName }; } let methods: OperationsConfig['methods'] | undefined; if (config.instance) { methods = 'instance'; } else if (config.asClass) { methods = 'static'; } let nesting: OperationsConfig['nesting'] | undefined; if (config.classStructure === 'off' || config.operationId === false) { nesting = 'id'; } else if (config.classStructure === 'auto') { nesting = 'operationId'; } let methodName: OperationsConfig['methodName'] | undefined; if (config.methodNameBuilder) { methodName = { casing: 'camelCase', name: config.methodNameBuilder, }; } return { containerName, methodName, methods, nesting, segmentName, strategy, }; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/operations/index.ts ================================================ export { resolveOperations } from './config'; export { resolveStrategy } from './resolve'; export type { OperationsConfig, UserOperationsConfig } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/operations/resolve.ts ================================================ import type { OperationPathStrategy, OperationStructureStrategy } from '@hey-api/shared'; import { OperationPath, OperationStrategy } from '@hey-api/shared'; import type { HeyApiSdkPlugin } from '../types'; function resolvePath(plugin: HeyApiSdkPlugin['Instance']): OperationPathStrategy { if (plugin.config.operations.nesting === 'id') { return OperationPath.id(); } if (plugin.config.operations.nesting === 'operationId') { return OperationPath.fromOperationId({ delimiters: plugin.config.operations.nestingDelimiters, fallback: OperationPath.id(), }); } return plugin.config.operations.nesting; } export function resolveStrategy(plugin: HeyApiSdkPlugin['Instance']): OperationStructureStrategy { if (plugin.config.operations.strategy === 'flat') { return OperationStrategy.flat({ path: (operation) => [resolvePath(plugin)(operation).join('.')], }); } if (plugin.config.operations.strategy === 'single') { const root = plugin.config.operations.containerName; return OperationStrategy.single({ path: resolvePath(plugin), root: typeof root.name === 'string' ? root.name : (root.name?.('') ?? ''), }); } if (plugin.config.operations.strategy === 'byTags') { return OperationStrategy.byTags({ fallback: plugin.config.operations.strategyDefaultTag, path: resolvePath(plugin), }); } return plugin.config.operations.strategy; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/operations/types.ts ================================================ import type { NamingConfig, NamingRule, OperationPathStrategy, OperationsStrategy, } from '@hey-api/shared'; export interface UserOperationsConfig { /** * Type of container for grouped operations. * * Ignored when `strategy` is `'flat'`. * * - `'class'` - Class with methods * * @default 'class' */ container?: 'class'; // * - `'object'` - Object with properties // container?: 'class' | 'object'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'Sdk' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'MyApi' * * @example * // Transform tag names with suffix * containerName: '{{name}}Service' * * @example * // With casing * containerName: { name: '{{name}}Service', casing: 'PascalCase' } */ containerName?: NamingRule; /** * Customize method/function names. * * Applied to the final segment of the path (the method name). */ methodName?: NamingRule; /** * How methods are attached to class containers. * * Only applies when `container` is `'class'`. * * - `'static'` - Static methods, no instantiation required * - `'instance'` - Instance methods, requires `new ClassName(config)` * * @default 'instance' */ methods?: 'instance' | 'static'; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control * * @default 'operationId' */ nesting?: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. * * @default /[./]/ */ nestingDelimiters?: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the method name). */ segmentName?: NamingRule; /** * Grouping strategy. * * - `'flat'` - Standalone functions, no grouping * - `'byTags'` - One container per operation tag * - `'single'` - All operations in one container * - Custom function for full control * * @default 'flat' */ strategy?: OperationsStrategy; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. * * @default 'default' */ strategyDefaultTag?: string; } export interface OperationsConfig { /** Type of container for grouped operations. */ container: 'class'; // * - `'object'` - Object with properties // container: 'class' | 'object'; /** Customize container names. */ containerName: NamingConfig; /** Customize method/function names. */ methodName: NamingConfig; /** How methods are attached to class containers. */ methods: 'instance' | 'static'; /** How to derive nesting structure from operations. */ nesting: 'operationId' | 'id' | OperationPathStrategy; /** Delimiters for splitting operationId. */ nestingDelimiters: RegExp; /** Customize nesting segment names. */ segmentName: NamingConfig; /** Grouping strategy. */ strategy: OperationsStrategy; /** Default container name for operations without tags. */ strategyDefaultTag: string; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/plugin.ts ================================================ import type { HeyApiSdkPlugin } from './types'; import { handlerV1 } from './v1/plugin'; export const handler: HeyApiSdkPlugin['Handler'] = (args) => handlerV1(args); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/shared/auth.ts ================================================ import type { Context, IR } from '@hey-api/shared'; import type { Auth } from '../../client-core/bundle/auth'; import type { HeyApiSdkPlugin } from '../types'; // TODO: parser - handle more security types const securitySchemeObjectToAuthObject = ({ securitySchemeObject, }: { securitySchemeObject: IR.SecurityObject; }): Auth | undefined => { if (securitySchemeObject.type === 'openIdConnect') { return { scheme: 'bearer', type: 'http', }; } if (securitySchemeObject.type === 'oauth2') { if ( securitySchemeObject.flows.password || securitySchemeObject.flows.authorizationCode || securitySchemeObject.flows.clientCredentials || securitySchemeObject.flows.implicit ) { return { scheme: 'bearer', type: 'http', }; } return; } if (securitySchemeObject.type === 'apiKey') { if (securitySchemeObject.in === 'header') { return { name: securitySchemeObject.name, type: 'apiKey', }; } if (securitySchemeObject.in === 'query' || securitySchemeObject.in == 'cookie') { return { in: securitySchemeObject.in, name: securitySchemeObject.name, type: 'apiKey', }; } return; } if (securitySchemeObject.type === 'http') { const scheme = securitySchemeObject.scheme.toLowerCase(); if (scheme === 'bearer' || scheme === 'basic') { return { scheme: scheme as 'bearer' | 'basic', type: 'http', }; } return; } return; }; export const operationAuth = ({ operation, plugin, }: { context: Context; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): Array => { if (!operation.security || !plugin.config.auth) { return []; } const auth: Array = []; for (const securitySchemeObject of operation.security) { const authObject = securitySchemeObjectToAuthObject({ securitySchemeObject, }); if (authObject) { auth.push(authObject); } else if (securitySchemeObject.type !== 'mutualTLS') { console.warn( `❗️ SDK warning: unsupported security scheme. Please open an issue if you'd like it added https://github.com/hey-api/openapi-ts/issues\n${JSON.stringify(securitySchemeObject, null, 2)}`, ); } } return auth; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/shared/class.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import { $ } from '../../../../ts-dsl'; import type { HeyApiSdkPlugin } from '../types'; export const createRegistryClass = ({ plugin, sdkSymbol, symbol, }: { plugin: HeyApiSdkPlugin['Instance']; sdkSymbol: Symbol; symbol: Symbol; }): ReturnType => { const symbolDefaultKey = plugin.symbol('defaultKey'); const symbolInstances = plugin.symbol('instances'); return $.class(symbol) .generic('T') .field(symbolDefaultKey, (f) => f.private().readonly().assign($.literal('default'))) .newline() .field(symbolInstances, (f) => f.private().readonly().type($.type('Map').generics('string', 'T')).assign($.new('Map')), ) .newline() .method('get', (m) => m .returns('T') .param('key', (p) => p.type('string').optional()) .do( $.const('instance').assign( $('this') .attr(symbolInstances) .attr('get') .call($('key').coalesce($('this').attr(symbolDefaultKey))), ), $.if($.not('instance')).do( $.throw('Error').message( $.template('No SDK client found. Create one with "new ') .add(sdkSymbol) .add('()" to fix this error.'), ), ), $.return('instance'), ), ) .newline() .method('set', (m) => m .returns('void') .param('value', (p) => p.type('T')) .param('key', (p) => p.type('string').optional()) .do( $('this') .attr(symbolInstances) .attr('set') .call($('key').coalesce($('this').attr(symbolDefaultKey)), 'value'), ), ); }; export const createClientClass = ({ plugin, symbol, }: { plugin: HeyApiSdkPlugin['Instance']; symbol: Symbol; }): ReturnType => { const symClient = plugin.getSymbol({ category: 'client' }); const optionalClient = Boolean(plugin.config.client && symClient); const symbolClient = plugin.external('client.Client'); return $.class(symbol) .field('client', (f) => f.protected().type(symbolClient)) .newline() .init((i) => i .param('args', (p) => p .optional(optionalClient) .type( $.type.object().prop('client', (p) => p.optional(optionalClient).type(symbolClient)), ), ) .do( $('this') .attr('client') .assign( $('args') .attr('client') .optional(optionalClient) .$if(optionalClient, (a) => a.coalesce(symClient!)), ), ), ); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/shared/constants.ts ================================================ export const nuxtTypeComposable = 'TComposable'; export const nuxtTypeDefault = 'DefaultT'; export const nuxtTypeResponse = 'ResT'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/shared/operation.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { statusCodeToGroup } from '@hey-api/shared'; import { getTypedConfig } from '../../../../config/utils'; import { getClientPlugin } from '../../../../plugins/@hey-api/client-core/utils'; import { $ } from '../../../../ts-dsl'; import type { Field, Fields } from '../../client-core/bundle/params'; import type { HeyApiSdkPlugin } from '../types'; import { isInstance } from '../v1/node'; import { operationAuth } from './auth'; import { nuxtTypeComposable, nuxtTypeDefault } from './constants'; import { getSignatureParameters } from './signature'; import { createRequestValidator, createResponseValidator } from './validator'; /** TODO: needs complete refactor */ export const operationOptionsType = ({ isDataAllowed = true, operation, plugin, throwOnError, }: { isDataAllowed?: boolean; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; throwOnError?: string; }): ReturnType => { const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const symbolDataType = isDataAllowed ? plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'typescript', }) : undefined; const symbolOptions = plugin.referenceSymbol({ category: 'type', resource: 'client-options', tool: 'sdk', }); if (isNuxtClient) { const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', }); return $.type(symbolOptions) .generic(nuxtTypeComposable) .generic(isDataAllowed ? (symbolDataType ?? 'unknown') : 'never') .generic(symbolResponseType ?? 'unknown') .generic(nuxtTypeDefault); } // TODO: refactor this to be more generic, works for now if (throwOnError) { return $.type(symbolOptions) .generic(isDataAllowed ? (symbolDataType ?? 'unknown') : 'never') .generic(throwOnError); } return $.type(symbolOptions).$if(!isDataAllowed || symbolDataType, (t) => t.generic(isDataAllowed ? symbolDataType! : 'never'), ); }; type OperationParameters = { argNames: Array; fields: Array; parameters: Array>; }; export function operationParameters({ isRequiredOptions, operation, plugin, }: { isRequiredOptions: boolean; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): OperationParameters { const result: OperationParameters = { argNames: [], fields: [], parameters: [], }; const pluginTypeScript = plugin.getPluginOrThrow('@hey-api/typescript'); const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; if (plugin.config.paramsStructure === 'flat') { const signature = getSignatureParameters({ operation, plugin }); const flatParams = $.type.object(); if (signature) { let isParametersRequired = false; for (const key in signature.parameters) { const parameter = signature.parameters[key]!; if (parameter.isRequired) { isParametersRequired = true; } flatParams.prop(parameter.name, (p) => p .required(parameter.isRequired) .type(pluginTypeScript.api.schemaToType(pluginTypeScript, parameter.schema)), ); } result.argNames.push('parameters'); for (const field of signature.fields) { result.fields.push(field); } result.parameters.push( $.param('parameters', (p) => p.required(isParametersRequired).type(flatParams)), ); } } result.parameters.push( $.param('options', (p) => p.required(isRequiredOptions).type( operationOptionsType({ isDataAllowed: plugin.config.paramsStructure === 'grouped', operation, plugin, throwOnError: isNuxtClient ? undefined : 'ThrowOnError', }), ), ), ); return result; } /** * Infers `responseType` value from provided response content type. This is * an adapted version of `getParseAs()` from the Fetch API client. * * From Axios documentation: * `responseType` indicates the type of data that the server will respond with * options are: 'arraybuffer', 'document', 'json', 'text', 'stream' * browser only: 'blob' */ const getResponseType = ( contentType: string | null | undefined, ): 'arraybuffer' | 'blob' | 'document' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { return; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } // Axios does not handle form data out of the box // if (cleanContent === 'multipart/form-data') { // return 'formData'; // } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export function operationStatements({ isRequiredOptions, opParameters, operation, plugin, }: { isRequiredOptions: boolean; opParameters: OperationParameters; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): Array> { const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: isNuxtClient ? 'response' : 'responses', }); const symbolErrorType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: isNuxtClient ? 'error' : 'errors', }); // TODO: transform parameters // const query = { // BarBaz: options.query.bar_baz, // qux_quux: options.query.qux_quux, // fooBar: options.query.foo_bar, // }; // if (operation.parameters) { // for (const name in operation.parameters.query) { // const parameter = operation.parameters.query[name] // if (parameter.name !== fieldName({ context, name: parameter.name })) { // console.warn(parameter.name) // } // } // } const reqOptions = $.object(); if (operation.body) { // Check if body has binary format - if so, don't use JSON serializer const isBinaryFormat = operation.body.schema?.format === 'binary'; switch (operation.body.type) { case 'form-data': { const symbol = plugin.external('client.formDataBodySerializer'); reqOptions.spread(symbol); break; } case 'json': // jsonBodySerializer is the default, no need to specify // unless the schema has binary format if (isBinaryFormat) { reqOptions.prop('bodySerializer', $.literal(null)); } break; case 'text': case 'octet-stream': // ensure we don't use any serializer by default reqOptions.prop('bodySerializer', $.literal(null)); break; case 'url-search-params': { const symbol = plugin.external('client.urlSearchParamsBodySerializer'); reqOptions.spread(symbol); break; } default: // For unrecognized media types with binary format, don't use JSON serializer if (isBinaryFormat) { reqOptions.prop('bodySerializer', $.literal(null)); } break; } } // TODO: parser - set parseAs to skip inference if every response has the same // content type. currently impossible because successes do not contain // header information const paramSerializers = $.object(); for (const name in operation.parameters?.query) { const parameter = operation.parameters.query[name]!; if (parameter.schema.type === 'array' || parameter.schema.type === 'tuple') { if (parameter.style !== 'form' || !parameter.explode) { // override the default settings for array serialization paramSerializers.prop( parameter.name, $.object().prop( 'array', $.object() .$if(parameter.explode === false, (o) => o.prop('explode', $.literal(parameter.explode)), ) .$if(parameter.style !== 'form', (o) => o.prop('style', $.literal(parameter.style))), ), ); } } else if (parameter.schema.type === 'object') { if (parameter.style !== 'deepObject' || !parameter.explode) { // override the default settings for object serialization paramSerializers.prop( parameter.name, $.object().prop( 'object', $.object() .$if(parameter.explode === false, (o) => o.prop('explode', $.literal(parameter.explode)), ) .$if(parameter.style !== 'deepObject', (o) => o.prop('style', $.literal(parameter.style)), ), ), ); } } } if (paramSerializers.hasProps()) { // TODO: if all parameters have the same serialization, // apply it globally to reduce output size reqOptions.prop('querySerializer', $.object().prop('parameters', paramSerializers)); } const requestValidator = createRequestValidator({ operation, plugin }); const responseValidator = createResponseValidator({ operation, plugin }); if (requestValidator) { reqOptions.prop('requestValidator', requestValidator.arrow()); } if (plugin.config.transformer) { const query: SymbolMeta = { category: 'transform', resource: 'operation', resourceId: operation.id, role: 'response', }; if (plugin.isSymbolRegistered(query)) { const ref = plugin.referenceSymbol(query); reqOptions.prop('responseTransformer', $(ref)); } } let hasServerSentEvents = false; let responseTypeValue: ReturnType | undefined; for (const statusCode in operation.responses) { const response = operation.responses[statusCode]!; // try to infer `responseType` option for Axios. We don't need this in // Fetch API client because it automatically detects the correct response // during runtime. if (!responseTypeValue && client.name === '@hey-api/client-axios') { // this doesn't handle default status code for now if (statusCodeToGroup({ statusCode }) === '2XX') { responseTypeValue = getResponseType(response.mediaType); if (responseTypeValue) { reqOptions.prop('responseType', $.literal(responseTypeValue)); } } } if (response.mediaType === 'text/event-stream') { hasServerSentEvents = true; } } if (responseValidator) { reqOptions.prop('responseValidator', responseValidator.arrow()); } if (plugin.config.responseStyle === 'data') { reqOptions.prop('responseStyle', $.literal(plugin.config.responseStyle)); } const auth = operationAuth({ context: plugin.context, operation, plugin }); if (auth.length) { reqOptions.prop('security', $.fromValue(auth)); } reqOptions.prop('url', $.literal(operation.path)); // options must go last to allow overriding parameters above reqOptions.spread('options'); const statements: Array> = []; const hasParams = opParameters.argNames.length; if (hasParams) { const args: Array> = []; const config: Array> = []; for (const argName of opParameters.argNames) { args.push($(argName)); } for (const field of opParameters.fields) { const shape = $.object(); if ('in' in field) { shape.prop('in', $.literal(field.in)); } if ('key' in field) { if (field.key) { shape.prop('key', $.literal(field.key)); } if (field.map) { shape.prop('map', $.literal(field.map)); } } config.push(shape); } const symbol = plugin.external('client.buildClientParams'); statements.push( $.const('params').assign( $(symbol).call($.array(...args), $.array($.object().prop('args', $.array(...config)))), ), ); reqOptions.spread('params'); } if (operation.body) { const parameterContentType = operation.parameters?.header?.['content-type']; const hasRequiredContentType = Boolean(parameterContentType?.required); // spreading required Content-Type on generated header would throw a TypeScript error if (!hasRequiredContentType) { const headers = $.object() .pretty() // form-data does not need Content-Type header, browser will set it automatically .prop( parameterContentType?.name ?? 'Content-Type', $.literal(operation.body.type === 'form-data' ? null : operation.body.mediaType), ) .spread($('options').attr('headers').required(isRequiredOptions)); if (hasParams) { headers.spread($('params').attr('headers')); } reqOptions.prop('headers', headers); } } const symbolClient = plugin.config.client ? plugin.getSymbol({ category: 'client', }) : undefined; let clientExpression: ReturnType; const optionsClient = $('options').attr('client').required(isRequiredOptions); if (isInstance(plugin)) { clientExpression = optionsClient.coalesce($('this').attr('client')); } else if (symbolClient) { clientExpression = optionsClient.coalesce(symbolClient); } else { clientExpression = optionsClient; } let functionName = hasServerSentEvents ? clientExpression.attr('sse') : clientExpression; functionName = functionName.attr(operation.method); statements.push( $.return( functionName .call(reqOptions) .$if( isNuxtClient, (f) => f .generic(nuxtTypeComposable) .generic($.type.or(symbolResponseType ?? 'unknown', nuxtTypeDefault)) .generic(symbolErrorType ?? 'unknown') .generic(nuxtTypeDefault), (f) => f .generic(symbolResponseType ?? 'unknown') .generic(symbolErrorType ?? 'unknown') .generic('ThrowOnError'), ) .$if(plugin.config.responseStyle === 'data', (f) => f.generic($.type.literal(plugin.config.responseStyle)), ), ), ); return statements; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/shared/signature.ts ================================================ import type { IR, PluginInstance } from '@hey-api/shared'; import { refToName, toCase } from '@hey-api/shared'; import type { Field } from '../../client-core/bundle/params'; type Location = keyof IR.ParametersObject | 'body'; type SignatureParameter = { /** * Is this parameter required in the SDK method signature? */ isRequired: boolean; /** * Parameter name in the SDK method signature. */ name: string; /** * If the name was modified due to conflicts, this holds the original name. */ originalName?: string; /** * Parameter schema object. */ schema: IR.SchemaObject; }; type SignatureParameters = Record; type Signature = { fields: ReadonlyArray; parameters: SignatureParameters; }; /** * Collects and resolves all operation parameters for flattened SDK signatures. * - Prefixes all conflicting names with their location (e.g. path_foo, query_foo) * - Returns a flat map of resolved parameter names to their metadata */ export function getSignatureParameters({ operation, }: { operation: IR.OperationObject; plugin: PluginInstance; }): Signature | undefined { // TODO: add cookies const locations = ['header', 'path', 'query'] as const satisfies ReadonlyArray; const nameToLocations: Record> = {}; const addParameter = (name: string, location: Location): void => { if (!nameToLocations[name]) { nameToLocations[name] = new Set(); } nameToLocations[name].add(location); }; for (const location of locations) { const parameters = operation.parameters?.[location]; if (parameters) { for (const key in parameters) { const parameter = parameters[key]!; addParameter(parameter.name, location); } } } if (operation.body) { // spread body if there's only a single object if ( !operation.body.schema.logicalOperator && operation.body.schema.type === 'object' && operation.body.schema.properties ) { const properties = operation.body.schema.properties; for (const key in properties) { addParameter(key, 'body'); } } else if (operation.body.schema.$ref) { // alias body for more ergonomic naming, e.g. user if the type is User const name = refToName(operation.body.schema.$ref); const key = toCase(name, 'camelCase'); addParameter(key, 'body'); } else { addParameter('body', 'body'); } } const conflicts = new Set(); for (const name in nameToLocations) { if (nameToLocations[name]!.size > 1) { conflicts.add(name); } } const signatureParameters: SignatureParameters = {}; const fields: Array = []; for (const location of locations) { const parameters = operation.parameters?.[location]; if (parameters) { for (const key in parameters) { const parameter = parameters[key]!; const originalName = parameter.name; const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; const signatureParameter: SignatureParameter = { isRequired: parameter.required ?? false, name, schema: parameter.schema, }; if (name !== originalName) { signatureParameter.originalName = originalName; } signatureParameters[name] = signatureParameter; fields.push({ in: location === 'header' ? 'headers' : location, key: name, ...(name !== originalName ? { map: originalName } : {}), }); } } } if (operation.body) { const location = 'body'; if ( !operation.body.schema.logicalOperator && operation.body.schema.type === 'object' && operation.body.schema.properties ) { const properties = operation.body.schema.properties; for (const originalName in properties) { const property = properties[originalName]!; const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; const signatureParameter: SignatureParameter = { isRequired: operation.body.schema.required?.includes(originalName) ?? false, name, schema: property, }; if (name !== originalName) { signatureParameter.originalName = originalName; } signatureParameters[name] = signatureParameter; fields.push({ in: location, key: name, ...(name !== originalName ? { map: originalName } : {}), }); } } else if (operation.body.schema.$ref) { const value = refToName(operation.body.schema.$ref); const originalName = toCase(value, 'camelCase'); const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; const signatureParameter: SignatureParameter = { isRequired: operation.body.required ?? false, name, schema: operation.body.schema, }; if (name !== originalName) { signatureParameter.originalName = originalName; } signatureParameters[name] = signatureParameter; fields.push({ key: name, map: 'body', }); } else { // never alias body signatureParameters.body = { isRequired: operation.body.required ?? false, name: 'body', schema: operation.body.schema, }; fields.push({ key: 'body', map: 'body', }); } } if (!Object.keys(signatureParameters).length) { return; } return { fields, parameters: signatureParameters }; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/shared/typeOptions.ts ================================================ import { getTypedConfig } from '../../../../config/utils'; import { clientFolderAbsolutePath } from '../../../../generate/client'; import { getClientPlugin } from '../../../../plugins/@hey-api/client-core/utils'; import { $ } from '../../../../ts-dsl'; import type { HeyApiSdkPlugin } from '../types'; import { isInstance } from '../v1/node'; import { nuxtTypeDefault, nuxtTypeResponse } from './constants'; export const createTypeOptions = ({ plugin }: { plugin: HeyApiSdkPlugin['Instance'] }) => { const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin)); const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const symbolTDataShape = plugin.symbol('TDataShape', { external: clientModule, kind: 'type', }); const symbolClient = plugin.symbol('Client', { external: clientModule, kind: 'type', meta: { category: 'external', resource: 'client.Client', tool: client.name, }, }); const symbolClientOptions = plugin.symbol('Options', { external: clientModule, kind: 'type', }); const symbolOptions = plugin.symbol('Options', { meta: { category: 'type', resource: 'client-options', tool: 'sdk', }, }); const typeOptions = $.type .alias(symbolOptions) .export() .$if( isNuxtClient, (t) => t .generic('TComposable', (g) => g.extends(plugin.external('client.Composable')).default($.type.literal('$fetch')), ) .generic('TData', (g) => g.extends(symbolTDataShape).default(symbolTDataShape)) .generic(nuxtTypeResponse, (g) => g.default('unknown')) .generic(nuxtTypeDefault, (g) => g.default('undefined')), (t) => t .generic('TData', (g) => g.extends(symbolTDataShape).default(symbolTDataShape)) .generic('ThrowOnError', (g) => g.extends('boolean').default('boolean')), ) .type( $.type.and( $.type(symbolClientOptions).$if( isNuxtClient, (t) => t .generic('TComposable') .generic('TData') .generic(nuxtTypeResponse) .generic(nuxtTypeDefault), (t) => t.generic('TData').generic('ThrowOnError'), ), $.type .object() .prop('client', (p) => p .doc([ 'You can provide a client instance returned by `createClient()` instead of', 'individual options. This might be also useful if you want to implement a', 'custom client.', ]) .required(!plugin.config.client && !isInstance(plugin)) .type(symbolClient), ) .prop('meta', (p) => p .doc([ 'You can pass arbitrary values through the `meta` object. This can be', "used to access values that aren't defined as part of the SDK function.", ]) .optional() .type($.type('Record').generics('string', 'unknown')), ), ), ); plugin.node(typeOptions); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/shared/validator.ts ================================================ import type { IR } from '@hey-api/shared'; import type { $ } from '../../../../ts-dsl'; import type { HeyApiSdkPlugin } from '../types'; interface ValidatorProps { operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; } export const createRequestValidator = ({ operation, plugin, }: ValidatorProps): ReturnType | undefined => { if (!plugin.config.validator.request) return; const validator = plugin.getPluginOrThrow(plugin.config.validator.request); if (!validator.api.createRequestValidator) return; return validator.api.createRequestValidator({ operation, // @ts-expect-error plugin: validator, }); }; export const createResponseValidator = ({ operation, plugin, }: ValidatorProps): ReturnType | undefined => { if (!plugin.config.validator.response) return; const validator = plugin.getPluginOrThrow(plugin.config.validator.response); if (!validator.api.createResponseValidator) return; return validator.api.createResponseValidator({ operation, // @ts-expect-error plugin: validator, }); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/types.ts ================================================ import type { DefinePlugin, NameTransformer, OperationsStrategy, Plugin } from '@hey-api/shared'; import type { PluginClientNames, PluginTransformerNames, PluginValidatorNames } from '../../types'; import type { ExamplesConfig, UserExamplesConfig } from './examples'; import type { OperationsConfig, UserOperationsConfig } from './operations'; export type UserConfig = Plugin.Name<'@hey-api/sdk'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Should the generated functions contain auth mechanisms? You may want to * disable this option if you're handling auth yourself or defining it * globally on the client and want to reduce the size of generated code. * * @default true */ auth?: boolean; /** * Use an internal client instance to send HTTP requests? This is useful if * you don't want to manually pass the client to each SDK function. * * You can customize the selected client output through its plugin. You can * also set `client` to `true` to automatically choose the client from your * defined plugins. If we can't detect a client plugin when using `true`, we * will default to `@hey-api/client-fetch`. * * @default true */ client?: PluginClientNames | boolean; /** * Generate code examples for SDK operations and attach them to the * input source (e.g. via `x-codeSamples`). * * Set to `false` to disable example generation entirely, or provide an * object for fine-grained control over the output and post-processing. * * @default false */ examples?: boolean | UserExamplesConfig; /** * Define the structure of generated SDK operations. * * String shorthand: * - `'byTags'` – one container per operation tag * - `'flat'` – standalone functions, no container * - `'single'` – all operations in a single container * - custom function for full control * * Use the object form for advanced configuration. * * @default 'flat' */ operations?: OperationsStrategy | UserOperationsConfig; /** * Define how request parameters are structured in generated SDK methods. * * - `'flat'` merges parameters into a single object. * - `'grouped'` separates parameters by transport layer. * * Use `'flat'` for simpler calls or `'grouped'` for stricter typing and code clarity. * * @default 'grouped' */ paramsStructure?: 'flat' | 'grouped'; /** * **This feature works only with the Fetch client** * * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: 'data' | 'fields'; /** * Transform response data before returning. This is useful if you want to * convert for example ISO strings into Date objects. However, transformation * adds runtime overhead, so it's not recommended to use unless necessary. * * You can customize the selected transformer output through its plugin. You * can also set `transformer` to `true` to automatically choose the * transformer from your defined plugins. * * @default false */ transformer?: PluginTransformerNames | boolean; /** * Validate request and/or response data against schema before returning. * This is useful if you want to ensure the request and/or response conforms * to a desired shape. However, validation adds runtime overhead, so it's * not recommended to use unless absolutely necessary. * * You can customize the validator output through its plugin. You can also * set `validator` to `true` to automatically choose the validator from your * defined plugins. * * You can enable/disable validation for requests and responses separately * by setting `validator` to an object `{ request, response }`. * * Ensure you have declared the selected library as a dependency to avoid * errors. * * @default false */ validator?: | PluginValidatorNames | boolean | { /** * Validate request data against schema before sending. * * Can be a validator plugin name or boolean (true to auto-select, false * to disable). * * @default false */ request?: PluginValidatorNames | boolean; /** * Validate response data against schema before returning. * * Can be a validator plugin name or boolean (true to auto-select, false * to disable). * * @default false */ response?: PluginValidatorNames | boolean; }; // DEPRECATED OPTIONS BELOW /** * Group operation methods into classes? When enabled, you can select which * classes to export with `sdk.include` and/or transform their names with * `sdk.classNameBuilder`. * * Note that by enabling this option, your SDKs will **NOT** * support {@link https://developer.mozilla.org/docs/Glossary/Tree_shaking tree-shaking}. * For this reason, it is disabled by default. * * @deprecated Use `operations: { strategy: "byTags" }` or `operations: { strategy: "single" }` instead. * @default false */ // eslint-disable-next-line typescript-sort-keys/interface asClass?: boolean; /** * Customize the generated class names. The name variable is obtained from * your OpenAPI specification tags or `instance` value. * * This option has no effect if `sdk.asClass` is `false`. * * @deprecated Use `operations: { containerName: "..." }` instead. */ classNameBuilder?: NameTransformer; /** * How should we structure your SDK? By default, we try to infer the ideal * structure using `operationId` keywords. If you prefer a flatter structure, * you can set `classStructure` to `off` to disable this behavior. * * @deprecated Use `operations: { nesting: "operationId" }` or `operations: { nesting: "id" }` instead. * @default 'auto' */ classStructure?: 'auto' | 'off'; /** * Set `instance` to create an instantiable SDK. Using `true` will use the * default instance name; in practice, you want to define your own by passing * a string value. * * @deprecated Use `operations: { strategy: "single", containerName: "Name", methods: "instance" }` instead. * @default false */ instance?: string | boolean; /** * Customise the name of methods within the service. By default, * `operation.id` is used. * * @deprecated Use `operations: { methodName: "..." }` instead. */ methodNameBuilder?: NameTransformer; /** * Use operation ID to generate operation names? * * @deprecated Use `operations: { nesting: "operationId" }` or `operations: { nesting: "id" }` instead. * @default true */ operationId?: boolean; /** * Define shape of returned value from service calls * * @deprecated * @default 'body' */ response?: 'body' | 'response'; }; export type Config = Plugin.Name<'@hey-api/sdk'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Should the generated functions contain auth mechanisms? You may want to * disable this option if you're handling auth yourself or defining it * globally on the client and want to reduce the size of generated code. * * @default true */ auth: boolean; /** * Use an internal client instance to send HTTP requests? This is useful if * you don't want to manually pass the client to each SDK function. * * You can customize the selected client output through its plugin. You can * also set `client` to `true` to automatically choose the client from your * defined plugins. If we can't detect a client plugin when using `true`, we * will default to `@hey-api/client-fetch`. * * @default true */ client: PluginClientNames | false; /** Configuration for generating SDK code examples. */ examples: ExamplesConfig; /** Define the structure of generated SDK operations. */ operations: OperationsConfig; /** * Define how request parameters are structured in generated SDK methods. * * - `'flat'` merges parameters into a single object. * - `'grouped'` separates parameters by transport layer. * * Use `'flat'` for simpler calls or `'grouped'` for stricter typing and code clarity. * * @default 'grouped' */ paramsStructure: 'flat' | 'grouped'; /** * **This feature works only with the Fetch client** * * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle: 'data' | 'fields'; /** * Transform response data before returning. This is useful if you want to * convert for example ISO strings into Date objects. However, transformation * adds runtime overhead, so it's not recommended to use unless necessary. * * You can customize the selected transformer output through its plugin. You * can also set `transformer` to `true` to automatically choose the * transformer from your defined plugins. * * @default false */ transformer: PluginTransformerNames | false; /** * Validate request and/or response data against schema before returning. * This is useful if you want to ensure the request and/or response conforms * to a desired shape. However, validation adds runtime overhead, so it's * not recommended to use unless absolutely necessary. */ validator: { /** * The validator plugin to use for request validation, or false to disable. * * @default false */ request: PluginValidatorNames | false; /** * The validator plugin to use for response validation, or false to disable. * * @default false */ response: PluginValidatorNames | false; }; // DEPRECATED OPTIONS BELOW /** * Define shape of returned value from service calls * * @deprecated * @default 'body' */ // eslint-disable-next-line typescript-sort-keys/interface response: 'body' | 'response'; }; export type HeyApiSdkPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/v1/node.ts ================================================ import type { StructureItem, StructureNode, StructureShell, Symbol, SymbolMeta, } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { applyNaming, toCase } from '@hey-api/shared'; import { getTypedConfig } from '../../../../config/utils'; import { getClientPlugin } from '../../../../plugins/@hey-api/client-core/utils'; import { createOperationComment, isOperationOptionsRequired, } from '../../../../plugins/shared/utils/operation'; import { $, ctx } from '../../../../ts-dsl'; import { createClientClass, createRegistryClass } from '../shared/class'; import { nuxtTypeComposable, nuxtTypeDefault } from '../shared/constants'; import { operationParameters, operationStatements } from '../shared/operation'; import type { HeyApiSdkPlugin } from '../types'; export interface OperationItem { operation: IR.OperationObject; path: ReadonlyArray; tags: ReadonlyArray | undefined; } export const source = globalThis.Symbol('@hey-api/sdk'); export function isInstance(plugin: HeyApiSdkPlugin['Instance']): boolean { const config = plugin.config.operations; return ( config.container === 'class' && config.methods === 'instance' && config.strategy !== 'flat' ); } function attachComment>(args: { node: T; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): T { const { node, operation, plugin } = args; return node.$if(plugin.config.comments && createOperationComment(operation), (n, v) => n.doc(v), ) as T; } function createShellMeta(node: StructureNode): SymbolMeta { return { category: 'utility', resource: 'class', resourceId: node.getPath().join('.'), tool: 'sdk', }; } function createFnSymbol( plugin: HeyApiSdkPlugin['Instance'], item: StructureItem & { data: OperationItem }, ): Symbol { const { operation, path, tags } = item.data; const name = item.location[item.location.length - 1]!; return plugin.symbol(applyNaming(name, plugin.config.operations.methodName), { meta: { category: 'sdk', path, resource: 'operation', resourceId: operation.id, tags, tool: 'sdk', }, }); } function childToNode( resource: StructureNode, plugin: HeyApiSdkPlugin['Instance'], ): ReadonlyArray> { const refChild = plugin.referenceSymbol(createShellMeta(resource)); const memberNameStr = toCase( refChild.name, plugin.config.operations.methodName.casing ?? 'camelCase', ); const memberName = plugin.symbol(memberNameStr); if (isInstance(plugin)) { const privateName = plugin.symbol(`_${memberNameStr}`); return [ $.field(privateName, (f) => f.private().optional().type(refChild)), $.getter(memberName, (g) => g.returns(refChild).do( $('this') .attr(privateName) .nullishAssign( $.new(refChild).args($.object().prop('client', $('this').attr('client'))), ) .return(), ), ), ]; } if (plugin.isSymbolRegistered(refChild.id)) { return [$.field(memberName, (f) => f.static().assign($(refChild)))]; } return [$.getter(memberName, (g) => g.public().static().do($.return(refChild)))]; } export function createShell(plugin: HeyApiSdkPlugin['Instance']): StructureShell { const client = getClientPlugin(getTypedConfig(plugin)); const isAngularClient = client.name === '@hey-api/client-angular'; return { define: (node) => { const symbol = plugin.symbol( applyNaming( node.name, node.isRoot ? plugin.config.operations.containerName : plugin.config.operations.segmentName, ), { meta: createShellMeta(node), }, ); // if (plugin.config.operations.container === 'object') { // const o = $.const(symbol).export().assign($.object()); // return { dependencies: [], node: o }; // } const c = $.class(symbol) .export() .$if(isInstance(plugin), (c) => c.extends( plugin.referenceSymbol({ category: 'utility', resource: 'class', resourceId: 'HeyApiClient', tool: 'sdk', }), ), ) .$if(isAngularClient && node.isRoot, (c) => c.decorator( plugin.external('@angular/core.Injectable'), $.object().prop('providedIn', $.literal('root')), ), ); const dependencies: Array> = []; if (node.isRoot && isInstance(plugin)) { enrichRootClass({ dependencies, node: c, plugin, symbol, }); } return { dependencies, node: c }; }, }; } function enrichRootClass(args: { dependencies: Array>; node: ReturnType; plugin: HeyApiSdkPlugin['Instance']; symbol: Symbol; }): void { const { dependencies, node, plugin, symbol } = args; const symbolClient = plugin.symbol('HeyApiClient', { meta: { category: 'utility', resource: 'class', resourceId: 'HeyApiClient', tool: 'sdk', }, }); dependencies.push(createClientClass({ plugin, symbol: symbolClient })); const symbolRegistry = plugin.symbol('HeyApiRegistry', { meta: { category: 'utility', resource: 'class', resourceId: 'HeyApiRegistry', tool: 'sdk', }, }); dependencies.push( createRegistryClass({ plugin, sdkSymbol: symbol, symbol: symbolRegistry, }), ); const isClientRequired = !plugin.config.client || !plugin.getSymbol({ category: 'client' }); const registry = plugin.symbol('__registry'); node.toAccessNode = (node, options) => { if (options.context) return; return $(node.name).attr(registry).attr('get').call(); }; node.do( $.field(registry, (f) => f.public().static().readonly().assign($.new(symbolRegistry).generic(symbol)), ), $.newline(), $.init((i) => i .param('args', (p) => p.required(isClientRequired).type( $.type .object() .prop('client', (p) => p.required(isClientRequired).type(plugin.external('client.Client')), ) .prop('key', (p) => p.optional().type('string')), ), ) .do( $('super').call('args'), $(symbol) .attr(registry) .attr('set') .call('this', $('args').attr('key').required(isClientRequired)), ), ), ); } function exampleIntent( node: ReturnType, operation: IR.OperationObject, plugin: HeyApiSdkPlugin['Instance'], ): void { const config = plugin.config.examples; if (!config.enabled) return; plugin.intent({ async run(context) { const { payload } = config; let example = ctx.example(node, { ...config, payload: (ctx) => (typeof payload === 'function' ? payload(operation, ctx) : payload), }); if (config.transform) { example = await config.transform(example, operation); } if (example) { context.setExample(operation, { lang: config.language, source: example, }); } }, }); } function implementFn>(args: { node: T; operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): T { const { node, operation, plugin } = args; const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, operation, }); const opParameters = operationParameters({ isRequiredOptions, operation, plugin, }); const statements = operationStatements({ isRequiredOptions, opParameters, operation, plugin, }); return node .$if( isNuxtClient, (m) => m .generic(nuxtTypeComposable, (t) => t.extends(plugin.external('client.Composable')).default($.type.literal('$fetch')), ) .generic(nuxtTypeDefault, (t) => t.$if( plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', }), (t, s) => t.extends(s).default(s), (t) => t.default('undefined'), ), ), (m) => m.generic('ThrowOnError', (t) => t .extends('boolean') .default( ('throwOnError' in client.config ? client.config.throwOnError : false) ?? false, ), ), ) .params(...opParameters.parameters) .do(...statements) as T; } export function toNode( model: StructureNode, plugin: HeyApiSdkPlugin['Instance'], ): { dependencies?: Array>; nodes: ReadonlyArray>; } { if (model.virtual) { const nodes: Array> = []; for (const item of model.itemsFrom(source)) { const { operation } = item.data; let node = $.const(createFnSymbol(plugin, item)) .export() .assign( implementFn({ node: $.func(), operation, plugin, }), ); node = attachComment({ node, operation, plugin }); nodes.push(node); exampleIntent(node, operation, plugin); } return { nodes }; } if (!model.shell) { return { nodes: [] }; } const nodes: Array> = []; const client = getClientPlugin(getTypedConfig(plugin)); const isAngularClient = client.name === '@hey-api/client-angular'; const shell = model.shell.define(model); const node = shell.node as ReturnType; let index = 0; for (const item of model.itemsFrom(source)) { const { operation } = item.data; if (node['~dsl'] === 'VarTsDsl') { // TODO: object } else { if (index > 0 || node.hasBody) node.newline(); const method = implementFn({ node: $.method(createFnSymbol(plugin, item), (m) => attachComment({ node: m, operation, plugin, }) .public() .static(!isAngularClient && !isInstance(plugin)), ), operation, plugin, }); node.do(method); exampleIntent(method, operation, plugin); } index += 1; } for (const child of model.children.values()) { if (node['~dsl'] === 'VarTsDsl') { // TODO: object } else { if (node.hasBody) node.newline(); node.do(...childToNode(child, plugin)); } } nodes.push(node); return { dependencies: shell.dependencies as Array>, nodes, }; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/sdk/v1/plugin.ts ================================================ import { StructureModel } from '@hey-api/codegen-core'; import { getTypedConfig } from '../../../../config/utils'; import { clientFolderAbsolutePath } from '../../../../generate/client'; import { getClientPlugin } from '../../../../plugins/@hey-api/client-core/utils'; import type { $ } from '../../../../ts-dsl'; import { resolveStrategy } from '../operations'; import { createTypeOptions } from '../shared/typeOptions'; import type { HeyApiSdkPlugin } from '../types'; import type { OperationItem } from './node'; import { createShell, source, toNode } from './node'; export const handlerV1: HeyApiSdkPlugin['Handler'] = ({ plugin }) => { const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin)); const client = getClientPlugin(getTypedConfig(plugin)); const isAngularClient = client.name === '@hey-api/client-angular'; const isNuxtClient = client.name === '@hey-api/client-nuxt'; plugin.symbol('formDataBodySerializer', { external: clientModule, meta: { category: 'external', resource: 'client.formDataBodySerializer', tool: client.name, }, }); plugin.symbol('urlSearchParamsBodySerializer', { external: clientModule, meta: { category: 'external', resource: 'client.urlSearchParamsBodySerializer', tool: client.name, }, }); plugin.symbol('buildClientParams', { external: clientModule, meta: { category: 'external', resource: 'client.buildClientParams', tool: client.name, }, }); if (isNuxtClient) { plugin.symbol('Composable', { external: clientModule, kind: 'type', meta: { category: 'external', resource: 'client.Composable', tool: client.name, }, }); } if (isAngularClient) { plugin.symbol('Injectable', { external: '@angular/core', meta: { category: 'external', resource: '@angular/core.Injectable', }, }); } createTypeOptions({ plugin }); const structure = new StructureModel(); const shell = createShell(plugin); const strategy = resolveStrategy(plugin); plugin.forEach( 'operation', (event) => { structure.insert({ data: { operation: event.operation, path: event._path, tags: event.tags, } satisfies OperationItem, locations: strategy(event.operation).map((path) => ({ path, shell })), source, }); }, { order: 'declarations' }, ); const allDependencies: Array> = []; const allNodes: Array> = []; for (const node of structure.walk()) { const { dependencies, nodes } = toNode(node, plugin); allDependencies.push(...(dependencies ?? [])); allNodes.push(...nodes); } const uniqueDependencies = new Map>(); for (const dep of allDependencies) { if (dep.symbol) uniqueDependencies.set(dep.symbol.id, dep); } for (const dep of uniqueDependencies.values()) { plugin.node(dep); } for (const node of allNodes) { plugin.node(node); } }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/transformers/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { bigIntExpressions, dateExpressions } from './expressions'; import { handler } from './plugin'; import type { HeyApiTransformersPlugin } from './types'; export const defaultConfig: HeyApiTransformersPlugin['Config'] = { config: { bigInt: true, dates: true, includeInEntry: false, transformers: [], typeTransformers: [], }, dependencies: ['@hey-api/typescript'], handler, name: '@hey-api/transformers', resolveConfig: (plugin) => { if (!plugin.config.transformers) { plugin.config.transformers = []; } if (plugin.config.dates) { plugin.config.transformers = [...plugin.config.transformers, dateExpressions]; } if (plugin.config.bigInt) { plugin.config.transformers = [...plugin.config.transformers, bigIntExpressions]; } }, tags: ['transformer'], }; /** * Type helper for `@hey-api/transformers`, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/transformers/expressions.ts ================================================ import { $ } from '../../../ts-dsl'; import type { ExpressionTransformer } from './types'; export const bigIntExpressions: ExpressionTransformer = ({ dataExpression, schema }) => { if (schema.type !== 'integer' || schema.format !== 'int64') { return; } const bigIntCallExpression = dataExpression !== undefined ? $('BigInt').call($.expr(dataExpression).attr('toString').call()) : undefined; if (bigIntCallExpression) { if (typeof dataExpression === 'string') { return [bigIntCallExpression]; } if (dataExpression) { return [$.expr(dataExpression).assign(bigIntCallExpression)]; } } return; }; export const dateExpressions: ExpressionTransformer = ({ dataExpression, schema }) => { if (schema.type !== 'string' || !(schema.format === 'date' || schema.format === 'date-time')) { return; } if (typeof dataExpression === 'string') { return [$.new('Date').arg(dataExpression)]; } if (dataExpression) { return [$.expr(dataExpression).assign($.new('Date').arg(dataExpression))]; } return; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/transformers/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { HeyApiTransformersPlugin, TypeTransformer } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/transformers/plugin.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { applyNaming, createOperationKey, operationResponsesMap, refToName } from '@hey-api/shared'; import type ts from 'typescript'; import { $ } from '../../../ts-dsl'; import type { HeyApiTransformersPlugin } from './types'; const dataVariableName = 'data'; // Track symbols that are currently being built so recursive references // can emit calls to transformers that will be implemented later. const buildingSymbols = new Set(); type Expr = ReturnType; function isNodeReturnStatement(node: Expr) { return node['~dsl'] === 'ReturnTsDsl'; } function schemaResponseTransformerNodes({ plugin, schema, }: { plugin: HeyApiTransformersPlugin['Instance']; schema: IR.SchemaObject; }): Array { const nodes = processSchemaType({ dataExpression: $(dataVariableName), plugin, schema, }); // append return statement if one does not already exist if (nodes.length) { const last = nodes[nodes.length - 1]!; if (!isNodeReturnStatement(last)) { nodes.push($.return(dataVariableName)); } } return nodes; } function processSchemaType({ dataExpression, plugin, schema, }: { dataExpression?: ts.Expression | string | ReturnType; plugin: HeyApiTransformersPlugin['Instance']; schema: IR.SchemaObject; }): Array { if (schema.$ref) { const query: SymbolMeta = { category: 'transform', resource: 'definition', resourceId: schema.$ref, }; const symbol = plugin.getSymbol(query) ?? plugin.symbol( applyNaming(refToName(schema.$ref), { case: 'camelCase', name: '{{name}}SchemaResponseTransformer', }), { meta: query, }, ); // Only compute the implementation if the symbol isn't already being built. // This prevents infinite recursion on self-referential schemas. We still // allow emitting a call when the symbol is currently being built so // parent nodes can reference the transformer that will be emitted later. if (!symbol.node && !buildingSymbols.has(symbol.id)) { buildingSymbols.add(symbol.id); try { const refSchema = plugin.context.resolveIrRef(schema.$ref); const nodes = schemaResponseTransformerNodes({ plugin, schema: refSchema, }); if (nodes.length) { const node = $.const(symbol).assign( // TODO: parser - add types, generate types without transforms $.func() .param(dataVariableName, (p) => p.type('any')) .do(...nodes), ); plugin.node(node); } } finally { buildingSymbols.delete(symbol.id); } } // Only emit a call if the symbol has a value (implementation) OR the // symbol is currently being built (recursive reference) — in the // latter case we allow emitting a call that will be implemented later. if (symbol.node || buildingSymbols.has(symbol.id)) { const ref = plugin.referenceSymbol(query); const callExpression = $(ref).call(dataExpression); if (dataExpression) { // In a map callback, the item needs to be returned, not just the transformation result if (typeof dataExpression === 'string' && dataExpression === 'item') { return [$.return(callExpression)]; } return [ typeof dataExpression === 'string' ? callExpression : $(dataExpression).assign(callExpression), ]; } } return []; } if (schema.type === 'array') { if (!dataExpression || typeof dataExpression === 'string') { return []; } // TODO: parser - handle tuples and complex arrays const nodes = !schema.items ? [] : processSchemaType({ dataExpression: 'item', plugin, schema: schema.items?.[0] ? schema.items[0] : { ...schema, type: undefined, }, }); if (!nodes.length) { return []; } // TODO: remove // Ensure the map callback has a return statement for the item const mapCallbackStatements: Array = nodes; const hasReturnStatement = mapCallbackStatements.some((stmt) => isNodeReturnStatement(stmt)); if (!hasReturnStatement) { mapCallbackStatements.push($.return('item')); } return [ $(dataExpression).assign( $(dataExpression) .attr('map') .call( $.func() .param('item', (p) => p.type('any')) .do(...mapCallbackStatements), ), ), ]; } if (schema.type === 'object') { let nodes: Array = []; const required = schema.required ?? []; for (const name in schema.properties) { const property = schema.properties[name]!; const propertyAccessExpression = $(dataExpression || dataVariableName).attr(name); const propertyNodes = processSchemaType({ dataExpression: propertyAccessExpression, plugin, schema: property, }); if (!propertyNodes.length) { continue; } const noNullableTypesInSchema = !property.items?.find((x) => x.type === 'null'); const requiredField = required.includes(name); // Cannot fully rely on required fields // Such value has to be present, but it doesn't guarantee that this value is not nullish if (requiredField && noNullableTypesInSchema) { nodes = nodes.concat(propertyNodes); } else { nodes.push( // todo: Probably, it would make more sense to go with if(x !== undefined && x !== null) instead of if(x) // this place influences all underlying transformers, while it's not exactly transformer itself // Keep in mind that !!0 === false, so it already makes output for Bigint undesirable $.if(propertyAccessExpression).do(...propertyNodes), ); } } return nodes; } if (schema.items) { if (schema.items.length === 1) { return processSchemaType({ dataExpression: 'item', plugin, schema: schema.items[0]!, }); } let arrayNodes: Array = []; // process 2 items if one of them is null if ( schema.logicalOperator === 'and' || (schema.items.length === 2 && schema.items.find((item) => item.type === 'null' || item.type === 'void')) ) { for (const item of schema.items) { const nodes = processSchemaType({ dataExpression: dataExpression || 'item', plugin, schema: item, }); if (nodes.length) { if (dataExpression) { arrayNodes = arrayNodes.concat(nodes); } else { // processed means the item was transformed arrayNodes.push($.if('item').do(...nodes), $.return('item')); } } } return arrayNodes; } // assume enums do not contain transformable values if (schema.type !== 'enum') { const hasSimpleTypes = (schema.items ?? []).every((item) => ( ['boolean', 'integer', 'null', 'number', 'string'] as ReadonlyArray ).includes(item.type), ); // Skip warning if items are processable through other mechanisms: // 1. All items are $ref-based (e.g., discriminated oneOf/anyOf) // 2. All items are nested allOf ($ref wrapped in allOf for discriminators) // These patterns are handled correctly by recursive processing logic const isProcessable = (schema.items ?? []).every((item) => { // Direct $ref items are processable if (item.$ref) { return true; } // Nested allOf items (common in discriminated unions) are processable if (item.logicalOperator === 'and' && item.items) { return true; } return false; }); if (!hasSimpleTypes && !isProcessable) { console.warn( `❗️ Transformers warning: schema ${JSON.stringify(schema)} is too complex and won't be currently processed. This will likely produce an incomplete transformer which is not what you want. Please open an issue if you'd like this improved https://github.com/hey-api/openapi-ts/issues`, ); } } } for (const transformer of plugin.config.transformers) { const t = transformer({ $, config: plugin.config, dataExpression, plugin, schema, }); if (t) { return t; } } return []; } // handles only response transformers for now export const handler: HeyApiTransformersPlugin['Handler'] = ({ plugin }) => { plugin.forEach( 'operation', ({ operation }) => { const { response } = operationResponsesMap(operation); if (!response) return; const isNullableUnion = response.items?.length === 2 && response.items.some((item) => item.type === 'null' || item.type === 'void'); if ( response.items && response.items.length > 1 && response.logicalOperator !== 'and' && !isNullableUnion ) { if (plugin.context.config.logs.level === 'debug') { console.warn( `❗️ Transformers warning: route ${createOperationKey(operation)} has ${response.items.length} non-void success responses. This is currently not handled and we will not generate a response transformer. Please open an issue if you'd like this feature https://github.com/hey-api/openapi-ts/issues`, ); } return; } const symbolResponse = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', }); if (!symbolResponse) return; // TODO: parser - consider handling simple string response which is also a date const nodes = schemaResponseTransformerNodes({ plugin, schema: response, }); if (!nodes.length) return; // For nullable union responses (e.g. anyOf: [SomeSchema, null]), wrap the // transformation in a null guard so that null data is returned as-is. // We require nodes.length >= 2 because we need at least one transformation // statement AND a return statement (empty .do() would fail validation). let finalNodes = nodes; if (isNullableUnion && nodes.length >= 2) { const lastNode = nodes[nodes.length - 1]!; if (isNodeReturnStatement(lastNode as Expr)) { const transformNodes = nodes.slice(0, -1) as Array; finalNodes = [$.if($(dataVariableName)).do(...transformNodes), lastNode]; } } const symbol = plugin.symbol( applyNaming(operation.id, { case: 'camelCase', name: '{{name}}ResponseTransformer', }), { meta: { category: 'transform', resource: 'operation', resourceId: operation.id, role: 'response', }, }, ); const value = $.const(symbol) .export() .assign( // TODO: parser - add types, generate types without transforms $.func() .async() .param(dataVariableName, (p) => p.type('any')) .returns($.type('Promise').generic(symbolResponse)) .do(...finalNodes), ); plugin.node(value); }, { order: 'declarations', }, ); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/transformers/types.ts ================================================ import type { IR } from '@hey-api/shared'; import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type ts from 'typescript'; import type { $, DollarTsDsl, MaybeTsDsl, TsDsl } from '../../../ts-dsl'; interface BaseTransformer extends DollarTsDsl { plugin: HeyApiTransformersPlugin['Instance']; schema: IR.SchemaObject; } export type ExpressionTransformer = ( ctx: BaseTransformer & { /** @deprecated Use `plugin` instead and access the config via `plugin.config` */ config: Omit; dataExpression?: ts.Expression | ReturnType | string; }, ) => Array> | undefined; /** * Returns the TypeScript type node for a schema with a specific format. * If undefined is returned, the default type will be used. */ export type TypeTransformer = (ctx: BaseTransformer) => MaybeTsDsl | undefined; export type UserConfig = Plugin.Name<'@hey-api/transformers'> & Plugin.Hooks & Plugin.UserExports & { /** * Convert long integers into BigInt values? * * @default true */ bigInt?: boolean; /** * Convert date strings into Date objects? * * @default true */ dates?: boolean; /** * Custom transforms to apply to the generated code. */ transformers?: ReadonlyArray; /** * Custom type transformers that modify the TypeScript types generated. */ typeTransformers?: ReadonlyArray; }; export type Config = Plugin.Name<'@hey-api/transformers'> & Plugin.Hooks & Plugin.Exports & { /** * Convert long integers into BigInt values? * * @default true */ bigInt: boolean; /** * Convert date strings into Date objects? * * @default true */ dates: boolean; /** * Custom transforms to apply to the generated code. */ transformers: ReadonlyArray; /** * Custom type transformers that modify the TypeScript types generated. */ typeTransformers: ReadonlyArray; }; export type HeyApiTransformersPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/api.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import type { Type } from './shared/types'; import type { HeyApiTypeScriptPlugin } from './types'; import { createProcessor } from './v1/processor'; export type IApi = { schemaToType: (plugin: HeyApiTypeScriptPlugin['Instance'], schema: IR.SchemaObject) => Type; }; export class Api implements IApi { schemaToType(plugin: HeyApiTypeScriptPlugin['Instance'], schema: IR.SchemaObject): Type { const processor = createProcessor(plugin); const result = processor.process({ export: false, meta: { resource: 'definition', resourceId: '', }, naming: plugin.config.definitions, path: [], plugin, schema, }); if (!result) { return $.type(plugin.config.topType); } return result.type; } } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { Api } from './api'; import { handler } from './plugin'; import type { HeyApiTypeScriptPlugin } from './types'; export const defaultConfig: HeyApiTypeScriptPlugin['Config'] = { api: new Api(), config: { case: 'PascalCase', comments: true, includeInEntry: true, topType: 'unknown', }, handler, name: '@hey-api/typescript', resolveConfig: (plugin, context) => { plugin.config.definitions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', name: '{{name}}', }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: plugin.config.definitions, }); plugin.config.enums = context.valueToObject({ defaultValue: { case: 'SCREAMING_SNAKE_CASE', constantsIgnoreNull: false, enabled: Boolean(plugin.config.enums), mode: 'javascript', }, mappers: { boolean: (enabled) => ({ enabled }), string: (mode) => ({ mode }), }, value: plugin.config.enums, }); plugin.config.errors = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', error: '{{name}}Error', name: '{{name}}Errors', }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: plugin.config.errors, }); plugin.config.requests = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', name: '{{name}}Data', }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: plugin.config.requests, }); plugin.config.responses = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', name: '{{name}}Responses', response: '{{name}}Response', }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: plugin.config.responses, }); plugin.config.webhooks = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', name: '{{name}}WebhookRequest', payload: '{{name}}WebhookPayload', }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: plugin.config.webhooks, }); }, }; /** * Type helper for `@hey-api/typescript` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { HeyApiTypeScriptResolvers } from './resolvers'; export type { HeyApiTypeScriptPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/plugin.ts ================================================ import type { HeyApiTypeScriptPlugin } from './types'; import { handlerV1 } from './v1/plugin'; export const handler: HeyApiTypeScriptPlugin['Handler'] = (args) => handlerV1(args); ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/resolvers.ts ================================================ import type { IR, Plugin, SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import type { $, DollarTsDsl } from '../../../ts-dsl'; import type { Type, TypeScriptResult } from './shared/types'; import type { HeyApiTypeScriptPlugin } from './types'; export type HeyApiTypeScriptResolvers = Plugin.Resolvers<{ /** * Resolver for array schemas. * * Allows customization of how array types are rendered. * * Returning `undefined` will execute the default resolver logic. */ array?: (ctx: ArrayResolverContext) => Type | undefined; /** * Resolver for boolean schemas. * * Allows customization of how boolean types are rendered. * * Returning `undefined` will execute the default resolver logic. */ boolean?: (ctx: BooleanResolverContext) => Type | undefined; /** * Resolver for enum schemas. * * Allows customization of how enum types are rendered. * * Returning `undefined` will execute the default resolver logic. */ enum?: (ctx: EnumResolverContext) => Type | undefined; /** * Resolver for intersection schemas. * * Allows customization of how intersection types are rendered. * * Returning `undefined` will execute the default resolver logic. */ intersection?: (ctx: IntersectionResolverContext) => Type | undefined; /** * Resolver for never schemas. * * Allows customization of how never types are rendered. * * Returning `undefined` will execute the default resolver logic. */ never?: (ctx: NeverResolverContext) => Type | undefined; /** * Resolver for null schemas. * * Allows customization of how null types are rendered. * * Returning `undefined` will execute the default resolver logic. */ null?: (ctx: NullResolverContext) => Type | undefined; /** * Resolver for number schemas. * * Allows customization of how number types are rendered. * * Returning `undefined` will execute the default resolver logic. */ number?: (ctx: NumberResolverContext) => Type | undefined; /** * Resolver for object schemas. * * Allows customization of how object types are rendered. * * Returning `undefined` will execute the default resolver logic. */ object?: (ctx: ObjectResolverContext) => Type | undefined; /** * Resolver for string schemas. * * Allows customization of how string types are rendered. * * Returning `undefined` will execute the default resolver logic. */ string?: (ctx: StringResolverContext) => Type | undefined; /** * Resolver for tuple schemas. * * Allows customization of how tuple types are rendered. * * Returning `undefined` will execute the default resolver logic. */ tuple?: (ctx: TupleResolverContext) => Type | undefined; /** * Resolver for undefined schemas. * * Allows customization of how undefined types are rendered. * * Returning `undefined` will execute the default resolver logic. */ undefined?: (ctx: UndefinedResolverContext) => Type | undefined; /** * Resolver for union schemas. * * Allows customization of how union types are rendered. * * Returning `undefined` will execute the default resolver logic. */ union?: (ctx: UnionResolverContext) => Type | undefined; /** * Resolver for unknown schemas. * * Allows customization of how unknown types are rendered. * * Returning `undefined` will execute the default resolver logic. */ unknown?: (ctx: UnknownResolverContext) => Type | undefined; /** * Resolver for void schemas. * * Allows customization of how void types are rendered. * * Returning `undefined` will execute the default resolver logic. */ void?: (ctx: VoidResolverContext) => Type | undefined; }>; interface BaseContext extends DollarTsDsl { /** The plugin instance. */ plugin: HeyApiTypeScriptPlugin['Instance']; } export interface ArrayResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base array type expression. */ base: (ctx: ArrayResolverContext) => Type; }; schema: SchemaWithType<'array'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface BooleanResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base boolean type expression. */ base: (ctx: BooleanResolverContext) => Type; /** * Returns the literal type for const values. */ const: (ctx: BooleanResolverContext) => Type | undefined; }; schema: SchemaWithType<'boolean'>; } export interface EnumResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base enum type expression. */ base: (ctx: EnumResolverContext) => Type; /** * Returns parsed enum items with metadata about the enum members. */ items: (ctx: EnumResolverContext) => { /** * String literal values for use with union types. */ enumMembers: Array>; /** * Whether the enum includes a null value. */ isNullable: boolean; }; }; schema: SchemaWithType<'enum'>; } export interface IntersectionResolverContext extends BaseContext { /** * The child results from walking intersection members. */ childResults: ReadonlyArray; /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base intersection type expression. */ base: (ctx: IntersectionResolverContext) => Type; }; /** * The parent schema containing the intersection. */ parentSchema: IR.SchemaObject; /** * The individual schemas being intersected. */ schemas: ReadonlyArray; } export interface NeverResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base never type expression. */ base: (ctx: NeverResolverContext) => Type; }; schema: SchemaWithType<'never'>; } export interface NullResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base null type expression. */ base: (ctx: NullResolverContext) => Type; }; schema: SchemaWithType<'null'>; } export interface NumberResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base number type expression. */ base: (ctx: NumberResolverContext) => Type; /** * Returns the literal type for const values. */ const: (ctx: NumberResolverContext) => Type | undefined; }; schema: SchemaWithType<'integer' | 'number'>; } export interface ObjectResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base object type expression. */ base: (ctx: ObjectResolverContext) => Type; /** * Returns the shape (properties) of the object type. */ shape: (ctx: ObjectResolverContext) => ReturnType; }; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface StringResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base string type expression. */ base: (ctx: StringResolverContext) => Type; /** * Returns the literal type for const values. */ const: (ctx: StringResolverContext) => Type | undefined; /** * Returns the format-specific type expression. */ format: (ctx: StringResolverContext) => Type | undefined; }; schema: SchemaWithType<'string'>; } export interface TupleResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base tuple type expression. */ base: (ctx: TupleResolverContext) => Type; /** * Returns the literal type for const tuple values. */ const: (ctx: TupleResolverContext) => Type | undefined; }; schema: SchemaWithType<'tuple'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface UnionResolverContext extends BaseContext { /** * The child results from walking union members. */ childResults: ReadonlyArray; /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base union type expression. */ base: (ctx: UnionResolverContext) => Type; }; /** * The parent schema containing the union. */ parentSchema: IR.SchemaObject; /** * The individual schemas being unioned. */ schemas: ReadonlyArray; } export interface UndefinedResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base undefined type expression. */ base: (ctx: UndefinedResolverContext) => Type; }; schema: SchemaWithType<'undefined'>; } export interface UnknownResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base unknown type expression. */ base: (ctx: UnknownResolverContext) => Type; }; schema: SchemaWithType<'unknown'>; } export interface VoidResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base void type expression. */ base: (ctx: VoidResolverContext) => Type; }; schema: SchemaWithType<'void'>; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/shared/clientOptions.ts ================================================ import type { IR } from '@hey-api/shared'; import { buildSymbolIn, parseUrl } from '@hey-api/shared'; import { getTypedConfig } from '../../../../config/utils'; import { getClientBaseUrlKey, getClientPlugin, } from '../../../../plugins/@hey-api/client-core/utils'; import type { TypeTsDsl } from '../../../../ts-dsl'; import { $ } from '../../../../ts-dsl'; import type { HeyApiTypeScriptPlugin } from '../types'; const serverToBaseUrlType = ({ server }: { server: IR.ServerObject }) => { const url = parseUrl(server.url); if (url.protocol && url.host) { return $.type.literal(server.url); } return $.type .template() .add(url.protocol || $.type('string')) .add('://') .add(url.host || $.type('string')) .add(url.port ? `:${url.port}` : '') .add(url.path || ''); }; export const createClientOptions = ({ nodeIndex, plugin, servers, }: { nodeIndex: number; plugin: HeyApiTypeScriptPlugin['Instance']; servers: ReadonlyArray; }) => { const client = getClientPlugin(getTypedConfig(plugin)); const types: Array = servers.map((server) => serverToBaseUrlType({ server })); if (!servers.length) { types.push($.type('string')); } else if (!('strictBaseUrl' in client.config && client.config.strictBaseUrl)) { types.push($.type.and($.type('string'), $.type.object())); } const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', resource: 'client', role: 'options', tool: 'typescript', }, name: 'ClientOptions', naming: { case: plugin.config.case, }, plugin, }), ); const node = $.type .alias(symbol) .export() .type( $.type .object() .prop(getClientBaseUrlKey(getTypedConfig(plugin)), (p) => p.type($.type.or(...types))), ); plugin.node(node, nodeIndex); }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/shared/export.ts ================================================ import type { IR } from '@hey-api/shared'; import { buildSymbolIn, pathToName, toCase } from '@hey-api/shared'; import { pathToJsonPointer } from '@hey-api/shared'; import { createSchemaComment } from '../../../../plugins/shared/utils/schema'; import { $, regexp } from '../../../../ts-dsl'; import type { HeyApiTypeScriptPlugin } from '../types'; import type { ProcessorContext } from './processor'; import type { TypeScriptFinal } from './types'; function resolveEnumKey({ baseName, duplicateAttempt, plugin, }: { baseName: string; duplicateAttempt: number; plugin: HeyApiTypeScriptPlugin['Instance']; }): string { let key = toCase(baseName, plugin.config.enums.case, { stripLeadingSeparators: false, }); regexp.number.lastIndex = 0; if ( regexp.number.test(key) && plugin.config.enums.enabled && (plugin.config.enums.mode === 'typescript' || plugin.config.enums.mode === 'typescript-const') ) { key = `_${key}`; } if (duplicateAttempt > 0) { const nameConflictResolver = plugin.context.config.output?.nameConflictResolver; if (nameConflictResolver) { const resolvedName = nameConflictResolver({ attempt: duplicateAttempt, baseName: key, }); if (resolvedName !== null) { key = resolvedName; } else { key = `${key}${duplicateAttempt + 1}`; } } else { key = `${key}${duplicateAttempt + 1}`; } } return key; } function buildEnumExport({ enumData, name, plugin, resourceId, schema, }: { enumData: TypeScriptFinal['enumData']; name: string; plugin: HeyApiTypeScriptPlugin['Instance']; resourceId: string; schema: IR.SchemaObject; }): boolean { if (!enumData || enumData.mode === 'type') return false; const mode = enumData.mode; const items = enumData.items; const duplicateCounts: Record = {}; const itemsWithAttempts = items.map((item, index) => { const candidateKey = toCase(item.key, plugin.config.enums.case, { stripLeadingSeparators: false, }); regexp.number.lastIndex = 0; const baseKey = regexp.number.test(candidateKey) && plugin.config.enums.enabled && (plugin.config.enums.mode === 'typescript' || plugin.config.enums.mode === 'typescript-const') ? `_${candidateKey}` : candidateKey; const duplicateAttempt = duplicateCounts[baseKey] ?? 0; duplicateCounts[baseKey] = duplicateAttempt + 1; return { duplicateAttempt, index, item, }; }); if (mode === 'javascript') { const filteredItems = plugin.config.enums.constantsIgnoreNull && items.some((item) => item.schema.const === null) ? items.filter((item) => item.schema.const !== null) : items; const symbolObject = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'utility', resource: 'definition', resourceId, tool: 'typescript', }, name, naming: plugin.config.definitions, plugin, schema, }), ); const objectNode = $.const(symbolObject) .export() .$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)) .assign( $.object( ...itemsWithAttempts .filter(({ item }) => filteredItems.includes(item)) .map(({ duplicateAttempt, item }) => $.prop({ kind: 'prop' as const, name: resolveEnumKey({ baseName: item.key, duplicateAttempt, plugin }), }) .$if(plugin.config.comments && createSchemaComment(item.schema), (p, v) => p.doc(v)) .value($.fromValue(item.schema.const)), ), ).as('const'), ); plugin.node(objectNode); const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', resource: 'definition', resourceId, tool: 'typescript', }, name, naming: plugin.config.definitions, plugin, schema, }), ); const node = $.type .alias(symbol) .export() .$if(plugin.config.comments && createSchemaComment(schema), (t, v) => t.doc(v)) .type($.type(symbolObject).idx($.type(symbolObject).typeofType().keyof()).typeofType()); plugin.node(node); return true; } if (mode === 'typescript' || mode === 'typescript-const') { const hasInvalidTypes = items.some( (item) => typeof item.schema.const !== 'number' && typeof item.schema.const !== 'string', ); if (hasInvalidTypes) return false; const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', resource: 'definition', resourceId, tool: 'typescript', }, name, naming: plugin.config.definitions, plugin, schema, }), ); const enumNode = $.enum(symbol) .export() .$if(plugin.config.comments && createSchemaComment(schema), (e, v) => e.doc(v)) .const(mode === 'typescript-const') .members( ...itemsWithAttempts.map(({ duplicateAttempt, item }) => $.member(resolveEnumKey({ baseName: item.key, duplicateAttempt, plugin })) .$if(plugin.config.comments && createSchemaComment(item.schema), (m, v) => m.doc(v)) .value($.fromValue(item.schema.const)), ), ); plugin.node(enumNode); return true; } return false; } export function exportAst({ final, meta, naming, namingAnchor, path, plugin, schema, tags, }: ProcessorContext & { final: TypeScriptFinal; }): void { const $ref = meta.resourceId || pathToJsonPointer(path); const name = pathToName(path, { anchor: namingAnchor }); const hasEnumExport = buildEnumExport({ enumData: final.enumData, name, plugin, resourceId: $ref, schema, }); // If enum declaration/const object has been emitted, do not emit fallback type alias. if (hasEnumExport) { return; } const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'definition', resourceId: $ref, tags, tool: 'typescript', }, name, naming, plugin, schema, }), ); const node = $.type .alias(symbol) .export() .$if(plugin.config.comments && createSchemaComment(schema), (t, v) => t.doc(v)) .type(final.type); plugin.node(node); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/shared/meta.ts ================================================ import type { IR } from '@hey-api/shared'; import type { TypeScriptMeta, TypeScriptResult } from './types'; /** * Creates default metadata from a schema. */ export function defaultMeta(schema: IR.SchemaObject): TypeScriptMeta { return { default: schema.default, readonly: schema.accessScope === 'read', }; } /** * Composes metadata from child results. * * @param children - Results from walking child schemas * @param overrides - Explicit overrides (e.g., from parent schema) */ export function composeMeta( children: ReadonlyArray, overrides?: Partial, ): TypeScriptMeta { return { default: overrides?.default, readonly: overrides?.readonly ?? children.some((c) => c.meta.readonly), }; } /** * Merges parent schema metadata with composed child metadata. * * @param parent - The parent schema * @param children - Results from walking child schemas */ export function inheritMeta( parent: IR.SchemaObject, children: ReadonlyArray, ): TypeScriptMeta { return composeMeta(children, { default: parent.default, readonly: parent.accessScope === 'read', }); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/shared/operation.ts ================================================ import type { IR } from '@hey-api/shared'; import { buildSymbolIn, deduplicateSchema, operationResponsesMap } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { HeyApiTypeScriptPlugin } from '../types'; import { createProcessor } from '../v1/processor'; const irParametersToIrSchema = ({ parameters, }: { parameters: Record; }): IR.SchemaObject => { const irSchema: IR.SchemaObject = { type: 'object', }; if (parameters) { const properties: Record = {}; const required: Array = []; for (const key in parameters) { const parameter = parameters[key]!; properties[parameter.name] = deduplicateSchema({ detectFormat: false, schema: parameter.schema, }); if (parameter.required) { required.push(parameter.name); } } irSchema.properties = properties; if (required.length) { irSchema.required = required; } } return irSchema; }; export const operationToType = ({ operation, path, plugin, tags, }: { operation: IR.OperationObject; path: ReadonlyArray; plugin: HeyApiTypeScriptPlugin['Instance']; tags?: ReadonlyArray; }): void => { const processor = createProcessor(plugin); const data: IR.SchemaObject = { properties: { body: operation.body?.schema ?? { type: 'never' }, ...(operation.parameters?.header ? { headers: irParametersToIrSchema({ parameters: operation.parameters.header, }), } : {}), path: operation.parameters?.path ? irParametersToIrSchema({ parameters: operation.parameters.path }) : { type: 'never' }, query: operation.parameters?.query ? irParametersToIrSchema({ parameters: operation.parameters.query }) : { type: 'never' }, url: { const: operation.path, type: 'string', }, }, type: 'object', }; const dataRequired: Array = []; if (operation.body?.required) { dataRequired.push('body'); } // do not set headers to never so we can always pass arbitrary values if (data.properties!.headers?.required) { dataRequired.push('headers'); } if (data.properties!.path!.required) { dataRequired.push('path'); } if (data.properties!.query!.required) { dataRequired.push('query'); } dataRequired.push('url'); if (dataRequired.length > 0) { data.required = dataRequired; } const dataResult = processor.process({ export: false, meta: { resource: 'operation', resourceId: operation.id, }, naming: plugin.config.definitions, path: [...path, operation.id, 'data'], plugin, schema: data, }); const dataSymbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'operation', resourceId: operation.id, role: 'data', tags, tool: 'typescript', }, name: operation.id, naming: plugin.config.requests, operation, plugin, }), ); const dataNode = $.type .alias(dataSymbol) .export() .type(dataResult?.type ?? $.type('never')); plugin.node(dataNode); const { error, errors, response, responses } = operationResponsesMap(operation); if (errors) { const errorsResult = processor.process({ export: false, meta: { resource: 'operation', resourceId: operation.id, }, naming: plugin.config.definitions, path: [...path, operation.id, 'errors'], plugin, schema: errors, }); const errorsSymbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'operation', resourceId: operation.id, role: 'errors', tags, tool: 'typescript', }, name: operation.id, naming: plugin.config.errors, operation, plugin, }), ); const errorsNode = $.type .alias(errorsSymbol) .export() .type(errorsResult?.type ?? $.type('never')); plugin.node(errorsNode); if (error) { const errorSymbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'operation', resourceId: operation.id, role: 'error', tags, tool: 'typescript', }, name: operation.id, naming: { case: plugin.config.errors.case, name: plugin.config.errors.error, }, operation, plugin, }), ); const errorNode = $.type .alias(errorSymbol) .export() .type($.type(errorsSymbol).idx($.type(errorsSymbol).keyof())); plugin.node(errorNode); } } if (responses) { const responsesResult = processor.process({ export: false, meta: { resource: 'operation', resourceId: operation.id, }, naming: plugin.config.definitions, path: [...path, operation.id, 'responses'], plugin, schema: responses, }); const responsesSymbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'operation', resourceId: operation.id, role: 'responses', tags, tool: 'typescript', }, name: operation.id, naming: plugin.config.responses, operation, plugin, }), ); const responsesNode = $.type .alias(responsesSymbol) .export() .type(responsesResult?.type ?? $.type('never')); plugin.node(responsesNode); if (response) { const responseSymbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'operation', resourceId: operation.id, role: 'response', tags, tool: 'typescript', }, name: operation.id, naming: { case: plugin.config.responses.case, name: plugin.config.responses.response, }, operation, plugin, }), ); const responseNode = $.type .alias(responseSymbol) .export() .type($.type(responsesSymbol).idx($.type(responsesSymbol).keyof())); plugin.node(responseNode); } } }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/shared/processor.ts ================================================ import type { IR, NamingConfig, SchemaProcessorContext } from '@hey-api/shared'; import type { HeyApiTypeScriptPlugin } from '../types'; import type { TypeScriptFinal } from './types'; export type ProcessorContext = SchemaProcessorContext & { /** Whether to export the result (default: true) */ export?: boolean; naming: NamingConfig; /** The plugin instance. */ plugin: HeyApiTypeScriptPlugin['Instance']; schema: IR.SchemaObject; }; export type ProcessorResult = { process: (ctx: ProcessorContext) => TypeScriptFinal | void; }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/shared/types.ts ================================================ import type { IR } from '@hey-api/shared'; import type { MaybeTsDsl, TypeTsDsl } from '../../../../ts-dsl'; export type Type = MaybeTsDsl; /** * Metadata that flows through schema walking. */ export interface TypeScriptMeta { /** Default value from schema. */ default?: unknown; /** Is this schema read-only? */ readonly: boolean; } export interface TypeScriptEnumData { items: Array<{ key: string; schema: IR.SchemaObject }>; mode: 'javascript' | 'typescript' | 'typescript-const' | 'type'; } /** * Result from walking a schema node. */ export interface TypeScriptResult { enumData?: TypeScriptEnumData; meta: TypeScriptMeta; type: Type; } /** * Finalized result after applyModifiers. */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface TypeScriptFinal extends Pick {} ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/shared/webhook.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { buildSymbolIn } from '@hey-api/shared'; import { createSchemaComment } from '../../../../plugins/shared/utils/schema'; import { $ } from '../../../../ts-dsl'; import type { HeyApiTypeScriptPlugin } from '../types'; import { createProcessor } from '../v1/processor'; export function webhookToType({ operation, path, plugin, tags, }: { operation: IR.OperationObject; path: ReadonlyArray; plugin: HeyApiTypeScriptPlugin['Instance']; tags?: ReadonlyArray; }): Symbol { const processor = createProcessor(plugin); let symbolWebhookPayload: Symbol | undefined; if (operation.body) { symbolWebhookPayload = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'webhook', resourceId: operation.id, role: 'payload', tags, tool: 'typescript', }, name: operation.id, naming: { case: plugin.config.webhooks.case, name: plugin.config.webhooks.payload, }, operation, plugin, }), ); const payloadResult = processor.process({ export: false, meta: { resource: 'webhook', resourceId: operation.id, }, naming: plugin.config.definitions, path: [...path, operation.id, 'payload'], plugin, schema: operation.body.schema, }); const payloadNode = $.type .alias(symbolWebhookPayload) .export() .$if(plugin.config.comments && createSchemaComment(operation.body.schema), (t, v) => t.doc(v)) .type(payloadResult?.type ?? $.type('never')); plugin.node(payloadNode); } const requestType = $.type .object() .prop('body', (p) => p .required(Boolean(symbolWebhookPayload)) .type(symbolWebhookPayload ? $.type(symbolWebhookPayload) : $.type('never')), ) .prop('key', (p) => p.required(true).type($.type.literal(operation.path))) .prop('path', (p) => p.required(false).type($.type('never'))) .prop('query', (p) => p.required(false).type($.type('never'))); const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, resource: 'webhook', resourceId: operation.id, role: 'data', tags, tool: 'typescript', }, name: operation.id, naming: plugin.config.webhooks, operation, plugin, }), ); const node = $.type.alias(symbol).export().type(requestType); plugin.node(node); return symbol; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/types.ts ================================================ import type { Casing, FeatureToggle, NameTransformer, NamingOptions } from '@hey-api/shared'; import type { DefinePlugin, Plugin } from '@hey-api/shared'; import type { IApi } from './api'; import type { HeyApiTypeScriptResolvers } from './resolvers'; export type EnumsType = 'javascript' | 'typescript' | 'typescript-const'; export type UserConfig = Plugin.Name<'@hey-api/typescript'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & HeyApiTypeScriptResolvers & { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Exclude; /** * Configuration for reusable schema definitions. * * Controls generation of shared types that can be referenced across * requests and responses. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default '{{name}}' */ definitions?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Naming pattern for generated names. * * @default '{{name}}' */ name?: NameTransformer; }; /** * By default, enums are emitted as types to preserve runtime-free output. * * However, you may want to generate enums as JavaScript objects or * TypeScript enums for runtime usage, interoperability, or integration with * other tools. * * @default false */ enums?: | boolean | EnumsType | { /** * Casing convention for generated names. * * @default 'SCREAMING_SNAKE_CASE' */ case?: Casing; /** * When generating enums as JavaScript objects, they'll contain a null * value if they're nullable. This might be undesirable if you want to do * `Object.values(Foo)` and have all values be of the same type. * * This setting is disabled by default to preserve the source schemas. * * @default false */ constantsIgnoreNull?: boolean; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Specifies the output mode for generated enums. * * Can be: * - `javascript`: Generates JavaScript objects * - `typescript`: Generates TypeScript enums * - `typescript-const`: Generates TypeScript const enums * * @default 'javascript' */ mode?: EnumsType; }; /** * Configuration for error-specific types. * * Controls generation of types for error response bodies and status codes. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default '{{name}}Errors' */ errors?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Naming pattern for generated names. * * @default '{{name}}Error' */ error?: NameTransformer; /** * Naming pattern for generated names. * * @default '{{name}}Errors' */ name?: NameTransformer; }; /** * Configuration for request-specific types. * * Controls generation of types for request bodies, query parameters, path * parameters, and headers. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default '{{name}}Data' */ requests?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Naming pattern for generated names. * * @default '{{name}}Data' */ name?: NameTransformer; }; /** * Configuration for response-specific types. * * Controls generation of types for response bodies and status codes. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default '{{name}}Responses' */ responses?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Naming pattern for generated names. * * @default '{{name}}Responses' */ name?: NameTransformer; /** * Naming pattern for generated names. * * @default '{{name}}Response' */ response?: NameTransformer; }; /** * The top type to use for untyped or unspecified schema values. * * Can be: * - `unknown` (default): safe top type, you must narrow before use * - `any`: disables type checking, can be used anywhere * * @default 'unknown' */ topType?: 'any' | 'unknown'; /** * Configuration for webhook-specific types. * * Controls generation of types for webhook payloads and webhook requests. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default '{{name}}WebhookRequest' */ webhooks?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Naming pattern for generated names. * * @default '{{name}}WebhookRequest' */ name?: NameTransformer; /** * Naming pattern for generated names. * * @default '{{name}}WebhookPayload' */ payload?: NameTransformer; }; }; export type Config = Plugin.Name<'@hey-api/typescript'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & HeyApiTypeScriptResolvers & { /** * Casing convention for generated names. */ case: Exclude; /** * Configuration for reusable schema definitions. * * Controls generation of shared types that can be referenced across * requests and responses. */ definitions: NamingOptions; /** * By default, enums are emitted as types to preserve runtime-free output. * * However, you may want to generate enums as JavaScript objects or * TypeScript enums for runtime usage, interoperability, or integration with * other tools. */ enums: FeatureToggle & { /** * Casing convention for generated names. */ case: Casing; /** * When generating enums as JavaScript objects, they'll contain a null * value if they're nullable. This might be undesirable if you want to do * `Object.values(Foo)` and have all values be of the same type. * * This setting is disabled by default to preserve the source schemas. * * @default false */ constantsIgnoreNull: boolean; /** * Specifies the output mode for generated enums. * * Can be: * - `javascript`: Generates JavaScript objects * - `typescript`: Generates TypeScript enums * - `typescript-const`: Generates TypeScript const enums * * @default 'javascript' */ mode: EnumsType; }; /** * Configuration for error-specific types. * * Controls generation of types for error response bodies and status codes. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object */ errors: NamingOptions & { /** * Naming pattern for generated names. */ error: NameTransformer; }; /** * Configuration for request-specific types. * * Controls generation of types for request bodies, query parameters, path * parameters, and headers. */ requests: NamingOptions; /** * Configuration for response-specific types. * * Controls generation of types for response bodies and status codes. */ responses: NamingOptions & { /** * Naming pattern for generated names. */ response: NameTransformer; }; /** * The top type to use for untyped or unspecified schema values. * * @default 'unknown' */ topType: 'any' | 'unknown'; /** * Configuration for webhook-specific types. * * Controls generation of types for webhook payloads and webhook requests. */ webhooks: NamingOptions & { /** * Naming pattern for generated names. */ payload: NameTransformer; }; }; export type HeyApiTypeScriptPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/plugin.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { buildSymbolIn, pathToJsonPointer } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { createClientOptions } from '../shared/clientOptions'; import { operationToType } from '../shared/operation'; import { webhookToType } from '../shared/webhook'; import type { HeyApiTypeScriptPlugin } from '../types'; import { createProcessor } from './processor'; export const handlerV1: HeyApiTypeScriptPlugin['Handler'] = ({ plugin }) => { const nodeClientIndex = plugin.node(null); const nodeWebhooksIndex = plugin.node(null); const servers: Array = []; const webhooks: Array = []; const processor = createProcessor(plugin); plugin.forEach( 'operation', 'parameter', 'requestBody', 'schema', 'server', 'webhook', (event) => { switch (event.type) { case 'operation': operationToType({ operation: event.operation, path: event._path, plugin, tags: event.tags, }); break; case 'parameter': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.parameter.schema, tags: event.tags, }); break; case 'requestBody': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.requestBody.schema, tags: event.tags, }); break; case 'schema': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.schema, tags: event.tags, }); break; case 'server': servers.push(event.server); break; case 'webhook': webhooks.push( webhookToType({ operation: event.operation, path: event._path, plugin, tags: event.tags, }), ); break; } }, { order: 'declarations', }, ); createClientOptions({ nodeIndex: nodeClientIndex, plugin, servers }); if (webhooks.length > 0) { const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', resource: 'webhook', tool: 'typescript', variant: 'container', }, name: 'Webhooks', naming: { case: plugin.config.case, }, plugin, }), ); const node = $.type .alias(symbol) .export() .type($.type.or(...webhooks)); plugin.node(node, nodeWebhooksIndex); } }; ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/processor.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { Hooks, IR } from '@hey-api/shared'; import { createSchemaProcessor, createSchemaWalker, pathToJsonPointer } from '@hey-api/shared'; import { exportAst } from '../shared/export'; import type { ProcessorContext, ProcessorResult } from '../shared/processor'; import type { TypeScriptFinal } from '../shared/types'; import type { HeyApiTypeScriptPlugin } from '../types'; import { createVisitor } from './walker'; export function createProcessor(plugin: HeyApiTypeScriptPlugin['Instance']): ProcessorResult { const processor = createSchemaProcessor(); const extractorHooks: ReadonlyArray['shouldExtract']> = [ plugin.config['~hooks']?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract, ]; function extractor(ctx: ProcessorContext): IR.SchemaObject { if (processor.hasEmitted(ctx.path)) { return ctx.schema; } for (const hook of extractorHooks) { const result = hook?.(ctx); if (result) { process({ namingAnchor: processor.context.anchor, tags: processor.context.tags, ...ctx, }); return { $ref: pathToJsonPointer(ctx.path) }; } } return ctx.schema; } function process(ctx: ProcessorContext): TypeScriptFinal | void { if (!processor.markEmitted(ctx.path)) return; const shouldExport = ctx.export !== false; return processor.withContext({ anchor: ctx.namingAnchor, tags: ctx.tags }, () => { const visitor = createVisitor({ schemaExtractor: extractor }); const walk = createSchemaWalker(visitor); const result = walk(ctx.schema, { path: ref(ctx.path), plugin, }); const final = visitor.applyModifiers(result, { path: ref(ctx.path), plugin, }) as TypeScriptFinal; if (shouldExport) { exportAst({ ...ctx, final, plugin }); return; } return final; }); } return { process }; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/array.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { deduplicateSchema } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { ArrayResolverContext } from '../../resolvers'; import type { Type, TypeScriptResult } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(ctx: ArrayResolverContext): Type { const { plugin, schema, walk } = ctx; if (!schema.items) { return $.type('Array').generic($.type(plugin.config.topType)); } const dedupedSchema = deduplicateSchema({ detectFormat: true, schema }); if (!dedupedSchema.items) { return $.type('Array').generic($.type(plugin.config.topType)); } const itemResults: Array = dedupedSchema.items.map((item) => walk(item, { path: ref([]), plugin, }), ); if (itemResults.length === 1) { return $.type('Array').generic(itemResults[0]!.type); } return dedupedSchema.logicalOperator === 'and' ? $.type('Array').generic($.type.and(...itemResults.map((r) => r.type))) : $.type('Array').generic($.type.or(...itemResults.map((r) => r.type))); } function arrayResolver(ctx: ArrayResolverContext): Type { return ctx.nodes.base(ctx); } export function arrayToAst({ plugin, schema, walk, walkerCtx, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'array'>; walk: Walker; walkerCtx: SchemaVisitorContext; }): Type { const ctx: ArrayResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.array; const result = resolver?.(ctx); return result ?? arrayResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/boolean.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { BooleanResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(): Type { return $.type('boolean'); } function constNode(ctx: BooleanResolverContext): Type | undefined { const { schema } = ctx; if (schema.const !== undefined) { return $.type.fromValue(schema.const); } } function booleanResolver(ctx: BooleanResolverContext): Type { const constResult = ctx.nodes.const(ctx); if (constResult) return constResult; return ctx.nodes.base(ctx); } export function booleanToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'boolean'>; }): Type { const ctx: BooleanResolverContext = { $, nodes: { base: baseNode, const: constNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.boolean; const result = resolver?.(ctx); return result ?? booleanResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/enum.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { EnumResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { TypeScriptEnumData } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function buildEnumData( plugin: HeyApiTypeScriptPlugin['Instance'], schema: SchemaWithType<'enum'>, ): TypeScriptEnumData | undefined { if (!plugin.config.enums.enabled) { return; } const items = schema.items ?? []; const mode = plugin.config.enums.mode; return { items: items.map((item, index) => { let key: string; if (item.title) { key = item.title; } else if (typeof item.const === 'number' || typeof item.const === 'string') { key = `${item.const}`; } else if (typeof item.const === 'boolean') { key = item.const ? 'true' : 'false'; } else if (item.const === null) { key = 'null'; } else { key = `${index}`; } return { key, schema: item }; }), mode, }; } function itemsNode(ctx: EnumResolverContext): ReturnType { const { schema } = ctx; const items = schema.items ?? []; const enumMembers: Array> = []; let isNullable = false; for (const item of items) { if (item.type === 'string' && typeof item.const === 'string') { enumMembers.push($.type.literal(item.const)); } else if (item.type === 'number' && typeof item.const === 'number') { enumMembers.push($.type.literal(item.const)); } else if (item.type === 'boolean' && typeof item.const === 'boolean') { enumMembers.push($.type.literal(item.const)); } else if (item.type === 'null' || item.const === null) { isNullable = true; } } return { enumMembers, isNullable }; } function baseNode(ctx: EnumResolverContext): Type { const { schema } = ctx; const items = schema.items ?? []; if (items.length === 0) { return $.type('never'); } const literalTypes = items .filter((item) => item.const !== undefined) .map((item) => $.type.fromValue(item.const)); return literalTypes.length > 0 ? $.type.or(...literalTypes) : $.type('string'); } function enumResolver(ctx: EnumResolverContext): Type { return ctx.nodes.base(ctx); } export function enumToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'enum'>; }): { enumData?: TypeScriptEnumData; type: Type; } { const enumData = buildEnumData(plugin, schema); const ctx: EnumResolverContext = { $, nodes: { base: baseNode, items: itemsNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.enum; const type = resolver?.(ctx) ?? enumResolver(ctx); return { enumData, type, }; } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/intersection.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { IntersectionResolverContext } from '../../resolvers'; import type { Type, TypeScriptResult } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(ctx: IntersectionResolverContext): Type { const { childResults } = ctx; if (childResults.length === 1) { return childResults[0]!.type; } return $.type.and(...childResults.map((r) => r.type)); } function intersectionResolver(ctx: IntersectionResolverContext): Type { return ctx.nodes.base(ctx); } export function intersectionToAst({ childResults, parentSchema, plugin, schemas, }: { childResults: ReadonlyArray; parentSchema: IR.SchemaObject; plugin: HeyApiTypeScriptPlugin['Instance']; schemas: ReadonlyArray; }): Type { const ctx: IntersectionResolverContext = { $, childResults, nodes: { base: baseNode, }, parentSchema, plugin, schemas, }; const resolver = plugin.config['~resolvers']?.intersection; const result = resolver?.(ctx); return result ?? intersectionResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/never.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { NeverResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(): Type { return $.type('never'); } function neverResolver(ctx: NeverResolverContext): Type { return ctx.nodes.base(ctx); } export function neverToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'never'>; }): Type { const ctx: NeverResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.never; const result = resolver?.(ctx); return result ?? neverResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/null.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { NullResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(): Type { return $.type.literal(null); } function nullResolver(ctx: NullResolverContext): Type { return ctx.nodes.base(ctx); } export function nullToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'null'>; }): Type { const ctx: NullResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.null; const result = resolver?.(ctx); return result ?? nullResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/number.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { NumberResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function constNode(ctx: NumberResolverContext): Type | undefined { const { schema } = ctx; if (schema.const !== undefined) { return $.type.fromValue(schema.const); } } function baseNode(ctx: NumberResolverContext): Type { const { plugin, schema } = ctx; if (schema.type === 'integer' && schema.format === 'int64') { if (plugin.getPlugin('@hey-api/transformers')?.config.bigInt) { return $.type('bigint'); } } return $.type('number'); } function numberResolver(ctx: NumberResolverContext): Type { const constResult = ctx.nodes.const(ctx); if (constResult) return constResult; return ctx.nodes.base(ctx); } export function numberToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'integer' | 'number'>; }): Type { const ctx: NumberResolverContext = { $, nodes: { base: baseNode, const: constNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.number; const result = resolver?.(ctx); return result ?? numberResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/object.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { IR, SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { deduplicateSchema } from '@hey-api/shared'; import { createSchemaComment } from '../../../../../plugins/shared/utils/schema'; import { $ } from '../../../../../ts-dsl'; import type { ObjectResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { TypeScriptResult } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function shapeNode(ctx: ObjectResolverContext): ReturnType { const { schema, walk, walkerCtx } = ctx; const shape = $.type.object(); const required = schema.required ?? []; for (const name in schema.properties) { const property = schema.properties[name]!; const propertyResult = walk(property, { path: ref([]), plugin: walkerCtx.plugin }); const isRequired = required.includes(name); shape.prop(name, (p) => p .$if(walkerCtx.plugin.config.comments && createSchemaComment(property), (p, v) => p.doc(v)) .readonly(property.accessScope === 'read') .required(isRequired) .type(propertyResult.type), ); } return shape; } function baseNode(ctx: ObjectResolverContext): Type { const { schema, walk, walkerCtx } = ctx; const shape = shapeNode(ctx); const required = schema.required ?? []; let indexSchemas: Array = []; let hasOptionalProperties = false; for (const name in schema.properties) { const property = schema.properties[name]!; const isRequired = required.includes(name); indexSchemas.push(property); if (!isRequired) { hasOptionalProperties = true; } } if (schema.patternProperties) { for (const pattern in schema.patternProperties) { const ir = schema.patternProperties[pattern]!; indexSchemas.unshift(ir); } } const hasPatterns = !!schema.patternProperties && Object.keys(schema.patternProperties).length > 0; const addPropsRaw = schema.additionalProperties; const addPropsObj = addPropsRaw !== false && addPropsRaw ? (addPropsRaw as IR.SchemaObject) : undefined; const shouldCreateIndex = hasPatterns || (!!addPropsObj && (addPropsObj.type !== 'never' || !indexSchemas.length)); if (shouldCreateIndex) { const addProps = addPropsObj; if (addProps && addProps.type !== 'never') { if (addProps.type === 'unknown') { const patternSchemas: Array = schema.patternProperties ? Object.values(schema.patternProperties) : []; indexSchemas = [addProps, ...patternSchemas]; } else { indexSchemas.unshift(addProps); } } else if (!hasPatterns && !indexSchemas.length && addProps && addProps.type === 'never') { indexSchemas = [addProps]; } if (hasOptionalProperties && addProps?.type !== 'unknown') { indexSchemas.push({ type: 'undefined' }); } if (indexSchemas.length > 0) { const unionSchema: IR.SchemaObject = indexSchemas.length === 1 ? indexSchemas[0]! : deduplicateSchema({ schema: { items: indexSchemas, logicalOperator: 'or' } }); const indexType = walk(unionSchema, { path: ref([]), plugin: walkerCtx.plugin }).type; if (schema.propertyNames?.$ref) { const propertyNamesResult = walk( { $ref: schema.propertyNames.$ref }, { path: ref([]), plugin: walkerCtx.plugin }, ); return $.type.mapped('key').key(propertyNamesResult.type).optional().type(indexType); } shape.idxSig('key', (i) => i.key('string').type(indexType)); } } return shape; } function objectResolver(ctx: ObjectResolverContext): Type { return ctx.nodes.base(ctx); } export function objectToAst({ plugin, schema, walk, walkerCtx, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: SchemaVisitorContext; }): Type { const ctx: ObjectResolverContext = { $, nodes: { base: baseNode, shape: shapeNode, }, plugin, schema, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.object; const result = resolver?.(ctx); return result ?? objectResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/string.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import type { SchemaWithType } from '@hey-api/shared'; import { toCase } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { StringResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function constNode(ctx: StringResolverContext): Type | undefined { const { schema } = ctx; if (schema.const !== undefined) { return $.type.fromValue(schema.const); } } function formatNode(ctx: StringResolverContext): Type | undefined { const { plugin, schema } = ctx; const { format } = schema; if (!format) return; if (format === 'binary') { return $.type.or($.type('Blob'), $.type('File')); } if (format === 'date-time' || format === 'date') { if (plugin.getPlugin('@hey-api/transformers')?.config.dates) { return $.type('Date'); } } if (format === 'typeid' && typeof schema.example === 'string') { const parts = String(schema.example).split('_'); parts.pop(); const typeidBase = parts.join('_'); const typeidQuery: SymbolMeta = { category: 'type', resource: 'type-id', resourceId: typeidBase, tool: 'typescript', }; if (!plugin.getSymbol(typeidQuery)) { const containerQuery: SymbolMeta = { category: 'type', resource: 'type-id', tool: 'typescript', variant: 'container', }; if (!plugin.getSymbol(containerQuery)) { const symbolTypeId = plugin.symbol('TypeID', { meta: containerQuery, }); const nodeTypeId = $.type .alias(symbolTypeId) .export() .generic('T', (g) => g.extends('string')) .type($.type.template().add($.type('T')).add('_').add($.type('string'))); plugin.node(nodeTypeId); } const refSymbol = plugin.referenceSymbol(containerQuery); const symbolTypeName = plugin.symbol(toCase(`${typeidBase}_id`, plugin.config.case), { meta: typeidQuery, }); const node = $.type .alias(symbolTypeName) .export() .type($.type(refSymbol).generic($.type.literal(typeidBase))); plugin.node(node); } return $.type(plugin.referenceSymbol(typeidQuery)); } } // eslint-disable-next-line @typescript-eslint/no-unused-vars function baseNode(ctx: StringResolverContext): Type { return $.type('string'); } function stringResolver(ctx: StringResolverContext): Type { if (ctx.schema.const !== undefined) { const constResult = ctx.nodes.const(ctx); if (constResult) return constResult; } const formatResult = ctx.nodes.format(ctx); if (formatResult) return formatResult; return ctx.nodes.base(ctx); } export function stringToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'string'>; }): Type { const ctx: StringResolverContext = { $, nodes: { base: baseNode, const: constNode, format: formatNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.string; const result = resolver?.(ctx); return result ?? stringResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/tuple.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { TupleResolverContext } from '../../resolvers'; import type { Type, TypeScriptResult } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(ctx: TupleResolverContext): Type { const { plugin, schema, walk } = ctx; const itemTypes: Array = []; if (schema.items) { schema.items.forEach((item) => { const result = walk(item, { path: ref([]), plugin }); itemTypes.push(result.type); }); } return $.type.tuple(...itemTypes); } function constNode(ctx: TupleResolverContext): Type | undefined { const { schema } = ctx; if (!schema.const || !Array.isArray(schema.const)) { return; } const itemTypes = schema.const.map((value) => $.type.fromValue(value)); return $.type.tuple(...itemTypes); } function tupleResolver(ctx: TupleResolverContext): Type { const constResult = ctx.nodes.const(ctx); if (constResult) return constResult; return ctx.nodes.base(ctx); } export function tupleToAst({ plugin, schema, walk, walkerCtx, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'tuple'>; walk: Walker; walkerCtx: SchemaVisitorContext; }): Type { const ctx: TupleResolverContext = { $, nodes: { base: baseNode, const: constNode, }, plugin, schema, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.tuple; const result = resolver?.(ctx); return result ?? tupleResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/undefined.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { UndefinedResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(): Type { return $.type('undefined'); } function undefinedResolver(ctx: UndefinedResolverContext): Type { return ctx.nodes.base(ctx); } export function undefinedToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'undefined'>; }): Type { const ctx: UndefinedResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.undefined; const result = resolver?.(ctx); return result ?? undefinedResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/union.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { UnionResolverContext } from '../../resolvers'; import type { Type, TypeScriptResult } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(ctx: UnionResolverContext): Type { const { childResults } = ctx; if (childResults.length === 1) { return childResults[0]!.type; } return $.type.or(...childResults.map((r) => r.type)); } function unionResolver(ctx: UnionResolverContext): Type { return ctx.nodes.base(ctx); } export function unionToAst({ childResults, parentSchema, plugin, schemas, }: { childResults: ReadonlyArray; parentSchema: IR.SchemaObject; plugin: HeyApiTypeScriptPlugin['Instance']; schemas: ReadonlyArray; }): Type { const ctx: UnionResolverContext = { $, childResults, nodes: { base: baseNode, }, parentSchema, plugin, schemas, }; const resolver = plugin.config['~resolvers']?.union; const result = resolver?.(ctx); return result ?? unionResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/unknown.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { UnknownResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(ctx: UnknownResolverContext): Type { return $.type(ctx.plugin.config.topType); } function unknownResolver(ctx: UnknownResolverContext): Type { return ctx.nodes.base(ctx); } export function unknownToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'unknown'>; }): Type { const ctx: UnknownResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.unknown; const result = resolver?.(ctx); return result ?? unknownResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/toAst/void.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../../ts-dsl'; import type { VoidResolverContext } from '../../resolvers'; import type { Type } from '../../shared/types'; import type { HeyApiTypeScriptPlugin } from '../../types'; function baseNode(): Type { return $.type('void'); } function voidResolver(ctx: VoidResolverContext): Type { return ctx.nodes.base(ctx); } export function voidToAst({ plugin, schema, }: { plugin: HeyApiTypeScriptPlugin['Instance']; schema: SchemaWithType<'void'>; }): Type { const ctx: VoidResolverContext = { $, nodes: { base: baseNode, }, plugin, schema, }; const resolver = plugin.config['~resolvers']?.void; const result = resolver?.(ctx); return result ?? voidResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/@hey-api/typescript/v1/walker.ts ================================================ import { fromRef } from '@hey-api/codegen-core'; import type { SchemaExtractor, SchemaVisitor } from '@hey-api/shared'; import { pathToJsonPointer } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { defaultMeta, inheritMeta } from '../shared/meta'; import type { ProcessorContext } from '../shared/processor'; import type { TypeScriptResult } from '../shared/types'; import type { HeyApiTypeScriptPlugin } from '../types'; import { arrayToAst } from './toAst/array'; import { booleanToAst } from './toAst/boolean'; import { enumToAst } from './toAst/enum'; import { intersectionToAst } from './toAst/intersection'; import { neverToAst } from './toAst/never'; import { nullToAst } from './toAst/null'; import { numberToAst } from './toAst/number'; import { objectToAst } from './toAst/object'; import { stringToAst } from './toAst/string'; import { tupleToAst } from './toAst/tuple'; import { undefinedToAst } from './toAst/undefined'; import { unionToAst } from './toAst/union'; import { unknownToAst } from './toAst/unknown'; import { voidToAst } from './toAst/void'; export interface VisitorConfig { /** Optional schema extractor function. */ schemaExtractor?: SchemaExtractor; } export function createVisitor( config: VisitorConfig, ): SchemaVisitor { const { schemaExtractor } = config; return { applyModifiers(result) { return { enumData: result.enumData, type: result.type, }; }, array(schema, ctx, walk) { const type = arrayToAst({ plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { meta: defaultMeta(schema), type, }; }, boolean(schema, ctx) { const type = booleanToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, enum(schema, ctx) { const { enumData, type } = enumToAst({ plugin: ctx.plugin, schema }); return { enumData, meta: defaultMeta(schema), type, }; }, integer(schema, ctx) { const type = numberToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, intercept(schema, ctx, walk) { if (schemaExtractor && !schema.$ref) { const extracted = schemaExtractor({ meta: { resource: 'definition', resourceId: pathToJsonPointer(fromRef(ctx.path)), }, naming: ctx.plugin.config.definitions, path: fromRef(ctx.path), plugin: ctx.plugin, schema, }); if (extracted !== schema) { return walk(extracted, ctx); } } const transformersPlugin = ctx.plugin.getPlugin('@hey-api/transformers'); if (transformersPlugin?.config.typeTransformers) { for (const typeTransformer of transformersPlugin.config.typeTransformers) { const typeNode = typeTransformer({ $, plugin: transformersPlugin, schema }); if (typeNode) { return { meta: defaultMeta(schema), type: typeNode }; } } } }, intersection(items, schemas, parentSchema, ctx) { const type = intersectionToAst({ childResults: items, parentSchema, plugin: ctx.plugin, schemas, }); return { meta: inheritMeta(parentSchema, items), type, }; }, never(schema, ctx) { const type = neverToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, null(schema, ctx) { const type = nullToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, number(schema, ctx) { const type = numberToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, object(schema, ctx, walk) { const type = objectToAst({ plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { meta: defaultMeta(schema), type, }; }, postProcess(result) { return result; }, reference($ref, schema, ctx) { const symbol = ctx.plugin.referenceSymbol({ category: 'type', resource: 'definition', resourceId: $ref, }); if (schema.omit && schema.omit.length > 0) { const omittedKeys = schema.omit.length === 1 ? $.type.literal(schema.omit[0]!) : $.type.or(...schema.omit.map((key) => $.type.literal(key))); return { meta: defaultMeta(schema), type: $.type('Omit').generics($.type(symbol), omittedKeys), }; } return { meta: defaultMeta(schema), type: $.type(symbol), }; }, string(schema, ctx) { const type = stringToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, tuple(schema, ctx, walk) { const type = tupleToAst({ plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { meta: defaultMeta(schema), type, }; }, undefined(schema, ctx) { const type = undefinedToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, union(items, schemas, parentSchema, ctx) { const type = unionToAst({ childResults: items, parentSchema, plugin: ctx.plugin, schemas, }); return { meta: inheritMeta(parentSchema, items), type, }; }, unknown(schema, ctx) { const type = unknownToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, void(schema, ctx) { const type = voidToAst({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), type, }; }, }; } ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from './plugin'; import type { PiniaColadaPlugin } from './types'; export const defaultConfig: PiniaColadaPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/typescript', '@hey-api/sdk'], handler: handler as PiniaColadaPlugin['Handler'], name: '@pinia/colada', resolveConfig: (plugin, context) => { plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}Query', }, mappers, value: plugin.config.queryOptions, }); }, }; /** * Type helper for `@pinia/colada` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { PiniaColadaPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/meta.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import type { PiniaColadaPlugin } from './types'; export const handleMeta = ( plugin: PiniaColadaPlugin['Instance'], operation: IR.OperationObject, configPath: 'queryOptions' | 'mutationOptions', ): ReturnType | undefined => { const metaFn = plugin.config[configPath].meta; if (!metaFn) return; const metaObject = metaFn(operation); if (!Object.keys(metaObject).length) return; return $.fromValue(metaObject); }; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/mutationOptions.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { getTypedConfig } from '../../../config/utils'; import { getClientPlugin } from '../../../plugins/@hey-api/client-core/utils'; import { createOperationComment } from '../../../plugins/shared/utils/operation'; import { $ } from '../../../ts-dsl'; import { handleMeta } from './meta'; import type { PiniaColadaPlugin } from './types'; import { useTypeError, useTypeResponse } from './useType'; import { getPublicTypeData } from './utils'; export const createMutationOptions = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; }): void => { const symbolMutationOptionsType = plugin.external(`${plugin.name}.UseMutationOptions`); const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const typeData = getPublicTypeData({ isNuxtClient, operation, plugin }); const options = plugin.symbol('options'); const fnOptions = plugin.symbol('vars'); const awaitSdkFn = $.lazy((ctx) => ctx .access( plugin.referenceSymbol({ category: 'sdk', resource: 'operation', resourceId: operation.id, }), ) .call( $.object().pretty().spread(options).spread(fnOptions).prop('throwOnError', $.literal(true)), ) .await(), ); const statements: Array> = []; if (plugin.getPluginOrThrow('@hey-api/sdk').config.responseStyle === 'data') { statements.push($.return(awaitSdkFn)); } else { statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } const mutationOpts = $.object() .pretty() .prop( 'mutation', $.func() .async() .param(fnOptions, (p) => p.$if(isNuxtClient, (f) => f.type($.type('Partial').generic(typeData))), ) .do(...statements), ) .$if(handleMeta(plugin, operation, 'mutationOptions'), (o, v) => o.prop('meta', v)); const symbolMutationOptions = plugin.symbol( applyNaming(operation.id, plugin.config.mutationOptions), ); const statement = $.const(symbolMutationOptions) .export() .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() .param(options, (p) => p.optional().type($.type('Partial').generic(typeData))) .returns( $.type(symbolMutationOptionsType) .generic(useTypeResponse({ operation, plugin })) .generic(typeData) .generic(useTypeError({ operation, plugin })), ) .do($.return(mutationOpts)), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/plugin.ts ================================================ import type { PiniaColadaPlugin } from './types'; import { handlerV0 } from './v0/plugin'; export const handler: PiniaColadaPlugin['Handler'] = (args) => handlerV0(args); ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/queryKey.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { applyNaming, hasOperationDataRequired } from '@hey-api/shared'; import { getTypedConfig } from '../../../config/utils'; import { clientFolderAbsolutePath } from '../../../generate/client'; import { getClientBaseUrlKey, getClientPlugin } from '../../../plugins/@hey-api/client-core/utils'; import { $ } from '../../../ts-dsl'; import type { PiniaColadaPlugin } from './types'; import { getPublicTypeData } from './utils'; const TOptionsType = 'TOptions'; export const createQueryKeyFunction = ({ plugin }: { plugin: PiniaColadaPlugin['Instance'] }) => { const symbolCreateQueryKey = plugin.symbol( applyNaming('createQueryKey', { case: plugin.config.case, }), { meta: { category: 'utility', resource: 'createQueryKey', tool: plugin.name, }, }, ); const symbolQueryKeyType = plugin.referenceSymbol({ category: 'type', resource: 'QueryKey', tool: plugin.name, }); const symbolJsonValue = plugin.external(`${plugin.name}._JSONValue`); const returnType = $.type(symbolQueryKeyType).generic(TOptionsType).idx(0); const baseUrlKey = getClientBaseUrlKey(getTypedConfig(plugin)); const symbolOptions = plugin.referenceSymbol({ category: 'type', resource: 'client-options', tool: 'sdk', }); const symbolClient = plugin.getSymbol({ category: 'client', }); const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin)); const symbolSerializeQueryValue = plugin.symbol('serializeQueryKeyValue', { external: clientModule, meta: { category: 'external', resource: `${clientModule}.serializeQueryKeyValue`, }, }); const fn = $.const(symbolCreateQueryKey).assign( $.func() .param('id', (p) => p.type('string')) .param('options', (p) => p.optional().type(TOptionsType)) .param('tags', (p) => p.optional().type('ReadonlyArray')) .returns($.type.tuple(returnType)) .generic(TOptionsType, (g) => g.extends(symbolOptions)) .do( $.const('params') .type(returnType) .assign( $.object() .prop('_id', 'id') .prop( baseUrlKey, $('options') .attr(baseUrlKey) .optional() .or( $('options') .attr('client') .optional() .$if(symbolClient, (a, v) => a.coalesce(v)) .attr('getConfig') .call() .attr(baseUrlKey), ), ) .as(returnType), ), $.if('tags').do( $('params').attr('tags').assign($('tags').as('unknown').as(symbolJsonValue)), ), $.if($('options').attr('body').optional().neq($.id('undefined'))).do( $.const('normalizedBody').assign( $(symbolSerializeQueryValue).call($('options').attr('body')), ), $.if($('normalizedBody').neq($.id('undefined'))).do( $('params').attr('body').assign('normalizedBody'), ), ), $.if($('options').attr('path').optional()).do( $('params').attr('path').assign($('options').attr('path')), ), $.if($('options').attr('query').optional().neq($.id('undefined'))).do( $.const('normalizedQuery').assign( $(symbolSerializeQueryValue).call($('options').attr('query')), ), $.if($('normalizedQuery').neq($.id('undefined'))).do( $('params').attr('query').assign('normalizedQuery'), ), ), $.return($.array($('params'))), ), ); plugin.node(fn); }; const createQueryKeyLiteral = ({ id, operation, plugin, }: { id: string; operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; }) => { const config = plugin.config.queryKeys; let tagsExpression: ReturnType | undefined; if (config.tags && operation.tags && operation.tags.length > 0) { tagsExpression = $.array(...operation.tags.map((tag) => $.literal(tag))); } const symbolCreateQueryKey = plugin.referenceSymbol({ category: 'utility', resource: 'createQueryKey', tool: plugin.name, }); const createQueryKeyCallExpression = $(symbolCreateQueryKey).call( $.literal(id), 'options', tagsExpression, ); return createQueryKeyCallExpression; }; export const createQueryKeyType = ({ plugin }: { plugin: PiniaColadaPlugin['Instance'] }) => { const symbolJsonValue = plugin.external(`${plugin.name}._JSONValue`); const symbolOptions = plugin.referenceSymbol({ category: 'type', resource: 'client-options', tool: 'sdk', }); const symbolQueryKeyType = plugin.symbol('QueryKey', { meta: { category: 'type', resource: 'QueryKey', tool: plugin.name, }, }); const queryKeyType = $.type .alias(symbolQueryKeyType) .export() .generic(TOptionsType, (g) => g.extends($.type(symbolOptions))) .type( $.type.tuple( $.type.and( $.type(`Pick<${TOptionsType}, 'path'>`), $.type .object() .prop('_id', (p) => p.type('string')) .prop(getClientBaseUrlKey(getTypedConfig(plugin)), (p) => p.optional().type(symbolJsonValue), ) .prop('body', (p) => p.optional().type(symbolJsonValue)) .prop('query', (p) => p.optional().type(symbolJsonValue)) .prop('tags', (p) => p.optional().type(symbolJsonValue)), ), ), ); plugin.node(queryKeyType); }; export const queryKeyStatement = ({ operation, plugin, symbol, }: { operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; symbol: Symbol; }) => { const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const statement = $.const(symbol) .export() .assign( $.func() .param('options', (p) => p .required(hasOperationDataRequired(operation)) .type(getPublicTypeData({ isNuxtClient, operation, plugin })), ) .do( createQueryKeyLiteral({ id: operation.id, operation, plugin, }).return(), ), ); return statement; }; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/queryOptions.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { getTypedConfig } from '../../../config/utils'; import { getClientPlugin } from '../../../plugins/@hey-api/client-core/utils'; import { createOperationComment, hasOperationSse, isOperationOptionsRequired, } from '../../../plugins/shared/utils/operation'; import { $ } from '../../../ts-dsl'; import { handleMeta } from './meta'; import { createQueryKeyFunction, createQueryKeyType, queryKeyStatement } from './queryKey'; import type { PiniaColadaPlugin } from './types'; import { useTypeError, useTypeResponse } from './useType'; import { getPublicTypeData } from './utils'; const optionsParamName = 'options'; const fnOptions = 'context'; export const createQueryOptions = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; }): void => { if (hasOperationSse({ operation })) { return; } const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, operation, }); if ( !plugin.getSymbol({ category: 'utility', resource: 'createQueryKey', tool: plugin.name, }) ) { createQueryKeyType({ plugin }); createQueryKeyFunction({ plugin }); } let keyExpression: ReturnType; if (plugin.config.queryKeys.enabled) { const symbolQueryKey = plugin.symbol(applyNaming(operation.id, plugin.config.queryKeys)); const node = queryKeyStatement({ operation, plugin, symbol: symbolQueryKey, }); plugin.node(node); keyExpression = $(symbolQueryKey).call(optionsParamName); } else { const symbolCreateQueryKey = plugin.referenceSymbol({ category: 'utility', resource: 'createQueryKey', tool: plugin.name, }); // Optionally include tags when configured let tagsExpr: ReturnType | undefined; if (plugin.config.queryKeys.tags && operation.tags && operation.tags.length > 0) { tagsExpr = $.array(...operation.tags.map((t) => $.literal(t))); } keyExpression = $(symbolCreateQueryKey).call( $.literal(operation.id), optionsParamName, tagsExpr, ); } const client = getClientPlugin(getTypedConfig(plugin)); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const typeData = getPublicTypeData({ isNuxtClient, operation, plugin }); const awaitSdkFn = $.lazy((ctx) => ctx .access( plugin.referenceSymbol({ category: 'sdk', resource: 'operation', resourceId: operation.id, }), ) .call( $.object().spread(optionsParamName).spread(fnOptions).prop('throwOnError', $.literal(true)), ) .await(), ); const statements: Array> = []; if (plugin.getPluginOrThrow('@hey-api/sdk').config.responseStyle === 'data') { statements.push($.return(awaitSdkFn)); } else { statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } const queryOpts = $.object() .pretty() .prop('key', keyExpression) .prop( 'query', $.func() .async() .param(fnOptions) .do(...statements), ) .$if(handleMeta(plugin, operation, 'queryOptions'), (o, v) => o.prop('meta', v)); const symbolQueryOptionsFn = plugin.symbol( applyNaming(operation.id, plugin.config.queryOptions), { meta: { category: 'hook', resource: 'operation', resourceId: operation.id, role: 'queryOptions', tool: plugin.name, }, }, ); const symbolDefineQueryOptions = plugin.external(`${plugin.name}.defineQueryOptions`); const statement = $.const(symbolQueryOptionsFn) .export() .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $(symbolDefineQueryOptions) .call( $.func() .param(optionsParamName, (p) => p.required(isRequiredOptions).type(typeData)) .do($.return(queryOpts)), ) .generics( typeData, useTypeResponse({ operation, plugin }), useTypeError({ operation, plugin }), ), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/types.ts ================================================ import type { Casing, FeatureToggle, NameTransformer, NamingOptions } from '@hey-api/shared'; import type { IR } from '@hey-api/shared'; import type { DefinePlugin, Plugin } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@pinia/colada'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated mutation options helpers. * * See {@link https://pinia-colada.esm.dev/guide/mutations.html Mutations} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Mutation' */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://pinia-colada.esm.dev/guide/query-keys.html Query Keys} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}QueryKey' */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://pinia-colada.esm.dev/guide/queries.html Queries} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Query' */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'@pinia/colada'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated mutation options helpers. */ mutationOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: ((operation: IR.OperationObject) => Record) | undefined; }; /** * Resolved configuration for generated query keys. * * See {@link https://pinia-colada.esm.dev/guide/query-keys.html Query Keys} */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * See {@link https://pinia-colada.esm.dev/guide/queries.html Queries} */ queryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: ((operation: IR.OperationObject) => Record) | undefined; }; }; export type PiniaColadaPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/useType.ts ================================================ import type { IR } from '@hey-api/shared'; import { getTypedConfig } from '../../../config/utils'; import { getClientPlugin } from '../../../plugins/@hey-api/client-core/utils'; import { operationOptionsType } from '../../../plugins/@hey-api/sdk/shared/operation'; import { $ } from '../../../ts-dsl'; import type { PiniaColadaPlugin } from './types'; export const useTypeData = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; }): ReturnType => { const pluginSdk = plugin.getPluginOrThrow('@hey-api/sdk'); return operationOptionsType({ operation, plugin: pluginSdk }); }; export const useTypeError = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; }): ReturnType => { const client = getClientPlugin(getTypedConfig(plugin)); const symbolErrorType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'error', }); const symbolError = symbolErrorType || 'Error'; if (client.name === '@hey-api/client-axios') { const symbol = plugin.external('axios.AxiosError'); return $.type(symbol).generic(symbolError); } return $.type(symbolError); }; export const useTypeResponse = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; }): ReturnType => { const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', }); return $.type(symbolResponseType ?? 'unknown'); }; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/utils.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import type { PiniaColadaPlugin } from './types'; import { useTypeData } from './useType'; export const getPublicTypeData = ({ isNuxtClient, operation, plugin, }: { isNuxtClient: boolean; operation: IR.OperationObject; plugin: PiniaColadaPlugin['Instance']; }) => { const typeData = useTypeData({ operation, plugin }); return isNuxtClient ? $.type('Omit').generic(typeData).generic('composable') : typeData; }; ================================================ FILE: packages/openapi-ts/src/plugins/@pinia/colada/v0/plugin.ts ================================================ import { createMutationOptions } from '../mutationOptions'; import { createQueryOptions } from '../queryOptions'; import type { PiniaColadaPlugin } from '../types'; export const handlerV0: PiniaColadaPlugin['Handler'] = ({ plugin }) => { plugin.symbol('defineQueryOptions', { external: plugin.name, meta: { category: 'external', resource: `${plugin.name}.defineQueryOptions`, }, }); plugin.symbol('UseMutationOptions', { external: plugin.name, kind: 'type', meta: { category: 'external', resource: `${plugin.name}.UseMutationOptions`, }, }); plugin.symbol('UseQueryOptions', { external: plugin.name, kind: 'type', meta: { category: 'external', resource: `${plugin.name}.UseQueryOptions`, }, }); plugin.symbol('_JSONValue', { external: plugin.name, kind: 'type', meta: { category: 'external', resource: `${plugin.name}._JSONValue`, }, }); plugin.symbol('AxiosError', { external: 'axios', kind: 'type', meta: { category: 'external', resource: 'axios.AxiosError', }, }); plugin.forEach( 'operation', ({ operation }) => { if (plugin.hooks.operation.isQuery(operation)) { if (plugin.config.queryOptions.enabled) { createQueryOptions({ operation, plugin }); } } if (plugin.hooks.operation.isMutation(operation)) { if (plugin.config.mutationOptions.enabled) { createMutationOptions({ operation, plugin }); } } }, { order: 'declarations', }, ); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/angular-query-experimental/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from '../../../plugins/@tanstack/query-core/plugin'; import type { TanStackAngularQueryPlugin } from './types'; export const defaultConfig: TanStackAngularQueryPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackAngularQueryPlugin['Handler'], name: '@tanstack/angular-query-experimental', resolveConfig: (plugin, context) => { plugin.config.infiniteQueryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteQueryKey', tags: false, }, mappers, value: plugin.config.infiniteQueryKeys, }); plugin.config.infiniteQueryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteOptions', }, mappers, value: plugin.config.infiniteQueryOptions, }); plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Options', }, mappers, value: plugin.config.queryOptions, }); }, }; /** * Type helper for `@tanstack/angular-query-experimental` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/angular-query-experimental/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { TanStackAngularQueryPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/angular-query-experimental/types.ts ================================================ import type { Casing, FeatureToggle, NameTransformer, NamingOptions } from '@hey-api/shared'; import type { IR } from '@hey-api/shared'; import type { DefinePlugin, Plugin } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@tanstack/angular-query-experimental'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/angular/reference/infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteQueryKey' * @see https://tanstack.com/query/v5/docs/framework/angular/reference/infiniteQueryOptions */ name?: NameTransformer; /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/angular/reference/infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteOptions' * @see https://tanstack.com/query/v5/docs/framework/angular/reference/infiniteQueryOptions */ name?: NameTransformer; }; /** * Configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/angular/reference/useMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Mutation' * @see https://tanstack.com/query/v5/docs/framework/angular/reference/useMutation */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/angular/reference/queryKey} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}QueryKey' * @see https://tanstack.com/query/v5/docs/framework/angular/reference/queryKey */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/angular/reference/queryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Options' * @see https://tanstack.com/query/v5/docs/framework/angular/reference/queryOptions */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'@tanstack/angular-query-experimental'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated infinite query key helpers. * * @see https://tanstack.com/query/v5/docs/framework/angular/reference/infiniteQueryOptions */ infiniteQueryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated infinite query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/angular/reference/infiniteQueryOptions */ infiniteQueryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated mutation options helpers. * * @see https://tanstack.com/query/v5/docs/framework/angular/reference/useMutation */ mutationOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated query keys. * * @see https://tanstack.com/query/v5/docs/framework/angular/reference/queryKey */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/angular/reference/queryOptions */ queryOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; }; export type TanStackAngularQueryPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/preact-query/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from '../../../plugins/@tanstack/query-core/plugin'; import type { TanStackPreactQueryPlugin } from './types'; export const defaultConfig: TanStackPreactQueryPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackPreactQueryPlugin['Handler'], name: '@tanstack/preact-query', resolveConfig: (plugin, context) => { plugin.config.infiniteQueryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteQueryKey', tags: false, }, mappers, value: plugin.config.infiniteQueryKeys, }); plugin.config.infiniteQueryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteOptions', }, mappers, value: plugin.config.infiniteQueryOptions, }); plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Options', }, mappers, value: plugin.config.queryOptions, }); plugin.config.useMutation = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: false, name: 'use{{name}}Mutation', }, mappers: { boolean: (enabled) => ({ enabled }), function: (name) => ({ enabled: true, name }), object: (fields) => ({ enabled: true, ...fields }), string: (name) => ({ enabled: true, name }), }, value: plugin.config.useMutation, }); plugin.config.useQuery = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: false, name: 'use{{name}}Query', }, mappers: { boolean: (enabled) => ({ enabled }), function: (name) => ({ enabled: true, name }), object: (fields) => ({ enabled: true, ...fields }), string: (name) => ({ enabled: true, name }), }, value: plugin.config.useQuery, }); if (plugin.config.useMutation.enabled) { if (!plugin.config.mutationOptions.enabled) { plugin.config.mutationOptions.enabled = true; plugin.config.mutationOptions.exported = false; } } if (plugin.config.useQuery.enabled) { if (!plugin.config.queryOptions.enabled) { plugin.config.queryOptions.enabled = true; plugin.config.queryOptions.exported = false; } } }, }; /** * Type helper for `@tanstack/preact-query` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/preact-query/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { TanStackPreactQueryPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/preact-query/types.ts ================================================ import type { Casing, FeatureToggle, NameTransformer, NamingOptions } from '@hey-api/shared'; import type { IR } from '@hey-api/shared'; import type { DefinePlugin, Plugin } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@tanstack/preact-query'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/infiniteQueryOptions infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/infiniteQueryOptions infiniteQueryOptions} * * @default '{{name}}InfiniteQueryKey' */ name?: NameTransformer; /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/infiniteQueryOptions infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/infiniteQueryOptions infiniteQueryOptions} * * @default '{{name}}InfiniteOptions' */ name?: NameTransformer; }; /** * Configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useMutation useMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useMutation useMutation} * * @default '{{name}}Mutation' */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/queryKey queryKey} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/guides/query-keys Query Keys} * * @default '{{name}}QueryKey' */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/queryOptions queryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/queryOptions queryOptions} * * @default '{{name}}Options' */ name?: NameTransformer; }; /** * Configuration for generated `useMutation()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useMutation useMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ useMutation?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default false */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useMutation useMutation} * * @default 'use{{name}}Mutation' */ name?: NameTransformer; }; /** * Configuration for generated `useQuery()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useQuery useQuery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ useQuery?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useQuery useQuery} * * @default 'use{{name}}Query' */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'@tanstack/preact-query'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/infiniteQueryOptions infiniteQueryOptions} */ infiniteQueryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/infiniteQueryOptions infiniteQueryOptions} */ infiniteQueryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useMutation useMutation} */ mutationOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/guides/query-keys Query Keys} */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/queryOptions queryOptions} */ queryOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Configuration for generated `useMutation()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useMutation useMutation} */ useMutation: NamingOptions & FeatureToggle; /** * Configuration for generated `useQuery()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/preact/reference/useQuery useQuery} */ useQuery: NamingOptions & FeatureToggle; }; export type TanStackPreactQueryPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/plugin.ts ================================================ import type { PluginHandler } from './types'; import { handlerV5 } from './v5/plugin'; export const handler: PluginHandler = (args) => handlerV5(args as Parameters[0]); ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/queryKey.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { applyNaming, hasOperationDataRequired } from '@hey-api/shared'; import type ts from 'typescript'; import { getTypedConfig } from '../../../config/utils'; import { getClientBaseUrlKey } from '../../../plugins/@hey-api/client-core/utils'; import type { TsDsl } from '../../../ts-dsl'; import { $ } from '../../../ts-dsl'; import { useTypeData } from './shared/useType'; import type { PluginInstance } from './types'; const TOptionsType = 'TOptions'; export const createQueryKeyFunction = ({ plugin }: { plugin: PluginInstance }) => { const symbolCreateQueryKey = plugin.symbol( applyNaming('createQueryKey', { case: plugin.config.case, }), { meta: { category: 'utility', resource: 'createQueryKey', tool: plugin.name, }, }, ); const symbolQueryKeyType = plugin.referenceSymbol({ category: 'type', resource: 'QueryKey', tool: plugin.name, }); const baseUrlKey = getClientBaseUrlKey(getTypedConfig(plugin)); const symbolClient = plugin.getSymbol({ category: 'client', }); const symbolOptions = plugin.referenceSymbol({ category: 'type', resource: 'client-options', tool: 'sdk', }); const returnType = $.type(symbolQueryKeyType).generic(TOptionsType).idx(0); const fn = $.const(symbolCreateQueryKey).assign( $.func() .param('id', (p) => p.type('string')) .param('options', (p) => p.optional().type(TOptionsType)) .param('infinite', (p) => p.optional().type('boolean')) .param('tags', (p) => p.optional().type('ReadonlyArray')) .generic(TOptionsType, (g) => g.extends(symbolOptions)) .returns($.type.tuple(returnType)) .do( $.const('params') .type(returnType) .assign( $.object() .prop('_id', 'id') .prop( baseUrlKey, $('options') .attr(baseUrlKey) .optional() .or( $('options') .attr('client') .optional() .$if(symbolClient, (a, v) => a.coalesce(v)) .attr('getConfig') .call() .attr(baseUrlKey), ), ) .as(returnType), ), $.if('infinite').do($('params').attr('_infinite').assign('infinite')), $.if('tags').do($('params').attr('tags').assign('tags')), $.if($('options').attr('body').optional()).do( $('params').attr('body').assign($('options').attr('body')), ), $.if($('options').attr('headers').optional()).do( $('params').attr('headers').assign($('options').attr('headers')), ), $.if($('options').attr('path').optional()).do( $('params').attr('path').assign($('options').attr('path')), ), $.if($('options').attr('query').optional()).do( $('params').attr('query').assign($('options').attr('query')), ), $.return($.array().element($('params'))), ), ); plugin.node(fn); }; const createQueryKeyLiteral = ({ id, isInfinite, operation, plugin, }: { id: string; isInfinite?: boolean; operation: IR.OperationObject; plugin: PluginInstance; }) => { const config = isInfinite ? plugin.config.infiniteQueryKeys : plugin.config.queryKeys; let tagsArray: TsDsl | undefined; if (config.tags && operation.tags && operation.tags.length > 0) { tagsArray = $.array().elements(...operation.tags); } const symbolCreateQueryKey = plugin.referenceSymbol({ category: 'utility', resource: 'createQueryKey', tool: plugin.name, }); const createQueryKeyCallExpression = $(symbolCreateQueryKey).call( $.literal(id), 'options', isInfinite || tagsArray ? $.literal(Boolean(isInfinite)) : undefined, tagsArray, ); return createQueryKeyCallExpression; }; export const createQueryKeyType = ({ plugin }: { plugin: PluginInstance }) => { const symbolOptions = plugin.referenceSymbol({ category: 'type', resource: 'client-options', tool: 'sdk', }); const symbolQueryKeyType = plugin.symbol('QueryKey', { meta: { category: 'type', resource: 'QueryKey', tool: plugin.name, }, }); const queryKeyType = $.type .alias(symbolQueryKeyType) .export() .generic(TOptionsType, (g) => g.extends(symbolOptions)) .type( $.type.tuple( $.type.and( $.type( `Pick<${TOptionsType}, '${getClientBaseUrlKey(getTypedConfig(plugin))}' | 'body' | 'headers' | 'path' | 'query'>`, ), $.type .object() .prop('_id', (p) => p.type('string')) .prop('_infinite', (p) => p.optional().type('boolean')) .prop('tags', (p) => p.optional().type('ReadonlyArray')), ), ), ); plugin.node(queryKeyType); }; export const queryKeyStatement = ({ isInfinite, operation, plugin, symbol, typeQueryKey, }: { isInfinite: boolean; operation: IR.OperationObject; plugin: PluginInstance; symbol: Symbol; typeQueryKey?: ReturnType; }) => { const typeData = useTypeData({ operation, plugin }); const statement = $.const(symbol) .export() .assign( $.func() .param('options', (p) => p.required(hasOperationDataRequired(operation)).type(typeData)) .$if(isInfinite && typeQueryKey, (f, v) => f.returns(v)) .do( createQueryKeyLiteral({ id: operation.id, isInfinite, operation, plugin, }).return(), ), ); return statement; }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/shared/meta.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { PluginInstance } from '../types'; export const handleMeta = ( plugin: PluginInstance, operation: IR.OperationObject, configPath: 'queryOptions' | 'infiniteQueryOptions' | 'mutationOptions', ): ReturnType | undefined => { const metaFn = plugin.config[configPath].meta; if (!metaFn) return; const metaObject = metaFn(operation); if (!Object.keys(metaObject).length) return; return $.fromValue(metaObject); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/shared/useType.ts ================================================ import type { IR } from '@hey-api/shared'; import { getTypedConfig } from '../../../../config/utils'; import { getClientPlugin } from '../../../../plugins/@hey-api/client-core/utils'; import { operationOptionsType } from '../../../../plugins/@hey-api/sdk/shared/operation'; import { $ } from '../../../../ts-dsl'; import type { PluginInstance } from '../types'; export const useTypeData = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): ReturnType => { const pluginSdk = plugin.getPluginOrThrow('@hey-api/sdk'); return operationOptionsType({ operation, plugin: pluginSdk }); }; export const useTypeError = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): ReturnType => { const client = getClientPlugin(getTypedConfig(plugin)); const symbolErrorType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'error', }); const symbolError = symbolErrorType || plugin.external(`${plugin.name}.DefaultError`); if (client.name === '@hey-api/client-axios') { const symbol = plugin.external('axios.AxiosError'); return $.type(symbol).generic(symbolError); } return $.type(symbolError); }; export const useTypeResponse = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): ReturnType => { const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', }); return $.type(symbolResponseType ?? 'unknown'); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/types.ts ================================================ import type { TanStackAngularQueryPlugin } from '../../../plugins/@tanstack/angular-query-experimental/types'; import type { TanStackPreactQueryPlugin } from '../../../plugins/@tanstack/preact-query/types'; import type { TanStackReactQueryPlugin } from '../../../plugins/@tanstack/react-query/types'; import type { TanStackSolidQueryPlugin } from '../../../plugins/@tanstack/solid-query/types'; import type { TanStackSvelteQueryPlugin } from '../../../plugins/@tanstack/svelte-query/types'; import type { TanStackVueQueryPlugin } from '../../../plugins/@tanstack/vue-query/types'; export interface PluginHandler { (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; (...args: Parameters): void; } export type PluginInstance = | TanStackAngularQueryPlugin['Instance'] | TanStackPreactQueryPlugin['Instance'] | TanStackReactQueryPlugin['Instance'] | TanStackSolidQueryPlugin['Instance'] | TanStackSvelteQueryPlugin['Instance'] | TanStackVueQueryPlugin['Instance']; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/v5/infiniteQueryOptions.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming, operationPagination } from '@hey-api/shared'; import { createOperationComment, isOperationOptionsRequired, } from '../../../../plugins/shared/utils/operation'; import type { TsDsl } from '../../../../ts-dsl'; import { $ } from '../../../../ts-dsl'; import { createQueryKeyFunction, createQueryKeyType, queryKeyStatement } from '../queryKey'; import { handleMeta } from '../shared/meta'; import { useTypeData, useTypeError, useTypeResponse } from '../shared/useType'; import type { PluginInstance } from '../types'; const createInfiniteParamsFunction = ({ plugin }: { plugin: PluginInstance }) => { const symbolCreateInfiniteParams = plugin.symbol( applyNaming('createInfiniteParams', { case: plugin.config.case, }), { meta: { category: 'utility', resource: 'createInfiniteParams', tool: plugin.name, }, }, ); const fn = $.const(symbolCreateInfiniteParams).assign( $.func() .generic('K', (g) => g.extends( $.type('Pick').generics( $.type('QueryKey').generic('Options').idx(0), $.type.or( $.type.literal('body'), $.type.literal('headers'), $.type.literal('path'), $.type.literal('query'), ), ), ), ) .param('queryKey', (p) => p.type('QueryKey')) .param('page', (p) => p.type('K')) .do( $.const('params').assign($.object().spread($('queryKey').attr(0))), $.if($('page').attr('body')).do( $('params') .attr('body') .assign( $.object() .pretty() .spread($('queryKey').attr(0).attr('body').as('any')) .spread($('page').attr('body').as('any')), ), ), $.if($('page').attr('headers')).do( $('params') .attr('headers') .assign( $.object() .pretty() .spread($('queryKey').attr(0).attr('headers')) .spread($('page').attr('headers')), ), ), $.if($('page').attr('path')).do( $('params') .attr('path') .assign( $.object() .pretty() .spread($('queryKey').attr(0).attr('path').as('any')) .spread($('page').attr('path').as('any')), ), ), $.if($('page').attr('query')).do( $('params') .attr('query') .assign( $.object() .pretty() .spread($('queryKey').attr(0).attr('query').as('any')) .spread($('page').attr('query').as('any')), ), ), $.return($('params').as('unknown').as($('page').typeofType())), ), ); plugin.node(fn); }; export const createInfiniteQueryOptions = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): void => { const pagination = operationPagination({ context: plugin.context, operation, }); if (!pagination) { return; } const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, operation, }); if ( !plugin.getSymbol({ category: 'utility', resource: 'createQueryKey', tool: plugin.name, }) ) { createQueryKeyType({ plugin }); createQueryKeyFunction({ plugin }); } if ( !plugin.getSymbol({ category: 'utility', resource: 'createInfiniteParams', tool: plugin.name, }) ) { createInfiniteParamsFunction({ plugin }); } const symbolInfiniteQueryOptions = plugin.external(`${plugin.name}.infiniteQueryOptions`); const symbolInfiniteDataType = plugin.external(`${plugin.name}.InfiniteData`); const typeData = useTypeData({ operation, plugin }); const typeResponse = useTypeResponse({ operation, plugin }); const symbolQueryKeyType = plugin.referenceSymbol({ category: 'type', resource: 'QueryKey', tool: plugin.name, }); const typeQueryKey = $.type(symbolQueryKeyType).generic(typeData); const typePageObjectParam = $.type('Pick').generics( typeQueryKey.idx(0), $.type.or( $.type.literal('body'), $.type.literal('headers'), $.type.literal('path'), $.type.literal('query'), ), ); const pluginTypeScript = plugin.getPluginOrThrow('@hey-api/typescript'); const type = pluginTypeScript.api.schemaToType(pluginTypeScript, pagination.schema); const symbolInfiniteQueryKey = plugin.symbol( applyNaming(operation.id, plugin.config.infiniteQueryKeys), ); const node = queryKeyStatement({ isInfinite: true, operation, plugin, symbol: symbolInfiniteQueryKey, typeQueryKey, }); plugin.node(node); const awaitSdkFn = $.lazy((ctx) => ctx .access( plugin.referenceSymbol({ category: 'sdk', resource: 'operation', resourceId: operation.id, }), ) .call( $.object() .spread('options') .spread('params') .prop('signal', $('signal')) .prop('throwOnError', $.literal(true)), ) .await(), ); const symbolCreateInfiniteParams = plugin.referenceSymbol({ category: 'utility', resource: 'createInfiniteParams', tool: plugin.name, }); const statements: Array> = [ $.const('page') .type(typePageObjectParam) .hint('@ts-ignore') .assign( $.ternary($('pageParam').typeofExpr().eq($.literal('object'))) .do('pageParam') .otherwise( $.object() .pretty() .prop(pagination.in, $.object().pretty().prop(pagination.name, $('pageParam'))), ), ), $.const('params').assign($(symbolCreateInfiniteParams).call('queryKey', 'page')), ]; if (plugin.getPluginOrThrow('@hey-api/sdk').config.responseStyle === 'data') { statements.push($.return(awaitSdkFn)); } else { statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } const symbolInfiniteQueryOptionsFn = plugin.symbol( applyNaming(operation.id, plugin.config.infiniteQueryOptions), ); const statement = $.const(symbolInfiniteQueryOptionsFn) .export() .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() .param('options', (p) => p.required(isRequiredOptions).type(typeData)) .do( $.return( $(symbolInfiniteQueryOptions) .call( $.object() .pretty() .hint('@ts-ignore') .prop( 'queryFn', $.func() .async() .param((p) => p.object('pageParam', 'queryKey', 'signal')) .do(...statements), ) .prop('queryKey', $(symbolInfiniteQueryKey).call('options')) .$if(handleMeta(plugin, operation, 'infiniteQueryOptions'), (o, v) => o.prop('meta', v), ), ) .generics( typeResponse, useTypeError({ operation, plugin }), $.type(symbolInfiniteDataType).generic(typeResponse), typeQueryKey, $.type.or(type, typePageObjectParam), ), ), ), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/v5/mutationOptions.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { createOperationComment, hasOperationSse, } from '../../../../plugins/shared/utils/operation'; import type { TsDsl } from '../../../../ts-dsl'; import { $ } from '../../../../ts-dsl'; import { handleMeta } from '../shared/meta'; import { useTypeData, useTypeError, useTypeResponse } from '../shared/useType'; import type { PluginInstance } from '../types'; export const createMutationOptions = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): void => { if (hasOperationSse({ operation })) { return; } const symbolMutationOptionsType = plugin.external(`${plugin.name}.MutationOptions`); const typeData = useTypeData({ operation, plugin }); const mutationType = $.type(symbolMutationOptionsType) .generic(useTypeResponse({ operation, plugin })) .generic(useTypeError({ operation, plugin })) .generic(typeData); const fnOptions = 'fnOptions'; const awaitSdkFn = $.lazy((ctx) => ctx .access( plugin.referenceSymbol({ category: 'sdk', resource: 'operation', resourceId: operation.id, }), ) .call($.object().spread('options').spread(fnOptions).prop('throwOnError', $.literal(true))) .await(), ); const statements: Array> = []; if (plugin.getPluginOrThrow('@hey-api/sdk').config.responseStyle === 'data') { statements.push($.return(awaitSdkFn)); } else { statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } const mutationOptionsFn = 'mutationOptions'; const symbolMutationOptions = plugin.symbol( applyNaming(operation.id, plugin.config.mutationOptions), { meta: { category: 'hook', resource: 'operation', resourceId: operation.id, role: 'mutationOptions', tool: plugin.name, }, }, ); const statement = $.const(symbolMutationOptions) .export(plugin.config.mutationOptions.exported) .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() .param('options', (p) => p.optional().type($.type('Partial').generic(typeData))) .returns(mutationType) .do( $.const(mutationOptionsFn) .type(mutationType) .assign( $.object() .pretty() .prop( 'mutationFn', $.func() .async() .param(fnOptions) .do(...statements), ) .$if(handleMeta(plugin, operation, 'mutationOptions'), (c, v) => c.prop('meta', v)), ), $(mutationOptionsFn).return(), ), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/v5/plugin.ts ================================================ import type { PluginHandler } from '../types'; import { createInfiniteQueryOptions } from './infiniteQueryOptions'; import { createMutationOptions } from './mutationOptions'; import { createQueryOptions } from './queryOptions'; import { createUseMutation } from './useMutation'; import { createUseQuery } from './useQuery'; export const handlerV5: PluginHandler = ({ plugin }) => { plugin.symbol('DefaultError', { external: plugin.name, kind: 'type', meta: { category: 'external', resource: `${plugin.name}.DefaultError`, }, }); plugin.symbol('InfiniteData', { external: plugin.name, kind: 'type', meta: { category: 'external', resource: `${plugin.name}.InfiniteData`, }, }); const mutationsType = plugin.name === '@tanstack/angular-query-experimental' || plugin.name === '@tanstack/svelte-query' || plugin.name === '@tanstack/solid-query' ? 'MutationOptions' : 'UseMutationOptions'; plugin.symbol(mutationsType, { external: plugin.name, kind: 'type', meta: { category: 'external', resource: `${plugin.name}.MutationOptions`, }, }); plugin.symbol('infiniteQueryOptions', { external: plugin.name, meta: { category: 'external', resource: `${plugin.name}.infiniteQueryOptions`, }, }); plugin.symbol('queryOptions', { external: plugin.name, meta: { category: 'external', resource: `${plugin.name}.queryOptions`, }, }); plugin.symbol('useMutation', { external: plugin.name, meta: { category: 'external', resource: `${plugin.name}.useMutation`, }, }); plugin.symbol('useQuery', { external: plugin.name, meta: { category: 'external', resource: `${plugin.name}.useQuery`, }, }); plugin.symbol('AxiosError', { external: 'axios', kind: 'type', meta: { category: 'external', resource: 'axios.AxiosError', }, }); plugin.forEach( 'operation', ({ operation }) => { if (plugin.hooks.operation.isQuery(operation)) { if (plugin.config.queryOptions.enabled) { createQueryOptions({ operation, plugin }); } if (plugin.config.infiniteQueryOptions.enabled) { createInfiniteQueryOptions({ operation, plugin }); } if ('useQuery' in plugin.config && plugin.config.useQuery.enabled) { createUseQuery({ operation, plugin }); } } if (plugin.hooks.operation.isMutation(operation)) { if (plugin.config.mutationOptions.enabled) { createMutationOptions({ operation, plugin }); } if ('useMutation' in plugin.config && plugin.config.useMutation.enabled) { createUseMutation({ operation, plugin }); } } }, { order: 'declarations', }, ); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/v5/queryOptions.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { createOperationComment, hasOperationSse, isOperationOptionsRequired, } from '../../../../plugins/shared/utils/operation'; import type { TsDsl } from '../../../../ts-dsl'; import { $ } from '../../../../ts-dsl'; import { createQueryKeyFunction, createQueryKeyType, queryKeyStatement } from '../queryKey'; import { handleMeta } from '../shared/meta'; import { useTypeData, useTypeError, useTypeResponse } from '../shared/useType'; import type { PluginInstance } from '../types'; const optionsParamName = 'options'; export const createQueryOptions = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): void => { if (hasOperationSse({ operation })) { return; } const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, operation, }); if ( !plugin.getSymbol({ category: 'utility', resource: 'createQueryKey', tool: plugin.name, }) ) { createQueryKeyType({ plugin }); createQueryKeyFunction({ plugin }); } const symbolQueryOptions = plugin.external(`${plugin.name}.queryOptions`); const symbolQueryKey = plugin.symbol(applyNaming(operation.id, plugin.config.queryKeys)); const node = queryKeyStatement({ isInfinite: false, operation, plugin, symbol: symbolQueryKey, }); plugin.node(node); const typeResponse = useTypeResponse({ operation, plugin }); const awaitSdkFn = $.lazy((ctx) => ctx .access( plugin.referenceSymbol({ category: 'sdk', resource: 'operation', resourceId: operation.id, }), ) .call( $.object() .spread(optionsParamName) .spread($('queryKey').attr(0)) .prop('signal', $('signal')) .prop('throwOnError', $.literal(true)), ) .await(), ); const statements: Array> = []; if (plugin.getPluginOrThrow('@hey-api/sdk').config.responseStyle === 'data') { statements.push($.return(awaitSdkFn)); } else { statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } const queryOptionsObj = $.object() .pretty() .prop( 'queryFn', $.func() .async() .param((p) => p.object('queryKey', 'signal')) .do(...statements), ) .prop('queryKey', $(symbolQueryKey).call(optionsParamName)) .$if(handleMeta(plugin, operation, 'queryOptions'), (o, v) => o.prop('meta', v)); const symbolQueryOptionsFn = plugin.symbol( applyNaming(operation.id, plugin.config.queryOptions), { meta: { category: 'hook', resource: 'operation', resourceId: operation.id, role: 'queryOptions', tool: plugin.name, }, }, ); // TODO: add type error // TODO: AxiosError const statement = $.const(symbolQueryOptionsFn) .export(plugin.config.queryOptions.exported) .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() .param(optionsParamName, (p) => p.required(isRequiredOptions).type(useTypeData({ operation, plugin })), ) .do( $(symbolQueryOptions) .call(queryOptionsObj) .generics( typeResponse, useTypeError({ operation, plugin }), typeResponse, $(symbolQueryKey).returnType(), ) .return(), ), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/v5/useMutation.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { createOperationComment } from '../../../../plugins/shared/utils/operation'; import { $ } from '../../../../ts-dsl'; import { useTypeData, useTypeError, useTypeResponse } from '../shared/useType'; import type { PluginInstance } from '../types'; const mutationOptionsParamName = 'mutationOptions'; export const createUseMutation = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): void => { if (!('useMutation' in plugin.config)) { return; } const symbolUseMutationFn = plugin.symbol(applyNaming(operation.id, plugin.config.useMutation)); const symbolUseMutation = plugin.external(`${plugin.name}.useMutation`); const typeData = useTypeData({ operation, plugin }); const symbolMutationOptionsType = plugin.external(`${plugin.name}.MutationOptions`); const mutationType = $.type(symbolMutationOptionsType) .generic(useTypeResponse({ operation, plugin })) .generic(useTypeError({ operation, plugin })) .generic(typeData); const symbolMutationOptionsFn = plugin.referenceSymbol({ category: 'hook', resource: 'operation', resourceId: operation.id, role: 'mutationOptions', tool: plugin.name, }); const func = $.func().param(mutationOptionsParamName, (p) => p .optional() .type( $.type('Partial').generic( $.type('Omit', (t) => t.generics(mutationType, $.type.literal('mutationFn'))), ), ), ); func.do( $(symbolUseMutation) .call($.object().spread($(symbolMutationOptionsFn).call()).spread(mutationOptionsParamName)) .return(), ); const statement = $.const(symbolUseMutationFn) .export() .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign(func); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/query-core/v5/useQuery.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { createOperationComment, hasOperationSse, isOperationOptionsRequired, } from '../../../../plugins/shared/utils/operation'; import { $ } from '../../../../ts-dsl'; import { useTypeData } from '../shared/useType'; import type { PluginInstance } from '../types'; const optionsParamName = 'options'; export const createUseQuery = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: PluginInstance; }): void => { if (hasOperationSse({ operation })) { return; } if (!('useQuery' in plugin.config)) { return; } const symbolUseQueryFn = plugin.symbol(applyNaming(operation.id, plugin.config.useQuery)); const symbolUseQuery = plugin.external(`${plugin.name}.useQuery`); const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, operation, }); const typeData = useTypeData({ operation, plugin }); const symbolQueryOptionsFn = plugin.referenceSymbol({ category: 'hook', resource: 'operation', resourceId: operation.id, role: 'queryOptions', tool: plugin.name, }); const statement = $.const(symbolUseQueryFn) .export() .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() .param(optionsParamName, (p) => p.required(isRequiredOptions).type(typeData)) .do($(symbolUseQuery).call($(symbolQueryOptionsFn).call(optionsParamName)).return()), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from '../../../plugins/@tanstack/query-core/plugin'; import type { TanStackReactQueryPlugin } from './types'; export const defaultConfig: TanStackReactQueryPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackReactQueryPlugin['Handler'], name: '@tanstack/react-query', resolveConfig: (plugin, context) => { plugin.config.infiniteQueryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteQueryKey', tags: false, }, mappers, value: plugin.config.infiniteQueryKeys, }); plugin.config.infiniteQueryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteOptions', }, mappers, value: plugin.config.infiniteQueryOptions, }); plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Options', }, mappers, value: plugin.config.queryOptions, }); plugin.config.useMutation = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: false, name: 'use{{name}}Mutation', }, mappers: { boolean: (enabled) => ({ enabled }), function: (name) => ({ enabled: true, name }), object: (fields) => ({ enabled: true, ...fields }), string: (name) => ({ enabled: true, name }), }, value: plugin.config.useMutation, }); plugin.config.useQuery = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: false, name: 'use{{name}}Query', }, mappers: { boolean: (enabled) => ({ enabled }), function: (name) => ({ enabled: true, name }), object: (fields) => ({ enabled: true, ...fields }), string: (name) => ({ enabled: true, name }), }, value: plugin.config.useQuery, }); if (plugin.config.useMutation.enabled) { if (!plugin.config.mutationOptions.enabled) { plugin.config.mutationOptions.enabled = true; plugin.config.mutationOptions.exported = false; } } if (plugin.config.useQuery.enabled) { if (!plugin.config.queryOptions.enabled) { plugin.config.queryOptions.enabled = true; plugin.config.queryOptions.exported = false; } } }, }; /** * Type helper for `@tanstack/react-query` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/react-query/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { TanStackReactQueryPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/react-query/types.ts ================================================ import type { Casing, FeatureToggle, NameTransformer, NamingOptions } from '@hey-api/shared'; import type { IR } from '@hey-api/shared'; import type { DefinePlugin, Plugin } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@tanstack/react-query'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * @default '{{name}}InfiniteQueryKey' */ name?: NameTransformer; /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * @default '{{name}}InfiniteOptions' */ name?: NameTransformer; }; /** * Configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} * * @default '{{name}}Mutation' */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryKey queryKey} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/guides/query-keys Query Keys} * * @default '{{name}}QueryKey' */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryOptions queryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryOptions queryOptions} * * @default '{{name}}Options' */ name?: NameTransformer; }; /** * Configuration for generated `useMutation()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ useMutation?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default false */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} * * @default 'use{{name}}Mutation' */ name?: NameTransformer; }; /** * Configuration for generated `useQuery()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useQuery useQuery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ useQuery?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useQuery useQuery} * * @default 'use{{name}}Query' */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'@tanstack/react-query'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} */ infiniteQueryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} */ infiniteQueryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} */ mutationOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/react/guides/query-keys Query Keys} */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryOptions queryOptions} */ queryOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Configuration for generated `useMutation()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} */ useMutation: NamingOptions & FeatureToggle; /** * Configuration for generated `useQuery()` function helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useQuery useQuery} */ useQuery: NamingOptions & FeatureToggle; }; export type TanStackReactQueryPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/solid-query/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from '../../../plugins/@tanstack/query-core/plugin'; import type { TanStackSolidQueryPlugin } from './types'; export const defaultConfig: TanStackSolidQueryPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackSolidQueryPlugin['Handler'], name: '@tanstack/solid-query', resolveConfig: (plugin, context) => { plugin.config.infiniteQueryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteQueryKey', tags: false, }, mappers, value: plugin.config.infiniteQueryKeys, }); plugin.config.infiniteQueryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteOptions', }, mappers, value: plugin.config.infiniteQueryOptions, }); plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Options', }, mappers, value: plugin.config.queryOptions, }); }, }; /** * Type helper for `@tanstack/solid-query` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/solid-query/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { TanStackSolidQueryPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/solid-query/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, IR, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@tanstack/solid-query'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/solid/reference/createInfiniteQuery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteQueryKey' * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createInfiniteQuery */ name?: NameTransformer; /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/solid/reference/createInfiniteQuery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteOptions' * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createInfiniteQuery */ name?: NameTransformer; }; /** * Configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/solid/reference/createMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Mutation' * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createMutation */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/solid/reference/queryKey} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}QueryKey' * @see https://tanstack.com/query/v5/docs/framework/solid/reference/queryKey */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/solid/reference/createQuery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Options' * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createQuery */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'@tanstack/solid-query'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated infinite query key helpers. * * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createInfiniteQuery */ infiniteQueryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated infinite query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createInfiniteQuery */ infiniteQueryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated mutation options helpers. * * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createMutation */ mutationOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated query keys. * * @see https://tanstack.com/query/v5/docs/framework/solid/reference/queryKey */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/solid/reference/createQuery */ queryOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; }; export type TanStackSolidQueryPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/svelte-query/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from '../../../plugins/@tanstack/query-core/plugin'; import type { TanStackSvelteQueryPlugin } from './types'; export const defaultConfig: TanStackSvelteQueryPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackSvelteQueryPlugin['Handler'], name: '@tanstack/svelte-query', resolveConfig: (plugin, context) => { plugin.config.infiniteQueryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteQueryKey', tags: false, }, mappers, value: plugin.config.infiniteQueryKeys, }); plugin.config.infiniteQueryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteOptions', }, mappers, value: plugin.config.infiniteQueryOptions, }); plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Options', }, mappers, value: plugin.config.queryOptions, }); }, }; /** * Type helper for `@tanstack/svelte-query` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/svelte-query/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { TanStackSvelteQueryPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/svelte-query/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, IR, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@tanstack/svelte-query'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createinfinitequery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteQueryKey' * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createinfinitequery */ name?: NameTransformer; /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createinfinitequery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteOptions' * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createinfinitequery */ name?: NameTransformer; }; /** * Configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createmutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Mutation' * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createmutation */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/react/guides/query-keys} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}QueryKey' * @see https://tanstack.com/query/v5/docs/framework/react/guides/query-keys */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createquery} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Options' * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createquery */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'@tanstack/svelte-query'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated infinite query key helpers. * * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createinfinitequery */ infiniteQueryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated infinite query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createinfinitequery */ infiniteQueryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated mutation options helpers. * * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createmutation */ mutationOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated query keys. * * @see https://tanstack.com/query/v5/docs/framework/react/guides/query-keys */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/svelte/reference/functions/createquery */ queryOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; }; export type TanStackSvelteQueryPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/vue-query/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from '../../../plugins/@tanstack/query-core/plugin'; import type { TanStackVueQueryPlugin } from './types'; export const defaultConfig: TanStackVueQueryPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackVueQueryPlugin['Handler'], name: '@tanstack/vue-query', resolveConfig: (plugin, context) => { plugin.config.infiniteQueryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteQueryKey', tags: false, }, mappers, value: plugin.config.infiniteQueryKeys, }); plugin.config.infiniteQueryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteOptions', }, mappers, value: plugin.config.infiniteQueryOptions, }); plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Options', }, mappers, value: plugin.config.queryOptions, }); }, }; /** * Type helper for `@tanstack/vue-query` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/vue-query/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { TanStackVueQueryPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/@tanstack/vue-query/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, IR, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'@tanstack/vue-query'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/vue/reference/infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteQueryKey' * @see https://tanstack.com/query/v5/docs/framework/vue/reference/infiniteQueryOptions */ name?: NameTransformer; /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/vue/reference/infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}InfiniteOptions' * @see https://tanstack.com/query/v5/docs/framework/vue/reference/infiniteQueryOptions */ name?: NameTransformer; }; /** * Configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/vue/reference/useMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Mutation' * @see https://tanstack.com/query/v5/docs/framework/vue/reference/useMutation */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/vue/reference/queryKey} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}QueryKey' * @see https://tanstack.com/query/v5/docs/framework/vue/reference/queryKey */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/vue/reference/queryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * @default '{{name}}Options' * @see https://tanstack.com/query/v5/docs/framework/vue/reference/queryOptions */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'@tanstack/vue-query'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated infinite query key helpers. * * @see https://tanstack.com/query/v5/docs/framework/vue/reference/infiniteQueryOptions */ infiniteQueryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated infinite query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/vue/reference/infiniteQueryOptions */ infiniteQueryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated mutation options helpers. * * @see https://tanstack.com/query/v5/docs/framework/vue/reference/useMutation */ mutationOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated query keys. * * @see https://tanstack.com/query/v5/docs/framework/vue/reference/queryKey */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * @see https://tanstack.com/query/v5/docs/framework/vue/reference/queryOptions */ queryOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; }; export type TanStackVueQueryPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/api.ts ================================================ import type { $ } from '../../ts-dsl'; import type { ValidatorArgs } from './shared/types'; import { createRequestValidatorV2, createResponseValidatorV2 } from './v2/api'; export type IApi = { createRequestValidator: (args: ValidatorArgs) => ReturnType | undefined; createResponseValidator: (args: ValidatorArgs) => ReturnType | undefined; }; export class Api implements IApi { createRequestValidator(args: ValidatorArgs): ReturnType | undefined { return createRequestValidatorV2(args); } createResponseValidator(args: ValidatorArgs): ReturnType | undefined { return createResponseValidatorV2(args); } } ================================================ FILE: packages/openapi-ts/src/plugins/arktype/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { Api } from './api'; import { handler } from './plugin'; import type { ArktypePlugin } from './types'; export const defaultConfig: ArktypePlugin['Config'] = { api: new Api(), config: { case: 'PascalCase', comments: true, includeInEntry: false, metadata: false, }, handler, name: 'arktype', resolveConfig: (plugin, context) => { plugin.config.types = context.valueToObject({ defaultValue: { infer: { case: 'PascalCase', enabled: false, }, }, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: plugin.config.types, }); plugin.config.definitions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.definitions, }); plugin.config.requests = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}Data', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}Data', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.requests, }); plugin.config.responses = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}Response', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}Response', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.responses, }); plugin.config.webhooks = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'PascalCase', enabled: true, name: '{{name}}WebhookRequest', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}WebhookRequest', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.webhooks, }); }, tags: ['validator'], }; /** * Type helper for Arktype plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/arktype/constants.ts ================================================ export const identifiers = { keywords: { false: 'false', true: 'true', }, /** * {@link https://arktype.io/docs/primitives#number Number} */ number: { Infinity: 'Infinity', NaN: 'NaN', NegativeInfinity: 'NegativeInfinity', epoch: 'epoch', integer: 'integer', safe: 'safe', }, /** * {@link https://arktype.io/docs/primitives Primitives} */ primitives: { bigint: 'bigint', boolean: 'boolean', keywords: 'keywords', null: 'null', number: 'number', string: 'string', symbol: 'symbol', undefined: 'undefined', unit: 'unit', }, /** * {@link https://arktype.io/docs/primitives#string String} */ string: { NFC: 'NFC', NFD: 'NFD', NFKC: 'NFKC', NFKD: 'NFKD', alpha: 'alpha', alphanumeric: 'alphanumeric', base64: 'base64', capitalize: 'capitalize', creditCard: 'creditCard', date: 'date', digits: 'digits', email: 'email', epoch: 'epoch', hex: 'hex', integer: 'integer', ip: 'ip', iso: 'iso', json: 'json', lower: 'lower', normalize: 'normalize', numeric: 'numeric', parse: 'parse', preformatted: 'preformatted', regex: 'regex', semver: 'semver', trim: 'trim', upper: 'upper', url: 'url', uuid: 'uuid', v1: 'v1', v2: 'v2', v3: 'v3', v4: 'v4', v5: 'v5', v6: 'v6', v7: 'v7', v8: 'v8', }, /** * {@link https://arktype.io/docs/type-api Type API} */ type: { $: '$', allows: 'allows', and: 'and', array: 'array', as: 'as', assert: 'assert', brand: 'brand', configure: 'configure', default: 'default', describe: 'describe', description: 'description', equals: 'equals', exclude: 'exclude', expression: 'expression', extends: 'extends', extract: 'extract', filter: 'filter', from: 'from', ifEquals: 'ifEquals', ifExtends: 'ifExtends', infer: 'infer', inferIn: 'inferIn', intersect: 'intersect', json: 'json', meta: 'meta', narrow: 'narrow', onDeepUndeclaredKey: 'onDeepUndeclaredKey', onUndeclaredKey: 'onUndeclaredKey', optional: 'optional', or: 'or', overlaps: 'overlaps', pipe: 'pipe', select: 'select', to: 'to', toJsonSchema: 'toJsonSchema', }, }; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { ArktypePlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/plugin.ts ================================================ import type { ArktypePlugin } from './types'; import { handlerV2 } from './v2/plugin'; export const handler: ArktypePlugin['Handler'] = (args) => handlerV2(args); ================================================ FILE: packages/openapi-ts/src/plugins/arktype/shared/export.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { createSchemaComment } from '../../../plugins/shared/utils/schema'; import { $ } from '../../../ts-dsl'; import { identifiers } from '../constants'; import type { ArktypePlugin } from '../types'; import type { Ast } from './types'; export function exportAst({ ast, plugin, schema, symbol, typeInferSymbol, }: { ast: Ast; plugin: ArktypePlugin['Instance']; schema: IR.SchemaObject; symbol: Symbol; typeInferSymbol: Symbol | undefined; }): void { const type = plugin.external('arktype.type'); const statement = $.const(symbol) .export() .$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)) // .type( // ast.typeName // ? (tsc.propertyAccessExpression({ // expression: z, // name: ast.typeName, // }) as unknown as ts.TypeNode) // : undefined, // ) .assign($(type).call(ast.def ? $.literal(ast.def) : ast.expression)); plugin.node(statement); if (typeInferSymbol) { const inferType = $.type .alias(typeInferSymbol) .export() .type($.type(symbol).attr(identifiers.type.infer).typeofType()); plugin.node(inferType); } } ================================================ FILE: packages/openapi-ts/src/plugins/arktype/shared/types.ts ================================================ import type { Refs, SymbolMeta } from '@hey-api/codegen-core'; import type { IR, SchemaExtractor } from '@hey-api/shared'; import type ts from 'typescript'; import type { $ } from '../../../ts-dsl'; import type { ArktypePlugin } from '../types'; export type Ast = { def: string; expression: ReturnType; hasLazyExpression?: boolean; typeName?: string | ts.Identifier; }; export type IrSchemaToAstOptions = { /** The plugin instance. */ plugin: ArktypePlugin['Instance']; /** Optional schema extractor function. */ schemaExtractor?: SchemaExtractor; /** The plugin state references. */ state: Refs; }; export type PluginState = Pick, 'path'> & Pick, 'tags'> & { hasLazyExpression: boolean; }; export type ValidatorArgs = { operation: IR.OperationObject; plugin: ArktypePlugin['Instance']; }; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; import type { IApi } from './api'; export type UserConfig = Plugin.Name<'arktype'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Configuration for reusable schema definitions. * * Controls generation of shared Arktype schemas that can be referenced * across requests and responses. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object */ definitions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}' */ name?: NameTransformer; }; }; }; /** * Enable Arktype metadata support? It's often useful to associate a schema * with some additional metadata for documentation, code generation, AI * structured outputs, form validation, and other purposes. * * @default false */ metadata?: boolean; /** * Configuration for request-specific Arktype schemas. * * Controls generation of Arktype schemas for request bodies, query parameters, path * parameters, and headers. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ requests?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}Data' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}Data' */ name?: NameTransformer; }; }; }; /** * Configuration for response-specific Arktype schemas. * * Controls generation of Arktype schemas for response bodies, error responses, * and status codes. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ responses?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}Response' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}Response' */ name?: NameTransformer; }; }; }; /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; }; }; /** * Configuration for webhook-specific Arktype schemas. * * Controls generation of Arktype schemas for webhook payloads. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ webhooks?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}WebhookRequest' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}WebhookRequest' */ name?: NameTransformer; }; }; }; }; export type Config = Plugin.Name<'arktype'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Configuration for reusable schema definitions. * * Controls generation of shared Arktype schemas that can be referenced across * requests and responses. */ definitions: NamingOptions & FeatureToggle & { /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types: { /** * Configuration for `infer` types. */ infer: NamingOptions & FeatureToggle; }; }; /** * Enable Arktype metadata support? It's often useful to associate a schema with * some additional metadata for documentation, code generation, AI * structured outputs, form validation, and other purposes. * * @default false */ metadata: boolean; /** * Configuration for request-specific Arktype schemas. * * Controls generation of Arktype schemas for request bodies, query parameters, path * parameters, and headers. */ requests: NamingOptions & FeatureToggle & { /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types: { /** * Configuration for `infer` types. */ infer: NamingOptions & FeatureToggle; }; }; /** * Configuration for response-specific Arktype schemas. * * Controls generation of Arktype schemas for response bodies, error responses, * and status codes. */ responses: NamingOptions & FeatureToggle & { /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types: { /** * Configuration for `infer` types. */ infer: NamingOptions & FeatureToggle; }; }; /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types: { /** * Configuration for `infer` types. */ infer: FeatureToggle & { /** * Casing convention for generated names. */ case: Casing; }; }; /** * Configuration for webhook-specific Arktype schemas. * * Controls generation of Arktype schemas for webhook payloads. */ webhooks: NamingOptions & FeatureToggle & { /** * Configuration for TypeScript type generation from Arktype schemas. * * Controls generation of TypeScript types based on the generated Arktype schemas. */ types: { /** * Configuration for `infer` types. */ infer: NamingOptions & FeatureToggle; }; }; }; export type ArktypePlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/v2/api.ts ================================================ import { $ } from '../../../ts-dsl'; import type { ValidatorArgs } from '../shared/types'; export const createRequestValidatorV2 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'arktype', }); if (!symbol) return; // const out = User({ // name: "Alan Turing", // device: { // platform: "enigma", // versions: [0, "1", 0n] // } // }) // if (out instanceof type.errors) { // // hover out.summary to see validation errors // console.error(out.summary) // } else { // // hover out to see your validated data // console.log(`Hello, ${out.name}`) // } const dataParameterName = 'data'; return $.func() .async() .param(dataParameterName) .do($(symbol).attr('parseAsync').call(dataParameterName).await().return()); }; export const createResponseValidatorV2 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'responses', tool: 'arktype', }); if (!symbol) return; const dataParameterName = 'data'; return $.func() .async() .param(dataParameterName) .do($(symbol).attr('parseAsync').call(dataParameterName).await().return()); }; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/v2/plugin.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import { fromRef, refs } from '@hey-api/codegen-core'; import type { IR, SchemaWithType } from '@hey-api/shared'; import { applyNaming, deduplicateSchema, pathToJsonPointer, refToName } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import { exportAst } from '../shared/export'; import type { Ast, IrSchemaToAstOptions, PluginState } from '../shared/types'; import type { ArktypePlugin } from '../types'; import { irSchemaWithTypeToAst } from './toAst'; export function irSchemaToAst({ // optional, plugin, schema, schemaExtractor, state, }: IrSchemaToAstOptions & { /** * Accept `optional` to handle optional object properties. We can't handle * this inside the object function because `.optional()` must come before * `.default()` which is handled in this function. */ optional?: boolean; schema: IR.SchemaObject; }): Ast { if (schemaExtractor && !schema.$ref) { const extracted = schemaExtractor({ meta: { resource: 'definition', resourceId: pathToJsonPointer(fromRef(state.path)), }, path: fromRef(state.path), schema, }); if (extracted !== schema) schema = extracted; } let ast: Partial = {}; // const z = plugin.referenceSymbol({ // category: 'external', // resource: 'arktype.type', // }); if (schema.$ref) { const query: SymbolMeta = { category: 'schema', resource: 'definition', resourceId: schema.$ref, tool: 'arktype', }; const refSymbol = plugin.referenceSymbol(query); if (plugin.isSymbolRegistered(query)) { const ref = $(refSymbol); ast.expression = ref; } else { // expression: z, // name: identifiers.lazy, const lazyExpression = $('TODO') .attr('TODO') .call($.func().returns('any').do($.return(refSymbol))); ast.expression = lazyExpression; ast.hasLazyExpression = true; state.hasLazyExpression['~ref'] = true; } } else if (schema.type) { const typeAst = irSchemaWithTypeToAst({ plugin, schema: schema as SchemaWithType, state, }); ast.def = typeAst.def; ast.expression = typeAst.expression; ast.hasLazyExpression = typeAst.hasLazyExpression; if (plugin.config.metadata && schema.description) { // TODO: add description // ast.expression = tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: ast.expression, // name: identifiers.register, // }), // parameters: [ // tsc.propertyAccessExpression({ // expression: z, // name: identifiers.globalRegistry, // }), // tsc.objectExpression({ // obj: [ // { // key: 'description', // value: tsc.stringLiteral({ text: schema.description }), // }, // ], // }), // ], // }); } } else if (schema.items) { schema = deduplicateSchema({ schema }); if (schema.items) { // const itemSchemas = schema.items.map((item, index) => // irSchemaToAst({ // plugin, // schema: item, // state: { // ...state, // _path: [...state._path, 'items', index], // }, // }), // ); // if (schema.logicalOperator === 'and') { // const firstSchema = schema.items[0]!; // // we want to add an intersection, but not every schema can use the same API. // // if the first item contains another array or not an object, we cannot use // // `.merge()` as that does not exist on `.union()` and non-object schemas. // if ( // firstSchema.logicalOperator === 'or' || // (firstSchema.type && firstSchema.type !== 'object') // ) { // ast.expression = tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: z, // name: identifiers.intersection, // }), // parameters: itemSchemas.map((schema) => schema.expression), // }); // } else { // ast.expression = itemSchemas[0]!.expression; // itemSchemas.slice(1).forEach((schema) => { // ast.expression = tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: ast.expression!, // name: identifiers.and, // }), // parameters: [ // schema.hasCircularReference // ? tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: z, // name: identifiers.lazy, // }), // parameters: [ // tsc.arrowFunction({ // statements: [ // tsc.returnStatement({ // expression: schema.expression, // }), // ], // }), // ], // }) // : schema.expression, // ], // }); // }); // } // } else { // ast.expression = tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: z, // name: identifiers.union, // }), // parameters: [ // tsc.arrayLiteralExpression({ // elements: itemSchemas.map((schema) => schema.expression), // }), // ], // }); // } } else { ast = irSchemaToAst({ plugin, schema, state }); } } else { // catch-all fallback for failed schemas const typeAst = irSchemaWithTypeToAst({ plugin, schema: { type: 'unknown', }, state, }); ast.def = typeAst.def; ast.expression = typeAst.expression; } // TODO: remove later if (!ast.expression) { const typeAst = irSchemaWithTypeToAst({ plugin, schema: { type: 'unknown', }, state, }); ast.expression = typeAst.expression; } // END TODO: remove later // if (ast.expression) { // if (schema.accessScope === 'read') { // ast.expression = tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: ast.expression, // name: identifiers.readonly, // }), // }); // } // if (optional) { // ast.expression = tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: z, // name: identifiers.optional, // }), // parameters: [ast.expression], // }); // ast.typeName = identifiers.ZodOptional; // } // if (schema.default !== undefined) { // const isBigInt = schema.type === 'integer' && schema.format === 'int64'; // const callParameter = numberParameter({ // isBigInt, // value: schema.default, // }); // if (callParameter) { // ast.expression = tsc.callExpression({ // functionName: tsc.propertyAccessExpression({ // expression: ast.expression, // name: identifiers.default, // }), // parameters: [callParameter], // }); // } // } // } return ast as Ast; } function handleComponent({ plugin, schema, state, }: IrSchemaToAstOptions & { schema: IR.SchemaObject; }): void { const $ref = pathToJsonPointer(fromRef(state.path)); const ast = irSchemaToAst({ plugin, schema, state }); const baseName = refToName($ref); const symbol = plugin.symbol(applyNaming(baseName, plugin.config.definitions), { meta: { category: 'schema', path: fromRef(state.path), resource: 'definition', resourceId: $ref, tags: fromRef(state.tags), tool: 'arktype', }, }); const typeInferSymbol = plugin.config.definitions.types.infer.enabled ? plugin.symbol(applyNaming(baseName, plugin.config.definitions.types.infer), { meta: { category: 'type', path: fromRef(state.path), resource: 'definition', resourceId: $ref, tool: 'arktype', variant: 'infer', }, }) : undefined; exportAst({ ast, plugin, schema, symbol, typeInferSymbol, }); } export const handlerV2: ArktypePlugin['Handler'] = ({ plugin }) => { plugin.symbol('type', { external: 'arktype', meta: { category: 'external', resource: 'arktype.type', }, }); plugin.forEach('operation', 'parameter', 'requestBody', 'schema', 'webhook', (event) => { const state = refs({ hasLazyExpression: false, path: event._path, tags: event.tags, }); switch (event.type) { // case 'operation': // operationToZodSchema({ // getZodSchema: (schema) => { // const state: State = { // circularReferenceTracker: [], // currentReferenceTracker: [], // hasCircularReference: false, // }; // return schemaToZodSchema({ plugin, schema, state }); // }, // operation: event.operation, // plugin, // }); // break; case 'parameter': handleComponent({ plugin, schema: event.parameter.schema, state, }); break; case 'requestBody': handleComponent({ plugin, schema: event.requestBody.schema, state, }); break; case 'schema': handleComponent({ plugin, schema: event.schema, state, }); break; // case 'webhook': // webhookToZodSchema({ // getZodSchema: (schema) => { // const state: State = { // circularReferenceTracker: [], // currentReferenceTracker: [], // hasCircularReference: false, // }; // return schemaToZodSchema({ plugin, schema, state }); // }, // operation: event.operation, // plugin, // }); // break; } }); }; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/v2/toAst/index.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { Ast, IrSchemaToAstOptions } from '../../shared/types'; import { nullToAst } from './null'; import { objectToAst } from './object'; import { stringToAst } from './string'; // import { arrayToAst } from "./array"; // import { booleanToAst } from "./boolean"; // import { enumToAst } from "./enum"; // import { neverToAst } from "./never"; // import { numberToAst } from "./number"; // import { tupleToAst } from "./tuple"; // import { undefinedToAst } from "./undefined"; // import { unknownToAst } from "./unknown"; // import { voidToAst } from "./void"; export function irSchemaWithTypeToAst({ schema, ...args }: IrSchemaToAstOptions & { schema: SchemaWithType; }): Omit { switch (schema.type) { // case 'array': // return arrayToAst({ // ...args, // schema: schema as SchemaWithType<'array'>, // }); // case 'boolean': // return booleanToAst({ // ...args, // schema: schema as SchemaWithType<'boolean'>, // }); // case 'enum': // return enumToAst({ // ...args, // schema: schema as SchemaWithType<'enum'>, // }); // case 'integer': // case 'number': // return numberToAst({ // ...args, // schema: schema as SchemaWithType<'integer' | 'number'>, // }); // case 'never': // return neverToAst({ // ...args, // schema: schema as SchemaWithType<'never'>, // }); case 'null': return nullToAst({ ...args, schema: schema as SchemaWithType<'null'>, }); case 'object': return objectToAst({ ...args, schema: schema as SchemaWithType<'object'>, }); case 'string': return stringToAst({ ...args, schema: schema as SchemaWithType<'string'>, }); // case 'tuple': // return tupleToAst({ // ...args, // schema: schema as SchemaWithType<'tuple'>, // }); // case 'undefined': // return undefinedToAst({ // ...args, // schema: schema as SchemaWithType<'undefined'>, // }); // case 'unknown': // return unknownToAst({ // ...args, // schema: schema as SchemaWithType<'unknown'>, // }); // case 'void': // return voidToAst({ // ...args, // schema: schema as SchemaWithType<'void'>, // }); } const type = args.plugin.external('arktype.type'); const expression = $(type).call( $.object() .prop('name', $.literal('string')) .prop('platform', $.literal("'android' | 'ios'")) .prop('versions?', $.literal('(number | string)[]')), ); return { def: '', expression, hasLazyExpression: false, }; } ================================================ FILE: packages/openapi-ts/src/plugins/arktype/v2/toAst/null.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { identifiers } from '../../constants'; import type { Ast, IrSchemaToAstOptions } from '../../shared/types'; export const nullToAst = ( // eslint-disable-next-line @typescript-eslint/no-unused-vars _args: IrSchemaToAstOptions & { schema: SchemaWithType<'null'>; }, ): Omit => { const result: Partial> = {}; result.def = identifiers.primitives.null; return result as Omit; }; ================================================ FILE: packages/openapi-ts/src/plugins/arktype/v2/toAst/object.ts ================================================ import { fromRef, ref } from '@hey-api/codegen-core'; import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; // import { identifiers } from '../../constants'; import type { Ast, IrSchemaToAstOptions } from '../../shared/types'; import { irSchemaToAst } from '../plugin'; export function objectToAst({ plugin, schema, state, }: IrSchemaToAstOptions & { schema: SchemaWithType<'object'>; }): Omit { const result: Partial> = {}; // TODO: parser - handle constants const shape = $.object().pretty(); const required = schema.required ?? []; for (const name in schema.properties) { const property = schema.properties[name]!; const isRequired = required.includes(name); const propertyAst = irSchemaToAst({ optional: !isRequired, plugin, schema: property, state: { ...state, path: ref([...fromRef(state.path), 'properties', name]), }, }); if (propertyAst.hasLazyExpression) { result.hasLazyExpression = true; } // if (propertyAst.hasCircularReference) { // properties.push( // tsc.getAccessorDeclaration({ // name: propertyName, // // @ts-expect-error // returnType: propertyAst.typeName // ? tsc.propertyAccessExpression({ // expression: 'TODO', // name: propertyAst.typeName, // }) // : undefined, // statements: [ // tsc.returnStatement({ // expression: propertyAst.expression, // }), // ], // }), // ); // } else { // properties.push( // tsc.propertyAssignment({ // initializer: propertyAst.expression, // name: ts.factory.createComputedPropertyName( // ts.factory.createStringLiteral(`${propertyName}?`), // ), // }), // ); // } shape.prop(isRequired ? name : `${name}?`, propertyAst.expression); } if ( schema.additionalProperties && (!schema.properties || !Object.keys(schema.properties).length) ) { const additionalAst = irSchemaToAst({ plugin, schema: schema.additionalProperties, state: { ...state, path: ref([...fromRef(state.path), 'additionalProperties']), }, }); // name: identifiers.record, result.expression = $('TODO').attr('record').call( // name: identifiers.string, $('TODO').attr('string').call(), additionalAst.expression, ); if (additionalAst.hasLazyExpression) { result.hasLazyExpression = true; } return result as Omit; } result.expression = shape; // return with typeName for circular references if (result.hasLazyExpression) { return { ...result, typeName: 'TODO', } as Ast; } return result as Omit; } ================================================ FILE: packages/openapi-ts/src/plugins/arktype/v2/toAst/string.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { identifiers } from '../../constants'; import type { Ast, IrSchemaToAstOptions } from '../../shared/types'; export const stringToAst = ({ schema, }: IrSchemaToAstOptions & { schema: SchemaWithType<'string'>; }): Omit => { const result: Partial> = {}; if (typeof schema.const === 'string') { result.def = schema.const; return result as Omit; } let def = identifiers.primitives.string; if (schema.format) { switch (schema.format) { case 'date': case 'date-time': case 'time': def = `${def}.${identifiers.string.date}.${identifiers.string.iso}`; break; case 'email': def = `${def}.${identifiers.string.email}`; break; case 'ipv4': def = `${def}.${identifiers.string.ip}.${identifiers.string.v4}`; break; case 'ipv6': def = `${def}.${identifiers.string.ip}.${identifiers.string.v6}`; break; case 'uri': def = `${def}.${identifiers.string.url}`; break; case 'uuid': def = `${def}.${identifiers.string.uuid}`; break; } } if (schema.minLength === schema.maxLength && schema.minLength !== undefined) { def = `${schema.minLength} <= ${def} <= ${schema.maxLength}`; } else { if (schema.maxLength !== undefined) { def = `${def} <= ${schema.maxLength}`; if (schema.minLength !== undefined) { def = `${schema.minLength} <= ${def}`; } } else if (schema.minLength !== undefined) { def = `${def} >= ${schema.minLength}`; } } if (schema.pattern) { def = `/${schema.pattern}/`; } result.def = def; return result as Omit; }; ================================================ FILE: packages/openapi-ts/src/plugins/config.ts ================================================ import type { Plugin, PluginConfigMap, PluginNames } from '@hey-api/shared'; import { defaultConfig as angularCommon } from '../plugins/@angular/common'; import { defaultConfig as fakerJsFaker } from '../plugins/@faker-js/faker'; import { defaultConfig as heyApiClientAngular } from '../plugins/@hey-api/client-angular'; import { defaultConfig as heyApiClientAxios } from '../plugins/@hey-api/client-axios'; import { defaultConfig as heyApiClientFetch } from '../plugins/@hey-api/client-fetch'; import { defaultConfig as heyApiClientKy } from '../plugins/@hey-api/client-ky'; import { defaultConfig as heyApiClientNext } from '../plugins/@hey-api/client-next'; import { defaultConfig as heyApiClientNuxt } from '../plugins/@hey-api/client-nuxt'; import { defaultConfig as heyApiClientOfetch } from '../plugins/@hey-api/client-ofetch'; import { defaultConfig as heyApiSchemas } from '../plugins/@hey-api/schemas'; import { defaultConfig as heyApiSdk } from '../plugins/@hey-api/sdk'; import { defaultConfig as heyApiTransformers } from '../plugins/@hey-api/transformers'; import { defaultConfig as heyApiTypeScript } from '../plugins/@hey-api/typescript'; import { defaultConfig as piniaColada } from '../plugins/@pinia/colada'; import { defaultConfig as tanStackAngularQuery } from '../plugins/@tanstack/angular-query-experimental'; import { defaultConfig as tanStackPreactQuery } from '../plugins/@tanstack/preact-query'; import { defaultConfig as tanStackReactQuery } from '../plugins/@tanstack/react-query'; import { defaultConfig as tanStackSolidQuery } from '../plugins/@tanstack/solid-query'; import { defaultConfig as tanStackSvelteQuery } from '../plugins/@tanstack/svelte-query'; import { defaultConfig as tanStackVueQuery } from '../plugins/@tanstack/vue-query'; import { defaultConfig as arktype } from '../plugins/arktype'; import { defaultConfig as fastify } from '../plugins/fastify'; import { defaultConfig as nestjs } from '../plugins/nestjs'; import { defaultConfig as orpc } from '../plugins/orpc'; import { defaultConfig as swr } from '../plugins/swr'; import { defaultConfig as valibot } from '../plugins/valibot'; import { defaultConfig as zod } from '../plugins/zod'; export const defaultPluginConfigs: { [K in PluginNames]: Plugin.Config; } = { '@angular/common': angularCommon, '@faker-js/faker': fakerJsFaker, '@hey-api/client-angular': heyApiClientAngular, '@hey-api/client-axios': heyApiClientAxios, '@hey-api/client-fetch': heyApiClientFetch, '@hey-api/client-ky': heyApiClientKy, '@hey-api/client-next': heyApiClientNext, '@hey-api/client-nuxt': heyApiClientNuxt, '@hey-api/client-ofetch': heyApiClientOfetch, '@hey-api/schemas': heyApiSchemas, '@hey-api/sdk': heyApiSdk, '@hey-api/transformers': heyApiTransformers, '@hey-api/typescript': heyApiTypeScript, '@pinia/colada': piniaColada, '@tanstack/angular-query-experimental': tanStackAngularQuery, '@tanstack/preact-query': tanStackPreactQuery, '@tanstack/react-query': tanStackReactQuery, '@tanstack/solid-query': tanStackSolidQuery, '@tanstack/svelte-query': tanStackSvelteQuery, '@tanstack/vue-query': tanStackVueQuery, arktype, fastify, nestjs, orpc, swr, valibot, zod, }; ================================================ FILE: packages/openapi-ts/src/plugins/fastify/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { handler } from './plugin'; import type { FastifyPlugin } from './types'; export const defaultConfig: FastifyPlugin['Config'] = { config: { includeInEntry: false, }, dependencies: ['@hey-api/typescript'], handler, name: 'fastify', }; /** * Type helper for `fastify` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/fastify/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { FastifyPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/fastify/plugin.ts ================================================ import type { IR } from '@hey-api/shared'; import { hasParameterGroupObjectRequired, operationResponsesMap } from '@hey-api/shared'; import { $ } from '../../ts-dsl'; import type { FastifyPlugin } from './types'; const operationToRouteHandler = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: FastifyPlugin['Instance']; }) => { const type = $.type.object(); const symbolDataType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'typescript', }); if (symbolDataType) { if (operation.body) { type.prop('Body', (p) => p .required(operation.body!.required) .type($.type(symbolDataType).idx($.type.literal('body'))), ); } if (operation.parameters) { if (operation.parameters.header) { type.prop('Headers', (p) => p .required(hasParameterGroupObjectRequired(operation.parameters!.header)) .type($.type(symbolDataType).idx($.type.literal('headers'))), ); } if (operation.parameters.path) { type.prop('Params', (p) => p .required(hasParameterGroupObjectRequired(operation.parameters!.path)) .type($.type(symbolDataType).idx($.type.literal('path'))), ); } if (operation.parameters.query) { type.prop('Querystring', (p) => p .required(hasParameterGroupObjectRequired(operation.parameters!.query)) .type($.type(symbolDataType).idx($.type.literal('query'))), ); } } } const { errors, responses } = operationResponsesMap(operation); let errorsTypeReference: ReturnType | undefined; const symbolErrorType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'errors', }); if (symbolErrorType && errors && errors.properties) { const keys = Object.keys(errors.properties); if (keys.length) { const hasDefaultResponse = keys.includes('default'); if (!hasDefaultResponse) { errorsTypeReference = $.type(symbolErrorType); } else if (keys.length > 1) { errorsTypeReference = $.type('Omit', (t) => t.generics($.type(symbolErrorType), $.type.literal('default')), ); } } } let responsesTypeReference: ReturnType | undefined = undefined; const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'responses', }); if (symbolResponseType && responses && responses.properties) { const keys = Object.keys(responses.properties); if (keys.length) { const hasDefaultResponse = keys.includes('default'); if (!hasDefaultResponse) { responsesTypeReference = $.type(symbolResponseType); } else if (keys.length > 1) { responsesTypeReference = $.type('Omit', (t) => t.generics($.type(symbolResponseType), $.type.literal('default')), ); } } } const replyTypes = [errorsTypeReference, responsesTypeReference].filter( (t): t is ReturnType => t !== undefined, ); if (replyTypes.length) { type.prop('Reply', (p) => p.type($.type.and(...replyTypes))); } if (type.isEmpty) { return; } const symbolRouteHandler = plugin.referenceSymbol({ category: 'type', resource: 'route-handler', tool: 'fastify', }); return { name: operation.id, type: $.type(symbolRouteHandler, (t) => t.generic(type)), }; }; export const handler: FastifyPlugin['Handler'] = ({ plugin }) => { plugin.symbol('RouteHandler', { external: 'fastify', kind: 'type', meta: { category: 'type', resource: 'route-handler', tool: 'fastify', }, }); const symbolRouteHandlers = plugin.symbol('RouteHandlers'); const type = $.type.object(); plugin.forEach( 'operation', ({ operation }) => { const routeHandler = operationToRouteHandler({ operation, plugin }); if (routeHandler) { type.prop(routeHandler.name, (p) => p.type(routeHandler.type)); } }, { order: 'declarations', }, ); const node = $.type.alias(symbolRouteHandlers).export().type(type); plugin.node(node); }; ================================================ FILE: packages/openapi-ts/src/plugins/fastify/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'fastify'> & Plugin.Hooks & Plugin.UserExports; export type FastifyPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/nestjs/config.ts ================================================ import { definePluginConfig } from '@hey-api/shared'; import { handler } from './plugin'; import type { NestJsPlugin } from './types'; export const defaultConfig: NestJsPlugin['Config'] = { config: { includeInEntry: false, }, dependencies: ['@hey-api/typescript'], handler, name: 'nestjs', }; /** * Type helper for `nestjs` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/nestjs/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { NestJsPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/nestjs/plugin.ts ================================================ import type { IR } from '@hey-api/shared'; import { hasParameterGroupObjectRequired, operationResponsesMap, toCase } from '@hey-api/shared'; import { $ } from '../../ts-dsl'; import type { NestJsPlugin } from './types'; const operationToMethod = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: NestJsPlugin['Instance']; }) => { const funcType = $.type.func(); const symbolDataType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'typescript', }); if (symbolDataType) { // Collect params so we can sort required before optional. // Without this, TypeScript would reject signatures like // (query?: T, body: U) => ... where optional precedes required. const params: Array<{ isRequired: boolean; key: string; }> = []; if (operation.parameters?.path) { params.push({ isRequired: hasParameterGroupObjectRequired(operation.parameters.path), key: 'path', }); } if (operation.parameters?.query) { params.push({ isRequired: hasParameterGroupObjectRequired(operation.parameters.query), key: 'query', }); } if (operation.body) { params.push({ isRequired: operation.body.required ?? false, key: 'body', }); } if (operation.parameters?.header) { params.push({ isRequired: hasParameterGroupObjectRequired(operation.parameters.header), key: 'headers', }); } // Stable sort: required params first, optional params last params.sort((a, b) => (a.isRequired === b.isRequired ? 0 : a.isRequired ? -1 : 1)); for (const param of params) { funcType.param(param.key, (p) => p.required(param.isRequired).type($.type(symbolDataType).idx($.type.literal(param.key))), ); } } // Use the response type alias (union of success bodies), not the // status-code-indexed responses map. NestJS controllers return values // directly, not status-code mappings. const { responses } = operationResponsesMap(operation); const symbolResponseType = plugin.querySymbol({ category: 'type', resource: 'operation', resourceId: operation.id, role: 'response', tool: 'typescript', }); if (symbolResponseType && responses) { funcType.returns($.type('Promise', (t) => t.generic($.type(symbolResponseType)))); } else { funcType.returns($.type('Promise', (t) => t.generic($.type('void')))); } return { name: operation.id, type: funcType, }; }; const emitTypeAlias = ({ methods, plugin, typeName, }: { methods: Array<{ name: string; type: ReturnType }>; plugin: NestJsPlugin['Instance']; typeName: string; }) => { const symbol = plugin.symbol(typeName); const type = $.type.object(); for (const method of methods) { type.prop(method.name, (p) => p.type(method.type)); } plugin.node($.type.alias(symbol).export().type(type)); }; export const handler: NestJsPlugin['Handler'] = ({ plugin }) => { // Collect operations by tag, then emit per-tag types const operationsByTag = new Map< string, Array<{ name: string; type: ReturnType }> >(); plugin.forEach( 'operation', ({ operation, tags }) => { const tag = tags?.[0] ?? 'default'; if (!operationsByTag.has(tag)) { operationsByTag.set(tag, []); } const method = operationToMethod({ operation, plugin }); operationsByTag.get(tag)!.push(method); }, { order: 'declarations', }, ); for (const [tag, methods] of operationsByTag) { const pascalTag = toCase(tag, 'PascalCase'); emitTypeAlias({ methods, plugin, typeName: `${pascalTag}ControllerMethods`, }); } }; ================================================ FILE: packages/openapi-ts/src/plugins/nestjs/types.ts ================================================ import type { DefinePlugin, Plugin } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'nestjs'> & Plugin.Hooks & Plugin.UserExports; export type NestJsPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/orpc/config.ts ================================================ import { log } from '@hey-api/codegen-core'; import { definePluginConfig } from '@hey-api/shared'; import { resolveContracts } from './contracts/config'; import { handler } from './plugin'; import type { OrpcPlugin } from './types'; const validatorInferWarn = 'You set `validator: true` but no validator plugin was found in your plugins. Add a validator plugin like `zod` to enable this feature. The validator option has been disabled.'; export const defaultConfig: OrpcPlugin['Config'] = { config: { includeInEntry: false, }, handler, name: 'orpc', resolveConfig: (plugin, context) => { if (typeof plugin.config.validator !== 'object') { plugin.config.validator = { input: plugin.config.validator, output: plugin.config.validator, }; } if (plugin.config.validator.input || plugin.config.validator.input === undefined) { if ( typeof plugin.config.validator.input === 'boolean' || plugin.config.validator.input === undefined ) { try { plugin.config.validator.input = context.pluginByTag('validator'); plugin.dependencies.add(plugin.config.validator.input!); } catch { // avoid showing the warning with default configuration as it would be confusing if (plugin.config.validator.input !== undefined) { log.warn(validatorInferWarn); } plugin.config.validator.input = false; } } else { plugin.dependencies.add(plugin.config.validator.input); } } else { plugin.config.validator.input = false; } if (plugin.config.validator.output || plugin.config.validator.output === undefined) { if ( typeof plugin.config.validator.output === 'boolean' || plugin.config.validator.output === undefined ) { try { plugin.config.validator.output = context.pluginByTag('validator'); plugin.dependencies.add(plugin.config.validator.output!); } catch { // avoid showing the warning with default configuration as it would be confusing if (plugin.config.validator.output !== undefined) { log.warn(validatorInferWarn); } plugin.config.validator.output = false; } } else { plugin.dependencies.add(plugin.config.validator.output); } } else { plugin.config.validator.output = false; } plugin.config.contracts = resolveContracts(plugin.config, context); }, }; /** * Type helper for oRPC plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/orpc/contracts/config.ts ================================================ import type { PluginContext } from '@hey-api/shared'; import type { UserConfig } from '../types'; import type { ContractsConfig } from './types'; type Config = Omit; export function resolveContracts(config: Config, context: PluginContext): ContractsConfig { return normalizeConfig(config.contracts, context); } function normalizeConfig(input: Config['contracts'], context: PluginContext): ContractsConfig { if (!input || typeof input === 'string' || typeof input === 'function') { input = { strategy: input }; } const strategy = input.strategy ?? 'single'; return context.valueToObject({ defaultValue: { container: 'object', nesting: 'operationId', nestingDelimiters: /[./]/, strategy, strategyDefaultTag: 'default', }, mappers: { object(value) { value.containerName = context.valueToObject({ defaultValue: strategy === 'single' ? { casing: 'camelCase', name: 'contract' } : { casing: 'camelCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.containerName, }); value.contractName = context.valueToObject({ defaultValue: { casing: 'camelCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.contractName, }); value.segmentName = context.valueToObject({ defaultValue: { casing: 'camelCase' }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: value.segmentName, }); return value; }, }, value: input, }) as ContractsConfig; } ================================================ FILE: packages/openapi-ts/src/plugins/orpc/contracts/index.ts ================================================ export { resolveContracts } from './config'; export { type ContractItem, createShell, source, toNode } from './node'; export { resolveStrategy } from './resolve'; export type { ContractsConfig, UserContractsConfig } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/orpc/contracts/node.ts ================================================ import type { StructureItem, StructureNode, StructureShell, Symbol, SymbolMeta, } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import { createOperationComment } from '../../shared/utils/operation'; import { getSuccessResponse, getTags, hasInput } from '../shared/operation'; import type { OrpcPlugin } from '../types'; export interface ContractItem { operation: IR.OperationObject; path: ReadonlyArray; tags: ReadonlyArray | undefined; } export const source = globalThis.Symbol('orpc'); function createShellMeta(node: StructureNode): SymbolMeta { return { category: 'contract', resource: 'container', resourceId: node.getPath().join('.'), tool: 'orpc', }; } function createContractSymbol( plugin: OrpcPlugin['Instance'], item: StructureItem & { data: ContractItem }, ): Symbol { const { operation, path, tags } = item.data; const name = item.location[item.location.length - 1]!; return plugin.symbol(applyNaming(name, plugin.config.contracts.contractName), { meta: { category: 'contract', path, resource: 'operation', resourceId: operation.id, role: 'contract', tags, tool: plugin.name, }, }); } function createContractExpression( plugin: OrpcPlugin['Instance'], operation: IR.OperationObject, baseSymbol: Symbol, ) { const successResponse = getSuccessResponse(operation); const tags = getTags(operation, plugin.config.contracts.strategyDefaultTag); let expression = $(baseSymbol) .attr('route') .call( $.object() .$if(operation.deprecated, (o, v) => o.prop('deprecated', $.literal(v))) .$if(operation.description, (o, v) => o.prop('description', $.literal(v))) .prop('method', $.literal(operation.method.toUpperCase())) .$if(operation.operationId, (o, v) => o.prop('operationId', $.literal(v))) .prop('path', $.literal(operation.path)) .$if( successResponse.hasOutput && successResponse.statusCode !== 200 && successResponse.statusCode, (o, v) => o.prop('successStatus', $.literal(v)), ) .$if(operation.summary, (o, v) => o.prop('summary', $.literal(v))) .$if(tags.length > 0 && tags, (o, v) => o.prop('tags', $.fromValue(v))), ); if (hasInput(operation) && plugin.config.validator.input) { expression = expression.attr('input').call( plugin.referenceSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'data', tool: plugin.config.validator.input, }), ); } if (successResponse.hasOutput && plugin.config.validator.output) { expression = expression.attr('output').call( plugin.referenceSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'responses', tool: plugin.config.validator.output, }), ); } return expression; } function buildContainerObject( node: StructureNode, plugin: OrpcPlugin['Instance'], symbols: Map, ): ReturnType { const obj = $.object(); for (const item of node.itemsFrom(source)) { const { operation } = item.data; const contractSymbol = symbols.get(operation.id)!; const name = item.location[item.location.length - 1]!; const propName = applyNaming(name, plugin.config.contracts.contractName); obj.prop(propName, contractSymbol); } for (const child of node.children.values()) { if (child.shell) { const childShell = child.shell.define(child); const childNode = childShell.node as ReturnType; const childSymbol = childNode.symbol; if (childSymbol) { const propName = applyNaming(child.name, plugin.config.contracts.segmentName); obj.prop(propName, childSymbol); } } } return obj; } export function createShell(plugin: OrpcPlugin['Instance']): StructureShell { const cache = new Map>(); return { define: (node) => { const resourceId = node.getPath().join('.'); const cached = cache.get(resourceId); if (cached) { return { dependencies: [], node: cached }; } const symbol = plugin.symbol( applyNaming( node.name, node.isRoot ? plugin.config.contracts.containerName : plugin.config.contracts.segmentName, ), { meta: createShellMeta(node), }, ); const o = $.const(symbol).export().assign($.object()); cache.set(resourceId, o); return { dependencies: [], node: o }; }, }; } export function toNode( model: StructureNode, plugin: OrpcPlugin['Instance'], baseSymbol: Symbol, ): { nodes: ReadonlyArray>; symbols?: Map; } { if (model.virtual) { const nodes: Array> = []; const symbols = new Map(); for (const item of model.itemsFrom(source)) { const { operation } = item.data; const contractSymbol = createContractSymbol(plugin, item); const expression = createContractExpression(plugin, operation, baseSymbol); const node = $.const(contractSymbol) .export() .$if(createOperationComment(operation), (n, v) => n.doc(v)) .assign(expression); nodes.push(node); symbols.set(operation.id, contractSymbol); } return { nodes, symbols }; } if (!model.shell) { return { nodes: [] }; } const nodes: Array> = []; const symbols = new Map(); for (const item of model.itemsFrom(source)) { const { operation } = item.data; const contractSymbol = createContractSymbol(plugin, item); const expression = createContractExpression(plugin, operation, baseSymbol); const node = $.const(contractSymbol) .export() .$if(createOperationComment(operation), (n, v) => n.doc(v)) .assign(expression); nodes.push(node); symbols.set(operation.id, contractSymbol); } const shell = model.shell.define(model); const containerSymbol = shell.node.symbol!; const obj = buildContainerObject(model, plugin, symbols); const containerNode = $.const(containerSymbol).export().assign(obj.pretty()); nodes.push(containerNode); return { nodes, symbols }; } ================================================ FILE: packages/openapi-ts/src/plugins/orpc/contracts/resolve.ts ================================================ import type { OperationPathStrategy, OperationStructureStrategy } from '@hey-api/shared'; import { OperationPath, OperationStrategy } from '@hey-api/shared'; import type { OrpcPlugin } from '../types'; function resolvePath(plugin: OrpcPlugin['Instance']): OperationPathStrategy { if (plugin.config.contracts.nesting === 'id') { return OperationPath.id(); } if (plugin.config.contracts.nesting === 'operationId') { return OperationPath.fromOperationId({ delimiters: plugin.config.contracts.nestingDelimiters, fallback: OperationPath.id(), }); } return plugin.config.contracts.nesting; } export function resolveStrategy(plugin: OrpcPlugin['Instance']): OperationStructureStrategy { if (plugin.config.contracts.strategy === 'flat') { return OperationStrategy.flat({ path: (operation) => [resolvePath(plugin)(operation).join('.')], }); } if (plugin.config.contracts.strategy === 'single') { const root = plugin.config.contracts.containerName; return OperationStrategy.single({ path: resolvePath(plugin), root: typeof root.name === 'string' ? root.name : (root.name?.('') ?? ''), }); } if (plugin.config.contracts.strategy === 'byTags') { return OperationStrategy.byTags({ fallback: plugin.config.contracts.strategyDefaultTag, path: resolvePath(plugin), }); } return plugin.config.contracts.strategy; } ================================================ FILE: packages/openapi-ts/src/plugins/orpc/contracts/types.ts ================================================ import type { NamingConfig, NamingRule, OperationPathStrategy, OperationsStrategy, } from '@hey-api/shared'; export interface UserContractsConfig { /** * Type of container for grouped contracts. * * Ignored when `strategy` is `'flat'`. * * - `'object'` - Object with properties * * @default 'object' */ container?: 'object'; /** * Customize container names. * * For `'single'` strategy, this sets the root container name. * For `'byTags'` strategy, this transforms tag names. * * @default 'contract' for `'single'` strategy * * @example * // Set root name for single strategy * containerName: 'myContract' * * @example * // Transform tag names with suffix * containerName: '{{name}}Contract' * * @example * // With casing * containerName: { name: '{{name}}Contract', casing: 'camelCase' } */ containerName?: NamingRule; /** * Customize contract names. * * Applied to the final segment of the path (the contract name). */ contractName?: NamingRule; /** * How to derive nesting structure from operations. * * - `'operationId'` - Split operationId by delimiters (e.g., `users.list` → `Users.list()`) * - `'id'` - Use operation id as-is, no nesting * - Custom function for full control * * @default 'operationId' */ nesting?: 'operationId' | 'id' | OperationPathStrategy; /** * Delimiters for splitting operationId. * * Only applies when `nesting` is `'operationId'`. * * @default /[./]/ */ nestingDelimiters?: RegExp; /** * Customize nesting segment names. * * Applied to intermediate path segments (not the contract name). */ segmentName?: NamingRule; /** * Grouping strategy. * * - `'flat'` - Standalone contracts, no grouping * - `'byTags'` - One container per operation tag * - `'single'` - All contracts in one container * - Custom function for full control * * @default 'single' */ strategy?: OperationsStrategy; /** * Default container name for operations without tags. * * Only applies when `strategy` is `'byTags'`. * * @default 'default' */ strategyDefaultTag?: string; } export interface ContractsConfig { /** Type of container for grouped operations. */ container: 'object'; /** Customize container names. */ containerName: NamingConfig; /** Customize contract names. */ contractName: NamingConfig; /** How to derive nesting structure from operations. */ nesting: 'operationId' | 'id' | OperationPathStrategy; /** Delimiters for splitting operationId. */ nestingDelimiters: RegExp; /** Customize nesting segment names. */ segmentName: NamingConfig; /** Grouping strategy. */ strategy: OperationsStrategy; /** Default container name for operations without tags. */ strategyDefaultTag: string; } ================================================ FILE: packages/openapi-ts/src/plugins/orpc/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { OrpcPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/orpc/plugin.ts ================================================ import type { OrpcPlugin } from './types'; import { handlerV1 } from './v1/plugin'; export const handler: OrpcPlugin['Handler'] = (args) => handlerV1(args); ================================================ FILE: packages/openapi-ts/src/plugins/orpc/shared/operation.ts ================================================ import type { IR } from '@hey-api/shared'; export function hasInput(operation: IR.OperationObject): boolean { const hasPathParams = Boolean( operation.parameters?.path && Object.keys(operation.parameters.path).length > 0, ); const hasQueryParams = Boolean( operation.parameters?.query && Object.keys(operation.parameters.query).length > 0, ); const hasHeaderParams = Boolean( operation.parameters?.header && Object.keys(operation.parameters.header).length > 0, ); const hasBody = Boolean(operation.body); return hasPathParams || hasQueryParams || hasHeaderParams || hasBody; } export function getSuccessResponse( operation: IR.OperationObject, ): { hasOutput: true; statusCode: number } | { hasOutput: false; statusCode?: undefined } { if (operation.responses) { for (const [statusCode, response] of Object.entries(operation.responses)) { const statusCodeNumber = Number.parseInt(statusCode, 10); if ( statusCodeNumber >= 200 && statusCodeNumber <= 399 && response?.mediaType && response?.schema ) { return { hasOutput: true, statusCode: statusCodeNumber }; } } } return { hasOutput: false, statusCode: undefined }; } export function getTags(operation: IR.OperationObject, defaultTag: string): ReadonlyArray { return operation.tags && operation.tags.length > 0 ? [...operation.tags] : [defaultTag]; } ================================================ FILE: packages/openapi-ts/src/plugins/orpc/types.ts ================================================ import type { DefinePlugin, OperationsStrategy, Plugin } from '@hey-api/shared'; import type { PluginValidatorNames } from '../types'; import type { ContractsConfig, UserContractsConfig } from './contracts/types'; export type UserConfig = Plugin.Name<'orpc'> & Plugin.Hooks & Plugin.UserExports & { /** * Define the structure of generated oRPC contracts. * * String shorthand: * - `'byTags'` – one container per operation tag * - `'flat'` – standalone functions, no container * - `'single'` – all operations in a single container * - custom function for full control * * Use the object form for advanced configuration. * * @default 'single' */ contracts?: OperationsStrategy | UserContractsConfig; /** * Validate input/output schemas. * * @default true */ validator?: | PluginValidatorNames | boolean | { /** * The validator plugin to use for input schemas. * * Can be a validator plugin name or boolean (true to auto-select, false * to disable). * * @default true */ input?: PluginValidatorNames | boolean; /** * The validator plugin to use for output schemas. * * Can be a validator plugin name or boolean (true to auto-select, false * to disable). * * @default true */ output?: PluginValidatorNames | boolean; }; }; export type Config = Plugin.Name<'orpc'> & Plugin.Hooks & Plugin.Exports & { /** Define the structure of generated oRPC contracts. */ contracts: ContractsConfig; /** Validate input/output schemas. */ validator: { /** The validator plugin to use for input schemas. */ input: PluginValidatorNames | false; /** The validator plugin to use for output schemas. */ output: PluginValidatorNames | false; }; }; export type OrpcPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/orpc/v1/plugin.ts ================================================ import { StructureModel } from '@hey-api/codegen-core'; import { $ } from '../../../ts-dsl'; import type { ContractItem } from '../contracts'; import { createShell, resolveStrategy, source, toNode } from '../contracts'; import type { OrpcPlugin } from '../types'; export const handlerV1: OrpcPlugin['Handler'] = ({ plugin }) => { const oc = plugin.symbol('oc', { external: '@orpc/contract', }); const baseSymbol = plugin.symbol('base'); const baseNode = $.const(baseSymbol) .export() .assign( $(oc) .attr('$route') .call($.object().prop('inputStructure', $.literal('detailed'))), ); plugin.node(baseNode); const structure = new StructureModel(); const shell = createShell(plugin); const strategy = resolveStrategy(plugin); plugin.forEach( 'operation', (event) => { structure.insert({ data: { operation: event.operation, path: event._path, tags: event.tags, } satisfies ContractItem, locations: strategy(event.operation).map((path) => ({ path, shell })), source, }); }, { order: 'declarations' }, ); const allNodes: Array> = []; for (const node of structure.walk()) { const { nodes } = toNode(node, plugin, baseSymbol); allNodes.push(...nodes); } for (const node of allNodes) { plugin.node(node); } }; ================================================ FILE: packages/openapi-ts/src/plugins/shared/utils/coerce.ts ================================================ import { $ } from '../../../ts-dsl'; export type MaybeBigInt = ( value: unknown, format: string | undefined, ) => ReturnType; export type ShouldCoerceToBigInt = (format: string | undefined) => boolean; export const shouldCoerceToBigInt: ShouldCoerceToBigInt = (format) => format === 'int64' || format === 'uint64'; export const maybeBigInt: MaybeBigInt = (value, format) => { if (!shouldCoerceToBigInt(format)) { return $.fromValue(value); } if (typeof value === 'string') { // handle invalid input if (value.endsWith('n')) value = value.slice(0, -1); return $('BigInt').call($.fromValue(value)); } if (typeof value === 'number') { return $('BigInt').call($.fromValue(value)); } return $.fromValue(value); }; ================================================ FILE: packages/openapi-ts/src/plugins/shared/utils/formats.ts ================================================ type Range = number | string; interface IntegerLimit { maxError: string; maxValue: Range; minError: string; minValue: Range; } export type GetIntegerLimit = (format: string | undefined) => IntegerLimit | undefined; const rangeErrors = (format: string, range: [Range, Range]) => ({ maxError: `Invalid value: Expected ${format} to be <= ${range[1]}`, minError: `Invalid value: Expected ${format} to be >= ${range[0]}`, }); const integerRange: Record = { int16: [-32768, 32767], int32: [-2147483648, 2147483647], int64: ['-9223372036854775808', '9223372036854775807'], int8: [-128, 127], uint16: [0, 65535], uint32: [0, 4294967295], uint64: ['0', '18446744073709551615'], uint8: [0, 255], }; export const getIntegerLimit: GetIntegerLimit = (format) => { if (!format) return; const range = integerRange[format]; if (!range) return; const errors = rangeErrors(format, range); return { maxValue: range[1], minValue: range[0], ...errors }; }; ================================================ FILE: packages/openapi-ts/src/plugins/shared/utils/operation.ts ================================================ import type { Context, IR } from '@hey-api/shared'; import { escapeComment, hasOperationDataRequired } from '@hey-api/shared'; import { getTypedConfig } from '../../../config/utils'; import { getClientPlugin } from '../../../plugins/@hey-api/client-core/utils'; import type { HeyApiSdkPlugin } from '../../../plugins/@hey-api/sdk'; import { isInstance } from '../../../plugins/@hey-api/sdk/v1/node'; export function createOperationComment( operation: IR.OperationObject, ): ReadonlyArray | undefined { const comments: Array = []; if (operation.summary) { comments.push(escapeComment(operation.summary)); } if (operation.description) { if (comments.length) { comments.push(''); // Add an empty line between summary and description } comments.push(escapeComment(operation.description)); } if (operation.deprecated) { if (comments.length) { comments.push(''); // Add an empty line before deprecated } comments.push('@deprecated'); } return comments.length ? comments : undefined; } /** * TODO: replace with plugin logic... * * @deprecated this needs to be refactored */ export function isOperationOptionsRequired({ context, operation, }: { context: Context; operation: IR.OperationObject; }): boolean { const config = getTypedConfig(context); const client = getClientPlugin(config); const isNuxtClient = client.name === '@hey-api/client-nuxt'; const plugin = config.plugins['@hey-api/sdk']; if (plugin) { if (!plugin.config.client && !isInstance(plugin as unknown as HeyApiSdkPlugin['Instance'])) { return true; } if (plugin.config.paramsStructure === 'flat') { return false; } } return isNuxtClient || hasOperationDataRequired(operation); } export function hasOperationSse({ operation }: { operation: IR.OperationObject }): boolean { for (const statusCode in operation.responses) { const response = operation.responses[statusCode]!; if (response.mediaType === 'text/event-stream') { return true; } } return false; } ================================================ FILE: packages/openapi-ts/src/plugins/shared/utils/schema.ts ================================================ import { escapeComment, type IR } from '@hey-api/shared'; export const createSchemaComment = (schema: IR.SchemaObject): ReadonlyArray | undefined => { const comments: Array = []; if (schema.title) { comments.push(escapeComment(schema.title)); } if (schema.description) { if (comments.length) { comments.push(''); // Add an empty line between title and description } comments.push(escapeComment(schema.description)); } if (schema.deprecated) { if (comments.length) { comments.push(''); // Add an empty line before deprecated } comments.push('@deprecated'); } return comments.length ? comments : undefined; }; ================================================ FILE: packages/openapi-ts/src/plugins/swr/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { handler } from './plugin'; import type { SwrPlugin } from './types'; export const defaultConfig: SwrPlugin['Config'] = { config: { case: 'camelCase', comments: true, includeInEntry: false, }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as SwrPlugin['Handler'], name: 'swr', resolveConfig: (plugin, context) => { plugin.config.infiniteQueryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteQueryKey', tags: false, }, mappers, value: plugin.config.infiniteQueryKeys, }); plugin.config.infiniteQueryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}InfiniteOptions', }, mappers, value: plugin.config.infiniteQueryOptions, }); plugin.config.mutationOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}Mutation', }, mappers, value: plugin.config.mutationOptions, }); plugin.config.queryKeys = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: '{{name}}QueryKey', tags: false, }, mappers, value: plugin.config.queryKeys, }); plugin.config.queryOptions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, exported: true, name: '{{name}}Options', }, mappers, value: plugin.config.queryOptions, }); plugin.config.useSwr = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'use{{name}}', }, mappers: { boolean: (enabled) => ({ enabled }), function: (name) => ({ enabled: true, name }), object: (fields) => ({ enabled: true, ...fields }), string: (name) => ({ enabled: true, name }), }, value: plugin.config.useSwr, }); if (plugin.config.useSwr.enabled) { // useSwr hooks consume queryOptions if (!plugin.config.queryOptions.enabled) { plugin.config.queryOptions.enabled = true; plugin.config.queryOptions.exported = false; } } }, }; /** * Type helper for `swr` plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/swr/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { SwrPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/swr/plugin.ts ================================================ import type { SwrPlugin } from './types'; import { handlerV2 } from './v2/plugin'; export const handler: SwrPlugin['Handler'] = (args) => handlerV2(args); ================================================ FILE: packages/openapi-ts/src/plugins/swr/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, IR, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; export type UserConfig = Plugin.Name<'swr'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * @default '{{name}}InfiniteQueryKey' */ name?: NameTransformer; /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ infiniteQueryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} * * @default '{{name}}InfiniteOptions' */ name?: NameTransformer; }; /** * Configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ mutationOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} * * @default '{{name}}Mutation' */ name?: NameTransformer; }; /** * Configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryKey queryKey} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryKeys?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/guides/query-keys Query Keys} * * @default '{{name}}QueryKey' */ name?: NameTransformer; /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags?: boolean; }; /** * Configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryOptions queryOptions} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ queryOptions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Whether to export generated symbols. * * @default true */ exported?: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta?: (operation: IR.OperationObject) => Record; /** * Naming pattern for generated names. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryOptions queryOptions} * * @default '{{name}}Options' */ name?: NameTransformer; }; /** * Configuration for generated `useSwr()` function helpers. * * See {@link https://swr.vercel.app/docs/api API} * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ useSwr?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * See {@link https://swr.vercel.app/docs/api API} * * @default 'use{{name}}' */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'swr'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & { /** * Casing convention for generated names. */ case: Casing; /** * Resolved configuration for generated infinite query key helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} */ infiniteQueryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in infinite query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated infinite query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/infiniteQueryOptions infiniteQueryOptions} */ infiniteQueryOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated infinite query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated mutation options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/useMutation useMutation} */ mutationOptions: NamingOptions & FeatureToggle & { /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated mutation options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Resolved configuration for generated query keys. * * See {@link https://tanstack.com/query/v5/docs/framework/react/guides/query-keys Query Keys} */ queryKeys: NamingOptions & FeatureToggle & { /** * Whether to include operation tags in query keys. * This will make query keys larger but provides better cache invalidation capabilities. * * @default false */ tags: boolean; }; /** * Resolved configuration for generated query options helpers. * * See {@link https://tanstack.com/query/v5/docs/framework/react/reference/queryOptions queryOptions} */ queryOptions: NamingOptions & FeatureToggle & { /** * Whether to export generated symbols. * * @default true */ exported: boolean; /** * Custom function to generate metadata for the operation. * Can return any valid meta object that will be included in the generated query options. * * @param operation - The operation object containing all available metadata * @returns A meta object with any properties you want to include * * @example * ```ts * meta: (operation) => ({ * customField: operation.id, * isDeprecated: operation.deprecated, * tags: operation.tags, * customObject: { * method: operation.method, * path: operation.path * } * }) * ``` * * @default undefined */ meta: (operation: IR.OperationObject) => Record; }; /** * Configuration for generated `useSwr()` function helpers. * * See {@link https://swr.vercel.app/docs/api API} */ useSwr: NamingOptions & FeatureToggle; }; export type SwrPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/swr/v2/plugin.ts ================================================ import type { SwrPlugin } from '../types'; import { createUseSwr } from './useSwr'; export const handlerV2: SwrPlugin['Handler'] = ({ plugin }) => { plugin.symbol('useSWR', { external: 'swr', importKind: 'default', kind: 'function', meta: { category: 'external', resource: 'swr', }, }); plugin.forEach( 'operation', ({ operation }) => { if (plugin.hooks.operation.isQuery(operation)) { // if (plugin.config.queryOptions.enabled) { // createQueryOptions({ operation, plugin }); // } // if (plugin.config.infiniteQueryOptions.enabled) { // createInfiniteQueryOptions({ operation, plugin }); // } if (plugin.config.useSwr.enabled) { createUseSwr({ operation, plugin }); } } }, { order: 'declarations', }, ); }; ================================================ FILE: packages/openapi-ts/src/plugins/swr/v2/useSwr.ts ================================================ import type { IR } from '@hey-api/shared'; import { applyNaming } from '@hey-api/shared'; import { createOperationComment, hasOperationSse } from '../../../plugins/shared/utils/operation'; import type { TsDsl } from '../../../ts-dsl'; import { $ } from '../../../ts-dsl'; import type { SwrPlugin } from '../types'; export const createUseSwr = ({ operation, plugin, }: { operation: IR.OperationObject; plugin: SwrPlugin['Instance']; }): void => { if (hasOperationSse({ operation })) { return; } const symbolUseSwr = plugin.external('swr'); const symbolUseQueryFn = plugin.symbol(applyNaming(operation.id, plugin.config.useSwr)); const awaitSdkFn = $.lazy((ctx) => ctx .access( plugin.referenceSymbol({ category: 'sdk', resource: 'operation', resourceId: operation.id, }), ) .call($.object().prop('throwOnError', $.literal(true))) .await(), ); const statements: Array> = []; if (plugin.getPluginOrThrow('@hey-api/sdk').config.responseStyle === 'data') { statements.push($.return(awaitSdkFn)); } else { statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } const statement = $.const(symbolUseQueryFn) .export() .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func().do( $(symbolUseSwr) .call( $.literal(operation.path), $.func() .async() .do(...statements), ) .return(), ), ); plugin.node(statement); }; ================================================ FILE: packages/openapi-ts/src/plugins/types.ts ================================================ export type PluginClientNames = | '@hey-api/client-angular' | '@hey-api/client-axios' | '@hey-api/client-fetch' | '@hey-api/client-ky' | '@hey-api/client-next' | '@hey-api/client-nuxt' | '@hey-api/client-ofetch'; export type PluginMockNames = '@faker-js/faker'; export type PluginTransformerNames = '@hey-api/transformers'; export type PluginValidatorNames = 'arktype' | 'valibot' | 'zod'; ================================================ FILE: packages/openapi-ts/src/plugins/valibot/api.ts ================================================ import type { $ } from '../../ts-dsl'; import type { ValidatorArgs } from './shared/types'; import { createRequestValidatorV1, createResponseValidatorV1 } from './v1/api'; export type IApi = { createRequestValidator: (args: ValidatorArgs) => ReturnType | undefined; createResponseValidator: (args: ValidatorArgs) => ReturnType | undefined; }; export class Api implements IApi { createRequestValidator(args: ValidatorArgs): ReturnType | undefined { return createRequestValidatorV1(args); } createResponseValidator(args: ValidatorArgs): ReturnType | undefined { return createResponseValidatorV1(args); } } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import { Api } from './api'; import { handler } from './plugin'; import type { ValibotPlugin } from './types'; export const defaultConfig: ValibotPlugin['Config'] = { api: new Api(), config: { case: 'camelCase', comments: true, includeInEntry: false, metadata: false, }, handler, name: 'valibot', resolveConfig: (plugin, context) => { plugin.config.definitions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'v{{name}}', }, mappers, value: plugin.config.definitions, }); plugin.config.requests = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'v{{name}}Data', }, mappers, value: plugin.config.requests, }); plugin.config.responses = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'v{{name}}Response', }, mappers, value: plugin.config.responses, }); plugin.config.webhooks = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'v{{name}}WebhookRequest', }, mappers, value: plugin.config.webhooks, }); }, tags: ['validator'], }; /** * Type helper for Valibot plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/valibot/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { ValibotResolvers } from './resolvers'; export type { ValibotPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/valibot/plugin.ts ================================================ import type { ValibotPlugin } from './types'; import { handlerV1 } from './v1/plugin'; export const handler: ValibotPlugin['Handler'] = (args) => handlerV1(args); ================================================ FILE: packages/openapi-ts/src/plugins/valibot/resolvers.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR, Plugin, SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import type { MaybeBigInt, ShouldCoerceToBigInt } from '../../plugins/shared/utils/coerce'; import type { GetIntegerLimit } from '../../plugins/shared/utils/formats'; import type { $, DollarTsDsl } from '../../ts-dsl'; import type { Pipe, PipeResult, Pipes, PipesUtils } from './shared/pipes'; import type { ValibotFinal, ValibotResult } from './shared/types'; import type { ValibotPlugin } from './types'; export type ValibotResolvers = Plugin.Resolvers<{ /** * Resolver for array schemas. * * Allows customization of how array types are rendered. * * Returning `undefined` will execute the default resolver logic. */ array?: (ctx: ArrayResolverContext) => PipeResult; /** * Resolver for boolean schemas. * * Allows customization of how boolean types are rendered. * * Returning `undefined` will execute the default resolver logic. */ boolean?: (ctx: BooleanResolverContext) => PipeResult; /** * Resolver for enum schemas. * * Allows customization of how enum types are rendered. * * Returning `undefined` will execute the default resolver logic. */ enum?: (ctx: EnumResolverContext) => PipeResult; /** * Resolver for intersection schemas. * * Allows customization of how intersection types are rendered. * * Returning `undefined` will execute the default resolver logic. */ intersection?: (ctx: IntersectionResolverContext) => PipeResult; /** * Resolver for never schemas. * * Allows customization of how never types are rendered. * * Returning `undefined` will execute the default resolver logic. */ never?: (ctx: NeverResolverContext) => PipeResult; /** * Resolver for null schemas. * * Allows customization of how null types are rendered. * * Returning `undefined` will execute the default resolver logic. */ null?: (ctx: NullResolverContext) => PipeResult; /** * Resolver for number schemas. * * Allows customization of how number types are rendered. * * Returning `undefined` will execute the default resolver logic. */ number?: (ctx: NumberResolverContext) => PipeResult; /** * Resolver for object schemas. * * Allows customization of how object types are rendered. * * Returning `undefined` will execute the default resolver logic. */ object?: (ctx: ObjectResolverContext) => PipeResult; /** * Resolver for string schemas. * * Allows customization of how string types are rendered. * * Returning `undefined` will execute the default resolver logic. */ string?: (ctx: StringResolverContext) => PipeResult; /** * Resolver for tuple schemas. * * Allows customization of how tuple types are rendered. * * Returning `undefined` will execute the default resolver logic. */ tuple?: (ctx: TupleResolverContext) => PipeResult; /** * Resolver for undefined schemas. * * Allows customization of how undefined types are rendered. * * Returning `undefined` will execute the default resolver logic. */ undefined?: (ctx: UndefinedResolverContext) => PipeResult; /** * Resolver for union schemas. * * Allows customization of how union types are rendered. * * Returning `undefined` will execute the default resolver logic. */ union?: (ctx: UnionResolverContext) => PipeResult; /** * Resolver for unknown schemas. * * Allows customization of how unknown types are rendered. * * Returning `undefined` will execute the default resolver logic. */ unknown?: (ctx: UnknownResolverContext) => PipeResult; /** * Resolvers for request and response validators. * * Allow customization of validator function bodies. * * Example path: `~resolvers.validator.request` or `~resolvers.validator.response` * * Returning `undefined` will execute the default resolver logic. */ validator?: | ValidatorResolver | { /** * Controls how the request validator function body is generated. * * Returning `undefined` will execute the default resolver logic. */ request?: ValidatorResolver; /** * Controls how the response validator function body is generated. * * Returning `undefined` will execute the default resolver logic. */ response?: ValidatorResolver; }; /** * Resolver for void schemas. * * Allows customization of how void types are rendered. * * Returning `undefined` will execute the default resolver logic. */ void?: (ctx: VoidResolverContext) => PipeResult; }>; type ValidatorResolver = (ctx: ValidatorResolverContext) => PipeResult | null | undefined; interface BaseContext extends DollarTsDsl { /** * Functions for working with pipes. */ pipes: PipesUtils & { /** * The current pipe. * * In Valibot, this represents a list of call expressions ("pipes") * being assembled to form a schema definition. * * Each pipe can be extended, modified, or replaced to customize * the resulting schema. */ current: Pipes; }; /** The plugin instance. */ plugin: ValibotPlugin['Instance']; /** * Provides access to commonly used symbols within the plugin. */ symbols: { v: Symbol; }; } export interface ArrayResolverContext extends BaseContext { applyModifiers: (result: ValibotResult, opts?: { optional?: boolean }) => ValibotFinal; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: ArrayResolverContext) => PipeResult; length: (ctx: ArrayResolverContext) => PipeResult; maxLength: (ctx: ArrayResolverContext) => PipeResult; minLength: (ctx: ArrayResolverContext) => PipeResult; }; schema: SchemaWithType<'array'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface BooleanResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: BooleanResolverContext) => PipeResult; const: (ctx: BooleanResolverContext) => PipeResult; }; schema: SchemaWithType<'boolean'>; } export interface EnumResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base enum expression (v.picklist([...])). */ base: (ctx: EnumResolverContext) => PipeResult; /** * Returns parsed enum items with metadata about the enum members. */ items: (ctx: EnumResolverContext) => { /** * String literal values for use with v.picklist([...]). */ enumMembers: Array>; /** * Whether the enum includes a null value. */ isNullable: boolean; }; }; schema: SchemaWithType<'enum'>; } export interface IntersectionResolverContext extends BaseContext { applyModifiers: (result: ValibotResult, opts?: { optional?: boolean }) => ValibotFinal; childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: IntersectionResolverContext) => PipeResult; }; parentSchema: IR.SchemaObject; schema: IR.SchemaObject; } export interface NeverResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: NeverResolverContext) => PipeResult; }; schema: SchemaWithType<'never'>; } export interface NullResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: NullResolverContext) => PipeResult; }; schema: SchemaWithType<'null'>; } export interface NumberResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: NumberResolverContext) => PipeResult; const: (ctx: NumberResolverContext) => PipeResult; max: (ctx: NumberResolverContext) => PipeResult; min: (ctx: NumberResolverContext) => PipeResult; }; schema: SchemaWithType<'integer' | 'number'>; /** * Utility functions for number schema processing. */ utils: { getIntegerLimit: GetIntegerLimit; maybeBigInt: MaybeBigInt; shouldCoerceToBigInt: ShouldCoerceToBigInt; }; } export interface ObjectResolverContext extends BaseContext { _childResults: Array; applyModifiers: (result: ValibotResult, opts: { optional?: boolean }) => ValibotFinal; /** * Nodes used to build different parts of the result. */ nodes: { additionalProperties: (ctx: ObjectResolverContext) => Pipe | null | undefined; base: (ctx: ObjectResolverContext) => Pipes | Pipe; shape: (ctx: ObjectResolverContext) => ReturnType; }; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface StringResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: StringResolverContext) => PipeResult; const: (ctx: StringResolverContext) => PipeResult; format: (ctx: StringResolverContext) => PipeResult; length: (ctx: StringResolverContext) => PipeResult; maxLength: (ctx: StringResolverContext) => PipeResult; minLength: (ctx: StringResolverContext) => PipeResult; pattern: (ctx: StringResolverContext) => PipeResult; }; schema: SchemaWithType<'string'>; } export interface TupleResolverContext extends BaseContext { applyModifiers: (result: ValibotResult, opts?: { optional?: boolean }) => ValibotFinal; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: TupleResolverContext) => PipeResult; const: (ctx: TupleResolverContext) => PipeResult; }; schema: SchemaWithType<'tuple'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface UndefinedResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: UndefinedResolverContext) => PipeResult; }; schema: SchemaWithType<'undefined'>; } export interface UnionResolverContext extends BaseContext { applyModifiers: (result: ValibotResult, opts?: { optional?: boolean }) => ValibotFinal; childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: UnionResolverContext) => PipeResult; }; parentSchema: IR.SchemaObject; schema: IR.SchemaObject; schemas: ReadonlyArray; } export interface UnknownResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: UnknownResolverContext) => PipeResult; }; schema: SchemaWithType<'unknown'>; } export interface ValidatorResolverContext extends BaseContext { operation: IR.OperationObject; /** * Provides access to commonly used symbols within the plugin. */ symbols: BaseContext['symbols'] & { schema: Symbol; }; } export interface VoidResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { base: (ctx: VoidResolverContext) => PipeResult; }; schema: SchemaWithType<'void'>; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/export.ts ================================================ import { buildSymbolIn, pathToName } from '@hey-api/shared'; import { createSchemaComment } from '../../../plugins/shared/utils/schema'; import { $ } from '../../../ts-dsl'; import { pipesToNode } from './pipes'; import type { ProcessorContext } from './processor'; import type { ValibotFinal } from './types'; export function exportAst({ final, meta, naming, namingAnchor, path, plugin, schema, tags, }: ProcessorContext & { final: ValibotFinal; }): void { const v = plugin.external('valibot.v'); const name = pathToName(path, { anchor: namingAnchor }); const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'schema', path, tags, tool: 'valibot', ...meta, }, name, naming, plugin, schema, }), ); const statement = $.const(symbol) .export() .$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)) .$if(final.typeName, (c) => c.type($.type(v).attr(final.typeName!))) .assign(pipesToNode(final.pipes, plugin)); plugin.node(statement); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/meta.ts ================================================ import type { IR } from '@hey-api/shared'; import type { ValibotMeta, ValibotResult } from './types'; /** * Creates default metadata from a schema. */ export function defaultMeta(schema: IR.SchemaObject): ValibotMeta { return { default: schema.default, format: schema.format, hasLazy: false, nullable: false, readonly: schema.accessScope === 'read', }; } /** * Composes metadata from child results. * * @param children - Results from walking child schemas * @param overrides - Explicit overrides (e.g., from parent schema) */ export function composeMeta( children: ReadonlyArray, overrides?: Partial, ): ValibotMeta { return { default: overrides?.default, format: overrides?.format, hasLazy: overrides?.hasLazy ?? children.some((c) => c.meta.hasLazy), nullable: overrides?.nullable ?? children.some((c) => c.meta.nullable), readonly: overrides?.readonly ?? children.some((c) => c.meta.readonly), }; } /** * Merges parent schema metadata with composed child metadata. * * @param parent - The parent schema * @param children - Results from walking child schemas */ export function inheritMeta( parent: IR.SchemaObject, children: ReadonlyArray, ): ValibotMeta { return composeMeta(children, { default: parent.default, format: parent.format, nullable: false, readonly: parent.accessScope === 'read', }); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/operation-schema.ts ================================================ import type { IR } from '@hey-api/shared'; export interface OperationSchemaResult { required: ReadonlyArray; schema: IR.SchemaObject; } export function buildOperationSchema(operation: IR.OperationObject): OperationSchemaResult { const requiredProperties = new Set(); const schema: IR.SchemaObject = { properties: { body: { type: 'never' }, path: { type: 'never' }, query: { type: 'never' }, }, type: 'object', }; if (operation.parameters) { // TODO: add support for cookies for (const location of ['header', 'path', 'query'] satisfies ReadonlyArray< keyof typeof operation.parameters >) { const params = operation.parameters[location]; if (!params) continue; const properties: Record = {}; const required: Array = []; const propKey = location === 'header' ? 'headers' : location; for (const key in params) { const parameter = params[key]!; properties[parameter.name] = parameter.schema; if (parameter.required) { required.push(parameter.name); requiredProperties.add(propKey); } } if (Object.keys(properties).length) { schema.properties![propKey] = { properties, required, type: 'object' }; } } } if (operation.body) { schema.properties!.body = operation.body.schema; if (operation.body.required) { requiredProperties.add('body'); } } schema.required = [...requiredProperties]; return { required: schema.required, schema }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/operation.ts ================================================ import type { IR } from '@hey-api/shared'; import { operationResponsesMap } from '@hey-api/shared'; import { buildOperationSchema } from './operation-schema'; import type { ProcessorContext, ProcessorResult } from './processor'; export function irOperationToAst({ operation, path, plugin, processor, tags, }: Pick & { operation: IR.OperationObject; processor: ProcessorResult; }): void { if (plugin.config.requests.enabled) { const { schema } = buildOperationSchema(operation); processor.process({ meta: { resource: 'operation', resourceId: operation.id, role: 'data', }, naming: plugin.config.requests, namingAnchor: operation.id, path, plugin, schema, tags, }); } if (plugin.config.responses.enabled) { if (operation.responses) { const { response } = operationResponsesMap(operation); if (response) { processor.process({ meta: { resource: 'operation', resourceId: operation.id, role: 'responses', }, naming: plugin.config.responses, namingAnchor: operation.id, path: [...path, 'responses'], plugin, schema: response, tags, }); } } } } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/pipes.ts ================================================ import { $ } from '../../../ts-dsl'; import type { ValibotPlugin } from '../types'; import { identifiers } from '../v1/constants'; export type Pipe = ReturnType; export type Pipes = Array; export type PipeResult = Pipes | Pipe | undefined; export interface PipesUtils { /** * Pushes a pipe result onto a pipes array. * * Handles single pipes, arrays of pipes, and undefined. */ push: (target: Pipes, result: PipeResult) => Pipes; /** * Converts a pipes array to a single node expression. */ toNode: (pipes: Pipes | Pipe, plugin: ValibotPlugin['Instance']) => Pipe; } function push(target: Pipes, result: PipeResult): Pipes { if (result === undefined) { return target; } if (result instanceof Array) { target.push(...result); } else { target.push(result); } return target; } function toNode(pipes: Pipes | Pipe, plugin: ValibotPlugin['Instance']): Pipe { if (!(pipes instanceof Array)) { return pipes; } if (pipes.length === 0) { const v = plugin.external('valibot.v'); return $(v).attr(identifiers.schemas.unknown).call(); } if (pipes.length === 1) { return pipes[0]!; } const v = plugin.external('valibot.v'); return $(v) .attr(identifiers.methods.pipe) .call(...pipes); } /** * Functions for working with pipes. */ export const pipes: PipesUtils = { push, toNode, }; /** * Convenience function for converting pipes to a node. * * Re-exported for backward compatibility. */ export function pipesToNode(pipes: Pipes | Pipe, plugin: ValibotPlugin['Instance']): Pipe { return toNode(pipes, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/processor.ts ================================================ import type { IR, NamingConfig, SchemaProcessorContext } from '@hey-api/shared'; import type { ValibotPlugin } from '../types'; import type { ValibotFinal } from './types'; export type ProcessorContext = SchemaProcessorContext & { /** Whether to export the result (default: true) */ export?: boolean; naming: NamingConfig; /** The plugin instance. */ plugin: ValibotPlugin['Instance']; schema: IR.SchemaObject; }; export type ProcessorResult = { process: (ctx: ProcessorContext) => ValibotFinal | void; }; ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/types.ts ================================================ import type { IR } from '@hey-api/shared'; import type ts from 'typescript'; import type { ValibotPlugin } from '../types'; import type { Pipes } from './pipes'; export type ValidatorArgs = { operation: IR.OperationObject; /** The plugin instance. */ plugin: ValibotPlugin['Instance']; }; /** * Metadata that flows through schema walking. */ export interface ValibotMeta { /** Default value from schema. */ default?: unknown; /** Original format (for BigInt coercion). */ format?: string; /** Whether this or any child contains a lazy reference. */ hasLazy: boolean; /** Does this schema explicitly allow null? */ nullable: boolean; /** Is this schema read-only? */ readonly: boolean; } /** * Result from walking a schema node. */ export interface ValibotResult { meta: ValibotMeta; pipes: Pipes; } /** * Finalized result after applyModifiers. */ export interface ValibotFinal extends Pick { /** Type annotation for schemas requiring explicit typing (e.g., lazy). */ typeName?: string | ts.Identifier; } /** * Result from composite handlers that walk children. */ export interface CompositeHandlerResult { childResults: Array; pipes: Pipes; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/shared/webhook.ts ================================================ import type { IR } from '@hey-api/shared'; import { buildOperationSchema } from './operation-schema'; import type { ProcessorContext, ProcessorResult } from './processor'; export function irWebhookToAst({ operation, path, plugin, processor, tags, }: Pick & { operation: IR.OperationObject; processor: ProcessorResult; }): void { if (plugin.config.webhooks.enabled) { const { schema } = buildOperationSchema(operation); processor.process({ meta: { resource: 'webhook', resourceId: operation.id, role: 'data', }, naming: plugin.config.webhooks, namingAnchor: operation.id, path, plugin, schema, tags, }); } } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, IR, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; import type { $, DollarTsDsl } from '../../ts-dsl'; import type { IApi } from './api'; import type { ValibotResolvers } from './resolvers'; export type UserConfig = Plugin.Name<'valibot'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & ValibotResolvers & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Configuration for reusable schema definitions. * * Controls generation of shared Valibot schemas that can be referenced * across requests and responses. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ definitions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'v{{name}}' */ name?: NameTransformer; }; /** * Enable Valibot metadata support? It's often useful to associate a schema * with some additional metadata for documentation, code generation, AI * structured outputs, form validation, and other purposes. * * Can be: * - `boolean`: Shorthand for the default metadata builder. When `true`, * attaches `{ description }` from the schema (if present) to the * generated Valibot schema via the metadata action. * - `function`: Custom metadata builder. Receives `{ $, node, schema }`, * where `node` is a pre-initialized `$.object()` node. Add properties to * `node` to populate the metadata object. Return value is ignored; an * empty `node` skips metadata for that schema. * * @default false */ metadata?: | boolean | (( ctx: DollarTsDsl & { node: ReturnType; schema: IR.SchemaObject }, ) => void); /** * Configuration for request-specific Valibot schemas. * * Controls generation of Valibot schemas for request bodies, query * parameters, path parameters, and headers. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ requests?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'v{{name}}Data' */ name?: NameTransformer; }; /** * Configuration for response-specific Valibot schemas. * * Controls generation of Valibot schemas for response bodies, error * responses, and status codes. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ responses?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'v{{name}}Response' */ name?: NameTransformer; }; /** * Configuration for webhook-specific Valibot schemas. * * Controls generation of Valibot schemas for webhook payloads. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ webhooks?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'v{{name}}WebhookRequest' */ name?: NameTransformer; }; }; export type Config = Plugin.Name<'valibot'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & ValibotResolvers & { /** Casing convention for generated names. */ case: Casing; /** Configuration for reusable schema definitions. */ definitions: NamingOptions & FeatureToggle; /** Enable Valibot metadata support? */ metadata: | boolean | (( ctx: DollarTsDsl & { node: ReturnType; schema: IR.SchemaObject }, ) => void); /** Configuration for request-specific Valibot schemas. */ requests: NamingOptions & FeatureToggle; /** Configuration for response-specific Valibot schemas. */ responses: NamingOptions & FeatureToggle; /** Configuration for webhook-specific Valibot schemas. */ webhooks: NamingOptions & FeatureToggle; }; export type ValibotPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/api.ts ================================================ import { $ } from '../../../ts-dsl'; import type { ValidatorResolverContext } from '../resolvers'; import { pipes } from '../shared/pipes'; import type { ValidatorArgs } from '../shared/types'; import { identifiers } from './constants'; const validatorResolver = (ctx: ValidatorResolverContext): ReturnType => { const { schema, v } = ctx.symbols; return $(v).attr(identifiers.async.parseAsync).call(schema, 'data').await().return(); }; export const createRequestValidatorV1 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'valibot', }); if (!symbol) return; const ctx: ValidatorResolverContext = { $, operation, pipes: { ...pipes, current: [], }, plugin, symbols: { schema: symbol, v: plugin.external('valibot.v'), }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.request; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } }; export const createResponseValidatorV1 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'responses', tool: 'valibot', }); if (!symbol) return; const ctx: ValidatorResolverContext = { $, operation, pipes: { ...pipes, current: [], }, plugin, symbols: { schema: symbol, v: plugin.external('valibot.v'), }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.response; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } }; ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/constants.ts ================================================ export const identifiers = { /** * {@link https://valibot.dev/api/#actions Actions} */ actions: { args: 'args', base64: 'base64', bic: 'bic', brand: 'brand', bytes: 'bytes', check: 'check', checkItems: 'checkItems', creditCard: 'creditCard', cuid2: 'cuid2', decimal: 'decimal', description: 'description', digits: 'digits', email: 'email', emoji: 'emoji', empty: 'empty', endsWith: 'endsWith', entries: 'entries', everyItem: 'everyItem', excludes: 'excludes', filterItems: 'filterItems', findItem: 'findItem', finite: 'finite', flavor: 'flavor', graphemes: 'graphemes', gtValue: 'gtValue', hash: 'hash', hexColor: 'hexColor', hexadecimal: 'hexadecimal', imei: 'imei', includes: 'includes', integer: 'integer', ip: 'ip', ipv4: 'ipv4', ipv6: 'ipv6', isoDate: 'isoDate', isoDateTime: 'isoDateTime', isoTime: 'isoTime', isoTimeSecond: 'isoTimeSecond', isoTimestamp: 'isoTimestamp', isoWeek: 'isoWeek', length: 'length', ltValue: 'ltValue', mac: 'mac', mac48: 'mac48', mac64: 'mac64', mapItems: 'mapItems', maxBytes: 'maxBytes', maxEntries: 'maxEntries', maxGraphemes: 'maxGraphemes', maxLength: 'maxLength', maxSize: 'maxSize', maxValue: 'maxValue', maxWords: 'maxWords', metadata: 'metadata', mimeType: 'mimeType', minBytes: 'minBytes', minEntries: 'minEntries', minGraphemes: 'minGraphemes', minLength: 'minLength', minSize: 'minSize', minValue: 'minValue', minWords: 'minWords', multipleOf: 'multipleOf', nanoid: 'nanoid', nonEmpty: 'nonEmpty', normalize: 'normalize', notBytes: 'notBytes', notEntries: 'notEntries', notGraphemes: 'notGraphemes', notLength: 'notLength', notSize: 'notSize', notValue: 'notValue', notValues: 'notValues', notWords: 'notWords', octal: 'octal', parseJson: 'parseJson', partialCheck: 'partialCheck', rawCheck: 'rawCheck', rawTransform: 'rawTransform', readonly: 'readonly', reduceItems: 'reduceItems', regex: 'regex', returns: 'returns', rfcEmail: 'rfcEmail', safeInteger: 'safeInteger', size: 'size', slug: 'slug', someItem: 'someItem', sortItems: 'sortItems', startsWith: 'startsWith', stringifyJson: 'stringifyJson', title: 'title', toLowerCase: 'toLowerCase', toMaxValue: 'toMaxValue', toMinValue: 'toMinValue', toUpperCase: 'toUpperCase', transform: 'transform', trim: 'trim', trimEnd: 'trimEnd', trimStart: 'trimStart', ulid: 'ulid', url: 'url', uuid: 'uuid', value: 'value', values: 'values', words: 'words', }, /** * {@link https://valibot.dev/api/#async Async} */ async: { argsAsync: 'argsAsync', arrayAsync: 'arrayAsync', awaitAsync: 'awaitAsync', checkAsync: 'checkAsync', checkItemsAsync: 'checkItemsAsync', customAsync: 'customAsync', exactOptionalAsync: 'exactOptionalAsync', fallbackAsync: 'fallbackAsync', forwardAsync: 'forwardAsync', getDefaultsAsync: 'getDefaultsAsync', getFallbacksAsync: 'getFallbacksAsync', intersectAsync: 'intersectAsync', lazyAsync: 'lazyAsync', looseObjectAsync: 'looseObjectAsync', looseTupleAsync: 'looseTupleAsync', mapAsync: 'mapAsync', nonNullableAsync: 'nonNullableAsync', nonNullishAsync: 'nonNullishAsync', nonOptionalAsync: 'nonOptionalAsync', nullableAsync: 'nullableAsync', nullishAsync: 'nullishAsync', objectAsync: 'objectAsync', objectWithRestAsync: 'objectWithRestAsync', optionalAsync: 'optionalAsync', parseAsync: 'parseAsync', parserAsync: 'parserAsync', partialAsync: 'partialAsync', partialCheckAsync: 'partialCheckAsync', pipeAsync: 'pipeAsync', rawCheckAsync: 'rawCheckAsync', rawTransformAsync: 'rawTransformAsync', recordAsync: 'recordAsync', requiredAsync: 'requiredAsync', returnsAsync: 'returnsAsync', safeParseAsync: 'safeParseAsync', safeParserAsync: 'safeParserAsync', setAsync: 'setAsync', strictObjectAsync: 'strictObjectAsync', strictTupleAsync: 'strictTupleAsync', transformAsync: 'transformAsync', tupleAsync: 'tupleAsync', tupleWithRestAsync: 'tupleWithRestAsync', undefinedableAsync: 'undefinedableAsync', unionAsync: 'unionAsync', variantAsync: 'variantAsync', }, /** * {@link https://valibot.dev/api/#methods Methods} */ methods: { assert: 'assert', config: 'config', fallback: 'fallback', flatten: 'flatten', forward: 'forward', getDefault: 'getDefault', getDefaults: 'getDefaults', getDescription: 'getDescription', getFallback: 'getFallback', getFallbacks: 'getFallbacks', getMetadata: 'getMetadata', getTitle: 'getTitle', is: 'is', keyof: 'keyof', message: 'message', omit: 'omit', parse: 'parse', parser: 'parser', partial: 'partial', pick: 'pick', pipe: 'pipe', required: 'required', safeParse: 'safeParse', safeParser: 'safeParser', summarize: 'summarize', unwrap: 'unwrap', }, /** * {@link https://valibot.dev/api/#schemas Schemas} */ schemas: { any: 'any', array: 'array', bigInt: 'bigint', blob: 'blob', boolean: 'boolean', custom: 'custom', date: 'date', enum: 'enum', exactOptional: 'exactOptional', file: 'file', function: 'function', instance: 'instance', intersect: 'intersect', lazy: 'lazy', literal: 'literal', looseObject: 'looseObject', looseTuple: 'looseTuple', map: 'map', nan: 'nan', never: 'never', nonNullable: 'nonNullable', nonNullish: 'nonNullish', nonOptional: 'nonOptional', null: 'null', nullable: 'nullable', nullish: 'nullish', number: 'number', object: 'object', objectWithRest: 'objectWithRest', optional: 'optional', picklist: 'picklist', promise: 'promise', record: 'record', set: 'set', strictObject: 'strictObject', strictTuple: 'strictTuple', string: 'string', symbol: 'symbol', tuple: 'tuple', tupleWithRest: 'tupleWithRest', undefined: 'undefined', undefinedable: 'undefinedable', union: 'union', unknown: 'unknown', variant: 'variant', void: 'void', }, /** * {@link https://valibot.dev/api/#storages Storages} */ storages: { // TODO: implement if necessary }, /** * {@link https://valibot.dev/api/#types Types} */ types: { // TODO: implement if necessary GenericSchema: 'GenericSchema', }, /** * {@link https://valibot.dev/api/#utils Utils} */ utils: { // TODO: implement if necessary }, }; ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/plugin.ts ================================================ import { pathToJsonPointer } from '@hey-api/shared'; import { irOperationToAst } from '../shared/operation'; import { irWebhookToAst } from '../shared/webhook'; import type { ValibotPlugin } from '../types'; import { createProcessor } from './processor'; export const handlerV1: ValibotPlugin['Handler'] = ({ plugin }) => { plugin.symbol('v', { external: 'valibot', importKind: 'namespace', meta: { category: 'external', resource: 'valibot.v', }, }); const processor = createProcessor(plugin); plugin.forEach('operation', 'parameter', 'requestBody', 'schema', 'webhook', (event) => { switch (event.type) { case 'operation': irOperationToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; case 'parameter': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.parameter.schema, tags: event.tags, }); break; case 'requestBody': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.requestBody.schema, tags: event.tags, }); break; case 'schema': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.schema, tags: event.tags, }); break; case 'webhook': irWebhookToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; } }); }; ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/processor.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { Hooks, IR } from '@hey-api/shared'; import { createSchemaProcessor, createSchemaWalker, pathToJsonPointer } from '@hey-api/shared'; import { exportAst } from '../shared/export'; import type { ProcessorContext, ProcessorResult } from '../shared/processor'; import type { ValibotFinal } from '../shared/types'; import type { ValibotPlugin } from '../types'; import { createVisitor } from './walker'; export function createProcessor(plugin: ValibotPlugin['Instance']): ProcessorResult { const processor = createSchemaProcessor(); const extractorHooks: ReadonlyArray['shouldExtract']> = [ plugin.config['~hooks']?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract, ]; function extractor(ctx: ProcessorContext): IR.SchemaObject { if (processor.hasEmitted(ctx.path)) { return ctx.schema; } for (const hook of extractorHooks) { const result = hook?.(ctx); if (result) { process({ namingAnchor: processor.context.anchor, tags: processor.context.tags, ...ctx, }); return { $ref: pathToJsonPointer(ctx.path) }; } } return ctx.schema; } function process(ctx: ProcessorContext): ValibotFinal | void { if (!processor.markEmitted(ctx.path)) return; const shouldExport = ctx.export !== false; return processor.withContext({ anchor: ctx.namingAnchor, tags: ctx.tags }, () => { const visitor = createVisitor({ schemaExtractor: extractor }); const walk = createSchemaWalker(visitor); const result = walk(ctx.schema, { path: ref(ctx.path), plugin, }); const final = visitor.applyModifiers(result, { path: ref(ctx.path), plugin, }) as ValibotFinal; if (shouldExport) { exportAst({ ...ctx, final, plugin }); return; } return final; }); } return { process }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/array.ts ================================================ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext, deduplicateSchema } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { ArrayResolverContext } from '../../resolvers'; import type { PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { CompositeHandlerResult, ValibotFinal, ValibotResult } from '../../shared/types'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; import { unknownToPipes } from './unknown'; interface ArrayToPipesContext { applyModifiers: (result: ValibotResult, options?: { optional?: boolean }) => ValibotFinal; plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'array'>; walk: Walker; walkerCtx: SchemaVisitorContext; } function baseNode(ctx: ArrayResolverContext): PipeResult { const { plugin, symbols } = ctx; const { v } = symbols; const arrayFn = $(v).attr(identifiers.schemas.array); let { schema: normalizedSchema } = ctx; if (normalizedSchema.items) { normalizedSchema = deduplicateSchema({ schema: normalizedSchema }); } if (!normalizedSchema.items) { return arrayFn.call(unknownToPipes({ plugin })); } const childResults: Array = []; const { applyModifiers, pipes, walk, walkerCtx } = ctx; for (let i = 0; i < normalizedSchema.items!.length; i++) { const item = normalizedSchema.items![i]!; const result = walk!(item, childContext(walkerCtx!, 'items', i)); childResults.push(result); } if (childResults.length === 1) { const itemNode = pipes.toNode(applyModifiers!(childResults[0]!).pipes, plugin); return arrayFn.call(itemNode); } return arrayFn.call(unknownToPipes({ plugin })); } function lengthNode(ctx: ArrayResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.minItems === schema.maxItems && schema.minItems !== undefined) { return $(v).attr(identifiers.actions.length).call($.fromValue(schema.minItems)); } } function maxLengthNode(ctx: ArrayResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.maxItems === undefined) return; return $(v).attr(identifiers.actions.maxLength).call($.fromValue(schema.maxItems)); } function minLengthNode(ctx: ArrayResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.minItems === undefined) return; return $(v).attr(identifiers.actions.minLength).call($.fromValue(schema.minItems)); } function arrayResolver(ctx: ArrayResolverContext): Pipes { const baseResult = ctx.nodes.base(ctx); if (baseResult) { ctx.pipes.push(ctx.pipes.current, baseResult); } const lengthResult = ctx.nodes.length(ctx); if (lengthResult) { ctx.pipes.push(ctx.pipes.current, lengthResult); } else { const minLengthResult = ctx.nodes.minLength(ctx); if (minLengthResult) { ctx.pipes.push(ctx.pipes.current, minLengthResult); } const maxLengthResult = ctx.nodes.maxLength(ctx); if (maxLengthResult) { ctx.pipes.push(ctx.pipes.current, maxLengthResult); } } return ctx.pipes.current; } export function arrayToPipes(ctx: ArrayToPipesContext): CompositeHandlerResult { const { plugin, schema, walk, walkerCtx } = ctx; const childResults: Array = []; if (schema.items) { const normalizedSchema = deduplicateSchema({ schema }); for (let i = 0; i < normalizedSchema.items!.length; i++) { const item = normalizedSchema.items![i]!; const result = walk(item, childContext(walkerCtx, 'items', i)); childResults.push(result); } } const resolverCtx: ArrayResolverContext = { $, applyModifiers: ctx.applyModifiers, nodes: { base: baseNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.array; const node = resolver?.(resolverCtx) ?? arrayResolver(resolverCtx); return { childResults, pipes: [resolverCtx.pipes.toNode(node, plugin)], }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/boolean.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { BooleanResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: BooleanResolverContext): PipeResult { const { symbols } = ctx; const { v } = symbols; return $(v).attr(identifiers.schemas.boolean).call(); } function constNode(ctx: BooleanResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (typeof schema.const !== 'boolean') return; return $(v).attr(identifiers.schemas.literal).call($.literal(schema.const)); } function booleanResolver(ctx: BooleanResolverContext): Pipes { const constResult = ctx.nodes.const(ctx); if (constResult) { return ctx.pipes.push(ctx.pipes.current, constResult); } const baseResult = ctx.nodes.base(ctx); if (baseResult) { ctx.pipes.push(ctx.pipes.current, baseResult); } return ctx.pipes.current; } export function booleanToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'boolean'>; }): Pipe { const ctx: BooleanResolverContext = { $, nodes: { base: baseNode, const: constNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.boolean; const node = resolver?.(ctx) ?? booleanResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/enum.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { EnumResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; import { unknownToPipes } from './unknown'; function itemsNode(ctx: EnumResolverContext): ReturnType { const { schema } = ctx; const enumMembers: Array> = []; let isNullable = false; for (const item of schema.items ?? []) { if (item.type === 'string' && typeof item.const === 'string') { enumMembers.push($.literal(item.const)); } else if (item.type === 'null' || item.const === null) { isNullable = true; } } return { enumMembers, isNullable }; } function baseNode(ctx: EnumResolverContext): PipeResult { const { symbols } = ctx; const { v } = symbols; const { enumMembers } = ctx.nodes.items(ctx); return $(v) .attr(identifiers.schemas.picklist) .call($.array(...enumMembers)); } function enumResolver(ctx: EnumResolverContext): Pipes { const { enumMembers } = ctx.nodes.items(ctx); if (!enumMembers.length) { return ctx.pipes.current; } const baseExpression = ctx.nodes.base(ctx); ctx.pipes.push(ctx.pipes.current, baseExpression); return ctx.pipes.current; } export interface EnumToPipesResult { isNullable: boolean; pipe: Pipe; } export function enumToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'enum'>; }): EnumToPipesResult { const v = plugin.external('valibot.v'); const { enumMembers, isNullable } = itemsNode({ $, nodes: { base: baseNode, items: itemsNode }, pipes: { ...pipes, current: [] }, plugin, schema, symbols: { v }, }); if (!enumMembers.length) { return { isNullable, pipe: unknownToPipes({ plugin }), }; } const ctx: EnumResolverContext = { $, nodes: { base: baseNode, items: itemsNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v }, }; const resolver = plugin.config['~resolvers']?.enum; const node = resolver?.(ctx) ?? enumResolver(ctx); return { isNullable, pipe: ctx.pipes.toNode(node, plugin), }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/intersection.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { IntersectionResolverContext } from '../../resolvers'; import type { PipeResult, Pipes } from '../../shared/pipes'; import { pipes, pipesToNode } from '../../shared/pipes'; import type { CompositeHandlerResult, ValibotFinal, ValibotResult } from '../../shared/types'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: IntersectionResolverContext): PipeResult { const { applyModifiers, childResults, plugin, symbols } = ctx; const { v } = symbols; if (childResults.length === 0) { return $(v).attr(identifiers.schemas.any).call(); } if (childResults.length === 1) { const finalResult = applyModifiers!(childResults[0]!); return finalResult.pipes; } const itemNodes = childResults.map((item) => pipesToNode(item.pipes, plugin)); return $(v) .attr(identifiers.schemas.intersect) .call($.array(...itemNodes)); } function intersectionResolver(ctx: IntersectionResolverContext): Pipes { const base = ctx.nodes.base(ctx); if (base) { ctx.pipes.push(ctx.pipes.current, base); } return ctx.pipes.current; } export function intersectionToPipes(ctx: { applyModifiers: (result: ValibotResult, options?: { optional?: boolean }) => ValibotFinal; childResults: Array; parentSchema: IR.SchemaObject; plugin: ValibotPlugin['Instance']; }): CompositeHandlerResult { const { applyModifiers, childResults, parentSchema, plugin } = ctx; const resolverCtx: IntersectionResolverContext = { $, applyModifiers, childResults, nodes: { base: baseNode, }, parentSchema, pipes: { ...pipes, current: [], }, plugin, schema: parentSchema, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.intersection; const node = resolver?.(resolverCtx) ?? intersectionResolver(resolverCtx); return { childResults, pipes: [resolverCtx.pipes.toNode(node, plugin)], }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/never.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { NeverResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: NeverResolverContext): PipeResult { const { symbols } = ctx; const { v } = symbols; return $(v).attr(identifiers.schemas.never).call(); } function neverResolver(ctx: NeverResolverContext): Pipes { const base = ctx.nodes.base(ctx); ctx.pipes.push(ctx.pipes.current, base); return ctx.pipes.current; } export function neverToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'never'>; }): Pipe { const ctx: NeverResolverContext = { $, nodes: { base: baseNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.never; const node = resolver?.(ctx) ?? neverResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/null.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { NullResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: NullResolverContext): PipeResult { const { symbols } = ctx; const { v } = symbols; return $(v).attr(identifiers.schemas.null).call(); } function nullResolver(ctx: NullResolverContext): Pipes { const base = ctx.nodes.base(ctx); ctx.pipes.push(ctx.pipes.current, base); return ctx.pipes.current; } export function nullToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'null'>; }): Pipe { const ctx: NullResolverContext = { $, nodes: { base: baseNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.null; const node = resolver?.(ctx) ?? nullResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/number.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { maybeBigInt, shouldCoerceToBigInt } from '../../../../plugins/shared/utils/coerce'; import { getIntegerLimit } from '../../../../plugins/shared/utils/formats'; import { $ } from '../../../../ts-dsl'; import type { NumberResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: NumberResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (ctx.utils.shouldCoerceToBigInt(schema.format)) { return [ $(v) .attr(identifiers.schemas.union) .call( $.array( $(v).attr(identifiers.schemas.number).call(), $(v).attr(identifiers.schemas.string).call(), $(v).attr(identifiers.schemas.bigInt).call(), ), ), $(v) .attr(identifiers.actions.transform) .call($.func().param('x').do($('BigInt').call('x').return())), ]; } const result: Pipes = []; result.push($(v).attr(identifiers.schemas.number).call()); if (schema.type === 'integer') { result.push($(v).attr(identifiers.actions.integer).call()); } return result; } function constNode(ctx: NumberResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.const === undefined) { return; } return $(v) .attr(identifiers.schemas.literal) .call(ctx.utils.maybeBigInt(schema.const, schema.format)); } function maxNode(ctx: NumberResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.exclusiveMaximum !== undefined) { return $(v) .attr(identifiers.actions.ltValue) .call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format)); } if (schema.maximum !== undefined) { return $(v) .attr(identifiers.actions.maxValue) .call(ctx.utils.maybeBigInt(schema.maximum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return $(v) .attr(identifiers.actions.maxValue) .call(ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.literal(limit.maxError)); } } function minNode(ctx: NumberResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.exclusiveMinimum !== undefined) { return $(v) .attr(identifiers.actions.gtValue) .call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format)); } if (schema.minimum !== undefined) { return $(v) .attr(identifiers.actions.minValue) .call(ctx.utils.maybeBigInt(schema.minimum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return $(v) .attr(identifiers.actions.minValue) .call(ctx.utils.maybeBigInt(limit.minValue, schema.format), $.literal(limit.minError)); } } function numberResolver(ctx: NumberResolverContext): Pipes { const constResult = ctx.nodes.const(ctx); if (constResult) { return ctx.pipes.push(ctx.pipes.current, constResult); } const baseResult = ctx.nodes.base(ctx); if (baseResult) { ctx.pipes.push(ctx.pipes.current, baseResult); } const minResult = ctx.nodes.min(ctx); if (minResult) { ctx.pipes.push(ctx.pipes.current, minResult); } const maxResult = ctx.nodes.max(ctx); if (maxResult) { ctx.pipes.push(ctx.pipes.current, maxResult); } return ctx.pipes.current; } export function numberToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'integer' | 'number'>; }): Pipe { const ctx: NumberResolverContext = { $, nodes: { base: baseNode, const: constNode, max: maxNode, min: minNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, utils: { getIntegerLimit, maybeBigInt, shouldCoerceToBigInt, }, }; const resolver = plugin.config['~resolvers']?.number; const node = resolver?.(ctx) ?? numberResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/object.ts ================================================ import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { ObjectResolverContext } from '../../resolvers'; import type { Pipe, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { CompositeHandlerResult, ValibotResult } from '../../shared/types'; import { identifiers } from '../constants'; function additionalPropertiesNode(ctx: ObjectResolverContext): Pipe | null | undefined { const { pipes, schema } = ctx; if (!schema.additionalProperties || !schema.additionalProperties.type) return; if (schema.additionalProperties.type === 'never') return null; const additionalResult = ctx.walk( schema.additionalProperties, childContext(ctx.walkerCtx, 'additionalProperties'), ); ctx._childResults.push(additionalResult); return pipes.toNode(additionalResult.pipes, ctx.plugin); } function baseNode(ctx: ObjectResolverContext): Pipes | Pipe { const { v } = ctx.symbols; const additional = ctx.nodes.additionalProperties(ctx); const shape = ctx.nodes.shape(ctx); if (additional === null) { return $(v).attr(identifiers.schemas.strictObject).call(shape); } if (additional) { if (shape.isEmpty) { return $(v) .attr(identifiers.schemas.record) .call($(v).attr(identifiers.schemas.string).call(), additional); } return $(v).attr(identifiers.schemas.objectWithRest).call(shape, additional); } return $(v).attr(identifiers.schemas.object).call(shape); } function objectResolver(ctx: ObjectResolverContext): Pipes | Pipe { // TODO: parser - handle constants return ctx.nodes.base(ctx); } function shapeNode(ctx: ObjectResolverContext): ReturnType { const { pipes, schema } = ctx; const shape = $.object().pretty(); for (const name in schema.properties) { const property = schema.properties[name]!; const isOptional = !schema.required?.includes(name); const propertyResult = ctx.walk(property, childContext(ctx.walkerCtx, 'properties', name)); ctx._childResults.push(propertyResult); const finalExpr = ctx.applyModifiers(propertyResult, { optional: isOptional }); shape.prop(name, pipes.toNode(finalExpr.pipes, ctx.plugin)); } return shape; } export function objectToPipes( ctx: Pick, ): CompositeHandlerResult { const { applyModifiers, plugin, schema, walk, walkerCtx } = ctx; const childResults: Array = []; const resolverCtx: ObjectResolverContext = { $, _childResults: childResults, applyModifiers, nodes: { additionalProperties: additionalPropertiesNode, base: baseNode, shape: shapeNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.object; const node = resolver?.(resolverCtx) ?? objectResolver(resolverCtx); return { childResults, pipes: [resolverCtx.pipes.toNode(node, plugin)], }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/string.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { shouldCoerceToBigInt } from '../../../../plugins/shared/utils/coerce'; import { $ } from '../../../../ts-dsl'; import type { StringResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; import { numberToPipes } from './number'; function baseNode(ctx: StringResolverContext): PipeResult { const { v } = ctx.symbols; return $(v).attr(identifiers.schemas.string).call(); } function constNode(ctx: StringResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (typeof schema.const !== 'string') return; return $(v).attr(identifiers.schemas.literal).call($.literal(schema.const)); } function formatNode(ctx: StringResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; switch (schema.format) { case 'date': return $(v).attr(identifiers.actions.isoDate).call(); case 'date-time': return $(v).attr(identifiers.actions.isoTimestamp).call(); case 'email': return $(v).attr(identifiers.actions.email).call(); case 'ipv4': case 'ipv6': return $(v).attr(identifiers.actions.ip).call(); case 'time': return $(v).attr(identifiers.actions.isoTimeSecond).call(); case 'uri': return $(v).attr(identifiers.actions.url).call(); case 'uuid': return $(v).attr(identifiers.actions.uuid).call(); } } function lengthNode(ctx: StringResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.minLength === undefined || schema.minLength !== schema.maxLength) return; return $(v).attr(identifiers.actions.length).call($.literal(schema.minLength)); } function maxLengthNode(ctx: StringResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.maxLength === undefined) return; return $(v).attr(identifiers.actions.maxLength).call($.literal(schema.maxLength)); } function minLengthNode(ctx: StringResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (schema.minLength === undefined) return; return $(v).attr(identifiers.actions.minLength).call($.literal(schema.minLength)); } function patternNode(ctx: StringResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (!schema.pattern) return; const flags = /\\[pP]\{/.test(schema.pattern) ? 'u' : undefined; return $(v).attr(identifiers.actions.regex).call($.regexp(schema.pattern, flags)); } function stringResolver(ctx: StringResolverContext): Pipes { const constNode = ctx.nodes.const(ctx); if (constNode) return ctx.pipes.push(ctx.pipes.current, constNode); const baseNode = ctx.nodes.base(ctx); if (baseNode) ctx.pipes.push(ctx.pipes.current, baseNode); const formatNode = ctx.nodes.format(ctx); if (formatNode) ctx.pipes.push(ctx.pipes.current, formatNode); const lengthNode = ctx.nodes.length(ctx); if (lengthNode) { ctx.pipes.push(ctx.pipes.current, lengthNode); } else { const minLengthNode = ctx.nodes.minLength(ctx); if (minLengthNode) ctx.pipes.push(ctx.pipes.current, minLengthNode); const maxLengthNode = ctx.nodes.maxLength(ctx); if (maxLengthNode) ctx.pipes.push(ctx.pipes.current, maxLengthNode); } const patternNode = ctx.nodes.pattern(ctx); if (patternNode) ctx.pipes.push(ctx.pipes.current, patternNode); return ctx.pipes.current; } export function stringToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'string'>; }): Pipe { if (shouldCoerceToBigInt(schema.format)) { return numberToPipes({ plugin, schema: { ...schema, type: 'number' }, }); } const ctx: StringResolverContext = { $, nodes: { base: baseNode, const: constNode, format: formatNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, pattern: patternNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.string; const node = resolver?.(ctx) ?? stringResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/tuple.ts ================================================ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { TupleResolverContext } from '../../resolvers'; import type { PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { CompositeHandlerResult, ValibotFinal, ValibotResult } from '../../shared/types'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; import { unknownToPipes } from './unknown'; interface TupleToPipesContext { applyModifiers: (result: ValibotResult, options?: { optional?: boolean }) => ValibotFinal; plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'tuple'>; walk: Walker; walkerCtx: SchemaVisitorContext; } function baseNode(ctx: TupleResolverContext): PipeResult { const { applyModifiers, pipes, plugin, schema, symbols, walk, walkerCtx } = ctx; if (!schema.items) { return unknownToPipes({ plugin }); } const { v } = symbols; const childResults: Array = []; for (let i = 0; i < schema.items.length; i++) { const item = schema.items[i]!; const result = walk!(item, childContext(walkerCtx!, 'items', i)); childResults.push(result); } const tupleElements = childResults.map((r) => pipes.toNode(applyModifiers!(r).pipes, plugin)); return $(v) .attr(identifiers.schemas.tuple) .call($.array(...tupleElements)); } function constNode(ctx: TupleResolverContext): PipeResult { const { schema, symbols } = ctx; const { v } = symbols; if (!schema.const || !Array.isArray(schema.const)) return; const tupleElements = schema.const.map((value) => $(v).attr(identifiers.schemas.literal).call($.fromValue(value)), ); return $(v) .attr(identifiers.schemas.tuple) .call($.array(...tupleElements)); } function tupleResolver(ctx: TupleResolverContext): Pipes { const constResult = ctx.nodes.const(ctx); if (constResult) { return ctx.pipes.push(ctx.pipes.current, constResult); } const baseResult = ctx.nodes.base(ctx); if (baseResult) { ctx.pipes.push(ctx.pipes.current, baseResult); } return ctx.pipes.current; } export function tupleToPipes(ctx: TupleToPipesContext): CompositeHandlerResult { const { plugin, schema, walk, walkerCtx } = ctx; const childResults: Array = []; if (schema.items) { for (let i = 0; i < schema.items.length; i++) { const item = schema.items[i]!; const result = walk(item, childContext(walkerCtx, 'items', i)); childResults.push(result); } } const resolverCtx: TupleResolverContext = { $, applyModifiers: ctx.applyModifiers, nodes: { base: baseNode, const: constNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.tuple; const node = resolver?.(resolverCtx) ?? tupleResolver(resolverCtx); return { childResults, pipes: [resolverCtx.pipes.toNode(node, plugin)], }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/undefined.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { UndefinedResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: UndefinedResolverContext): PipeResult { const { symbols } = ctx; const { v } = symbols; return $(v).attr(identifiers.schemas.undefined).call(); } function undefinedResolver(ctx: UndefinedResolverContext): Pipes { const base = ctx.nodes.base(ctx); ctx.pipes.push(ctx.pipes.current, base); return ctx.pipes.current; } export function undefinedToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'undefined'>; }): Pipe { const ctx: UndefinedResolverContext = { $, nodes: { base: baseNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.undefined; const node = resolver?.(ctx) ?? undefinedResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/union.ts ================================================ import type { IR } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { UnionResolverContext } from '../../resolvers'; import type { PipeResult, Pipes } from '../../shared/pipes'; import { pipes, pipesToNode } from '../../shared/pipes'; import type { CompositeHandlerResult, ValibotFinal, ValibotResult } from '../../shared/types'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: UnionResolverContext): PipeResult { const { childResults, plugin, schemas, symbols } = ctx; const { v } = symbols; const nonNullItems: Array = []; childResults.forEach((item, index) => { const schema = schemas[index]!; if (schema.type !== 'null' && schema.const !== null) { nonNullItems.push(item); } }); if (nonNullItems.length === 0) { return $(v).attr(identifiers.schemas.null).call(); } if (nonNullItems.length === 1) { return nonNullItems[0]!.pipes; } const itemNodes = nonNullItems.map((i) => pipesToNode(i.pipes, plugin)); return $(v) .attr(identifiers.schemas.union) .call($.array(...itemNodes)); } function unionResolver(ctx: UnionResolverContext): Pipes { const base = ctx.nodes.base(ctx); if (base) { ctx.pipes.push(ctx.pipes.current, base); } return ctx.pipes.current; } export function unionToPipes(ctx: { applyModifiers: (result: ValibotResult, options?: { optional?: boolean }) => ValibotFinal; childResults: Array; parentSchema: IR.SchemaObject; plugin: ValibotPlugin['Instance']; schemas: ReadonlyArray; }): CompositeHandlerResult { const { applyModifiers, childResults, parentSchema, plugin, schemas } = ctx; const resolverCtx: UnionResolverContext = { $, applyModifiers, childResults, nodes: { base: baseNode, }, parentSchema, pipes: { ...pipes, current: [], }, plugin, schema: parentSchema, schemas, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.union; const node = resolver?.(resolverCtx) ?? unionResolver(resolverCtx); return { childResults, pipes: [resolverCtx.pipes.toNode(node, plugin)], }; } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/unknown.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { UnknownResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: UnknownResolverContext): PipeResult { const { symbols } = ctx; const { v } = symbols; return $(v).attr(identifiers.schemas.unknown).call(); } function unknownResolver(ctx: UnknownResolverContext): Pipes { const base = ctx.nodes.base(ctx); ctx.pipes.push(ctx.pipes.current, base); return ctx.pipes.current; } export function unknownToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema?: SchemaWithType<'unknown'>; }): Pipe { const ctx: UnknownResolverContext = { $, nodes: { base: baseNode, }, pipes: { ...pipes, current: [], }, plugin, schema: schema ?? { type: 'unknown' }, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.unknown; const node = resolver?.(ctx) ?? unknownResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/toAst/void.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import type { VoidResolverContext } from '../../resolvers'; import type { Pipe, PipeResult, Pipes } from '../../shared/pipes'; import { pipes } from '../../shared/pipes'; import type { ValibotPlugin } from '../../types'; import { identifiers } from '../constants'; function baseNode(ctx: VoidResolverContext): PipeResult { const { symbols } = ctx; const { v } = symbols; return $(v).attr(identifiers.schemas.void).call(); } function voidResolver(ctx: VoidResolverContext): Pipes { const base = ctx.nodes.base(ctx); ctx.pipes.push(ctx.pipes.current, base); return ctx.pipes.current; } export function voidToPipes({ plugin, schema, }: { plugin: ValibotPlugin['Instance']; schema: SchemaWithType<'void'>; }): Pipe { const ctx: VoidResolverContext = { $, nodes: { base: baseNode, }, pipes: { ...pipes, current: [], }, plugin, schema, symbols: { v: plugin.external('valibot.v'), }, }; const resolver = plugin.config['~resolvers']?.void; const node = resolver?.(ctx) ?? voidResolver(ctx); return ctx.pipes.toNode(node, plugin); } ================================================ FILE: packages/openapi-ts/src/plugins/valibot/v1/walker.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import { fromRef } from '@hey-api/codegen-core'; import type { SchemaExtractor, SchemaVisitor } from '@hey-api/shared'; import { pathToJsonPointer } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import { maybeBigInt } from '../../shared/utils/coerce'; import { composeMeta, defaultMeta, inheritMeta } from '../shared/meta'; import type { Pipes } from '../shared/pipes'; import { pipesToNode } from '../shared/pipes'; import type { ProcessorContext } from '../shared/processor'; import type { ValibotFinal, ValibotMeta, ValibotResult } from '../shared/types'; import type { ValibotPlugin } from '../types'; import { identifiers } from './constants'; import { arrayToPipes } from './toAst/array'; import { booleanToPipes } from './toAst/boolean'; import { enumToPipes } from './toAst/enum'; import { intersectionToPipes } from './toAst/intersection'; import { neverToPipes } from './toAst/never'; import { nullToPipes } from './toAst/null'; import { numberToPipes } from './toAst/number'; import { objectToPipes } from './toAst/object'; import { stringToPipes } from './toAst/string'; import { tupleToPipes } from './toAst/tuple'; import { undefinedToPipes } from './toAst/undefined'; import { unionToPipes } from './toAst/union'; import { unknownToPipes } from './toAst/unknown'; import { voidToPipes } from './toAst/void'; export interface VisitorConfig { /** Optional schema extractor function. */ schemaExtractor?: SchemaExtractor; } function getDefaultValue(meta: ValibotMeta): ReturnType { return meta.format ? maybeBigInt(meta.default, meta.format) : $.fromValue(meta.default); } export function createVisitor( config: VisitorConfig, ): SchemaVisitor { const { schemaExtractor } = config; return { applyModifiers(result, ctx, options = {}): ValibotFinal { const { optional } = options; const v = ctx.plugin.external('valibot.v'); const pipes: Pipes = [...result.pipes]; if (result.meta.readonly) { pipes.push($(v).attr(identifiers.actions.readonly).call()); } const hasDefault = result.meta.default !== undefined; const needsOptional = optional || hasDefault; const needsNullable = result.meta.nullable; const innerNode = pipesToNode(pipes, ctx.plugin); let finalPipes: Pipes; if (needsOptional && needsNullable) { if (hasDefault) { finalPipes = [ $(v).attr(identifiers.schemas.nullish).call(innerNode, getDefaultValue(result.meta)), ]; } else { finalPipes = [$(v).attr(identifiers.schemas.nullish).call(innerNode)]; } } else if (needsOptional) { if (hasDefault) { finalPipes = [ $(v).attr(identifiers.schemas.optional).call(innerNode, getDefaultValue(result.meta)), ]; } else { finalPipes = [$(v).attr(identifiers.schemas.optional).call(innerNode)]; } } else if (needsNullable) { finalPipes = [$(v).attr(identifiers.schemas.nullable).call(innerNode)]; } else { finalPipes = pipes; } return { pipes: finalPipes, typeName: result.meta.hasLazy ? identifiers.types.GenericSchema : undefined, }; }, array(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ValibotFinal; const { childResults, pipes } = arrayToPipes({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { meta: inheritMeta(schema, childResults), pipes, }; }, boolean(schema, ctx) { const pipe = booleanToPipes({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), pipes: [pipe], }; }, enum(schema, ctx) { const { isNullable, pipe } = enumToPipes({ plugin: ctx.plugin, schema }); return { meta: { ...defaultMeta(schema), nullable: isNullable, }, pipes: [pipe], }; }, integer(schema, ctx) { const pipe = numberToPipes({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), pipes: [pipe], }; }, intercept(schema, ctx, walk) { if (schemaExtractor && !schema.$ref) { const extracted = schemaExtractor({ meta: { resource: 'definition', resourceId: pathToJsonPointer(fromRef(ctx.path)), }, naming: ctx.plugin.config.definitions, path: fromRef(ctx.path), plugin: ctx.plugin, schema, }); if (extracted !== schema) { return walk(extracted, ctx); } } }, intersection(items, schemas, parentSchema, ctx) { const applyModifiers: Parameters[0]['applyModifiers'] = ( result, opts, ) => this.applyModifiers(result, ctx, opts) as ValibotFinal; const { pipes } = intersectionToPipes({ applyModifiers, childResults: items, parentSchema, plugin: ctx.plugin, }); return { meta: composeMeta(items, { default: parentSchema.default }), pipes, }; }, never(schema, ctx) { const pipe = neverToPipes({ plugin: ctx.plugin, schema }); return { meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, pipes: [pipe], }; }, null(schema, ctx) { const pipe = nullToPipes({ plugin: ctx.plugin, schema }); return { meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, pipes: [pipe], }; }, number(schema, ctx) { const pipe = numberToPipes({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), pipes: [pipe], }; }, object(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = ( result, opts, ) => this.applyModifiers(result, ctx, opts) as ValibotFinal; const { childResults, pipes } = objectToPipes({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { meta: inheritMeta(schema, childResults), pipes, }; }, postProcess(result, schema, ctx) { const metadata = ctx.plugin.config.metadata; if (!metadata) { return result; } const node = $.object(); if (typeof metadata === 'function') { metadata({ $, node, schema }); } else if (schema.description) { node.prop('description', $.literal(schema.description)); } if (node.isEmpty) { return result; } const v = ctx.plugin.external('valibot.v'); const metadataExpr = $(v).attr(identifiers.actions.metadata).call(node); return { meta: result.meta, pipes: [...result.pipes, metadataExpr], }; }, reference($ref, schema, ctx) { const v = ctx.plugin.external('valibot.v'); const query: SymbolMeta = { category: 'schema', resource: 'definition', resourceId: $ref, tool: 'valibot', }; const refSymbol = ctx.plugin.referenceSymbol(query); const isRegistered = ctx.plugin.isSymbolRegistered(query); if (isRegistered) { return { meta: defaultMeta(schema), pipes: [$(refSymbol)], }; } return { meta: { ...defaultMeta(schema), hasLazy: true, }, pipes: [ $(v) .attr(identifiers.schemas.lazy) .call($.func().do($(refSymbol).return())), ], }; }, string(schema, ctx) { const pipe = stringToPipes({ plugin: ctx.plugin, schema }); return { meta: defaultMeta(schema), pipes: [pipe], }; }, tuple(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ValibotFinal; const { childResults, pipes } = tupleToPipes({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { meta: inheritMeta(schema, childResults), pipes, }; }, undefined(schema, ctx) { const pipe = undefinedToPipes({ plugin: ctx.plugin, schema }); return { meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, pipes: [pipe], }; }, union(items, schemas, parentSchema, ctx) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ValibotFinal; const hasNull = schemas.some((s) => s.type === 'null') || items.some((i) => i.meta.nullable); const { pipes } = unionToPipes({ applyModifiers, childResults: items, parentSchema, plugin: ctx.plugin, schemas, }); return { meta: composeMeta(items, { default: parentSchema.default, nullable: hasNull, }), pipes, }; }, unknown(schema, ctx) { const pipe = unknownToPipes({ plugin: ctx.plugin }); return { meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, pipes: [pipe], }; }, void(schema, ctx) { const pipe = voidToPipes({ plugin: ctx.plugin, schema }); return { meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, pipes: [pipe], }; }, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/api.ts ================================================ import type { $ } from '../../ts-dsl'; import { createRequestValidatorMini, createResponseValidatorMini } from './mini/api'; import type { ValidatorArgs } from './shared/types'; import { createRequestValidatorV3, createResponseValidatorV3 } from './v3/api'; import { createRequestValidatorV4, createResponseValidatorV4 } from './v4/api'; export type IApi = { createRequestValidator: (args: ValidatorArgs) => ReturnType | undefined; createResponseValidator: (args: ValidatorArgs) => ReturnType | undefined; }; export class Api implements IApi { createRequestValidator(args: ValidatorArgs): ReturnType | undefined { const { plugin } = args; switch (plugin.config.compatibilityVersion) { case 3: return createRequestValidatorV3(args); case 'mini': return createRequestValidatorMini(args); case 4: default: return createRequestValidatorV4(args); } } createResponseValidator(args: ValidatorArgs): ReturnType | undefined { const { plugin } = args; switch (plugin.config.compatibilityVersion) { case 3: return createResponseValidatorV3(args); case 'mini': return createResponseValidatorMini(args); case 4: default: return createResponseValidatorV4(args); } } } ================================================ FILE: packages/openapi-ts/src/plugins/zod/config.ts ================================================ import { definePluginConfig, mappers } from '@hey-api/shared'; import colors from 'ansi-colors'; import { Api } from './api'; import { handler } from './plugin'; import type { ZodPlugin } from './types'; type CompatibilityVersion = NonNullable; export const defaultConfig: ZodPlugin['Config'] = { api: new Api(), config: { case: 'camelCase', comments: true, includeInEntry: false, metadata: false, }, handler, name: 'zod', resolveConfig: (plugin, context) => { const packageName = 'zod'; const version = context.package.getVersion(packageName); const inferCompatibleVersion = (): CompatibilityVersion => { if (version && (version.major === 4 || version.major === 3)) { return version.major; } // default compatibility version return 4; }; const ensureCompatibleVersion = ( compatibilityVersion: CompatibilityVersion | undefined, ): CompatibilityVersion => { if (!compatibilityVersion) { return inferCompatibleVersion(); } if (!version) { return compatibilityVersion; } if ( compatibilityVersion === 4 || compatibilityVersion === 3 || compatibilityVersion === 'mini' ) { if (!context.package.satisfies(version, '>=3.25.0 <5.0.0')) { const compatibleVersion = inferCompatibleVersion(); console.warn( `🔌 ${colors.yellow('Warning:')} Installed ${colors.cyan(packageName)} ${colors.cyan(`v${version.version}`)} does not support compatibility version ${colors.yellow(String(compatibilityVersion))}, using ${colors.yellow(String(compatibleVersion))}.`, ); return compatibleVersion; } } return compatibilityVersion; }; plugin.config.compatibilityVersion = ensureCompatibleVersion( plugin.config.compatibilityVersion, ); plugin.config.dates = context.valueToObject({ defaultValue: { local: false, offset: false, }, value: plugin.config.dates, }); plugin.config.types = context.valueToObject({ defaultValue: { infer: { case: 'PascalCase', enabled: false, }, }, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: plugin.config.types, }); plugin.config.definitions = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'z{{name}}', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}ZodType', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.definitions, }); plugin.config.requests = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'z{{name}}Data', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}DataZodType', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.requests, }); plugin.config.responses = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'z{{name}}Response', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}ResponseZodType', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.responses, }); plugin.config.webhooks = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', enabled: true, name: 'z{{name}}WebhookRequest', types: { ...plugin.config.types, infer: { ...(plugin.config.types.infer as Extract< typeof plugin.config.types.infer, Record >), name: '{{name}}WebhookRequestZodType', }, }, }, mappers: { ...mappers, object: (fields, defaultValue) => ({ ...fields, types: context.valueToObject({ defaultValue: defaultValue.types!, mappers: { object: (fields, defaultValue) => ({ ...fields, infer: context.valueToObject({ defaultValue: { ...(defaultValue.infer as Extract< typeof defaultValue.infer, Record >), enabled: fields.infer !== undefined ? Boolean(fields.infer) : ( defaultValue.infer as Extract< typeof defaultValue.infer, Record > ).enabled, }, mappers, value: fields.infer, }), }), }, value: fields.types, }), }), }, value: plugin.config.webhooks, }); }, tags: ['validator'], }; /** * Type helper for Zod plugin, returns {@link Plugin.Config} object */ export const defineConfig = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts/src/plugins/zod/constants.ts ================================================ // TODO: this is inaccurate, it combines identifiers for all supported versions export const identifiers = { AnyZodObject: 'AnyZodObject', ZodMiniOptional: 'ZodMiniOptional', ZodOptional: 'ZodOptional', ZodTypeAny: 'ZodTypeAny', _default: '_default', and: 'and', array: 'array', bigint: 'bigint', boolean: 'boolean', check: 'check', coerce: 'coerce', date: 'date', datetime: 'datetime', default: 'default', describe: 'describe', email: 'email', enum: 'enum', globalRegistry: 'globalRegistry', gt: 'gt', gte: 'gte', guid: 'guid', infer: 'infer', int: 'int', intersection: 'intersection', ip: 'ip', ipv4: 'ipv4', ipv6: 'ipv6', iso: 'iso', lazy: 'lazy', length: 'length', literal: 'literal', lt: 'lt', lte: 'lte', max: 'max', maxLength: 'maxLength', maximum: 'maximum', // Zod Mini min: 'min', minLength: 'minLength', minimum: 'minimum', // Zod Mini never: 'never', null: 'null', nullable: 'nullable', nullish: 'nullish', number: 'number', object: 'object', optional: 'optional', parseAsync: 'parseAsync', readonly: 'readonly', record: 'record', regex: 'regex', register: 'register', string: 'string', time: 'time', tuple: 'tuple', undefined: 'undefined', union: 'union', unknown: 'unknown', url: 'url', uuid: 'uuid', void: 'void', }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/index.ts ================================================ export { defaultConfig, defineConfig } from './config'; export type { ZodResolvers } from './resolvers'; export type { ZodPlugin } from './types'; ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/api.ts ================================================ import { $ } from '../../../ts-dsl'; import { identifiers } from '../constants'; import type { ValidatorResolverContext } from '../resolvers'; import type { ValidatorArgs } from '../shared/types'; const validatorResolver = (ctx: ValidatorResolverContext): ReturnType => { const { schema } = ctx.symbols; return $(schema).attr(identifiers.parseAsync).call('data').await().return(); }; export const createRequestValidatorMini = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'zod', }); if (!symbol) return; const z = plugin.external('zod.z'); const ctx: ValidatorResolverContext = { $, chain: { current: $(z), }, operation, plugin, symbols: { schema: symbol, z, }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.request; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } return; }; export const createResponseValidatorMini = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'responses', tool: 'zod', }); if (!symbol) return; const z = plugin.external('zod.z'); const ctx: ValidatorResolverContext = { $, chain: { current: $(z), }, operation, plugin, symbols: { schema: symbol, z, }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.response; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } return; }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/plugin.ts ================================================ import { pathToJsonPointer } from '@hey-api/shared'; import { getZodModule } from '../shared/module'; import { irOperationToAst } from '../shared/operation'; import { irWebhookToAst } from '../shared/webhook'; import type { ZodPlugin } from '../types'; import { createProcessor } from './processor'; export const handlerMini: ZodPlugin['Handler'] = ({ plugin }) => { plugin.symbol('z', { external: getZodModule({ plugin }), importKind: 'namespace', meta: { category: 'external', resource: 'zod.z', }, }); const processor = createProcessor(plugin); plugin.forEach('operation', 'parameter', 'requestBody', 'schema', 'webhook', (event) => { switch (event.type) { case 'operation': irOperationToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; case 'parameter': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.parameter.schema, tags: event.tags, }); break; case 'requestBody': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.requestBody.schema, tags: event.tags, }); break; case 'schema': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.schema, tags: event.tags, }); break; case 'webhook': irWebhookToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; } }); }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/processor.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { createSchemaProcessor, createSchemaWalker, pathToJsonPointer } from '@hey-api/shared'; import { exportAst } from '../shared/export'; import type { ProcessorContext, ProcessorResult } from '../shared/processor'; import type { ZodFinal } from '../shared/types'; import type { ZodPlugin } from '../types'; import { createVisitor } from './walker'; export function createProcessor(plugin: ZodPlugin['Instance']): ProcessorResult { const processor = createSchemaProcessor(); const hooks = [plugin.config['~hooks']?.schemas, plugin.context.config.parser.hooks.schemas]; function extractor(ctx: ProcessorContext): IR.SchemaObject { if (processor.hasEmitted(ctx.path)) { return ctx.schema; } for (const hook of hooks) { const result = hook?.shouldExtract?.(ctx); if (result) { process({ namingAnchor: processor.context.anchor, tags: processor.context.tags, ...ctx, }); return { $ref: pathToJsonPointer(ctx.path) }; } } return ctx.schema; } function process(ctx: ProcessorContext): ZodFinal | void { if (!processor.markEmitted(ctx.path)) return; const shouldExport = ctx.export !== false; return processor.withContext({ anchor: ctx.namingAnchor, tags: ctx.tags }, () => { const visitor = createVisitor({ schemaExtractor: extractor }); const walk = createSchemaWalker(visitor); const result = walk(ctx.schema, { path: ref(ctx.path), plugin, }); const final = visitor.applyModifiers(result, { path: ref(ctx.path), plugin, }) as ZodFinal; if (shouldExport) { exportAst({ ...ctx, final, plugin }); return; } return final; }); } return { process }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/array.ts ================================================ import { childContext, deduplicateSchema } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { ArrayResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { CompositeHandlerResult, ZodResult } from '../../shared/types'; import { unknownToAst } from './unknown'; type ArrayToAstOptions = Pick< ArrayResolverContext, 'applyModifiers' | 'plugin' | 'schema' | 'walk' | 'walkerCtx' >; function baseNode(ctx: ArrayResolverContext): Chain { const { applyModifiers, childResults, plugin, schema, symbols } = ctx; const { z } = symbols; const arrayFn = $(z).attr(identifiers.array); let normalizedSchema = schema; if (normalizedSchema.items) { normalizedSchema = deduplicateSchema({ schema: normalizedSchema }); } if (!normalizedSchema.items) { return arrayFn.call( unknownToAst({ plugin, schema: { type: 'unknown', }, }), ); } if (childResults.length === 1) { const itemNode = applyModifiers(childResults[0]!, { optional: false }).expression; return arrayFn.call(itemNode); } if (childResults.length > 1) { const itemExpressions: Array = childResults.map( (result) => applyModifiers(result, { optional: false }).expression, ); if (normalizedSchema.logicalOperator === 'and') { return arrayFn.call( $(z) .attr(identifiers.intersection) .call(...itemExpressions), ); } else { return arrayFn.call( $(z) .attr(identifiers.union) .call($.array(...itemExpressions)), ); } } return arrayFn.call( unknownToAst({ plugin, schema: { type: 'unknown', }, }), ); } function lengthNode(ctx: ArrayResolverContext): ChainResult { const { schema } = ctx; if (schema.minItems === schema.maxItems && schema.minItems !== undefined) { return ctx.chain.current.attr(identifiers.length).call($.fromValue(schema.minItems)); } } function maxLengthNode(ctx: ArrayResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.maxItems === undefined) return; return $(z).attr(identifiers.maxLength).call($.fromValue(schema.maxItems)); } function minLengthNode(ctx: ArrayResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.minItems === undefined) return; return $(z).attr(identifiers.minLength).call($.fromValue(schema.minItems)); } function arrayResolver(ctx: ArrayResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; const lengthResult = ctx.nodes.length(ctx); if (lengthResult) { ctx.chain.current = lengthResult; } else { const minLengthResult = ctx.nodes.minLength(ctx); const maxLengthResult = ctx.nodes.maxLength(ctx); if (minLengthResult && maxLengthResult) { ctx.chain.current = ctx.chain.current .attr(identifiers.check) .call(minLengthResult, maxLengthResult); } else if (minLengthResult) { ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(minLengthResult); } else if (maxLengthResult) { ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(maxLengthResult); } } return ctx.chain.current; } export function arrayToAst({ applyModifiers, plugin, schema, walk, walkerCtx, }: ArrayToAstOptions): CompositeHandlerResult { const childResults: Array = []; let schemaCopy = schema; const z = plugin.external('zod.z'); if (schemaCopy.items) { schemaCopy = deduplicateSchema({ schema: schemaCopy }); schemaCopy.items!.forEach((item, index) => { const itemResult = walk(item, childContext(walkerCtx, 'items', index)); childResults.push(itemResult); }); } const ctx: ArrayResolverContext = { $, applyModifiers, chain: { current: $(z), }, childResults, nodes: { base: baseNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.array; const expression = resolver?.(ctx) ?? arrayResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/boolean.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { BooleanResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: BooleanResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.boolean).call(); } function constNode(ctx: BooleanResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (typeof schema.const !== 'boolean') return; return $(z).attr(identifiers.literal).call($.literal(schema.const)); } function booleanResolver(ctx: BooleanResolverContext): Chain { const constResult = ctx.nodes.const(ctx); if (constResult) { ctx.chain.current = constResult; return ctx.chain.current; } const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function booleanToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'boolean'>; }): Chain { const z = plugin.external('zod.z'); const ctx: BooleanResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.boolean; return resolver?.(ctx) ?? booleanResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/enum.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { EnumResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; import { unknownToAst } from './unknown'; function itemsNode(ctx: EnumResolverContext): ReturnType { const { schema, symbols } = ctx; const { z } = symbols; const enumMembers: Array> = []; const literalMembers: Array = []; let isNullable = false; let allStrings = true; for (const item of schema.items ?? []) { if (item.type === 'string' && typeof item.const === 'string') { const literal = $.literal(item.const); enumMembers.push(literal); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if ( (item.type === 'number' || item.type === 'integer') && typeof item.const === 'number' ) { allStrings = false; const literal = $.literal(item.const); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if (item.type === 'boolean' && typeof item.const === 'boolean') { allStrings = false; const literal = $.literal(item.const); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if (item.type === 'null' || item.const === null) { isNullable = true; } } return { allStrings, enumMembers, isNullable, literalMembers, }; } function baseNode(ctx: EnumResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; const { allStrings, enumMembers, literalMembers } = ctx.nodes.items(ctx); if (allStrings && enumMembers.length > 0) { return $(z) .attr(identifiers.enum) .call($.array(...enumMembers)); } if (literalMembers.length === 1) { return literalMembers[0]!; } return $(z) .attr(identifiers.union) .call($.array(...literalMembers)); } function enumResolver(ctx: EnumResolverContext): Chain { const { literalMembers } = ctx.nodes.items(ctx); if (!literalMembers.length) { return ctx.chain.current; } const baseExpression = ctx.nodes.base(ctx); ctx.chain.current = baseExpression; return ctx.chain.current; } export function enumToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'enum'>; }): Chain { const z = plugin.external('zod.z'); const ctx: EnumResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, items: itemsNode, }, plugin, schema, symbols: { z, }, }; const { literalMembers } = itemsNode(ctx); if (!literalMembers.length) { return unknownToAst({ plugin, schema: { type: 'unknown', }, }); } const resolver = plugin.config['~resolvers']?.enum; return resolver?.(ctx) ?? enumResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/never.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NeverResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NeverResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.never).call(); } function neverResolver(ctx: NeverResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function neverToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'never'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NeverResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.never; return resolver?.(ctx) ?? neverResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/null.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NullResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NullResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.null).call(); } function nullResolver(ctx: NullResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function nullToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'null'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NullResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.null; return resolver?.(ctx) ?? nullResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/number.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { maybeBigInt, shouldCoerceToBigInt } from '../../../../plugins/shared/utils/coerce'; import { getIntegerLimit } from '../../../../plugins/shared/utils/formats'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NumberResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NumberResolverContext): Chain { const { schema, symbols } = ctx; const { z } = symbols; if (ctx.utils.shouldCoerceToBigInt(schema.format)) { return $(z).attr(identifiers.coerce).attr(identifiers.bigint).call(); } let chain = $(z).attr(identifiers.number).call(); if (schema.type === 'integer') { chain = $(z).attr(identifiers.int).call(); } return chain; } function constNode(ctx: NumberResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.const === undefined) return; return $(z).attr(identifiers.literal).call(ctx.utils.maybeBigInt(schema.const, schema.format)); } function maxNode(ctx: NumberResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.exclusiveMaximum !== undefined) { return $(z) .attr(identifiers.lt) .call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format)); } if (schema.maximum !== undefined) { return $(z).attr(identifiers.lte).call(ctx.utils.maybeBigInt(schema.maximum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return $(z) .attr(identifiers.maximum) .call( ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.object().prop('error', $.literal(limit.maxError)), ); } return; } function minNode(ctx: NumberResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.exclusiveMinimum !== undefined) { return $(z) .attr(identifiers.gt) .call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format)); } if (schema.minimum !== undefined) { return $(z).attr(identifiers.gte).call(ctx.utils.maybeBigInt(schema.minimum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return $(z) .attr(identifiers.minimum) .call( ctx.utils.maybeBigInt(limit.minValue, schema.format), $.object().prop('error', $.literal(limit.minError)), ); } return; } function numberResolver(ctx: NumberResolverContext): Chain { const constNode = ctx.nodes.const(ctx); if (constNode) { ctx.chain.current = constNode; return ctx.chain.current; } const baseNode = ctx.nodes.base(ctx); if (baseNode) ctx.chain.current = baseNode; const checks: Array = []; const minNode = ctx.nodes.min(ctx); if (minNode) checks.push(minNode); const maxNode = ctx.nodes.max(ctx); if (maxNode) checks.push(maxNode); if (checks.length > 0) { ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(...checks); } return ctx.chain.current; } export function numberToNode({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'integer' | 'number'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NumberResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, max: maxNode, min: minNode, }, plugin, schema, symbols: { z, }, utils: { getIntegerLimit, maybeBigInt, shouldCoerceToBigInt, }, }; const resolver = plugin.config['~resolvers']?.number; return resolver?.(ctx) ?? numberResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/object.ts ================================================ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { ObjectResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { CompositeHandlerResult, ZodFinal, ZodResult } from '../../shared/types'; import type { ZodPlugin } from '../../types'; type WalkerCtx = SchemaVisitorContext; interface ObjectToAstOptions { applyModifiers: (result: ZodResult, opts: { optional?: boolean }) => ZodFinal; plugin: ZodPlugin['Instance']; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: WalkerCtx; } type ExtendedContext = ObjectResolverContext & { applyModifiers: ObjectToAstOptions['applyModifiers']; walk: ObjectToAstOptions['walk']; walkerCtx: ObjectToAstOptions['walkerCtx']; }; function additionalPropertiesNode(ctx: ExtendedContext): Chain | null | undefined { const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx; if ( !schema.additionalProperties || (schema.properties && Object.keys(schema.properties).length > 0) ) { return; } const additionalResult = walk( schema.additionalProperties, childContext(walkerCtx, 'additionalProperties'), ); _childResults.push(additionalResult); const finalExpr = applyModifiers(additionalResult, {}); return finalExpr.expression; } function baseNode(ctx: ExtendedContext): Chain { const { nodes, symbols } = ctx; const { z } = symbols; const additional = nodes.additionalProperties(ctx); const shape = nodes.shape(ctx); if (additional) { return $(z).attr(identifiers.record).call($(z).attr(identifiers.string).call(), additional); } return $(z).attr(identifiers.object).call(shape); } function objectResolver(ctx: ExtendedContext): Chain { return ctx.nodes.base(ctx); } function shapeNode(ctx: ExtendedContext): ReturnType { const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx; const shape = $.object().pretty(); for (const name in schema.properties) { const property = schema.properties[name]!; const isOptional = !schema.required?.includes(name); const propertyResult = walk(property, childContext(walkerCtx, 'properties', name)); _childResults.push(propertyResult); const finalExpr = applyModifiers(propertyResult, { optional: isOptional, }); shape.prop(name, finalExpr.expression); } return shape; } export function objectToAst(options: ObjectToAstOptions): CompositeHandlerResult { const { applyModifiers, plugin, schema, walk, walkerCtx } = options; const childResults: Array = []; const z = plugin.external('zod.z'); const ctx: ExtendedContext = { $, _childResults: childResults, applyModifiers, chain: { current: $(z), }, nodes: { additionalProperties: additionalPropertiesNode, base: baseNode, shape: shapeNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.object; const node = resolver?.(ctx) ?? objectResolver(ctx); return { childResults, expression: node, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/string.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { StringResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: StringResolverContext): Chain { const { z } = ctx.symbols; return $(z).attr(identifiers.string).call(); } function constNode(ctx: StringResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (typeof schema.const !== 'string') return; return $(z).attr(identifiers.literal).call($.literal(schema.const)); } function formatNode(ctx: StringResolverContext): ChainResult { const { plugin, schema, symbols } = ctx; const { z } = symbols; switch (schema.format) { case 'date': return $(z).attr(identifiers.iso).attr(identifiers.date).call(); case 'date-time': { const obj = $.object() .$if(plugin.config.dates.offset, (o) => o.prop('offset', $.literal(true))) .$if(plugin.config.dates.local, (o) => o.prop('local', $.literal(true))); return $(z) .attr(identifiers.iso) .attr(identifiers.datetime) .call(obj.hasProps() ? obj : undefined); } case 'email': return $(z).attr(identifiers.email).call(); case 'guid': return $(z).attr(identifiers.guid).call(); case 'ipv4': return $(z).attr(identifiers.ipv4).call(); case 'ipv6': return $(z).attr(identifiers.ipv6).call(); case 'time': return $(z).attr(identifiers.iso).attr(identifiers.time).call(); case 'uri': return $(z).attr(identifiers.url).call(); case 'uuid': return $(z).attr(identifiers.uuid).call(); } return; } function lengthNode(ctx: StringResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.minLength === undefined || schema.minLength !== schema.maxLength) return; return $(z).attr(identifiers.length).call($.literal(schema.minLength)); } function maxLengthNode(ctx: StringResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.maxLength === undefined) return; return $(z).attr(identifiers.maxLength).call($.literal(schema.maxLength)); } function minLengthNode(ctx: StringResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.minLength === undefined) return; return $(z).attr(identifiers.minLength).call($.literal(schema.minLength)); } function patternNode(ctx: StringResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (!schema.pattern) return; const flags = /\\[pP]\{/.test(schema.pattern) ? 'u' : undefined; return $(z).attr(identifiers.regex).call($.regexp(schema.pattern, flags)); } function stringResolver(ctx: StringResolverContext): Chain { const constNode = ctx.nodes.const(ctx); if (constNode) { ctx.chain.current = constNode; return ctx.chain.current; } const baseNode = ctx.nodes.base(ctx); if (baseNode) ctx.chain.current = baseNode; const formatNode = ctx.nodes.format(ctx); if (formatNode) ctx.chain.current = formatNode; const checks: Array = []; const lengthNode = ctx.nodes.length(ctx); if (lengthNode) { checks.push(lengthNode); } else { const minLengthNode = ctx.nodes.minLength(ctx); if (minLengthNode) checks.push(minLengthNode); const maxLengthNode = ctx.nodes.maxLength(ctx); if (maxLengthNode) checks.push(maxLengthNode); } const patternNode = ctx.nodes.pattern(ctx); if (patternNode) checks.push(patternNode); if (checks.length > 0) { ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(...checks); } return ctx.chain.current; } export function stringToNode({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'string'>; }): Chain { const z = plugin.external('zod.z'); const ctx: StringResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, format: formatNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, pattern: patternNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.string; return resolver?.(ctx) ?? stringResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/tuple.ts ================================================ import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { TupleResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { CompositeHandlerResult, ZodResult } from '../../shared/types'; type TupleToAstOptions = Pick< TupleResolverContext, 'applyModifiers' | 'plugin' | 'schema' | 'walk' | 'walkerCtx' >; function baseNode(ctx: TupleResolverContext): Chain { const { applyModifiers, childResults, symbols } = ctx; const { z } = symbols; const tupleFn = $(z).attr(identifiers.tuple); if (childResults.length === 0) { return tupleFn.call($.array()); } const tupleElements = childResults.map( (result) => applyModifiers(result, { optional: false }).expression, ); return tupleFn.call($.array(...tupleElements)); } function constNode(ctx: TupleResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (!schema.const || !Array.isArray(schema.const)) return; const tupleElements = schema.const.map((value) => $(z).attr(identifiers.literal).call($.fromValue(value)), ); return $(z) .attr(identifiers.tuple) .call($.array(...tupleElements)); } function tupleResolver(ctx: TupleResolverContext): Chain { const constResult = ctx.nodes.const(ctx); if (constResult) { ctx.chain.current = constResult; return ctx.chain.current; } const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function tupleToAst({ applyModifiers, plugin, schema, walk, walkerCtx, }: TupleToAstOptions): CompositeHandlerResult { const childResults: Array = []; const z = plugin.external('zod.z'); if (schema.items) { schema.items.forEach((item, index) => { const itemResult = walk(item, childContext(walkerCtx, 'items', index)); childResults.push(itemResult); }); } const ctx: TupleResolverContext = { $, applyModifiers, chain: { current: $(z), }, childResults, nodes: { base: baseNode, const: constNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.tuple; const expression = resolver?.(ctx) ?? tupleResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/undefined.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { UndefinedResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: UndefinedResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.undefined).call(); } function undefinedResolver(ctx: UndefinedResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function undefinedToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'undefined'>; }): Chain { const z = plugin.external('zod.z'); const ctx: UndefinedResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.undefined; return resolver?.(ctx) ?? undefinedResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/unknown.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { UnknownResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: UnknownResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.unknown).call(); } function unknownResolver(ctx: UnknownResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function unknownToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'unknown'>; }): Chain { const z = plugin.external('zod.z'); const ctx: UnknownResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.unknown; return resolver?.(ctx) ?? unknownResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/toAst/void.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { VoidResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: VoidResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.void).call(); } function voidResolver(ctx: VoidResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function voidToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'void'>; }): Chain { const z = plugin.external('zod.z'); const ctx: VoidResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.void; return resolver?.(ctx) ?? voidResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/mini/walker.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import { fromRef } from '@hey-api/codegen-core'; import type { SchemaExtractor, SchemaVisitor } from '@hey-api/shared'; import { pathToJsonPointer } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import { maybeBigInt, shouldCoerceToBigInt } from '../../shared/utils/coerce'; import { identifiers } from '../constants'; import type { Chain } from '../shared/chain'; import { defaultMeta, inheritMeta } from '../shared/meta'; import type { ProcessorContext } from '../shared/processor'; import type { ZodFinal, ZodResult } from '../shared/types'; import type { ZodPlugin } from '../types'; import { arrayToAst } from './toAst/array'; import { booleanToAst } from './toAst/boolean'; import { enumToAst } from './toAst/enum'; import { neverToAst } from './toAst/never'; import { nullToAst } from './toAst/null'; import { numberToNode } from './toAst/number'; import { objectToAst } from './toAst/object'; import { stringToNode } from './toAst/string'; import { tupleToAst } from './toAst/tuple'; import { undefinedToAst } from './toAst/undefined'; import { unknownToAst } from './toAst/unknown'; import { voidToAst } from './toAst/void'; export interface VisitorConfig { /** Optional schema extractor function. */ schemaExtractor?: SchemaExtractor; } export function createVisitor( config: VisitorConfig, ): SchemaVisitor { const { schemaExtractor } = config; return { applyModifiers(result, ctx, options = {}): ZodFinal { const { optional } = options; const z = ctx.plugin.external('zod.z'); let expression = result.expression; if (result.meta.readonly) { expression = $(z).attr(identifiers.readonly).call(expression); } const hasDefault = result.meta.default !== undefined; const needsNullable = result.meta.nullable; if (optional && needsNullable) { expression = $(z).attr(identifiers.nullish).call(expression); } else if (optional) { expression = $(z).attr(identifiers.optional).call(expression); } else if (needsNullable) { expression = $(z).attr(identifiers.nullable).call(expression); } if (hasDefault) { expression = $(z) .attr(identifiers._default) .call( expression, result.meta.format ? maybeBigInt(result.meta.default, result.meta.format) : $.fromValue(result.meta.default), ); } return { expression, }; }, array(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = arrayToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, boolean(schema, ctx) { const expression = booleanToAst({ plugin: ctx.plugin, schema }); return { expression, meta: defaultMeta(schema), }; }, enum(schema, ctx) { const expression = enumToAst({ plugin: ctx.plugin, schema }); const hasNull = schema.items?.some((item) => item.type === 'null' || item.const === null) ?? false; return { expression, meta: { ...defaultMeta(schema), nullable: hasNull, }, }; }, integer(schema, ctx) { const expression = numberToNode({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), format: schema.format, }, }; }, intercept(schema, ctx, walk) { if (schemaExtractor && !schema.$ref) { const extracted = schemaExtractor({ meta: { resource: 'definition', resourceId: pathToJsonPointer(fromRef(ctx.path)), }, naming: ctx.plugin.config.definitions, path: fromRef(ctx.path), plugin: ctx.plugin, schema, }); if (extracted !== schema) { return walk(extracted, ctx); } } }, intersection(items, schemas, parentSchema, ctx) { const z = ctx.plugin.external('zod.z'); const hasAnyLazy = items.some((item) => item.meta.hasLazy); let expression = items[0]!.expression; items.slice(1).forEach((item) => { expression = $(z) .attr(identifiers.intersection) .call( expression, item.meta.hasLazy ? $(z).attr(identifiers.lazy).call($.func().do(item.expression.return())) : item.expression, ); }); return { expression, meta: { default: parentSchema.default, format: parentSchema.format, hasLazy: hasAnyLazy, isLazy: false, nullable: items.some((i) => i.meta.nullable), readonly: items.some((i) => i.meta.readonly), }, }; }, never(schema, ctx) { const expression = neverToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, null(schema, ctx) { const expression = nullToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, number(schema, ctx) { const expression = numberToNode({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), format: schema.format, }, }; }, object(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = objectToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, postProcess(result, schema, ctx) { const { metadata } = ctx.plugin.config; if (!metadata) { return result; } const node = $.object(); if (metadata === true) { if (!schema.description) { return result; } node.pretty().prop('description', $.literal(schema.description)); } else { metadata({ $, node, schema }); } if (node.isEmpty) { return result; } const z = ctx.plugin.external('zod.z'); return { ...result, expression: result.expression .attr(identifiers.register) .call($(z).attr(identifiers.globalRegistry), node), }; }, reference($ref, schema, ctx) { const z = ctx.plugin.external('zod.z'); const query: SymbolMeta = { category: 'schema', resource: 'definition', resourceId: $ref, tool: 'zod', }; const refSymbol = ctx.plugin.referenceSymbol(query); if (ctx.plugin.isSymbolRegistered(query)) { return { expression: $(refSymbol), meta: defaultMeta(schema), }; } return { expression: $(z) .attr(identifiers.lazy) .call($.func().returns('any').do($(refSymbol).return())), meta: { ...defaultMeta(schema), hasLazy: true, isLazy: true, }, }; }, string(schema, ctx) { if (shouldCoerceToBigInt(schema.format)) { const expression = numberToNode({ plugin: ctx.plugin, schema: { ...schema, type: 'number' }, }); return { expression, meta: defaultMeta(schema), }; } const expression = stringToNode({ plugin: ctx.plugin, schema }); return { expression, meta: defaultMeta(schema), }; }, tuple(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = tupleToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, undefined(schema, ctx) { const expression = undefinedToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, union(items, schemas, parentSchema, ctx) { const z = ctx.plugin.external('zod.z'); const hasAnyLazy = items.some((item) => item.meta.hasLazy); const hasNull = schemas.some((s) => s.type === 'null') || items.some((i) => i.meta.nullable); const nonNullItems: typeof items = []; items.forEach((item, index) => { const schema = schemas[index]!; if (schema.type !== 'null' && schema.const !== null) { nonNullItems.push(item); } }); let expression: Chain; if (nonNullItems.length === 0) { expression = $(z).attr(identifiers.null).call(); } else if (nonNullItems.length === 1) { expression = nonNullItems[0]!.expression; } else { expression = $(z) .attr(identifiers.union) .call( $.array() .pretty() .elements(...nonNullItems.map((item) => item.expression)), ); } return { expression, meta: { default: parentSchema.default, format: parentSchema.format, hasLazy: hasAnyLazy, isLazy: false, nullable: hasNull, readonly: items.some((i) => i.meta.readonly), }, }; }, unknown(schema, ctx) { const expression = unknownToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, void(schema, ctx) { const expression = voidToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/plugin.ts ================================================ import { handlerMini } from './mini/plugin'; import type { ZodPlugin } from './types'; import { handlerV3 } from './v3/plugin'; import { handlerV4 } from './v4/plugin'; export const handler: ZodPlugin['Handler'] = (args) => { const { plugin } = args; switch (plugin.config.compatibilityVersion) { case 3: return handlerV3(args); case 'mini': return handlerMini(args); case 4: default: return handlerV4(args); } }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/resolvers.ts ================================================ import type { Symbol } from '@hey-api/codegen-core'; import type { IR, Plugin, SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import type { MaybeArray } from '@hey-api/types'; import type ts from 'typescript'; import type { MaybeBigInt, ShouldCoerceToBigInt } from '../../plugins/shared/utils/coerce'; import type { GetIntegerLimit } from '../../plugins/shared/utils/formats'; import type { $, DollarTsDsl, TsDsl } from '../../ts-dsl'; import type { Chain, ChainResult } from './shared/chain'; import type { ZodFinal, ZodResult } from './shared/types'; import type { ZodPlugin } from './types'; export type ZodResolvers = Plugin.Resolvers<{ /** * Resolver for array schemas. * * Allows customization of how array types are rendered. * * Returning `undefined` will execute the default resolver logic. */ array?: (ctx: ArrayResolverContext) => ChainResult; /** * Resolver for boolean schemas. * * Allows customization of how boolean types are rendered. * * Returning `undefined` will execute the default resolver logic. */ boolean?: (ctx: BooleanResolverContext) => ChainResult; /** * Resolver for enum schemas. * * Allows customization of how enum types are rendered. * * Returning `undefined` will execute the default resolver logic. */ enum?: (ctx: EnumResolverContext) => ChainResult; /** * Resolver for intersection schemas. * * Allows customization of how intersection types are rendered. * * Returning `undefined` will execute the default resolver logic. */ intersection?: (ctx: IntersectionResolverContext) => ChainResult; /** * Resolver for never schemas. * * Allows customization of how never types are rendered. * * Returning `undefined` will execute the default resolver logic. */ never?: (ctx: NeverResolverContext) => ChainResult; /** * Resolver for null schemas. * * Allows customization of how null types are rendered. * * Returning `undefined` will execute the default resolver logic. */ null?: (ctx: NullResolverContext) => ChainResult; /** * Resolver for number schemas. * * Allows customization of how number types are rendered. * * Returning `undefined` will execute the default resolver logic. */ number?: (ctx: NumberResolverContext) => ChainResult; /** * Resolver for object schemas. * * Allows customization of how object types are rendered. * * Returning `undefined` will execute the default resolver logic. */ object?: (ctx: ObjectResolverContext) => ChainResult; /** * Resolver for string schemas. * * Allows customization of how string types are rendered. * * Returning `undefined` will execute the default resolver logic. */ string?: (ctx: StringResolverContext) => ChainResult; /** * Resolver for tuple schemas. * * Allows customization of how tuple types are rendered. * * Returning `undefined` will execute the default resolver logic. */ tuple?: (ctx: TupleResolverContext) => ChainResult; /** * Resolver for undefined schemas. * * Allows customization of how undefined types are rendered. * * Returning `undefined` will execute the default resolver logic. */ undefined?: (ctx: UndefinedResolverContext) => ChainResult; /** * Resolver for union schemas. * * Allows customization of how union types are rendered. * * Returning `undefined` will execute the default resolver logic. */ union?: (ctx: UnionResolverContext) => ChainResult; /** * Resolver for unknown schemas. * * Allows customization of how unknown types are rendered. * * Returning `undefined` will execute the default resolver logic. */ unknown?: (ctx: UnknownResolverContext) => ChainResult; /** * Resolvers for request and response validators. * * Allow customization of validator function bodies. * * Example path: `~resolvers.validator.request` or `~resolvers.validator.response` * * Returning `undefined` will execute the default resolver logic. */ validator?: | ValidatorResolver | { /** * Controls how the request validator function body is generated. * * Returning `undefined` will execute the default resolver logic. */ request?: ValidatorResolver; /** * Controls how the response validator function body is generated. * * Returning `undefined` will execute the default resolver logic. */ response?: ValidatorResolver; }; /** * Resolver for void schemas. * * Allows customization of how void types are rendered. * * Returning `undefined` will execute the default resolver logic. */ void?: (ctx: VoidResolverContext) => ChainResult; }>; type ValidatorResolver = ( ctx: ValidatorResolverContext, ) => MaybeArray> | null | undefined; interface BaseContext extends DollarTsDsl { /** * Functions for working with chains. */ chain: { /** * The current chain. * * In Zod, this represents a chain of method calls being assembled * to form a schema definition (e.g., `z.string().min(1).max(10)`). * * Each method can be extended, modified, or replaced to customize * the resulting schema. */ current: Chain; }; /** The plugin instance. */ plugin: ZodPlugin['Instance']; /** * Provides access to commonly used symbols within the plugin. */ symbols: { z: Symbol; }; } export interface ArrayResolverContext extends BaseContext { applyModifiers: (result: ZodResult, opts?: { optional?: boolean }) => ZodFinal; /** * Child results from processing array items. */ childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base array expression (z.array(...)). */ base: (ctx: ArrayResolverContext) => Chain; /** * Returns a length constraint (when minItems === maxItems), if applicable. */ length: (ctx: ArrayResolverContext) => ChainResult; /** * Returns a maxItems constraint, if applicable. */ maxLength: (ctx: ArrayResolverContext) => ChainResult; /** * Returns a minItems constraint, if applicable. */ minLength: (ctx: ArrayResolverContext) => ChainResult; }; schema: SchemaWithType<'array'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface BooleanResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base boolean expression (z.boolean()). */ base: (ctx: BooleanResolverContext) => Chain; /** * Returns a literal expression for the const value, if present. */ const: (ctx: BooleanResolverContext) => ChainResult; }; schema: SchemaWithType<'boolean'>; } export interface EnumResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base enum expression (z.enum([...]) or z.union([...])). */ base: (ctx: EnumResolverContext) => Chain; /** * Returns parsed enum items with metadata about the enum members. */ items: (ctx: EnumResolverContext) => { /** * Whether all enum members are strings. */ allStrings: boolean; /** * String literal values for use with z.enum([...]). */ enumMembers: Array>; /** * Whether the enum includes a null value. */ isNullable: boolean; /** * Zod literal expressions for each enum member. */ literalMembers: Array; }; }; schema: SchemaWithType<'enum'>; } export interface IntersectionResolverContext extends BaseContext { childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base intersection expression. */ base: (ctx: IntersectionResolverContext) => Chain; }; parentSchema: IR.SchemaObject; schema: IR.SchemaObject; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface NeverResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base never expression (z.never()). */ base: (ctx: NeverResolverContext) => Chain; }; schema: SchemaWithType<'never'>; } export interface NullResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base null expression (z.null()). */ base: (ctx: NullResolverContext) => Chain; }; schema: SchemaWithType<'null'>; } export interface NumberResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base number expression (z.number() or z.coerce.number()). */ base: (ctx: NumberResolverContext) => Chain; /** * Returns a literal expression for the const value, if present. */ const: (ctx: NumberResolverContext) => ChainResult; /** * Returns the maximum value constraint. */ max: (ctx: NumberResolverContext) => ChainResult; /** * Returns the minimum value constraint. */ min: (ctx: NumberResolverContext) => ChainResult; }; schema: SchemaWithType<'integer' | 'number'>; /** * Utility functions for number schema processing. */ utils: { getIntegerLimit: GetIntegerLimit; maybeBigInt: MaybeBigInt; shouldCoerceToBigInt: ShouldCoerceToBigInt; }; } export interface ObjectResolverContext extends BaseContext { /** * Child results from processing object properties. * Used for metadata composition. */ _childResults: Array; applyModifiers: (result: ZodResult, opts: { optional?: boolean }) => ZodFinal; /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the additional properties expression, if any. */ additionalProperties: (ctx: ObjectResolverContext) => Chain | null | undefined; /** * Returns the base object expression (z.object({...}) or z.record(...)). */ base: (ctx: ObjectResolverContext) => Chain; /** * Returns the object shape (property definitions). */ shape: (ctx: ObjectResolverContext) => ReturnType; }; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface StringResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base string expression (z.string()). */ base: (ctx: StringResolverContext) => Chain; /** * Returns a literal expression for the const value, if present. */ const: (ctx: StringResolverContext) => ChainResult; /** * Returns a format validation expression, if applicable. */ format: (ctx: StringResolverContext) => ChainResult; /** * Returns a length constraint (when min === max), if applicable. */ length: (ctx: StringResolverContext) => ChainResult; /** * Returns a maxLength constraint, if applicable. */ maxLength: (ctx: StringResolverContext) => ChainResult; /** * Returns a minLength constraint, if applicable. */ minLength: (ctx: StringResolverContext) => ChainResult; /** * Returns a pattern (regex) constraint, if applicable. */ pattern: (ctx: StringResolverContext) => ChainResult; }; schema: SchemaWithType<'string'>; } export interface TupleResolverContext extends BaseContext { applyModifiers: (result: ZodResult, opts?: { optional?: boolean }) => ZodFinal; childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base tuple expression (z.tuple([...])). */ base: (ctx: TupleResolverContext) => Chain; /** * Returns a literal expression for the const value, if present. */ const: (ctx: TupleResolverContext) => ChainResult; }; schema: SchemaWithType<'tuple'>; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface UndefinedResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base undefined expression (z.undefined()). */ base: (ctx: UndefinedResolverContext) => Chain; }; schema: SchemaWithType<'undefined'>; } export interface UnionResolverContext extends BaseContext { childResults: Array; /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base union expression. */ base: (ctx: UnionResolverContext) => Chain; }; parentSchema: IR.SchemaObject; schema: IR.SchemaObject; schemas: ReadonlyArray; walk: Walker; walkerCtx: SchemaVisitorContext; } export interface UnknownResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base unknown expression (z.unknown()). */ base: (ctx: UnknownResolverContext) => Chain; }; schema: SchemaWithType<'unknown'>; } export interface ValidatorResolverContext extends BaseContext { operation: IR.OperationObject; /** * Provides access to commonly used symbols within the plugin. */ symbols: BaseContext['symbols'] & { schema: Symbol; }; } export interface VoidResolverContext extends BaseContext { /** * Nodes used to build different parts of the result. */ nodes: { /** * Returns the base void expression (z.void()). */ base: (ctx: VoidResolverContext) => Chain; }; schema: SchemaWithType<'void'>; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/chain.ts ================================================ import type { $ } from '../../../ts-dsl'; export type Chain = ReturnType; export type ChainResult = Chain | undefined; ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/export.ts ================================================ import { buildSymbolIn, pathToName } from '@hey-api/shared'; import { createSchemaComment } from '../../../plugins/shared/utils/schema'; import { $ } from '../../../ts-dsl'; import { identifiers } from '../constants'; import type { ProcessorContext } from './processor'; import type { ZodFinal } from './types'; export function exportAst({ final, meta, naming, namingAnchor, path, plugin, schema, tags, }: ProcessorContext & { final: ZodFinal; meta?: Record; }): void { const z = plugin.external('zod.z'); const name = pathToName(path, { anchor: namingAnchor }); const symbol = plugin.registerSymbol( buildSymbolIn({ meta: { category: 'schema', path, tags, tool: 'zod', ...meta, }, name, naming, plugin, schema, }), ); const typeInferSymbol = naming.types.infer.enabled ? plugin.registerSymbol( buildSymbolIn({ meta: { category: 'type', path, tags, tool: 'zod', variant: 'infer', ...meta, }, name, naming: naming.types.infer, plugin, schema, }), ) : undefined; const statement = $.const(symbol) .export() .$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)) .$if(final.typeName, (c) => c.type($.type(z).attr(final.typeName!))) .assign(final.expression); plugin.node(statement); if (typeInferSymbol) { const inferType = $.type .alias(typeInferSymbol) .export() .type($.type(z).attr(identifiers.infer).generic($(symbol).typeofType())); plugin.node(inferType); } } ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/meta.ts ================================================ import type { IR } from '@hey-api/shared'; import type { ZodMeta, ZodResult } from './types'; /** * Creates default metadata from a schema. */ export function defaultMeta(schema: IR.SchemaObject): ZodMeta { return { default: schema.default, format: schema.format, hasLazy: false, isLazy: false, isObject: false, nullable: false, readonly: schema.accessScope === 'read', }; } /** * Composes metadata from child results. * * @param children - Results from walking child schemas * @param overrides - Explicit overrides (e.g., from parent schema) */ export function composeMeta( children: ReadonlyArray, overrides?: Partial, ): ZodMeta { return { default: overrides?.default, format: overrides?.format, hasLazy: overrides?.hasLazy ?? children.some((c) => c.meta.hasLazy), isLazy: overrides?.isLazy ?? children.some((c) => c.meta.isLazy), isObject: overrides?.isObject ?? children.some((c) => c.meta.isObject), nullable: overrides?.nullable ?? children.some((c) => c.meta.nullable), readonly: overrides?.readonly ?? children.some((c) => c.meta.readonly), }; } /** * Merges parent schema metadata with composed child metadata. * * @param parent - The parent schema * @param children - Results from walking child schemas */ export function inheritMeta(parent: IR.SchemaObject, children: ReadonlyArray): ZodMeta { return composeMeta(children, { default: parent.default, format: parent.format, nullable: false, readonly: parent.accessScope === 'read', }); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/module.ts ================================================ import type { ZodPlugin } from '../types'; export function getZodModule({ plugin }: { plugin: ZodPlugin['Instance'] }): string { const version = plugin.package.getVersion('zod'); if (version) { if (plugin.package.satisfies(version, '<4.0.0')) { switch (plugin.config.compatibilityVersion) { case 3: default: return 'zod'; case 4: return 'zod/v4'; case 'mini': return 'zod/v4-mini'; } } } switch (plugin.config.compatibilityVersion) { case 3: return 'zod/v3'; case 4: default: return 'zod'; case 'mini': return 'zod/mini'; } } ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/operation-schema.ts ================================================ import type { IR } from '@hey-api/shared'; export interface OperationSchemaResult { required: ReadonlyArray; schema: IR.SchemaObject; } export function buildOperationSchema(operation: IR.OperationObject): OperationSchemaResult { const requiredProperties = new Set(); const schema: IR.SchemaObject = { properties: { body: { type: 'never' }, path: { type: 'never' }, query: { type: 'never' }, }, type: 'object', }; if (operation.parameters) { // TODO: add support for cookies for (const location of ['header', 'path', 'query'] satisfies ReadonlyArray< keyof typeof operation.parameters >) { const params = operation.parameters[location]; if (!params) continue; const properties: Record = {}; const required: Array = []; const propKey = location === 'header' ? 'headers' : location; for (const key in params) { const parameter = params[key]!; properties[parameter.name] = parameter.schema; if (parameter.required) { required.push(parameter.name); requiredProperties.add(propKey); } } if (Object.keys(properties).length) { schema.properties![propKey] = { properties, required, type: 'object' }; } } } if (operation.body) { schema.properties!.body = operation.body.schema; if (operation.body.required) { requiredProperties.add('body'); } } schema.required = [...requiredProperties]; return { required: schema.required, schema }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/operation.ts ================================================ import type { IR } from '@hey-api/shared'; import { operationResponsesMap } from '@hey-api/shared'; import { buildOperationSchema } from './operation-schema'; import type { ProcessorContext, ProcessorResult } from './processor'; export function irOperationToAst({ operation, path, plugin, processor, tags, }: Pick & { operation: IR.OperationObject; processor: ProcessorResult; }): void { if (plugin.config.requests.enabled) { const { schema } = buildOperationSchema(operation); processor.process({ meta: { resource: 'operation', resourceId: operation.id, role: 'data', }, naming: plugin.config.requests, namingAnchor: operation.id, path, plugin, schema, tags, }); } if (plugin.config.responses.enabled) { if (operation.responses) { const { response } = operationResponsesMap(operation); if (response) { processor.process({ meta: { resource: 'operation', resourceId: operation.id, role: 'responses', }, naming: plugin.config.responses, namingAnchor: operation.id, path: [...path, 'responses'], plugin, schema: response, tags, }); } } } } ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/processor.ts ================================================ import type { IR, NamingConfig, SchemaProcessorContext } from '@hey-api/shared'; import type { ZodPlugin } from '../types'; import type { TypeOptions, ZodFinal } from './types'; export type ProcessorContext = SchemaProcessorContext & { /** Whether to export the result (default: true) */ export?: boolean; naming: NamingConfig & TypeOptions; /** The plugin instance. */ plugin: ZodPlugin['Instance']; schema: IR.SchemaObject; }; export type ProcessorResult = { process: (ctx: ProcessorContext) => ZodFinal | void; }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/types.ts ================================================ import type { FeatureToggle, IR, NamingOptions } from '@hey-api/shared'; import type ts from 'typescript'; import type { ZodPlugin } from '../types'; import type { Chain } from './chain'; export type ValidatorArgs = { operation: IR.OperationObject; /** The plugin instance. */ plugin: ZodPlugin['Instance']; }; export type TypeOptions = { types: { infer: NamingOptions & FeatureToggle; }; }; /** * Metadata that flows through schema walking. */ export interface ZodMeta { /** Default value from schema. */ default?: unknown; /** Original format (for BigInt coercion). */ format?: string; /** Whether this or any child contains a lazy reference. */ hasLazy: boolean; /** Whether this schema itself is emitted as lazy. */ isLazy: boolean; /** Whether this schema resolves to an object shape. */ isObject?: boolean; /** Does this schema explicitly allow null? */ nullable: boolean; /** Is this schema read-only? */ readonly: boolean; } /** * Result from walking a schema node. */ export interface ZodResult { expression: Chain; meta: ZodMeta; } /** * Finalized result after applyModifiers. */ export interface ZodFinal extends Pick { /** Type annotation for schemas requiring explicit typing (e.g., lazy). */ typeName?: string | ts.Identifier; } /** * Result from composite handlers that walk children. */ export interface CompositeHandlerResult extends Pick { childResults: Array; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/shared/webhook.ts ================================================ import type { IR } from '@hey-api/shared'; import { buildOperationSchema } from './operation-schema'; import type { ProcessorContext, ProcessorResult } from './processor'; export function irWebhookToAst({ operation, path, plugin, processor, tags, }: Pick & { operation: IR.OperationObject; processor: ProcessorResult; }): void { if (plugin.config.webhooks.enabled) { const { schema } = buildOperationSchema(operation); processor.process({ meta: { resource: 'webhook', resourceId: operation.id, role: 'data', }, naming: plugin.config.webhooks, namingAnchor: operation.id, path, plugin, schema, tags, }); } } ================================================ FILE: packages/openapi-ts/src/plugins/zod/types.ts ================================================ import type { Casing, DefinePlugin, FeatureToggle, IR, NameTransformer, NamingOptions, Plugin, } from '@hey-api/shared'; import type { $, DollarTsDsl } from '../../ts-dsl'; import type { IApi } from './api'; import type { ZodResolvers } from './resolvers'; import type { TypeOptions } from './shared/types'; export type UserConfig = Plugin.Name<'zod'> & Plugin.Hooks & Plugin.UserComments & Plugin.UserExports & ZodResolvers & { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * The compatibility version to target for generated output. * * Can be: * - `4`: [Zod 4](https://zod.dev/packages/zod) (default). * - `3`: [Zod 3](https://v3.zod.dev/). * - `'mini'`: [Zod Mini](https://zod.dev/packages/mini). * * @default 4 */ compatibilityVersion?: 3 | 4 | 'mini'; /** * Configuration for date handling in generated Zod schemas. * * Controls how date values are processed and validated using Zod's * date validation features. */ dates?: { /** * Whether to allow unqualified (timezone-less) datetimes: * * When enabled, Zod will accept datetime strings without timezone information. * When disabled, Zod will require timezone information in datetime strings. * * @default false */ local?: boolean; /** * Whether to include timezone offset information when handling dates. * * When enabled, date strings will preserve timezone information. * When disabled, dates will be treated as local time. * * @default false */ offset?: boolean; }; /** * Configuration for reusable schema definitions. * * Controls generation of shared Zod schemas that can be referenced across * requests and responses. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ definitions?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'z{{name}}' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Zod schemas. * * Controls generation of TypeScript types based on the generated Zod schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}ZodType' */ name?: NameTransformer; }; }; }; /** * Enable Zod metadata support? It's often useful to associate a schema with * some additional metadata for documentation, code generation, AI * structured outputs, form validation, and other purposes. * * Can be: * - `boolean`: Shorthand for the default metadata builder. When `true`, * attaches `{ description }` from the schema (if present) to the * generated Zod schema via the metadata API. * - `function`: Custom metadata builder. Receives `{ $, node, schema }`, * where `node` is a pre-initialized `$.object().pretty()` node. Add * properties to `node` to populate the metadata object. Return value is * ignored; an empty `node` skips metadata for that schema. * Note: **not supported for Zod 3** (use `boolean` only). * * @default false */ metadata?: | boolean | (( ctx: DollarTsDsl & { node: ReturnType; schema: IR.SchemaObject }, ) => void); /** * Configuration for request-specific Zod schemas. * * Controls generation of Zod schemas for request bodies, query parameters, path * parameters, and headers. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ requests?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'z{{name}}Data' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Zod schemas. * * Controls generation of TypeScript types based on the generated Zod schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}DataZodType' */ name?: NameTransformer; }; }; }; /** * Configuration for response-specific Zod schemas. * * Controls generation of Zod schemas for response bodies, error responses, * and status codes. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ responses?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'z{{name}}Response' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Zod schemas. * * Controls generation of TypeScript types based on the generated Zod schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}ResponseZodType' */ name?: NameTransformer; }; }; }; /** * Configuration for TypeScript type generation from Zod schemas. * * Controls generation of TypeScript types based on the generated Zod schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; }; }; /** * Configuration for webhook-specific Zod schemas. * * Controls generation of Zod schemas for webhook payloads. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default true */ webhooks?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'camelCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default 'z{{name}}WebhookRequest' */ name?: NameTransformer; /** * Configuration for TypeScript type generation from Zod schemas. * * Controls generation of TypeScript types based on the generated Zod schemas. */ types?: { /** * Configuration for `infer` types. * * Can be: * - `boolean`: Shorthand for `{ enabled: boolean }` * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default false */ infer?: | boolean | NameTransformer | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Naming pattern for generated names. * * @default '{{name}}WebhookRequestZodType' */ name?: NameTransformer; }; }; }; }; export type Config = Plugin.Name<'zod'> & Plugin.Hooks & Plugin.Comments & Plugin.Exports & ZodResolvers & { /** Casing convention for generated names. */ case: Casing; /** The compatibility version to target for generated output. */ compatibilityVersion: 3 | 4 | 'mini'; /** Configuration for date handling in generated Zod schemas. */ dates: { /** Whether to allow unqualified (timezone-less) datetimes. */ local: boolean; /** Whether to include timezone offset information when handling dates. */ offset: boolean; }; /** Configuration for reusable schema definitions. */ definitions: NamingOptions & FeatureToggle & TypeOptions; /** Enable Zod metadata support? */ metadata: | boolean | (( ctx: DollarTsDsl & { node: ReturnType; schema: IR.SchemaObject }, ) => void); /** Configuration for request-specific Zod schemas. */ requests: NamingOptions & FeatureToggle & TypeOptions; /** Configuration for response-specific Zod schemas. */ responses: NamingOptions & FeatureToggle & TypeOptions; /** Configuration for TypeScript type generation from Zod schemas. */ types: { /** Configuration for `infer` types. */ infer: FeatureToggle & { /** Casing convention for generated names. */ case: Casing; }; }; /** Configuration for webhook-specific Zod schemas. */ webhooks: NamingOptions & FeatureToggle & TypeOptions; }; export type ZodPlugin = DefinePlugin; ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/api.ts ================================================ import { $ } from '../../../ts-dsl'; import { identifiers } from '../constants'; import type { ValidatorResolverContext } from '../resolvers'; import type { ValidatorArgs } from '../shared/types'; const validatorResolver = (ctx: ValidatorResolverContext): ReturnType => { const { schema } = ctx.symbols; return $(schema).attr(identifiers.parseAsync).call('data').await().return(); }; export const createRequestValidatorV3 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'zod', }); if (!symbol) return; const z = plugin.external('zod.z'); const ctx: ValidatorResolverContext = { $, chain: { current: $(z), }, operation, plugin, symbols: { schema: symbol, z, }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.request; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } return; }; export const createResponseValidatorV3 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'responses', tool: 'zod', }); if (!symbol) return; const z = plugin.external('zod.z'); const ctx: ValidatorResolverContext = { $, chain: { current: $(z), }, operation, plugin, symbols: { schema: symbol, z, }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.response; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } return; }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/plugin.ts ================================================ import { pathToJsonPointer } from '@hey-api/shared'; import { getZodModule } from '../shared/module'; import { irOperationToAst } from '../shared/operation'; import { irWebhookToAst } from '../shared/webhook'; import type { ZodPlugin } from '../types'; import { createProcessor } from './processor'; export const handlerV3: ZodPlugin['Handler'] = ({ plugin }) => { plugin.symbol('z', { external: getZodModule({ plugin }), meta: { category: 'external', resource: 'zod.z', }, }); const processor = createProcessor(plugin); plugin.forEach('operation', 'parameter', 'requestBody', 'schema', 'webhook', (event) => { switch (event.type) { case 'operation': irOperationToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; case 'parameter': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.parameter.schema, tags: event.tags, }); break; case 'requestBody': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.requestBody.schema, tags: event.tags, }); break; case 'schema': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.schema, tags: event.tags, }); break; case 'webhook': irWebhookToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; } }); }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/processor.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { createSchemaProcessor, createSchemaWalker, pathToJsonPointer } from '@hey-api/shared'; import { exportAst } from '../shared/export'; import type { ProcessorContext, ProcessorResult } from '../shared/processor'; import type { ZodFinal } from '../shared/types'; import type { ZodPlugin } from '../types'; import { createVisitor } from './walker'; export function createProcessor(plugin: ZodPlugin['Instance']): ProcessorResult { const processor = createSchemaProcessor(); const hooks = [plugin.config['~hooks']?.schemas, plugin.context.config.parser.hooks.schemas]; function extractor(ctx: ProcessorContext): IR.SchemaObject { if (processor.hasEmitted(ctx.path)) { return ctx.schema; } for (const hook of hooks) { const result = hook?.shouldExtract?.(ctx); if (result) { process({ namingAnchor: processor.context.anchor, tags: processor.context.tags, ...ctx, }); return { $ref: pathToJsonPointer(ctx.path) }; } } return ctx.schema; } function process(ctx: ProcessorContext): ZodFinal | void { if (!processor.markEmitted(ctx.path)) return; const shouldExport = ctx.export !== false; return processor.withContext({ anchor: ctx.namingAnchor, tags: ctx.tags }, () => { const visitor = createVisitor({ schemaExtractor: extractor }); const walk = createSchemaWalker(visitor); const result = walk(ctx.schema, { path: ref(ctx.path), plugin, }); const final = visitor.applyModifiers(result, { path: ref(ctx.path), plugin, }) as ZodFinal; if (shouldExport) { exportAst({ ...ctx, final, plugin }); return; } return final; }); } return { process }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/array.ts ================================================ import { childContext, deduplicateSchema } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { ArrayResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { CompositeHandlerResult, ZodResult } from '../../shared/types'; import { unknownToAst } from './unknown'; type ArrayToAstOptions = Pick< ArrayResolverContext, 'applyModifiers' | 'plugin' | 'schema' | 'walk' | 'walkerCtx' >; function baseNode(ctx: ArrayResolverContext): Chain { const { applyModifiers, childResults, plugin, schema, symbols } = ctx; const { z } = symbols; const arrayFn = $(z).attr(identifiers.array); let normalizedSchema = schema; if (normalizedSchema.items) { normalizedSchema = deduplicateSchema({ schema: normalizedSchema }); } if (!normalizedSchema.items) { return arrayFn.call( unknownToAst({ plugin, schema: { type: 'unknown', }, }), ); } if (childResults.length === 1) { const itemNode = applyModifiers(childResults[0]!, { optional: false }).expression; return arrayFn.call(itemNode); } if (childResults.length > 1) { const itemExpressions: Array = childResults.map( (result) => applyModifiers(result, { optional: false }).expression, ); const firstSchema = normalizedSchema.items[0]; if (normalizedSchema.logicalOperator === 'and') { let intersectionExpression: Chain; if ( firstSchema?.logicalOperator === 'or' || (firstSchema?.type && firstSchema.type !== 'object') ) { intersectionExpression = $(z) .attr(identifiers.intersection) .call(...itemExpressions); } else { intersectionExpression = itemExpressions[0]!; for (let i = 1; i < itemExpressions.length; i++) { intersectionExpression = intersectionExpression .attr(identifiers.and) .call(itemExpressions[i]); } } return arrayFn.call(intersectionExpression); } else { return arrayFn.call( $(z) .attr(identifiers.union) .call($.array(...itemExpressions)), ); } } return arrayFn.call( unknownToAst({ plugin, schema: { type: 'unknown', }, }), ); } function lengthNode(ctx: ArrayResolverContext): ChainResult { const { schema } = ctx; if (schema.minItems === schema.maxItems && schema.minItems !== undefined) { return ctx.chain.current.attr(identifiers.length).call($.fromValue(schema.minItems)); } } function maxLengthNode(ctx: ArrayResolverContext): ChainResult { const { schema } = ctx; if (schema.maxItems === undefined) return; return ctx.chain.current.attr(identifiers.max).call($.fromValue(schema.maxItems)); } function minLengthNode(ctx: ArrayResolverContext): ChainResult { const { schema } = ctx; if (schema.minItems === undefined) return; return ctx.chain.current.attr(identifiers.min).call($.fromValue(schema.minItems)); } function arrayResolver(ctx: ArrayResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; const lengthResult = ctx.nodes.length(ctx); if (lengthResult) { ctx.chain.current = lengthResult; } else { const minLengthResult = ctx.nodes.minLength(ctx); if (minLengthResult) { ctx.chain.current = minLengthResult; } const maxLengthResult = ctx.nodes.maxLength(ctx); if (maxLengthResult) { ctx.chain.current = maxLengthResult; } } return ctx.chain.current; } export function arrayToAst({ applyModifiers, plugin, schema, walk, walkerCtx, }: ArrayToAstOptions): CompositeHandlerResult { const childResults: Array = []; let schemaCopy = schema; const z = plugin.external('zod.z'); if (schemaCopy.items) { schemaCopy = deduplicateSchema({ schema: schemaCopy }); schemaCopy.items!.forEach((item, index) => { const itemResult = walk(item, childContext(walkerCtx, 'items', index)); childResults.push(itemResult); }); } const ctx: ArrayResolverContext = { $, applyModifiers, chain: { current: $(z), }, childResults, nodes: { base: baseNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.array; const expression = resolver?.(ctx) ?? arrayResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/boolean.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { BooleanResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: BooleanResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.boolean).call(); } function constNode(ctx: BooleanResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (typeof schema.const !== 'boolean') return; return $(z).attr(identifiers.literal).call($.literal(schema.const)); } function booleanResolver(ctx: BooleanResolverContext): Chain { const constResult = ctx.nodes.const(ctx); if (constResult) { ctx.chain.current = constResult; return ctx.chain.current; } const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function booleanToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'boolean'>; }): Chain { const z = plugin.external('zod.z'); const ctx: BooleanResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.boolean; return resolver?.(ctx) ?? booleanResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/enum.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { EnumResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function itemsNode(ctx: EnumResolverContext): ReturnType { const { schema, symbols } = ctx; const { z } = symbols; const enumMembers: Array> = []; const literalMembers: Array = []; let isNullable = false; let allStrings = true; for (const item of schema.items ?? []) { if (item.type === 'string' && typeof item.const === 'string') { const literal = $.literal(item.const); enumMembers.push(literal); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if ( (item.type === 'number' || item.type === 'integer') && typeof item.const === 'number' ) { allStrings = false; const literal = $.literal(item.const); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if (item.type === 'boolean' && typeof item.const === 'boolean') { allStrings = false; const literal = $.literal(item.const); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if (item.type === 'null' || item.const === null) { isNullable = true; } } return { allStrings, enumMembers, isNullable, literalMembers, }; } function baseNode(ctx: EnumResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; const { allStrings, enumMembers, literalMembers } = ctx.nodes.items(ctx); if (allStrings && enumMembers.length > 0) { return $(z) .attr(identifiers.enum) .call($.array(...enumMembers)); } else if (literalMembers.length === 1) { return literalMembers[0]!; } else { return $(z) .attr(identifiers.union) .call($.array(...literalMembers)); } } function enumResolver(ctx: EnumResolverContext): Chain { const { literalMembers } = ctx.nodes.items(ctx); if (!literalMembers.length) { return ctx.chain.current; } const baseExpression = ctx.nodes.base(ctx); ctx.chain.current = baseExpression; return ctx.chain.current; } export function enumToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'enum'>; }): Chain { const z = plugin.external('zod.z'); const ctx: EnumResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, items: itemsNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.enum; return resolver?.(ctx) ?? enumResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/never.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NeverResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NeverResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.never).call(); } function neverResolver(ctx: NeverResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function neverToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'never'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NeverResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.never; return resolver?.(ctx) ?? neverResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/null.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NullResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NullResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.null).call(); } function nullResolver(ctx: NullResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function nullToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'null'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NullResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.null; return resolver?.(ctx) ?? nullResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/number.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { maybeBigInt, shouldCoerceToBigInt } from '../../../../plugins/shared/utils/coerce'; import { getIntegerLimit } from '../../../../plugins/shared/utils/formats'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NumberResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NumberResolverContext): Chain { const { schema, symbols } = ctx; const { z } = symbols; if (ctx.utils.shouldCoerceToBigInt(schema.format)) { return $(z).attr(identifiers.coerce).attr(identifiers.bigint).call(); } let chain = $(z).attr(identifiers.number).call(); if (schema.type === 'integer') { chain = chain.attr(identifiers.int).call(); } return chain; } function constNode(ctx: NumberResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.const === undefined) return; return $(z).attr(identifiers.literal).call(ctx.utils.maybeBigInt(schema.const, schema.format)); } function maxNode(ctx: NumberResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.exclusiveMaximum !== undefined) { return chain.current .attr(identifiers.lt) .call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format)); } if (schema.maximum !== undefined) { return chain.current .attr(identifiers.lte) .call(ctx.utils.maybeBigInt(schema.maximum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return chain.current .attr(identifiers.max) .call( ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.object().prop('message', $.literal(limit.maxError)), ); } return; } function minNode(ctx: NumberResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.exclusiveMinimum !== undefined) { return chain.current .attr(identifiers.gt) .call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format)); } if (schema.minimum !== undefined) { return chain.current .attr(identifiers.gte) .call(ctx.utils.maybeBigInt(schema.minimum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return chain.current .attr(identifiers.min) .call( ctx.utils.maybeBigInt(limit.minValue, schema.format), $.object().prop('message', $.literal(limit.minError)), ); } return; } function numberResolver(ctx: NumberResolverContext): Chain { const constNode = ctx.nodes.const(ctx); if (constNode) { ctx.chain.current = constNode; return ctx.chain.current; } const baseNode = ctx.nodes.base(ctx); if (baseNode) ctx.chain.current = baseNode; const minNode = ctx.nodes.min(ctx); if (minNode) ctx.chain.current = minNode; const maxNode = ctx.nodes.max(ctx); if (maxNode) ctx.chain.current = maxNode; return ctx.chain.current; } export function numberToNode({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'integer' | 'number'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NumberResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, max: maxNode, min: minNode, }, plugin, schema, symbols: { z, }, utils: { getIntegerLimit, maybeBigInt, shouldCoerceToBigInt, }, }; const resolver = plugin.config['~resolvers']?.number; return resolver?.(ctx) ?? numberResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/object.ts ================================================ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { ObjectResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { CompositeHandlerResult, ZodFinal, ZodResult } from '../../shared/types'; import type { ZodPlugin } from '../../types'; type WalkerCtx = SchemaVisitorContext; interface ObjectToAstOptions { applyModifiers: (result: ZodResult, opts: { optional?: boolean }) => ZodFinal; plugin: ZodPlugin['Instance']; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: WalkerCtx; } type ExtendedContext = ObjectResolverContext; function additionalPropertiesNode(ctx: ExtendedContext): Chain | null | undefined { const { applyModifiers, schema, walk, walkerCtx } = ctx; if ( !schema.additionalProperties || (schema.properties && Object.keys(schema.properties).length > 0) ) { return; } const additionalResult = walk( schema.additionalProperties, childContext(walkerCtx, 'additionalProperties'), ); ctx._childResults.push(additionalResult); const finalExpr = applyModifiers(additionalResult, {}); return finalExpr.expression; } function baseNode(ctx: ExtendedContext): Chain { const { nodes, symbols } = ctx; const { z } = symbols; const additional = nodes.additionalProperties(ctx); const shape = nodes.shape(ctx); if (additional) { return $(z).attr(identifiers.record).call(additional); } return $(z).attr(identifiers.object).call(shape); } function objectResolver(ctx: ExtendedContext): Chain { return ctx.nodes.base(ctx); } function shapeNode(ctx: ExtendedContext): ReturnType { const { applyModifiers, schema, walk, walkerCtx } = ctx; const shape = $.object().pretty(); for (const name in schema.properties) { const property = schema.properties[name]!; const isOptional = !schema.required?.includes(name); const propertyResult = walk(property, childContext(walkerCtx, 'properties', name)); ctx._childResults.push(propertyResult); const finalExpr = applyModifiers(propertyResult, { optional: isOptional, }); shape.prop(name, finalExpr.expression); } return shape; } export function objectToAst(options: ObjectToAstOptions): CompositeHandlerResult { const { applyModifiers, plugin, schema, walk, walkerCtx } = options; const childResults: Array = []; const z = plugin.external('zod.z'); const ctx: ExtendedContext = { $, _childResults: childResults, applyModifiers, chain: { current: $(z), }, nodes: { additionalProperties: additionalPropertiesNode, base: baseNode, shape: shapeNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.object; const node = resolver?.(ctx) ?? objectResolver(ctx); return { childResults, expression: node, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/string.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { StringResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: StringResolverContext): Chain { const { z } = ctx.symbols; return $(z).attr(identifiers.string).call(); } function constNode(ctx: StringResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (typeof schema.const !== 'string') return; return $(z).attr(identifiers.literal).call($.literal(schema.const)); } function formatNode(ctx: StringResolverContext): ChainResult { const { chain, plugin, schema } = ctx; switch (schema.format) { case 'date': return chain.current.attr(identifiers.date).call(); case 'date-time': { const obj = $.object() .$if(plugin.config.dates.offset, (o) => o.prop('offset', $.literal(true))) .$if(plugin.config.dates.local, (o) => o.prop('local', $.literal(true))); return chain.current.attr(identifiers.datetime).call(obj.hasProps() ? obj : undefined); } case 'email': return chain.current.attr(identifiers.email).call(); case 'ipv4': case 'ipv6': return chain.current.attr(identifiers.ip).call(); case 'time': return chain.current.attr(identifiers.time).call(); case 'uri': return chain.current.attr(identifiers.url).call(); case 'uuid': return chain.current.attr(identifiers.uuid).call(); } return; } function lengthNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.minLength === undefined || schema.minLength !== schema.maxLength) return; return chain.current.attr(identifiers.length).call($.literal(schema.minLength)); } function maxLengthNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.maxLength === undefined) return; return chain.current.attr(identifiers.max).call($.literal(schema.maxLength)); } function minLengthNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.minLength === undefined) return; return chain.current.attr(identifiers.min).call($.literal(schema.minLength)); } function patternNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (!schema.pattern) return; const flags = /\\[pP]\{/.test(schema.pattern) ? 'u' : undefined; return chain.current.attr(identifiers.regex).call($.regexp(schema.pattern, flags)); } function stringResolver(ctx: StringResolverContext): Chain { const constNode = ctx.nodes.const(ctx); if (constNode) { ctx.chain.current = constNode; return ctx.chain.current; } const baseNode = ctx.nodes.base(ctx); if (baseNode) ctx.chain.current = baseNode; const formatNode = ctx.nodes.format(ctx); if (formatNode) ctx.chain.current = formatNode; const lengthNode = ctx.nodes.length(ctx); if (lengthNode) { ctx.chain.current = lengthNode; } else { const minLengthNode = ctx.nodes.minLength(ctx); if (minLengthNode) ctx.chain.current = minLengthNode; const maxLengthNode = ctx.nodes.maxLength(ctx); if (maxLengthNode) ctx.chain.current = maxLengthNode; } const patternNode = ctx.nodes.pattern(ctx); if (patternNode) ctx.chain.current = patternNode; return ctx.chain.current; } export function stringToNode({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'string'>; }): Chain { const z = plugin.external('zod.z'); const ctx: StringResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, format: formatNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, pattern: patternNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.string; return resolver?.(ctx) ?? stringResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/tuple.ts ================================================ import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { TupleResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { CompositeHandlerResult, ZodResult } from '../../shared/types'; type TupleToAstOptions = Pick< TupleResolverContext, 'applyModifiers' | 'plugin' | 'schema' | 'walk' | 'walkerCtx' >; function baseNode(ctx: TupleResolverContext): Chain { const { applyModifiers, childResults, symbols } = ctx; const { z } = symbols; const tupleFn = $(z).attr(identifiers.tuple); if (childResults.length === 0) { return tupleFn.call($.array()); } const tupleElements = childResults.map( (result) => applyModifiers(result, { optional: false }).expression, ); return tupleFn.call($.array(...tupleElements)); } function constNode(ctx: TupleResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (!schema.const || !Array.isArray(schema.const)) return; const tupleElements = schema.const.map((value) => $(z).attr(identifiers.literal).call($.fromValue(value)), ); return $(z) .attr(identifiers.tuple) .call($.array(...tupleElements)); } function tupleResolver(ctx: TupleResolverContext): Chain { const constResult = ctx.nodes.const(ctx); if (constResult) { ctx.chain.current = constResult; return ctx.chain.current; } const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function tupleToAst({ applyModifiers, plugin, schema, walk, walkerCtx, }: TupleToAstOptions): CompositeHandlerResult { const childResults: Array = []; const z = plugin.external('zod.z'); if (schema.items) { schema.items.forEach((item, index) => { const itemResult = walk(item, childContext(walkerCtx, 'items', index)); childResults.push(itemResult); }); } const ctx: TupleResolverContext = { $, applyModifiers, chain: { current: $(z), }, childResults, nodes: { base: baseNode, const: constNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.tuple; const expression = resolver?.(ctx) ?? tupleResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/undefined.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { UndefinedResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: UndefinedResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.undefined).call(); } function undefinedResolver(ctx: UndefinedResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function undefinedToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'undefined'>; }): Chain { const z = plugin.external('zod.z'); const ctx: UndefinedResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.undefined; return resolver?.(ctx) ?? undefinedResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/unknown.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { UnknownResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: UnknownResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.unknown).call(); } function unknownResolver(ctx: UnknownResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function unknownToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'unknown'>; }): Chain { const z = plugin.external('zod.z'); const ctx: UnknownResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.unknown; return resolver?.(ctx) ?? unknownResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/toAst/void.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { VoidResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: VoidResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.void).call(); } function voidResolver(ctx: VoidResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function voidToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'void'>; }): Chain { const z = plugin.external('zod.z'); const ctx: VoidResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.void; return resolver?.(ctx) ?? voidResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v3/walker.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import { fromRef } from '@hey-api/codegen-core'; import type { SchemaExtractor, SchemaVisitor } from '@hey-api/shared'; import { pathToJsonPointer } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import { maybeBigInt, shouldCoerceToBigInt } from '../../shared/utils/coerce'; import { identifiers } from '../constants'; import type { Chain } from '../shared/chain'; import { defaultMeta, inheritMeta } from '../shared/meta'; import type { ProcessorContext } from '../shared/processor'; import type { ZodFinal, ZodResult } from '../shared/types'; import type { ZodPlugin } from '../types'; import { arrayToAst } from './toAst/array'; import { booleanToAst } from './toAst/boolean'; import { enumToAst } from './toAst/enum'; import { neverToAst } from './toAst/never'; import { nullToAst } from './toAst/null'; import { numberToNode } from './toAst/number'; import { objectToAst } from './toAst/object'; import { stringToNode } from './toAst/string'; import { tupleToAst } from './toAst/tuple'; import { undefinedToAst } from './toAst/undefined'; import { unknownToAst } from './toAst/unknown'; import { voidToAst } from './toAst/void'; export interface VisitorConfig { /** Optional schema extractor function. */ schemaExtractor?: SchemaExtractor; } export function createVisitor( config: VisitorConfig, ): SchemaVisitor { const { schemaExtractor } = config; return { applyModifiers(result, ctx, options = {}): ZodFinal { const { optional } = options; let expression = result.expression; if (result.meta.readonly) { expression = expression.attr(identifiers.readonly).call(); } const hasDefault = result.meta.default !== undefined; const needsNullable = result.meta.nullable; if (optional && needsNullable) { expression = expression.attr(identifiers.nullish).call(); } else if (optional) { expression = expression.attr(identifiers.optional).call(); } else if (needsNullable) { expression = expression.attr(identifiers.nullable).call(); } if (hasDefault) { expression = expression .attr(identifiers.default) .call( result.meta.format ? maybeBigInt(result.meta.default, result.meta.format) : $.fromValue(result.meta.default), ); } return { expression, typeName: result.meta.hasLazy ? result.meta.isObject ? identifiers.AnyZodObject : identifiers.ZodTypeAny : undefined, }; }, array(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = arrayToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, boolean(schema, ctx) { const expression = booleanToAst({ plugin: ctx.plugin, schema }); return { expression, meta: defaultMeta(schema), }; }, enum(schema, ctx) { const expression = enumToAst({ plugin: ctx.plugin, schema }); const hasNull = schema.items?.some((item) => item.type === 'null' || item.const === null) ?? false; return { expression, meta: { ...defaultMeta(schema), nullable: hasNull, }, }; }, integer(schema, ctx) { const expression = numberToNode({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), format: schema.format, }, }; }, intercept(schema, ctx, walk) { if (schemaExtractor && !schema.$ref) { const extracted = schemaExtractor({ meta: { resource: 'definition', resourceId: pathToJsonPointer(fromRef(ctx.path)), }, naming: ctx.plugin.config.definitions, path: fromRef(ctx.path), plugin: ctx.plugin, schema, }); if (extracted !== schema) { return walk(extracted, ctx); } } }, intersection(items, schemas, parentSchema, ctx) { const z = ctx.plugin.external('zod.z'); const hasAnyLazy = items.some((item) => item.meta.hasLazy); const firstSchema = schemas[0]; let expression: Chain; if ( firstSchema?.logicalOperator === 'or' || (firstSchema?.type && firstSchema.type !== 'object') ) { expression = $(z) .attr(identifiers.intersection) .call(...items.map((item) => item.expression)); } else { expression = items[0]!.expression; items.slice(1).forEach((item) => { expression = expression .attr(identifiers.and) .call( item.meta.hasLazy && !item.meta.isLazy ? $(z).attr(identifiers.lazy).call($.func().do(item.expression.return())) : item.expression, ); }); } return { expression, meta: { default: parentSchema.default, format: parentSchema.format, hasLazy: hasAnyLazy, isLazy: false, nullable: items.some((i) => i.meta.nullable), readonly: items.some((i) => i.meta.readonly), }, }; }, never(schema, ctx) { const expression = neverToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, null(schema, ctx) { const expression = nullToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, number(schema, ctx) { const expression = numberToNode({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), format: schema.format, }, }; }, object(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = objectToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: { ...inheritMeta(schema, childResults), isObject: true, }, }; }, postProcess(result, schema, ctx) { if (ctx.plugin.config.metadata && schema.description) { return { ...result, expression: result.expression .attr(identifiers.describe) .call($.literal(schema.description)), }; } return result; }, reference($ref, schema, ctx) { const z = ctx.plugin.external('zod.z'); const query: SymbolMeta = { category: 'schema', resource: 'definition', resourceId: $ref, tool: 'zod', }; const refSymbol = ctx.plugin.referenceSymbol(query); if (ctx.plugin.isSymbolRegistered(query)) { return { expression: $(refSymbol), meta: defaultMeta(schema), }; } return { expression: $(z) .attr(identifiers.lazy) .call($.func().do($(refSymbol).return())), meta: { ...defaultMeta(schema), hasLazy: true, isLazy: true, }, }; }, string(schema, ctx) { if (shouldCoerceToBigInt(schema.format)) { const expression = numberToNode({ plugin: ctx.plugin, schema: { ...schema, type: 'number' }, }); return { expression, meta: defaultMeta(schema), }; } const expression = stringToNode({ plugin: ctx.plugin, schema }); return { expression, meta: defaultMeta(schema), }; }, tuple(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = tupleToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, undefined(schema, ctx) { const expression = undefinedToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, union(items, schemas, parentSchema, ctx) { const z = ctx.plugin.external('zod.z'); const hasAnyLazy = items.some((item) => item.meta.hasLazy); const hasNull = schemas.some((s) => s.type === 'null') || items.some((i) => i.meta.nullable); const nonNullItems: typeof items = []; items.forEach((item, index) => { const schema = schemas[index]!; if (schema.type !== 'null' && schema.const !== null) { nonNullItems.push(item); } }); let expression: Chain; if (nonNullItems.length === 0) { expression = $(z).attr(identifiers.null).call(); } else if (nonNullItems.length === 1) { expression = nonNullItems[0]!.expression; } else { expression = $(z) .attr(identifiers.union) .call( $.array() .pretty() .elements(...nonNullItems.map((item) => item.expression)), ); } return { expression, meta: { default: parentSchema.default, format: parentSchema.format, hasLazy: hasAnyLazy, isLazy: false, nullable: hasNull, readonly: items.some((i) => i.meta.readonly), }, }; }, unknown(schema, ctx) { const expression = unknownToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, void(schema, ctx) { const expression = voidToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/api.ts ================================================ import { $ } from '../../../ts-dsl'; import { identifiers } from '../constants'; import type { ValidatorResolverContext } from '../resolvers'; import type { ValidatorArgs } from '../shared/types'; const validatorResolver = (ctx: ValidatorResolverContext): ReturnType => { const { schema } = ctx.symbols; return $(schema).attr(identifiers.parseAsync).call('data').await().return(); }; export const createRequestValidatorV4 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'data', tool: 'zod', }); if (!symbol) return; const z = plugin.external('zod.z'); const ctx: ValidatorResolverContext = { $, chain: { current: $(z), }, operation, plugin, symbols: { schema: symbol, z, }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.request; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } return; }; export const createResponseValidatorV4 = ({ operation, plugin, }: ValidatorArgs): ReturnType | undefined => { const symbol = plugin.getSymbol({ category: 'schema', resource: 'operation', resourceId: operation.id, role: 'responses', tool: 'zod', }); if (!symbol) return; const z = plugin.external('zod.z'); const ctx: ValidatorResolverContext = { $, chain: { current: $(z), }, operation, plugin, symbols: { schema: symbol, z, }, }; const validator = plugin.config['~resolvers']?.validator; const resolver = typeof validator === 'function' ? validator : validator?.response; const candidates = [resolver, validatorResolver]; for (const candidate of candidates) { const statements = candidate?.(ctx); if (statements === null) return; if (statements !== undefined) { return $.func() .async() .param('data') .do(...(statements instanceof Array ? statements : [statements])); } } return; }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/plugin.ts ================================================ import { pathToJsonPointer } from '@hey-api/shared'; import { getZodModule } from '../shared/module'; import { irOperationToAst } from '../shared/operation'; import { irWebhookToAst } from '../shared/webhook'; import type { ZodPlugin } from '../types'; import { createProcessor } from './processor'; export const handlerV4: ZodPlugin['Handler'] = ({ plugin }) => { plugin.symbol('z', { external: getZodModule({ plugin }), importKind: 'namespace', meta: { category: 'external', resource: 'zod.z', }, }); const processor = createProcessor(plugin); plugin.forEach('operation', 'parameter', 'requestBody', 'schema', 'webhook', (event) => { switch (event.type) { case 'operation': irOperationToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; case 'parameter': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.parameter.schema, tags: event.tags, }); break; case 'requestBody': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.requestBody.schema, tags: event.tags, }); break; case 'schema': processor.process({ meta: { resource: 'definition', resourceId: pathToJsonPointer(event._path), }, naming: plugin.config.definitions, path: event._path, plugin, schema: event.schema, tags: event.tags, }); break; case 'webhook': irWebhookToAst({ operation: event.operation, path: event._path, plugin, processor, tags: event.tags, }); break; } }); }; ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/processor.ts ================================================ import { ref } from '@hey-api/codegen-core'; import type { IR } from '@hey-api/shared'; import { createSchemaProcessor, createSchemaWalker, pathToJsonPointer } from '@hey-api/shared'; import { exportAst } from '../shared/export'; import type { ProcessorContext, ProcessorResult } from '../shared/processor'; import type { ZodFinal } from '../shared/types'; import type { ZodPlugin } from '../types'; import { createVisitor } from './walker'; export function createProcessor(plugin: ZodPlugin['Instance']): ProcessorResult { const processor = createSchemaProcessor(); const hooks = [plugin.config['~hooks']?.schemas, plugin.context.config.parser.hooks.schemas]; function extractor(ctx: ProcessorContext): IR.SchemaObject { if (processor.hasEmitted(ctx.path)) { return ctx.schema; } for (const hook of hooks) { const result = hook?.shouldExtract?.(ctx); if (result) { process({ namingAnchor: processor.context.anchor, tags: processor.context.tags, ...ctx, }); return { $ref: pathToJsonPointer(ctx.path) }; } } return ctx.schema; } function process(ctx: ProcessorContext): ZodFinal | void { if (!processor.markEmitted(ctx.path)) return; const shouldExport = ctx.export !== false; return processor.withContext({ anchor: ctx.namingAnchor, tags: ctx.tags }, () => { const visitor = createVisitor({ schemaExtractor: extractor }); const walk = createSchemaWalker(visitor); const result = walk(ctx.schema, { path: ref(ctx.path), plugin, }); const final = visitor.applyModifiers(result, { path: ref(ctx.path), plugin, }) as ZodFinal; if (shouldExport) { exportAst({ ...ctx, final, plugin }); return; } return final; }); } return { process }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/array.ts ================================================ import { childContext, deduplicateSchema } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { ArrayResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { CompositeHandlerResult, ZodResult } from '../../shared/types'; import { unknownToAst } from './unknown'; type ArrayToAstOptions = Pick< ArrayResolverContext, 'applyModifiers' | 'plugin' | 'schema' | 'walk' | 'walkerCtx' >; function baseNode(ctx: ArrayResolverContext): Chain { const { applyModifiers, childResults, plugin, schema, symbols } = ctx; const { z } = symbols; const arrayFn = $(z).attr(identifiers.array); let normalizedSchema = schema; if (normalizedSchema.items) { normalizedSchema = deduplicateSchema({ schema: normalizedSchema }); } if (!normalizedSchema.items) { return arrayFn.call( unknownToAst({ plugin, schema: { type: 'unknown', }, }), ); } if (childResults.length === 1) { const itemNode = applyModifiers(childResults[0]!, { optional: false }).expression; return arrayFn.call(itemNode); } if (childResults.length > 1) { const itemExpressions: Array = childResults.map( (result) => applyModifiers(result, { optional: false }).expression, ); const firstSchema = normalizedSchema.items[0]; if (normalizedSchema.logicalOperator === 'and') { let intersectionExpression: Chain; if ( firstSchema?.logicalOperator === 'or' || (firstSchema?.type && firstSchema.type !== 'object') ) { intersectionExpression = $(z) .attr(identifiers.intersection) .call(...itemExpressions); } else { intersectionExpression = itemExpressions[0]!; for (let i = 1; i < itemExpressions.length; i++) { intersectionExpression = intersectionExpression .attr(identifiers.and) .call(itemExpressions[i]); } } return arrayFn.call(intersectionExpression); } else { return arrayFn.call( $(z) .attr(identifiers.union) .call($.array(...itemExpressions)), ); } } return arrayFn.call( unknownToAst({ plugin, schema: { type: 'unknown', }, }), ); } function lengthNode(ctx: ArrayResolverContext): ChainResult { const { schema } = ctx; if (schema.minItems === schema.maxItems && schema.minItems !== undefined) { return ctx.chain.current.attr(identifiers.length).call($.fromValue(schema.minItems)); } } function maxLengthNode(ctx: ArrayResolverContext): ChainResult { const { schema } = ctx; if (schema.maxItems === undefined) return; return ctx.chain.current.attr(identifiers.max).call($.fromValue(schema.maxItems)); } function minLengthNode(ctx: ArrayResolverContext): ChainResult { const { schema } = ctx; if (schema.minItems === undefined) return; return ctx.chain.current.attr(identifiers.min).call($.fromValue(schema.minItems)); } function arrayResolver(ctx: ArrayResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; const lengthResult = ctx.nodes.length(ctx); if (lengthResult) { ctx.chain.current = lengthResult; } else { const minLengthResult = ctx.nodes.minLength(ctx); if (minLengthResult) { ctx.chain.current = minLengthResult; } const maxLengthResult = ctx.nodes.maxLength(ctx); if (maxLengthResult) { ctx.chain.current = maxLengthResult; } } return ctx.chain.current; } export function arrayToAst({ applyModifiers, plugin, schema, walk, walkerCtx, }: ArrayToAstOptions): CompositeHandlerResult { const childResults: Array = []; let schemaCopy = schema; const z = plugin.external('zod.z'); if (schemaCopy.items) { schemaCopy = deduplicateSchema({ schema: schemaCopy }); schemaCopy.items!.forEach((item, index) => { const itemResult = walk(item, childContext(walkerCtx, 'items', index)); childResults.push(itemResult); }); } const ctx: ArrayResolverContext = { $, applyModifiers, chain: { current: $(z), }, childResults, nodes: { base: baseNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.array; const expression = resolver?.(ctx) ?? arrayResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/boolean.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { BooleanResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: BooleanResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.boolean).call(); } function constNode(ctx: BooleanResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (typeof schema.const !== 'boolean') return; return $(z).attr(identifiers.literal).call($.literal(schema.const)); } function booleanResolver(ctx: BooleanResolverContext): Chain { const constResult = ctx.nodes.const(ctx); if (constResult) { ctx.chain.current = constResult; return ctx.chain.current; } const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function booleanToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'boolean'>; }): Chain { const z = plugin.external('zod.z'); const ctx: BooleanResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.boolean; return resolver?.(ctx) ?? booleanResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/enum.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { EnumResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; import { unknownToAst } from './unknown'; function itemsNode(ctx: EnumResolverContext): ReturnType { const { schema, symbols } = ctx; const { z } = symbols; const enumMembers: Array> = []; const literalMembers: Array = []; let isNullable = false; let allStrings = true; for (const item of schema.items ?? []) { if (item.type === 'string' && typeof item.const === 'string') { const literal = $.literal(item.const); enumMembers.push(literal); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if ( (item.type === 'number' || item.type === 'integer') && typeof item.const === 'number' ) { allStrings = false; const literal = $.literal(item.const); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if (item.type === 'boolean' && typeof item.const === 'boolean') { allStrings = false; const literal = $.literal(item.const); literalMembers.push($(z).attr(identifiers.literal).call(literal)); } else if (item.type === 'null' || item.const === null) { isNullable = true; } } return { allStrings, enumMembers, isNullable, literalMembers, }; } function baseNode(ctx: EnumResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; const { allStrings, enumMembers, literalMembers } = ctx.nodes.items(ctx); if (allStrings && enumMembers.length > 0) { return $(z) .attr(identifiers.enum) .call($.array(...enumMembers)); } if (literalMembers.length === 1) { return literalMembers[0]!; } return $(z) .attr(identifiers.union) .call($.array(...literalMembers)); } function enumResolver(ctx: EnumResolverContext): Chain { const { literalMembers } = ctx.nodes.items(ctx); if (!literalMembers.length) { return ctx.chain.current; } const baseExpression = ctx.nodes.base(ctx); ctx.chain.current = baseExpression; return ctx.chain.current; } export function enumToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'enum'>; }): Chain { const z = plugin.external('zod.z'); const ctx: EnumResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, items: itemsNode, }, plugin, schema, symbols: { z, }, }; const { literalMembers } = itemsNode(ctx); if (!literalMembers.length) { return unknownToAst({ plugin, schema: { type: 'unknown', }, }); } const resolver = plugin.config['~resolvers']?.enum; return resolver?.(ctx) ?? enumResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/intersection.ts ================================================ import type { IR } from '@hey-api/shared'; import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { IntersectionResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodResult } from '../../shared/types'; type IntersectionToAstOptions = Pick< IntersectionResolverContext, 'parentSchema' | 'plugin' | 'walk' | 'walkerCtx' > & { schemas: ReadonlyArray; }; function baseNode(ctx: IntersectionResolverContext): Chain { const { childResults, symbols } = ctx; const { z } = symbols; if (childResults.length === 0) { return $(z).attr(identifiers.never).call(); } return $(z) .attr(identifiers.intersection) .call(...childResults.map((result) => result.expression)); } function intersectionResolver(ctx: IntersectionResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function intersectionToAst({ parentSchema, plugin, schemas, walk, walkerCtx, }: IntersectionToAstOptions): { childResults: Array; expression: Chain; } { const z = plugin.external('zod.z'); const childResults: Array = []; schemas.forEach((schema, index) => { const itemResult = walk(schema, childContext(walkerCtx, 'allOf', index)); childResults.push(itemResult); }); const ctx: IntersectionResolverContext = { $, chain: { current: $(z), }, childResults, nodes: { base: baseNode, }, parentSchema, plugin, schema: parentSchema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.intersection; const expression = resolver?.(ctx) ?? intersectionResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/never.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NeverResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NeverResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.never).call(); } function neverResolver(ctx: NeverResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function neverToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'never'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NeverResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.never; return resolver?.(ctx) ?? neverResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/null.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NullResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NullResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.null).call(); } function nullResolver(ctx: NullResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function nullToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'null'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NullResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.null; return resolver?.(ctx) ?? nullResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/number.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { maybeBigInt, shouldCoerceToBigInt } from '../../../../plugins/shared/utils/coerce'; import { getIntegerLimit } from '../../../../plugins/shared/utils/formats'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { NumberResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: NumberResolverContext): Chain { const { schema, symbols } = ctx; const { z } = symbols; if (ctx.utils.shouldCoerceToBigInt(schema.format)) { return $(z).attr(identifiers.coerce).attr(identifiers.bigint).call(); } let chain = $(z).attr(identifiers.number).call(); if (schema.type === 'integer') { chain = $(z).attr(identifiers.int).call(); } return chain; } function constNode(ctx: NumberResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (schema.const === undefined) return; return $(z).attr(identifiers.literal).call(ctx.utils.maybeBigInt(schema.const, schema.format)); } function maxNode(ctx: NumberResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.exclusiveMaximum !== undefined) { return chain.current .attr(identifiers.lt) .call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format)); } if (schema.maximum !== undefined) { return chain.current .attr(identifiers.lte) .call(ctx.utils.maybeBigInt(schema.maximum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return chain.current .attr(identifiers.max) .call( ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.object().prop('error', $.literal(limit.maxError)), ); } return; } function minNode(ctx: NumberResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.exclusiveMinimum !== undefined) { return chain.current .attr(identifiers.gt) .call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format)); } if (schema.minimum !== undefined) { return chain.current .attr(identifiers.gte) .call(ctx.utils.maybeBigInt(schema.minimum, schema.format)); } const limit = ctx.utils.getIntegerLimit(schema.format); if (limit) { return chain.current .attr(identifiers.min) .call( ctx.utils.maybeBigInt(limit.minValue, schema.format), $.object().prop('error', $.literal(limit.minError)), ); } return; } function numberResolver(ctx: NumberResolverContext): Chain { const constNode = ctx.nodes.const(ctx); if (constNode) { ctx.chain.current = constNode; return ctx.chain.current; } const baseNode = ctx.nodes.base(ctx); if (baseNode) ctx.chain.current = baseNode; const minNode = ctx.nodes.min(ctx); if (minNode) ctx.chain.current = minNode; const maxNode = ctx.nodes.max(ctx); if (maxNode) ctx.chain.current = maxNode; return ctx.chain.current; } export function numberToNode({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'integer' | 'number'>; }): Chain { const z = plugin.external('zod.z'); const ctx: NumberResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, max: maxNode, min: minNode, }, plugin, schema, symbols: { z, }, utils: { getIntegerLimit, maybeBigInt, shouldCoerceToBigInt, }, }; const resolver = plugin.config['~resolvers']?.number; return resolver?.(ctx) ?? numberResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/object.ts ================================================ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { ObjectResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { CompositeHandlerResult, ZodFinal, ZodResult } from '../../shared/types'; import type { ZodPlugin } from '../../types'; type WalkerCtx = SchemaVisitorContext; interface ObjectToAstOptions { applyModifiers: (result: ZodResult, opts: { optional?: boolean }) => ZodFinal; plugin: ZodPlugin['Instance']; schema: SchemaWithType<'object'>; walk: Walker; walkerCtx: WalkerCtx; } type ExtendedContext = ObjectResolverContext & { applyModifiers: ObjectToAstOptions['applyModifiers']; walk: ObjectToAstOptions['walk']; walkerCtx: ObjectToAstOptions['walkerCtx']; }; function additionalPropertiesNode(ctx: ExtendedContext): Chain | null | undefined { const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx; if ( !schema.additionalProperties || (schema.properties && Object.keys(schema.properties).length > 0) ) { return; } const additionalResult = walk( schema.additionalProperties, childContext(walkerCtx, 'additionalProperties'), ); _childResults.push(additionalResult); const finalExpr = applyModifiers(additionalResult, {}); return finalExpr.expression; } function baseNode(ctx: ExtendedContext): Chain { const { nodes, symbols } = ctx; const { z } = symbols; const additional = nodes.additionalProperties(ctx); const shape = nodes.shape(ctx); if (additional) { return $(z).attr(identifiers.record).call($(z).attr(identifiers.string).call(), additional); } return $(z).attr(identifiers.object).call(shape); } function objectResolver(ctx: ExtendedContext): Chain { return ctx.nodes.base(ctx); } function shapeNode(ctx: ExtendedContext): ReturnType { const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx; const shape = $.object().pretty(); for (const name in schema.properties) { const property = schema.properties[name]!; const isOptional = !schema.required?.includes(name); const propertyResult = walk(property, childContext(walkerCtx, 'properties', name)); _childResults.push(propertyResult); const finalExpr = applyModifiers(propertyResult, { optional: isOptional, }); shape.prop(name, finalExpr.expression); } return shape; } export function objectToAst(options: ObjectToAstOptions): CompositeHandlerResult { const { applyModifiers, plugin, schema, walk, walkerCtx } = options; const childResults: Array = []; const z = plugin.external('zod.z'); const ctx: ExtendedContext = { $, _childResults: childResults, applyModifiers, chain: { current: $(z), }, nodes: { additionalProperties: additionalPropertiesNode, base: baseNode, shape: shapeNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.object; const node = resolver?.(ctx) ?? objectResolver(ctx); return { childResults, expression: node, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/string.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { StringResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: StringResolverContext): Chain { const { z } = ctx.symbols; return $(z).attr(identifiers.string).call(); } function constNode(ctx: StringResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (typeof schema.const !== 'string') return; return $(z).attr(identifiers.literal).call($.literal(schema.const)); } function formatNode(ctx: StringResolverContext): ChainResult { const { plugin, schema, symbols } = ctx; const { z } = symbols; switch (schema.format) { case 'date': return $(z).attr(identifiers.iso).attr(identifiers.date).call(); case 'date-time': { const obj = $.object() .$if(plugin.config.dates.offset, (o) => o.prop('offset', $.literal(true))) .$if(plugin.config.dates.local, (o) => o.prop('local', $.literal(true))); return $(z) .attr(identifiers.iso) .attr(identifiers.datetime) .call(obj.hasProps() ? obj : undefined); } case 'email': return $(z).attr(identifiers.email).call(); case 'guid': return $(z).attr(identifiers.guid).call(); case 'ipv4': return $(z).attr(identifiers.ipv4).call(); case 'ipv6': return $(z).attr(identifiers.ipv6).call(); case 'time': return $(z).attr(identifiers.iso).attr(identifiers.time).call(); case 'uri': return $(z).attr(identifiers.url).call(); case 'uuid': return $(z).attr(identifiers.uuid).call(); } return; } function lengthNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.minLength === undefined || schema.minLength !== schema.maxLength) return; return chain.current.attr(identifiers.length).call($.literal(schema.minLength)); } function maxLengthNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.maxLength === undefined) return; return chain.current.attr(identifiers.max).call($.literal(schema.maxLength)); } function minLengthNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (schema.minLength === undefined) return; return chain.current.attr(identifiers.min).call($.literal(schema.minLength)); } function patternNode(ctx: StringResolverContext): ChainResult { const { chain, schema } = ctx; if (!schema.pattern) return; const flags = /\\[pP]\{/.test(schema.pattern) ? 'u' : undefined; return chain.current.attr(identifiers.regex).call($.regexp(schema.pattern, flags)); } function stringResolver(ctx: StringResolverContext): Chain { const constNode = ctx.nodes.const(ctx); if (constNode) { ctx.chain.current = constNode; return ctx.chain.current; } const baseNode = ctx.nodes.base(ctx); if (baseNode) ctx.chain.current = baseNode; const formatNode = ctx.nodes.format(ctx); if (formatNode) ctx.chain.current = formatNode; const lengthNode = ctx.nodes.length(ctx); if (lengthNode) { ctx.chain.current = lengthNode; } else { const minLengthNode = ctx.nodes.minLength(ctx); if (minLengthNode) ctx.chain.current = minLengthNode; const maxLengthNode = ctx.nodes.maxLength(ctx); if (maxLengthNode) ctx.chain.current = maxLengthNode; } const patternNode = ctx.nodes.pattern(ctx); if (patternNode) ctx.chain.current = patternNode; return ctx.chain.current; } export function stringToNode({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'string'>; }): Chain { const z = plugin.external('zod.z'); const ctx: StringResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, const: constNode, format: formatNode, length: lengthNode, maxLength: maxLengthNode, minLength: minLengthNode, pattern: patternNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.string; return resolver?.(ctx) ?? stringResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/tuple.ts ================================================ import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { TupleResolverContext } from '../../resolvers'; import type { Chain, ChainResult } from '../../shared/chain'; import type { CompositeHandlerResult, ZodResult } from '../../shared/types'; type TupleToAstOptions = Pick< TupleResolverContext, 'applyModifiers' | 'plugin' | 'schema' | 'walk' | 'walkerCtx' >; function baseNode(ctx: TupleResolverContext): Chain { const { applyModifiers, childResults, symbols } = ctx; const { z } = symbols; const tupleFn = $(z).attr(identifiers.tuple); if (childResults.length === 0) { return tupleFn.call($.array()); } const tupleElements = childResults.map( (result) => applyModifiers(result, { optional: false }).expression, ); return tupleFn.call($.array(...tupleElements)); } function constNode(ctx: TupleResolverContext): ChainResult { const { schema, symbols } = ctx; const { z } = symbols; if (!schema.const || !Array.isArray(schema.const)) return; const tupleElements = schema.const.map((value) => $(z).attr(identifiers.literal).call($.fromValue(value)), ); return $(z) .attr(identifiers.tuple) .call($.array(...tupleElements)); } function tupleResolver(ctx: TupleResolverContext): Chain { const constResult = ctx.nodes.const(ctx); if (constResult) { ctx.chain.current = constResult; return ctx.chain.current; } const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function tupleToAst({ applyModifiers, plugin, schema, walk, walkerCtx, }: TupleToAstOptions): CompositeHandlerResult { const childResults: Array = []; const z = plugin.external('zod.z'); if (schema.items) { schema.items.forEach((item, index) => { const itemResult = walk(item, childContext(walkerCtx, 'items', index)); childResults.push(itemResult); }); } const ctx: TupleResolverContext = { $, applyModifiers, chain: { current: $(z), }, childResults, nodes: { base: baseNode, const: constNode, }, plugin, schema, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.tuple; const expression = resolver?.(ctx) ?? tupleResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/undefined.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { UndefinedResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: UndefinedResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.undefined).call(); } function undefinedResolver(ctx: UndefinedResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function undefinedToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'undefined'>; }): Chain { const z = plugin.external('zod.z'); const ctx: UndefinedResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.undefined; return resolver?.(ctx) ?? undefinedResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/union.ts ================================================ import { childContext } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { UnionResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodResult } from '../../shared/types'; type UnionToAstOptions = Pick< UnionResolverContext, 'parentSchema' | 'plugin' | 'schemas' | 'walk' | 'walkerCtx' >; function baseNode(ctx: UnionResolverContext): Chain { const { childResults, schemas, symbols } = ctx; const { z } = symbols; if (childResults.length === 0) { return $(z).attr(identifiers.null).call(); } const nonNullItems: Array = []; childResults.forEach((result, index) => { const schema = schemas[index]!; if (schema.type !== 'null' && schema.const !== null) { nonNullItems.push(result); } }); let expression: Chain; if (nonNullItems.length === 0) { expression = $(z).attr(identifiers.null).call(); } else if (nonNullItems.length === 1) { expression = nonNullItems[0]!.expression; } else { expression = $(z) .attr(identifiers.union) .call( $.array() .pretty() .elements(...nonNullItems.map((item) => item.expression)), ); } return expression; } function unionResolver(ctx: UnionResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function unionToAst({ parentSchema, plugin, schemas, walk, walkerCtx }: UnionToAstOptions): { childResults: Array; expression: Chain; } { const z = plugin.external('zod.z'); const childResults: Array = []; schemas.forEach((schema, index) => { const itemResult = walk(schema, childContext(walkerCtx, 'anyOf', index)); childResults.push(itemResult); }); const ctx: UnionResolverContext = { $, chain: { current: $(z), }, childResults, nodes: { base: baseNode, }, parentSchema, plugin, schema: parentSchema, schemas, symbols: { z, }, walk, walkerCtx, }; const resolver = plugin.config['~resolvers']?.union; const expression = resolver?.(ctx) ?? unionResolver(ctx); return { childResults, expression, }; } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/unknown.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { UnknownResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: UnknownResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.unknown).call(); } function unknownResolver(ctx: UnknownResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function unknownToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'unknown'>; }): Chain { const z = plugin.external('zod.z'); const ctx: UnknownResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.unknown; return resolver?.(ctx) ?? unknownResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/toAst/void.ts ================================================ import type { SchemaWithType } from '@hey-api/shared'; import { $ } from '../../../../ts-dsl'; import { identifiers } from '../../constants'; import type { VoidResolverContext } from '../../resolvers'; import type { Chain } from '../../shared/chain'; import type { ZodPlugin } from '../../types'; function baseNode(ctx: VoidResolverContext): Chain { const { symbols } = ctx; const { z } = symbols; return $(z).attr(identifiers.void).call(); } function voidResolver(ctx: VoidResolverContext): Chain { const baseResult = ctx.nodes.base(ctx); ctx.chain.current = baseResult; return ctx.chain.current; } export function voidToAst({ plugin, schema, }: { plugin: ZodPlugin['Instance']; schema: SchemaWithType<'void'>; }): Chain { const z = plugin.external('zod.z'); const ctx: VoidResolverContext = { $, chain: { current: $(z), }, nodes: { base: baseNode, }, plugin, schema, symbols: { z, }, }; const resolver = plugin.config['~resolvers']?.void; return resolver?.(ctx) ?? voidResolver(ctx); } ================================================ FILE: packages/openapi-ts/src/plugins/zod/v4/walker.ts ================================================ import type { SymbolMeta } from '@hey-api/codegen-core'; import { fromRef } from '@hey-api/codegen-core'; import type { SchemaExtractor, SchemaVisitor } from '@hey-api/shared'; import { pathToJsonPointer } from '@hey-api/shared'; import { $ } from '../../../ts-dsl'; import { maybeBigInt, shouldCoerceToBigInt } from '../../shared/utils/coerce'; import { identifiers } from '../constants'; import type { Chain } from '../shared/chain'; import { defaultMeta, inheritMeta } from '../shared/meta'; import type { ProcessorContext } from '../shared/processor'; import type { ZodFinal, ZodResult } from '../shared/types'; import type { ZodPlugin } from '../types'; import { arrayToAst } from './toAst/array'; import { booleanToAst } from './toAst/boolean'; import { enumToAst } from './toAst/enum'; import { neverToAst } from './toAst/never'; import { nullToAst } from './toAst/null'; import { numberToNode } from './toAst/number'; import { objectToAst } from './toAst/object'; import { stringToNode } from './toAst/string'; import { tupleToAst } from './toAst/tuple'; import { undefinedToAst } from './toAst/undefined'; import { unknownToAst } from './toAst/unknown'; import { voidToAst } from './toAst/void'; export interface VisitorConfig { /** Optional schema extractor function. */ schemaExtractor?: SchemaExtractor; } export function createVisitor( config: VisitorConfig, ): SchemaVisitor { const { schemaExtractor } = config; return { applyModifiers(result, ctx, options = {}): ZodFinal { const { optional } = options; let expression = result.expression; if (result.meta.readonly) { expression = expression.attr(identifiers.readonly).call(); } const hasDefault = result.meta.default !== undefined; const needsNullable = result.meta.nullable; if (optional && needsNullable) { expression = expression.attr(identifiers.nullish).call(); } else if (optional) { expression = expression.attr(identifiers.optional).call(); } else if (needsNullable) { expression = expression.attr(identifiers.nullable).call(); } if (hasDefault) { expression = expression .attr(identifiers.default) .call( result.meta.format ? maybeBigInt(result.meta.default, result.meta.format) : $.fromValue(result.meta.default), ); } return { expression, }; }, array(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = arrayToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, boolean(schema, ctx) { const expression = booleanToAst({ plugin: ctx.plugin, schema }); return { expression, meta: defaultMeta(schema), }; }, enum(schema, ctx) { const expression = enumToAst({ plugin: ctx.plugin, schema }); const hasNull = schema.items?.some((item) => item.type === 'null' || item.const === null) ?? false; return { expression, meta: { ...defaultMeta(schema), nullable: hasNull, }, }; }, integer(schema, ctx) { const expression = numberToNode({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), format: schema.format, }, }; }, intercept(schema, ctx, walk) { if (schemaExtractor && !schema.$ref) { const extracted = schemaExtractor({ meta: { resource: 'definition', resourceId: pathToJsonPointer(fromRef(ctx.path)), }, naming: ctx.plugin.config.definitions, path: fromRef(ctx.path), plugin: ctx.plugin, schema, }); if (extracted !== schema) { return walk(extracted, ctx); } } }, intersection(items, schemas, parentSchema, ctx) { const z = ctx.plugin.external('zod.z'); const hasAnyLazy = items.some((item) => item.meta.hasLazy); const firstSchema = schemas[0]; let expression: Chain; if ( firstSchema?.logicalOperator === 'or' || (firstSchema?.type && firstSchema.type !== 'object') ) { expression = $(z) .attr(identifiers.intersection) .call(...items.map((item) => item.expression)); } else { expression = items[0]!.expression; items.slice(1).forEach((item) => { expression = expression .attr(identifiers.and) .call( item.meta.hasLazy ? $(z).attr(identifiers.lazy).call($.func().do(item.expression.return())) : item.expression, ); }); } return { expression, meta: { default: parentSchema.default, format: parentSchema.format, hasLazy: hasAnyLazy, isLazy: false, nullable: items.some((i) => i.meta.nullable), readonly: items.some((i) => i.meta.readonly), }, }; }, never(schema, ctx) { const expression = neverToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, null(schema, ctx) { const expression = nullToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, number(schema, ctx) { const expression = numberToNode({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), format: schema.format, }, }; }, object(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = objectToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, postProcess(result, schema, ctx) { const { metadata } = ctx.plugin.config; if (!metadata) { return result; } const node = $.object(); if (metadata === true) { if (!schema.description) { return result; } node.pretty().prop('description', $.literal(schema.description)); } else { metadata({ $, node, schema }); } if (node.isEmpty) { return result; } const z = ctx.plugin.external('zod.z'); return { ...result, expression: result.expression .attr(identifiers.register) .call($(z).attr(identifiers.globalRegistry), node), }; }, reference($ref, schema, ctx) { const z = ctx.plugin.external('zod.z'); const query: SymbolMeta = { category: 'schema', resource: 'definition', resourceId: $ref, tool: 'zod', }; const refSymbol = ctx.plugin.referenceSymbol(query); if (ctx.plugin.isSymbolRegistered(query)) { return { expression: $(refSymbol), meta: defaultMeta(schema), }; } return { expression: $(z) .attr(identifiers.lazy) .call($.func().returns('any').do($(refSymbol).return())), meta: { ...defaultMeta(schema), hasLazy: true, isLazy: true, }, }; }, string(schema, ctx) { if (shouldCoerceToBigInt(schema.format)) { const expression = numberToNode({ plugin: ctx.plugin, schema: { ...schema, type: 'number' }, }); return { expression, meta: defaultMeta(schema), }; } const expression = stringToNode({ plugin: ctx.plugin, schema }); return { expression, meta: defaultMeta(schema), }; }, tuple(schema, ctx, walk) { const applyModifiers: Parameters[0]['applyModifiers'] = (result, opts) => this.applyModifiers(result, ctx, opts) as ZodFinal; const { childResults, expression } = tupleToAst({ applyModifiers, plugin: ctx.plugin, schema, walk, walkerCtx: ctx, }); return { expression, meta: inheritMeta(schema, childResults), }; }, undefined(schema, ctx) { const expression = undefinedToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, union(items, schemas, parentSchema, ctx) { const z = ctx.plugin.external('zod.z'); const hasAnyLazy = items.some((item) => item.meta.hasLazy); const hasNull = schemas.some((s) => s.type === 'null') || items.some((i) => i.meta.nullable); const nonNullItems: typeof items = []; items.forEach((item, index) => { const schema = schemas[index]!; if (schema.type !== 'null' && schema.const !== null) { nonNullItems.push(item); } }); let expression: Chain; if (nonNullItems.length === 0) { expression = $(z).attr(identifiers.null).call(); } else if (nonNullItems.length === 1) { expression = nonNullItems[0]!.expression; } else { expression = $(z) .attr(identifiers.union) .call( $.array() .pretty() .elements(...nonNullItems.map((item) => item.expression)), ); } return { expression, meta: { default: parentSchema.default, format: parentSchema.format, hasLazy: hasAnyLazy, isLazy: false, nullable: hasNull, readonly: items.some((i) => i.meta.readonly), }, }; }, unknown(schema, ctx) { const expression = unknownToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, void(schema, ctx) { const expression = voidToAst({ plugin: ctx.plugin, schema }); return { expression, meta: { ...defaultMeta(schema), nullable: false, readonly: false, }, }; }, }; } ================================================ FILE: packages/openapi-ts/src/run.ts ================================================ #!/usr/bin/env node import { runCli } from './cli'; runCli(); ================================================ FILE: packages/openapi-ts/src/ts-compiler/__snapshots__/nodes/expressions/identifier/identifier.ts ================================================ let x; let y; y = 42; x = y; ================================================ FILE: packages/openapi-ts/src/ts-compiler/__snapshots__/nodes/expressions/literal/primitive.ts ================================================ let s; let n; let b; let c; let none; s = "hello"; n = 123; b = true; c = false; none = null; ================================================ FILE: packages/openapi-ts/src/ts-compiler/__snapshots__/nodes/statements/var/const.ts ================================================ const answer = 42; ================================================ FILE: packages/openapi-ts/src/ts-compiler/__snapshots__/nodes/statements/var/let.ts ================================================ let message = "hello"; ================================================ FILE: packages/openapi-ts/src/ts-compiler/__snapshots__/nodes/statements/var/var.ts ================================================ var count = 0; ================================================ FILE: packages/openapi-ts/src/ts-compiler/__tests__/constants.ts ================================================ import path from 'node:path'; export const snapshotsDir = path.join(__dirname, '..', '__snapshots__'); export const tmpDir = path.join(__dirname, '..', '.tmp'); ================================================ FILE: packages/openapi-ts/src/ts-compiler/__tests__/globalTeardown.ts ================================================ import fs from 'node:fs'; import { tmpDir } from './constants'; export function teardown() { fs.rmSync(tmpDir, { force: true, recursive: true }); } ================================================ FILE: packages/openapi-ts/src/ts-compiler/__tests__/nodes/expressions/identifier.test.ts ================================================ import { ts } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('identifier expression', () => { it('assignment', async () => { const file = ts.factory.createSourceFile([ ts.factory.createVariableStatement('let', 'x'), ts.factory.createVariableStatement('let', 'y'), ts.factory.createAssignment( ts.factory.createIdentifier('y'), undefined, ts.factory.createLiteral(42), ), ts.factory.createAssignment( ts.factory.createIdentifier('x'), undefined, ts.factory.createIdentifier('y'), ), ]); await assertPrintedMatchesSnapshot(file, 'identifier.ts'); }); }); ================================================ FILE: packages/openapi-ts/src/ts-compiler/__tests__/nodes/expressions/literal.test.ts ================================================ import { ts } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('literal expression', () => { it('primitive variables', async () => { const file = ts.factory.createSourceFile([ ts.factory.createVariableStatement('let', 's'), ts.factory.createVariableStatement('let', 'n'), ts.factory.createVariableStatement('let', 'b'), ts.factory.createVariableStatement('let', 'c'), ts.factory.createVariableStatement('let', 'none'), ts.factory.createAssignment( ts.factory.createIdentifier('s'), undefined, ts.factory.createLiteral('hello'), ), ts.factory.createAssignment( ts.factory.createIdentifier('n'), undefined, ts.factory.createLiteral(123), ), ts.factory.createAssignment( ts.factory.createIdentifier('b'), undefined, ts.factory.createLiteral(true), ), ts.factory.createAssignment( ts.factory.createIdentifier('c'), undefined, ts.factory.createLiteral(false), ), ts.factory.createAssignment( ts.factory.createIdentifier('none'), undefined, ts.factory.createLiteral(null), ), ]); await assertPrintedMatchesSnapshot(file, 'primitive.ts'); }); }); ================================================ FILE: packages/openapi-ts/src/ts-compiler/__tests__/nodes/statements/var.test.ts ================================================ import { ts } from '../../../index'; import { assertPrintedMatchesSnapshot } from '../utils'; describe('variable statement', () => { it('const', async () => { const file = ts.factory.createSourceFile([ ts.factory.createVariableStatement('const', 'answer', ts.factory.createLiteral(42)), ]); await assertPrintedMatchesSnapshot(file, 'const.ts'); }); it('let', async () => { const file = ts.factory.createSourceFile([ ts.factory.createVariableStatement('let', 'message', ts.factory.createLiteral('hello')), ]); await assertPrintedMatchesSnapshot(file, 'let.ts'); }); it('var', async () => { const file = ts.factory.createSourceFile([ ts.factory.createVariableStatement('var', 'count', ts.factory.createLiteral(0)), ]); await assertPrintedMatchesSnapshot(file, 'var.ts'); }); }); ================================================ FILE: packages/openapi-ts/src/ts-compiler/__tests__/nodes/utils.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { ts } from '../../index'; import { snapshotsDir, tmpDir } from '../constants'; function getCallerFile(): string { const error = new Error(); const stack = (error.stack ?? '').split('\n'); const callerLine = stack.find((line) => line.includes('.test.ts')); if (!callerLine) { throw new Error('Could not find test file in stack trace'); } const match = callerLine.match(/\(([^)]+)\)/) || callerLine.match(/at (.+):\d+:\d+/); if (!match?.[1]) { throw new Error('Could not extract file path'); } return match[1]; } export async function assertPrintedMatchesSnapshot( file: ts.SourceFile, filename: string, ): Promise { const result = ts.createPrinter().printFile(file); const caller = getCallerFile(); const relPath = path .relative(path.join(process.cwd(), 'src', 'ts-compiler', '__tests__'), caller) .replace(/\.test\.ts$/, ''); const outputPath = path.join(tmpDir, relPath, filename); const outputDir = path.dirname(outputPath); fs.mkdirSync(outputDir, { recursive: true }); fs.writeFileSync(outputPath, result); const snapshotPath = path.join(snapshotsDir, relPath, filename); const snapshotDir = path.dirname(snapshotPath); fs.mkdirSync(snapshotDir, { recursive: true }); await expect(result).toMatchFileSnapshot(snapshotPath); } ================================================ FILE: packages/openapi-ts/src/ts-compiler/index.ts ================================================ import type { TsNode as _TsNode, TsNodeBase as _TsNodeBase } from './nodes/base'; import type { TsExpression as _TsExpression } from './nodes/expression'; import type { TsIdentifier as _TsIdentifier } from './nodes/expressions/identifier'; import type { TsLiteral as _TsLiteral, TsLiteralValue as _TsLiteralValue, } from './nodes/expressions/literal'; import { factory } from './nodes/factory'; import { TsNodeKind } from './nodes/kinds'; import type { TsStatement as _TsStatement } from './nodes/statement'; import type { TsAssignment as _TsAssignment } from './nodes/statements/assignment'; import type { TsVariableStatement as _TsVariableStatement } from './nodes/statements/var'; import type { TsSourceFile } from './nodes/structure/sourceFile'; import type { TsType as _TsType } from './nodes/type'; import type { TsPrinterOptions as _TsPrinterOptions } from './printer'; import { createPrinter, printAst } from './printer'; // eslint-disable-next-line @typescript-eslint/no-namespace export namespace ts { // Base / Core export type Node = _TsNode; export type NodeBase = _TsNodeBase; export type NodeKind = TsNodeKind; export type Expression = _TsExpression; export type Statement = _TsStatement; export type Type = _TsType; // Structure export type SourceFile = TsSourceFile; // Declarations // ... // Statements export type Assignment = _TsAssignment; export type VariableStatement = _TsVariableStatement; // Expressions export type Identifier = _TsIdentifier; export type Literal = _TsLiteral; // Printer export type PrinterOptions = _TsPrinterOptions; // Miscellaneous export type LiteralValue = _TsLiteralValue; } export const ts = { TsNodeKind, createPrinter, factory, printAst, } as const; export { factory }; ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/base.ts ================================================ import type { TsExpression } from './expression'; import type { TsNodeKind } from './kinds'; import type { TsStatement } from './statement'; // import type { TsBlock } from './statements/block'; import type { TsSourceFile } from './structure/sourceFile'; export interface TsNodeBase { kind: TsNodeKind; leadingComments?: ReadonlyArray; trailingComments?: ReadonlyArray; } // TsBlock | export type TsNode = TsExpression | TsSourceFile | TsStatement; ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/expression.ts ================================================ import type { TsIdentifier } from './expressions/identifier'; import type { TsLiteral } from './expressions/literal'; export type TsExpression = TsIdentifier | TsLiteral; ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/expressions/identifier.ts ================================================ import type { TsNodeBase } from '../base'; import { TsNodeKind } from '../kinds'; export interface TsIdentifier extends TsNodeBase { kind: TsNodeKind.Identifier; text: string; } export function createIdentifier( text: string, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): TsIdentifier { return { kind: TsNodeKind.Identifier, leadingComments, text, trailingComments, }; } ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/expressions/literal.ts ================================================ import type { TsNodeBase } from '../base'; import { TsNodeKind } from '../kinds'; export type TsLiteralValue = string | number | boolean | bigint | null; export interface TsLiteral extends TsNodeBase { kind: TsNodeKind.Literal; value: TsLiteralValue; } export function createLiteral( value: TsLiteralValue, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): TsLiteral { return { kind: TsNodeKind.Literal, leadingComments, trailingComments, value, }; } ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/factory.ts ================================================ import { createIdentifier } from './expressions/identifier'; import { createLiteral } from './expressions/literal'; import { createAssignment } from './statements/assignment'; import { createVariableStatement } from './statements/var'; import { createSourceFile } from './structure/sourceFile'; export const factory = { createAssignment, createIdentifier, createLiteral, createSourceFile, createVariableStatement, }; ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/kinds.ts ================================================ export enum TsNodeKind { Assignment = 'Assignment', Identifier = 'Identifier', Literal = 'Literal', SourceFile = 'SourceFile', VariableStatement = 'VariableStatement', } ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/statement.ts ================================================ import type { TsAssignment } from './statements/assignment'; import type { TsVariableStatement } from './statements/var'; export type TsStatement = TsAssignment | TsVariableStatement; ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/statements/assignment.ts ================================================ import type { TsNodeBase } from '../base'; import type { TsExpression } from '../expression'; import { TsNodeKind } from '../kinds'; export interface TsAssignment extends TsNodeBase { kind: TsNodeKind.Assignment; target: TsExpression; type?: TsExpression; value?: TsExpression; } export function createAssignment( target: TsExpression, type?: TsExpression, value?: TsExpression, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): TsAssignment { if (!type && !value) { throw new Error('Assignment requires at least type or value'); } return { kind: TsNodeKind.Assignment, leadingComments, target, trailingComments, type, value, }; } ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/statements/var.ts ================================================ import type { TsNodeBase } from '../base'; import type { TsExpression } from '../expression'; import { TsNodeKind } from '../kinds'; import type { TsType } from '../type'; export type TsVariableKeyword = 'var' | 'let' | 'const'; export interface TsVariableStatement extends TsNodeBase { initializer?: TsExpression; keyword: TsVariableKeyword; kind: TsNodeKind.VariableStatement; name: string; typeAnnotation?: TsType; } export function createVariableStatement( keyword: TsVariableKeyword, name: string, initializer?: TsExpression, typeAnnotation?: TsType, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): TsVariableStatement { return { initializer, keyword, kind: TsNodeKind.VariableStatement, leadingComments, name, trailingComments, typeAnnotation, }; } ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/structure/sourceFile.ts ================================================ import type { TsNode, TsNodeBase } from '../base'; import { TsNodeKind } from '../kinds'; export interface TsSourceFile extends TsNodeBase { kind: TsNodeKind.SourceFile; statements: ReadonlyArray; } export function createSourceFile( statements: ReadonlyArray, leadingComments?: ReadonlyArray, trailingComments?: ReadonlyArray, ): TsSourceFile { return { kind: TsNodeKind.SourceFile, leadingComments, statements, trailingComments, }; } ================================================ FILE: packages/openapi-ts/src/ts-compiler/nodes/type.ts ================================================ export type TsType = never; ================================================ FILE: packages/openapi-ts/src/ts-compiler/printer.ts ================================================ import type { TsNode } from './nodes/base'; import { TsNodeKind } from './nodes/kinds'; export interface TsPrinterOptions { /** * Number of spaces per indentation level. * * @default 2 */ indentSize?: number; /** * Whether to add trailing semicolons to statements. * * @default true */ semicolons?: boolean; } const DEFAULT_INDENT_SIZE = 2; const DEFAULT_SEMICOLONS = true; export function createPrinter(options?: TsPrinterOptions) { const indentSize = options?.indentSize ?? DEFAULT_INDENT_SIZE; const semicolons = options?.semicolons ?? DEFAULT_SEMICOLONS; let indentLevel = 0; function printComments( parts: Array, lines: ReadonlyArray, indent?: boolean, ): void { if (indent) indentLevel += 1; parts.push(...lines.map((line) => printLine(`// ${line}`))); if (indent) indentLevel -= 1; } function printLine(line: string): string { if (line === '') return ''; return ' '.repeat(indentLevel * indentSize) + line; } function printNode(node: TsNode): string { const parts: Array = []; if (node.leadingComments) { printComments(parts, node.leadingComments); } switch (node.kind) { case TsNodeKind.Assignment: { const target = printNode(node.target); if (node.type) { const type = printNode(node.type); if (node.value) { parts.push(printLine(`${target}: ${type} = ${printNode(node.value)}`)); } else { parts.push(printLine(`${target}: ${type}`)); } } else { parts.push(printLine(`${target} = ${printNode(node.value!)}`)); } if (semicolons) { const lastIndex = parts.length - 1; parts[lastIndex] += ';'; } break; } case TsNodeKind.Identifier: parts.push(node.text); break; case TsNodeKind.Literal: if (typeof node.value === 'string') { parts.push(`"${node.value}"`); } else if (typeof node.value === 'boolean') { parts.push(node.value ? 'true' : 'false'); } else if (node.value === null) { parts.push('null'); } else { parts.push(String(node.value)); } break; case TsNodeKind.SourceFile: parts.push(...node.statements.map(printNode)); break; case TsNodeKind.VariableStatement: { const keyword = node.keyword; const name = node.name; let line = `${keyword} ${name}`; if (node.typeAnnotation) { line += `: ${printNode(node.typeAnnotation)}`; } if (node.initializer) { line += ` = ${printNode(node.initializer)}`; } if (semicolons) { line += ';'; } parts.push(printLine(line)); break; } default: throw new Error(`Unsupported node kind: ${(node as { kind: string }).kind}`); } if (node.trailingComments) { printComments(parts, node.trailingComments); } return parts.join('\n'); } function printFile(node: TsNode): string { const parts: Array = [printNode(node), '']; return parts.join('\n'); } return { printFile, }; } export function printAst(node: TsNode): string { return JSON.stringify(node, null, 2); } ================================================ FILE: packages/openapi-ts/src/ts-dsl/base.ts ================================================ // TODO: symbol should be protected, but needs to be public to satisfy types import type { AnalysisContext, File, FromRef, Language, Node, NodeName, NodeNameSanitizer, NodeRelationship, NodeScope, Ref, Symbol, } from '@hey-api/codegen-core'; import { fromRef, isNode, isRef, isSymbol, nodeBrand, ref } from '@hey-api/codegen-core'; import type { AnyString } from '@hey-api/types'; import ts from 'typescript'; import type { AccessOptions } from './utils/context'; export abstract class TsDsl implements Node { // eslint-disable-next-line @typescript-eslint/no-unused-vars analyze(_: AnalysisContext): void {} clone(): this { const cloned = Object.create(Object.getPrototypeOf(this)); Object.assign(cloned, this); return cloned; } exported?: boolean; file?: File; get name(): Node['name'] { return { ...this._name, set: (value) => { this._name = ref(value); if (isSymbol(value)) { value.setNode(this); } }, toString: () => (this._name ? this.$name(this._name) : ''), } as Node['name']; } readonly nameSanitizer?: NodeNameSanitizer; language: Language = 'typescript'; parent?: Node; root: boolean = false; scope?: NodeScope = 'value'; structuralChildren?: Map; structuralParents?: Map; symbol?: Symbol; toAst(): T { return undefined as unknown as T; } readonly '~brand' = nodeBrand; /** Branding property to identify the DSL class at runtime. */ abstract readonly '~dsl': AnyString; /** Conditionally applies a callback to this builder. */ $if( this: T, value: V, ifTrue: (self: T, v: Exclude) => R | void, ifFalse?: (self: T, v: Extract) => R | void, ): R | T; $if( this: T, value: V, ifTrue: (v: Exclude) => R | void, ifFalse?: (v: Extract) => R | void, ): R | T; $if( this: T, value: V, ifTrue: () => R | void, ifFalse?: () => R | void, ): R | T; $if( this: T, value: V, ifTrue: any, ifFalse?: any, ): R | T { if (value) { // Try calling with (self, value), then (value), then () let result: R | void | undefined; try { result = ifTrue?.(this, value as Exclude); } catch { // ignore and try other signatures } if (result === undefined) { try { result = ifTrue?.(value as Exclude); } catch { // ignore and try zero-arg } } if (result === undefined) { try { result = ifTrue?.(); } catch { // swallow } } return (result ?? this) as R | T; } if (ifFalse) { let result: R | void | undefined; try { result = ifFalse?.(this, value as Extract); } catch { // ignore } if (result === undefined) { try { result = ifFalse?.(value as Extract); } catch { // ignore } } if (result === undefined) { try { result = ifFalse?.(); } catch { // ignore } } return (result ?? this) as R | T; } return this; } /** Access patterns for this node. */ toAccessNode?( node: this, options: AccessOptions, ctx: { /** The full chain. */ chain: ReadonlyArray; /** Position in the chain (0 = root). */ index: number; /** Is this the leaf node? */ isLeaf: boolean; /** Is this the root node? */ isRoot: boolean; /** Total length of the chain. */ length: number; }, ): TsDsl | undefined; protected $maybeId( expr: T, ): T extends string ? ts.Identifier : T { return (typeof expr === 'string' ? ts.factory.createIdentifier(expr) : expr) as T extends string ? ts.Identifier : T; } protected $name(name: Ref): string { const value = fromRef(name); if (isSymbol(value)) { try { return value.finalName; } catch { return value.name; } } return String(value); } protected $node(value: I): NodeOfMaybe { if (value === undefined) { return undefined as NodeOfMaybe; } // @ts-expect-error if (isRef(value)) value = fromRef(value); if (isSymbol(value)) { return this.$maybeId(value.finalName) as NodeOfMaybe; } if (typeof value === 'string') { return this.$maybeId(value) as NodeOfMaybe; } if (value instanceof Array) { return value.map((item) => { if (isRef(item)) item = fromRef(item); return this.unwrap(item); }) as NodeOfMaybe; } return this.unwrap(value as any) as NodeOfMaybe; } protected $type(value: I, args?: ReadonlyArray): TypeOfMaybe { if (value === undefined) { return undefined as TypeOfMaybe; } // @ts-expect-error if (isRef(value)) value = fromRef(value); if (isSymbol(value)) { return ts.factory.createTypeReferenceNode(value.finalName, args) as TypeOfMaybe; } if (typeof value === 'string') { return ts.factory.createTypeReferenceNode(value, args) as TypeOfMaybe; } if (typeof value === 'boolean') { const literal = value ? ts.factory.createTrue() : ts.factory.createFalse(); return ts.factory.createLiteralTypeNode(literal) as TypeOfMaybe; } if (typeof value === 'number') { return ts.factory.createLiteralTypeNode( ts.factory.createNumericLiteral(value), ) as TypeOfMaybe; } if (value instanceof Array) { return value.map((item) => this.$type(item, args)) as TypeOfMaybe; } return this.unwrap(value as any) as TypeOfMaybe; } private _name?: Ref; /** Unwraps nested nodes into raw TypeScript AST. */ private unwrap(value: I): I extends TsDsl ? N : I { return (isNode(value) ? value.toAst() : value) as I extends TsDsl ? N : I; } } type NodeOfMaybe = undefined extends I ? NodeOf>> | undefined : NodeOf>; type NodeOf = I extends ReadonlyArray ? ReadonlyArray ? N : U> : I extends string ? ts.Expression : I extends TsDsl ? N : I extends ts.Node ? I : never; export type MaybeTsDsl = T extends TsDsl ? U | TsDsl : T extends ts.Node ? T | TsDsl : never; export abstract class TypeTsDsl< T extends | ts.LiteralTypeNode | ts.QualifiedName | ts.TypeElement | ts.TypeNode | ts.TypeParameterDeclaration = ts.TypeNode, > extends TsDsl {} type TypeOfMaybe = undefined extends I ? TypeOf>> | undefined : TypeOf>; type TypeOf = I extends ReadonlyArray ? ReadonlyArray> : I extends string ? ts.TypeNode : I extends boolean ? ts.LiteralTypeNode : I extends TsDsl ? N : I extends ts.TypeNode ? I : never; ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/class.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { isSymbol, ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { NewlineTsDsl } from '../layout/newline'; import { DecoratorMixin } from '../mixins/decorator'; import { DocMixin } from '../mixins/doc'; import { AbstractMixin, DefaultMixin, ExportMixin } from '../mixins/modifiers'; import { TypeParamsMixin } from '../mixins/type-params'; import { safeRuntimeName } from '../utils/name'; import { FieldTsDsl } from './field'; import { InitTsDsl } from './init'; import { MethodTsDsl } from './method'; type Body = Array>; const Mixed = AbstractMixin( DecoratorMixin(DefaultMixin(DocMixin(ExportMixin(TypeParamsMixin(TsDsl))))), ); export class ClassTsDsl extends Mixed { readonly '~dsl' = 'ClassTsDsl'; override readonly nameSanitizer = safeRuntimeName; protected baseClass?: Ref; protected body: Body = []; constructor(name: NodeName) { super(); this.name.set(name); if (isSymbol(name)) { name.setKind('class'); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.baseClass); ctx.analyze(this.name); ctx.pushScope(); try { for (const item of this.body) { ctx.analyze(item); } } finally { ctx.popScope(); } } /** Returns true if the class has any members. */ get hasBody(): boolean { return this.body.length > 0; } /** Adds one or more class members (fields, methods, etc.). */ do(...items: Body): this { this.body.push(...items); return this; } /** Records a base class to extend from. */ extends(base?: NodeName): this { this.baseClass = base ? ref(base) : undefined; return this; } /** Adds a class field. */ field(name: NodeName, fn?: (f: FieldTsDsl) => void): this { const f = new FieldTsDsl(name, fn); this.body.push(f); return this; } /** Adds a class constructor. */ init(fn?: InitTsDsl | ((i: InitTsDsl) => void)): this { const i = typeof fn === 'function' ? new InitTsDsl(fn) : fn || new InitTsDsl(); this.body.push(i); return this; } /** Adds a class method. */ method(name: NodeName, fn?: (m: MethodTsDsl) => void): this { const m = new MethodTsDsl(name, fn); this.body.push(m); return this; } /** Inserts an empty line between members for formatting. */ newline(): this { this.body.push(new NewlineTsDsl()); return this; } override toAst() { const body = this.$node(this.body) as ReadonlyArray; const node = ts.factory.createClassDeclaration( [...this.$decorators(), ...this.modifiers], this.$node(this.name) as ts.Identifier, this.$generics(), this._heritage(), body, ); return this.$docs(node); } /** Builds heritage clauses (extends). */ private _heritage(): ReadonlyArray { const node = this.$node(this.baseClass); if (!node) return []; return [ ts.factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [ ts.factory.createExpressionWithTypeArguments(node, undefined), ]), ]; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/decorator.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { ArgsMixin } from '../mixins/args'; import { safeRuntimeName } from '../utils/name'; const Mixed = ArgsMixin(TsDsl); export class DecoratorTsDsl extends Mixed { readonly '~dsl' = 'DecoratorTsDsl'; override readonly nameSanitizer = safeRuntimeName; constructor(name: NodeName, ...args: ReadonlyArray>) { super(); this.name.set(name); this.args(...args); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); } override toAst() { const target = this.$node(this.name); const args = this.$args(); return ts.factory.createDecorator( args.length ? ts.factory.createCallExpression(target, undefined, args) : target, ); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/enum.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import { isSymbol } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { DocMixin } from '../mixins/doc'; import { ConstMixin, ExportMixin } from '../mixins/modifiers'; import { safeRuntimeName } from '../utils/name'; import { EnumMemberTsDsl } from './member'; type Value = string | number | MaybeTsDsl; type ValueFn = Value | ((m: EnumMemberTsDsl) => void); const Mixed = ConstMixin(DocMixin(ExportMixin(TsDsl))); export class EnumTsDsl extends Mixed { readonly '~dsl' = 'EnumTsDsl'; override readonly nameSanitizer = safeRuntimeName; private _members: Array = []; constructor(name: NodeName, fn?: (e: EnumTsDsl) => void) { super(); this.name.set(name); if (isSymbol(name)) { name.setKind('enum'); } fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.pushScope(); try { for (const member of this._members) { ctx.analyze(member); } } finally { ctx.popScope(); } } /** Adds an enum member. */ member(name: string, value?: ValueFn): this { const m = new EnumMemberTsDsl(name, value); this._members.push(m); return this; } /** Adds multiple enum members. */ members(...members: ReadonlyArray): this { this._members.push(...members); return this; } override toAst() { const node = ts.factory.createEnumDeclaration( this.modifiers, this.$node(this.name) as ts.Identifier, this.$node(this._members) as ReadonlyArray, ); return this.$docs(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/field.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl, TypeTsDsl } from '../base'; import { DecoratorMixin } from '../mixins/decorator'; import { DocMixin } from '../mixins/doc'; import { PrivateMixin, ProtectedMixin, PublicMixin, ReadonlyMixin, StaticMixin, } from '../mixins/modifiers'; import { OptionalMixin } from '../mixins/optional'; import { ValueMixin } from '../mixins/value'; import { TokenTsDsl } from '../token'; import { TypeExprTsDsl } from '../type/expr'; import { safeAccessorName } from '../utils/name'; export type FieldType = NodeName | TypeTsDsl; const Mixed = DecoratorMixin( DocMixin( OptionalMixin( PrivateMixin( ProtectedMixin( PublicMixin(ReadonlyMixin(StaticMixin(ValueMixin(TsDsl)))), ), ), ), ), ); export class FieldTsDsl extends Mixed { readonly '~dsl' = 'FieldTsDsl'; override readonly nameSanitizer = safeAccessorName; protected _type?: TypeTsDsl; constructor(name: NodeName, fn?: (f: FieldTsDsl) => void) { super(); this.name.set(name); fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.analyze(this._type); } /** Sets the field type. */ type(type: FieldType): this { this._type = type instanceof TypeTsDsl ? type : new TypeExprTsDsl(type); return this; } override toAst() { const node = ts.factory.createPropertyDeclaration( [...this.$decorators(), ...this.modifiers], this.$node(this.name) as ts.PropertyName, this._optional ? this.$node(new TokenTsDsl().optional()) : undefined, this.$type(this._type), this.$value(), ); return this.$docs(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/func.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import { isSymbol } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { AsMixin } from '../mixins/as'; import { DecoratorMixin } from '../mixins/decorator'; import { DoMixin } from '../mixins/do'; import { DocMixin } from '../mixins/doc'; import { AbstractMixin, AsyncMixin, PrivateMixin, ProtectedMixin, PublicMixin, StaticMixin, } from '../mixins/modifiers'; import { ParamMixin } from '../mixins/param'; import { TypeParamsMixin } from '../mixins/type-params'; import { TypeReturnsMixin } from '../mixins/type-returns'; import { BlockTsDsl } from '../stmt/block'; import { safeRuntimeName } from '../utils/name'; export type FuncMode = 'arrow' | 'decl' | 'expr'; const Mixed = AbstractMixin( AsMixin( AsyncMixin( DecoratorMixin( DoMixin( DocMixin( ParamMixin( PrivateMixin( ProtectedMixin( PublicMixin( StaticMixin(TypeParamsMixin(TypeReturnsMixin(TsDsl))), ), ), ), ), ), ), ), ), ), ); class ImplFuncTsDsl extends Mixed { readonly '~dsl' = 'FuncTsDsl'; override readonly nameSanitizer = safeRuntimeName; protected mode?: FuncMode; constructor(); constructor(fn: (f: ImplFuncTsDsl<'arrow'>) => void); constructor(name: NodeName); constructor(name: NodeName, fn: (f: ImplFuncTsDsl<'decl'>) => void); constructor( name?: NodeName | ((f: ImplFuncTsDsl<'arrow'>) => void), fn?: (f: ImplFuncTsDsl<'decl'>) => void, ) { super(); if (typeof name === 'function') { this.mode = 'arrow'; name(this as unknown as FuncTsDsl<'arrow'>); } else if (name) { this.mode = 'decl'; this.name.set(name); if (isSymbol(name)) { name.setKind('function'); } fn?.(this as unknown as FuncTsDsl<'decl'>); } } override analyze(ctx: AnalysisContext): void { ctx.pushScope(); try { super.analyze(ctx); ctx.analyze(this.name); } finally { ctx.popScope(); } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Switches the function to an arrow function form. */ arrow(): FuncTsDsl<'arrow'> { this.mode = 'arrow'; return this as unknown as FuncTsDsl<'arrow'>; } /** Switches the function to a function declaration form. */ decl(): FuncTsDsl<'decl'> { this.mode = 'decl'; return this as unknown as FuncTsDsl<'decl'>; } /** Switches the function to a function expression form. */ expr(): FuncTsDsl<'expr'> { this.mode = 'expr'; return this as unknown as FuncTsDsl<'expr'>; } // @ts-expect-error --- need to fix types --- override toAst(): M extends 'decl' ? ts.FunctionDeclaration : M extends 'expr' ? ts.FunctionExpression : ts.ArrowFunction { this.$validate(); const body = this.$node(new BlockTsDsl(...this._do).pretty()); if (this.mode === 'decl') { const node = ts.factory.createFunctionDeclaration( [...this.$decorators(), ...this.modifiers], undefined, this.$node(this.name) as ts.Identifier, this.$generics(), this.$params(), this.$returns(), body, ) as any; return this.$docs(node); } if (this.mode === 'expr') { const node = ts.factory.createFunctionExpression( this.modifiers, undefined, this.$node(this.name) as ts.Identifier, this.$generics(), this.$params(), this.$returns(), body, ) as any; return this.$docs(node); } const node = ts.factory.createArrowFunction( this.modifiers, this.$generics(), this.$params(), this.$returns(), undefined, body.statements.length === 1 && ts.isReturnStatement(body.statements[0]!) && body.statements[0].expression ? body.statements[0].expression : body, ) as any; return this.$docs(node); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Function ${this.mode} missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (this.mode === 'decl' && !this.name.toString()) missing.push('name'); return missing; } } export const FuncTsDsl = ImplFuncTsDsl as { new (): FuncTsDsl<'arrow'>; new (fn: (f: FuncTsDsl<'arrow'>) => void): FuncTsDsl<'arrow'>; new (name: NodeName): FuncTsDsl<'decl'>; new (name: NodeName, fn: (f: FuncTsDsl<'decl'>) => void): FuncTsDsl<'decl'>; } & typeof ImplFuncTsDsl; export type FuncTsDsl = ImplFuncTsDsl; ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/getter.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { DecoratorMixin } from '../mixins/decorator'; import { DoMixin } from '../mixins/do'; import { DocMixin } from '../mixins/doc'; import { AbstractMixin, AsyncMixin, PrivateMixin, ProtectedMixin, PublicMixin, StaticMixin, } from '../mixins/modifiers'; import { ParamMixin } from '../mixins/param'; import { TypeReturnsMixin } from '../mixins/type-returns'; import { BlockTsDsl } from '../stmt/block'; import { safeAccessorName } from '../utils/name'; const Mixed = AbstractMixin( AsyncMixin( DecoratorMixin( DoMixin( DocMixin( ParamMixin( PrivateMixin( ProtectedMixin( PublicMixin(StaticMixin(TypeReturnsMixin(TsDsl))), ), ), ), ), ), ), ), ); export class GetterTsDsl extends Mixed { readonly '~dsl' = 'GetterTsDsl'; override readonly nameSanitizer = safeAccessorName; constructor(name: NodeName, fn?: (g: GetterTsDsl) => void) { super(); this.name.set(name); fn?.(this); } override analyze(ctx: AnalysisContext): void { ctx.analyze(this.name); ctx.pushScope(); try { super.analyze(ctx); } finally { ctx.popScope(); } } override toAst() { const node = ts.factory.createGetAccessorDeclaration( [...this.$decorators(), ...this.modifiers], this.$node(this.name) as ts.PropertyName, this.$params(), this.$returns(), this.$node(new BlockTsDsl(...this._do).pretty()), ); return this.$docs(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/init.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { DecoratorMixin } from '../mixins/decorator'; import { DoMixin } from '../mixins/do'; import { DocMixin } from '../mixins/doc'; import { PrivateMixin, ProtectedMixin, PublicMixin } from '../mixins/modifiers'; import { ParamMixin } from '../mixins/param'; import { BlockTsDsl } from '../stmt/block'; const Mixed = DecoratorMixin( DoMixin( DocMixin( ParamMixin(PrivateMixin(ProtectedMixin(PublicMixin(TsDsl)))), ), ), ); export class InitTsDsl extends Mixed { readonly '~dsl' = 'InitTsDsl'; constructor(fn?: (i: InitTsDsl) => void) { super(); fn?.(this); } override analyze(ctx: AnalysisContext): void { ctx.pushScope(); try { super.analyze(ctx); } finally { ctx.popScope(); } } override toAst() { const node = ts.factory.createConstructorDeclaration( [...this.$decorators(), ...this.modifiers], this.$params(), this.$node(new BlockTsDsl(...this._do).pretty()), ); return this.$docs(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/member.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { DocMixin } from '../mixins/doc'; import { safeMemberName } from '../utils/name'; type Value = string | number | MaybeTsDsl; type ValueFn = Value | ((m: EnumMemberTsDsl) => void); const Mixed = DocMixin(TsDsl); export class EnumMemberTsDsl extends Mixed { readonly '~dsl' = 'EnumMemberTsDsl'; private _value?: Value; constructor(name: NodeName, value?: ValueFn) { super(); this.name.set(name); if (typeof value === 'function') { value(this); } else { this.value(value); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._value); } /** Sets the enum member value. */ value(value?: Value): this { this._value = value; return this; } override toAst() { const node = ts.factory.createEnumMember( this.$node(safeMemberName(this.name.toString())), this.$node(this._value), ); return this.$docs(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/method.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { DecoratorMixin } from '../mixins/decorator'; import { DoMixin } from '../mixins/do'; import { DocMixin } from '../mixins/doc'; import { AbstractMixin, AsyncMixin, PrivateMixin, ProtectedMixin, PublicMixin, StaticMixin, } from '../mixins/modifiers'; import { OptionalMixin } from '../mixins/optional'; import { ParamMixin } from '../mixins/param'; import { TypeParamsMixin } from '../mixins/type-params'; import { TypeReturnsMixin } from '../mixins/type-returns'; import { BlockTsDsl } from '../stmt/block'; import { TokenTsDsl } from '../token'; import { safeAccessorName } from '../utils/name'; const Mixed = AbstractMixin( AsyncMixin( DecoratorMixin( DoMixin( DocMixin( OptionalMixin( ParamMixin( PrivateMixin( ProtectedMixin( PublicMixin( StaticMixin(TypeParamsMixin(TypeReturnsMixin(TsDsl))), ), ), ), ), ), ), ), ), ), ); export class MethodTsDsl extends Mixed { readonly '~dsl' = 'MethodTsDsl'; override readonly nameSanitizer = safeAccessorName; constructor(name: NodeName, fn?: (m: MethodTsDsl) => void) { super(); this.name.set(name); fn?.(this); } override analyze(ctx: AnalysisContext): void { ctx.analyze(this.name); ctx.pushScope(); try { super.analyze(ctx); } finally { ctx.popScope(); } } override toAst() { const node = ts.factory.createMethodDeclaration( [...this.$decorators(), ...this.modifiers], undefined, this.$node(this.name) as ts.PropertyName, this._optional ? this.$node(new TokenTsDsl().optional()) : undefined, this.$generics(), this.$params(), this.$returns(), this.$node(new BlockTsDsl(...this._do).pretty()), ); return this.$docs(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/param.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl, TypeTsDsl } from '../base'; import { DecoratorMixin } from '../mixins/decorator'; import { OptionalMixin } from '../mixins/optional'; import { PatternMixin } from '../mixins/pattern'; import { ValueMixin } from '../mixins/value'; import { TokenTsDsl } from '../token'; import { TypeExprTsDsl } from '../type/expr'; export type ParamName = NodeName | ParamFn; export type ParamFn = (p: ParamTsDsl) => void; export type ParamCtor = (name: ParamName, fn?: ParamFn) => ParamTsDsl; const Mixed = DecoratorMixin( OptionalMixin(PatternMixin(ValueMixin(TsDsl))), ); export class ParamTsDsl extends Mixed { readonly '~dsl' = 'ParamTsDsl'; protected _type?: TypeTsDsl; constructor(name: ParamName, fn?: ParamFn) { super(); if (typeof name === 'function') { name(this); } else { this.name.set(name); fn?.(this); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.analyze(this._type); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the parameter type. */ type(type: string | TypeTsDsl): this { this._type = type instanceof TypeTsDsl ? type : new TypeExprTsDsl(type); return this; } override toAst() { this.$validate(); return ts.factory.createParameterDeclaration( this.$decorators(), undefined, this.$pattern() ?? this.name.toString(), this._optional ? this.$node(new TokenTsDsl().optional()) : undefined, this.$type(this._type), this.$value(), ); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Parameter missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.$pattern() && !this.name.toString()) missing.push('name or pattern (.array()/.object())'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/pattern.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import ts from 'typescript'; import { TsDsl } from '../base'; import { IdTsDsl } from '../expr/id'; import { TokenTsDsl } from '../token'; const Mixed = TsDsl; /** * Builds binding patterns (e.g. `{ foo, bar }`, `[a, b, ...rest]`). */ export class PatternTsDsl extends Mixed { readonly '~dsl' = 'PatternTsDsl'; protected pattern?: | { kind: 'array'; values: ReadonlyArray } | { kind: 'object'; values: Record }; protected _spread?: string; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Defines an array pattern (e.g. `[a, b, c]`). */ array(...props: ReadonlyArray | [ReadonlyArray]): this { const values = props[0] instanceof Array ? [...props[0]] : (props as ReadonlyArray); this.pattern = { kind: 'array', values }; return this; } /** Defines an object pattern (e.g. `{ a, b: alias }`). */ object(...props: ReadonlyArray | Record>): this { const entries: Record = {}; for (const p of props) { if (typeof p === 'string') entries[p] = p; else if (p instanceof Array) for (const n of p) entries[n] = n; else Object.assign(entries, p); } this.pattern = { kind: 'object', values: entries }; return this; } /** Adds a spread element (e.g. `...rest`, `...options`, `...args`). */ spread(name: string): this { this._spread = name; return this; } override toAst() { this.$validate(); if (this.pattern.kind === 'object') { const elements = Object.entries(this.pattern.values).map(([key, alias]) => key === alias ? ts.factory.createBindingElement(undefined, undefined, key, undefined) : ts.factory.createBindingElement(undefined, key, alias, undefined), ); const spread = this.createSpread(); if (spread) elements.push(spread); return ts.factory.createObjectBindingPattern(elements); } if (this.pattern.kind === 'array') { const elements = this.pattern.values.map((p) => ts.factory.createBindingElement(undefined, undefined, p, undefined), ); const spread = this.createSpread(); if (spread) elements.push(spread); return ts.factory.createArrayBindingPattern(elements); } throw new Error('PatternTsDsl requires object() or array() pattern'); } $validate(): asserts this is this & { pattern: | { kind: 'array'; values: ReadonlyArray } | { kind: 'object'; values: Record }; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Binding pattern missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.pattern) missing.push('.array() or .object()'); return missing; } private createSpread(): ts.BindingElement | undefined { return this._spread ? ts.factory.createBindingElement( this.$node(new TokenTsDsl().spread()), undefined, this.$node(new IdTsDsl(this._spread)), ) : undefined; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/decl/setter.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { DecoratorMixin } from '../mixins/decorator'; import { DoMixin } from '../mixins/do'; import { DocMixin } from '../mixins/doc'; import { AbstractMixin, AsyncMixin, PrivateMixin, ProtectedMixin, PublicMixin, StaticMixin, } from '../mixins/modifiers'; import { ParamMixin } from '../mixins/param'; import { BlockTsDsl } from '../stmt/block'; import { safeAccessorName } from '../utils/name'; const Mixed = AbstractMixin( AsyncMixin( DecoratorMixin( DoMixin( DocMixin( ParamMixin( PrivateMixin( ProtectedMixin(PublicMixin(StaticMixin(TsDsl))), ), ), ), ), ), ), ); export class SetterTsDsl extends Mixed { readonly '~dsl' = 'SetterTsDsl'; override readonly nameSanitizer = safeAccessorName; constructor(name: NodeName, fn?: (s: SetterTsDsl) => void) { super(); this.name.set(name); fn?.(this); } override analyze(ctx: AnalysisContext): void { ctx.analyze(this.name); ctx.pushScope(); try { super.analyze(ctx); } finally { ctx.popScope(); } } override toAst() { const node = ts.factory.createSetAccessorDeclaration( [...this.$decorators(), ...this.modifiers], this.$node(this.name) as ts.PropertyName, this.$params(), this.$node(new BlockTsDsl(...this._do).pretty()), ); return this.$docs(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/array.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { AsMixin } from '../mixins/as'; import { LayoutMixin } from '../mixins/layout'; import { LiteralTsDsl } from './literal'; const Mixed = AsMixin(LayoutMixin(TsDsl)); export class ArrayTsDsl extends Mixed { readonly '~dsl' = 'ArrayTsDsl'; protected _elements: Array< | { expr: MaybeTsDsl; kind: 'element' } | { expr: MaybeTsDsl; kind: 'spread' } > = []; constructor(...exprs: Array>) { super(); this.elements(...exprs); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const item of this._elements) { ctx.analyze(item.expr); } } /** Adds a single array element. */ element(expr: string | number | boolean | MaybeTsDsl): this { const node = typeof expr === 'string' || typeof expr === 'number' || typeof expr === 'boolean' ? new LiteralTsDsl(expr) : expr; this._elements.push({ expr: node, kind: 'element' }); return this; } /** Adds multiple array elements. */ elements(...exprs: ReadonlyArray>): this { for (const expr of exprs) this.element(expr); return this; } /** Adds a spread element (`...expr`). */ spread(expr: MaybeTsDsl): this { this._elements.push({ expr, kind: 'spread' }); return this; } override toAst() { const elements = this._elements.map((item) => { const node = this.$node(item.expr); return item.kind === 'spread' ? ts.factory.createSpreadElement(node) : node; }); return ts.factory.createArrayLiteralExpression( elements, this.$multiline(this._elements.length), ); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/as.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl, TypeTsDsl } from '../base'; import { TsDsl } from '../base'; import { AsMixin } from '../mixins/as'; import { ExprMixin } from '../mixins/expr'; import { f } from '../utils/factories'; export type AsExpr = NodeName | MaybeTsDsl; export type AsType = NodeName | TypeTsDsl; export type AsCtor = (expr: AsExpr, type: AsType) => AsTsDsl; const Mixed = AsMixin(ExprMixin(TsDsl)); export class AsTsDsl extends Mixed { readonly '~dsl' = 'AsTsDsl'; protected expr: Ref; protected type: Ref; constructor(expr: AsExpr, type: AsType) { super(); this.expr = ref(expr); this.type = ref(type); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.expr); ctx.analyze(this.type); } override toAst() { return ts.factory.createAsExpression(this.$node(this.expr), this.$type(this.type)); } } f.as.set((...args) => new AsTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/attr.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { fromRef, isSymbol, ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { AsMixin } from '../mixins/as'; import { ExprMixin } from '../mixins/expr'; import { OperatorMixin } from '../mixins/operator'; import { OptionalMixin } from '../mixins/optional'; import { TokenTsDsl } from '../token'; import { f } from '../utils/factories'; import { regexp } from '../utils/regexp'; import { LiteralTsDsl } from './literal'; export type AttrLeft = NodeName | MaybeTsDsl; export type AttrCtor = (left: AttrLeft, right: NodeName) => AttrTsDsl; const Mixed = AsMixin( ExprMixin( OperatorMixin(OptionalMixin(TsDsl)), ), ); export class AttrTsDsl extends Mixed { readonly '~dsl' = 'AttrTsDsl'; protected left: Ref; constructor(left: AttrLeft, right: NodeName) { super(); this.left = ref(left); this.name.set(right); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.left); ctx.analyze(this.name); } override toAst() { const leftNode = this.$node(this.left); regexp.typeScriptIdentifier.lastIndex = 0; const right = fromRef(this.name); if (!regexp.typeScriptIdentifier.test(this.name.toString())) { let value = isSymbol(right) ? right.finalName : right; if (typeof value === 'string') { if ( (value.startsWith("'") && value.endsWith("'")) || (value.startsWith('"') && value.endsWith('"')) ) { value = value.slice(1, -1); } } if (this._optional) { return ts.factory.createElementAccessChain( leftNode, this.$node(new TokenTsDsl().questionDot()), this.$node(new LiteralTsDsl(value)), ); } return ts.factory.createElementAccessExpression( leftNode, this.$node(new LiteralTsDsl(value)), ); } if (this._optional) { return ts.factory.createPropertyAccessChain( leftNode, this.$node(new TokenTsDsl().questionDot()), this.$node(this.name) as ts.MemberName, ); } return ts.factory.createPropertyAccessExpression( leftNode, this.$node(this.name) as ts.MemberName, ); } } f.attr.set((...args) => new AttrTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/await.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { ExprMixin } from '../mixins/expr'; import { f } from '../utils/factories'; export type AwaitExpr = NodeName | MaybeTsDsl; export type AwaitCtor = (expr: AwaitExpr) => AwaitTsDsl; const Mixed = ExprMixin(TsDsl); export class AwaitTsDsl extends Mixed { readonly '~dsl' = 'AwaitTsDsl'; protected _awaitExpr: Ref; constructor(expr: AwaitExpr) { super(); this._awaitExpr = ref(expr); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._awaitExpr); } override toAst() { return ts.factory.createAwaitExpression(this.$node(this._awaitExpr)); } } f.await.set((...args) => new AwaitTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/binary.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { AsMixin } from '../mixins/as'; import { ExprMixin } from '../mixins/expr'; type Expr = NodeName | MaybeTsDsl; type Op = Operator | ts.BinaryOperator; type Operator = | '!=' | '!==' | '&&' | '*' | '+' | '-' | '/' | '<' | '<=' | '=' | '==' | '===' | '>' | '>=' | '??' | '??=' | '||'; const Mixed = AsMixin(ExprMixin(TsDsl)); export class BinaryTsDsl extends Mixed { readonly '~dsl' = 'BinaryTsDsl'; protected _base: Ref; protected _expr?: Ref; protected _op?: Op; constructor(base: Expr, op?: Op, expr?: Expr) { super(); this._base = ref(base); this._op = op; if (expr) this._expr = ref(expr); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._base); ctx.analyze(this._expr); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Logical AND — `this && expr` */ and(expr: Expr): this { return this.opAndExpr('&&', expr); } /** Creates an assignment expression (e.g. `this = expr`). */ assign(expr: Expr): this { return this.opAndExpr('=', expr); } /** Nullish coalescing — `this ?? expr` */ coalesce(expr: Expr): this { return this.opAndExpr('??', expr); } /** Division — `this / expr` */ div(expr: Expr): this { return this.opAndExpr('/', expr); } /** Strict equality — `this === expr` */ eq(expr: Expr): this { return this.opAndExpr('===', expr); } /** Greater than — `this > expr` */ gt(expr: Expr): this { return this.opAndExpr('>', expr); } /** Greater than or equal — `this >= expr` */ gte(expr: Expr): this { return this.opAndExpr('>=', expr); } /** Loose equality — `this == expr` */ looseEq(expr: Expr): this { return this.opAndExpr('==', expr); } /** Loose inequality — `this != expr` */ looseNeq(expr: Expr): this { return this.opAndExpr('!=', expr); } /** Less than — `this < expr` */ lt(expr: Expr): this { return this.opAndExpr('<', expr); } /** Less than or equal — `this <= expr` */ lte(expr: Expr): this { return this.opAndExpr('<=', expr); } /** Subtraction — `this - expr` */ minus(expr: Expr): this { return this.opAndExpr('-', expr); } /** Strict inequality — `this !== expr` */ neq(expr: Expr): this { return this.opAndExpr('!==', expr); } /** Nullish assignment — `this ??= expr` */ nullishAssign(expr: Expr): this { return this.opAndExpr('??=', expr); } /** Logical OR — `this || expr` */ or(expr: Expr): this { return this.opAndExpr('||', expr); } /** Addition — `this + expr` */ plus(expr: Expr): this { return this.opAndExpr('+', expr); } /** Multiplication — `this * expr` */ times(expr: Expr): this { return this.opAndExpr('*', expr); } override toAst() { this.$validate(); const base = this.$node(this._base); const operator = typeof this._op === 'string' ? this.opToToken(this._op) : this._op; return ts.factory.createBinaryExpression(base, operator, this.$node(this._expr)); } $validate(): asserts this is this & { _expr: Ref; _op: Op; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Binary expression missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._op) missing.push('operator (e.g., .eq(), .plus())'); if (!this._expr) missing.push('right-hand expression'); return missing; } /** Sets the binary operator and right-hand operand for this expression. */ private opAndExpr(op: Op, expr: Expr): this { this._expr = ref(expr); this._op = op; return this; } private opToToken(op: Operator): ts.BinaryOperator | ts.BinaryOperatorToken { const tokenMap: Record = { '!=': ts.SyntaxKind.ExclamationEqualsToken, '!==': ts.SyntaxKind.ExclamationEqualsEqualsToken, '&&': ts.SyntaxKind.AmpersandAmpersandToken, '*': ts.SyntaxKind.AsteriskToken, '+': ts.SyntaxKind.PlusToken, '-': ts.SyntaxKind.MinusToken, '/': ts.SyntaxKind.SlashToken, '<': ts.SyntaxKind.LessThanToken, '<=': ts.SyntaxKind.LessThanEqualsToken, '=': ts.SyntaxKind.EqualsToken, '==': ts.SyntaxKind.EqualsEqualsToken, '===': ts.SyntaxKind.EqualsEqualsEqualsToken, '>': ts.SyntaxKind.GreaterThanToken, '>=': ts.SyntaxKind.GreaterThanEqualsToken, '??': ts.SyntaxKind.QuestionQuestionToken, '??=': ts.SyntaxKind.QuestionQuestionEqualsToken, '||': ts.SyntaxKind.BarBarToken, }; const token = tokenMap[op]; if (!token) { throw new Error(`Unsupported operator: ${op}`); } return token; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/call.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { ArgsMixin } from '../mixins/args'; import { AsMixin } from '../mixins/as'; import { ExprMixin } from '../mixins/expr'; import { TypeArgsMixin } from '../mixins/type-args'; import { f } from '../utils/factories'; export type CallArgs = ReadonlyArray; export type CallCallee = NodeName | MaybeTsDsl; export type CallCtor = (callee: CallCallee, ...args: CallArgs) => CallTsDsl; const Mixed = ArgsMixin(AsMixin(ExprMixin(TypeArgsMixin(TsDsl)))); export class CallTsDsl extends Mixed { readonly '~dsl' = 'CallTsDsl'; protected _callee: Ref; constructor(callee: CallCallee, ...args: CallArgs) { super(); this._callee = ref(callee); this.args(...args); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._callee); } override toAst() { return ts.factory.createCallExpression( this.$node(this._callee), this.$generics(), this.$args(), ); } } f.call.set((...args) => new CallTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/expr.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { isNode, isSymbol, ref } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { AsMixin } from '../mixins/as'; import { ExprMixin } from '../mixins/expr'; import { OperatorMixin } from '../mixins/operator'; import { TypeExprMixin } from '../mixins/type-expr'; type Id = NodeName | MaybeTsDsl; const Mixed = AsMixin(ExprMixin(OperatorMixin(TypeExprMixin(TsDsl)))); export class ExprTsDsl extends Mixed { readonly '~dsl' = 'ExprTsDsl'; protected _exprInput: Ref; constructor(id: Id) { super(); this._exprInput = ref(id); if (typeof id === 'string' || isSymbol(id)) { this.name.set(id); } else if (isNode(id)) { this.name.set(id.name); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._exprInput); } override toAst() { return this.$node(this._exprInput); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/fromValue.ts ================================================ import { isNode } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { TsDsl } from '../base'; import { ArrayTsDsl } from './array'; import { LiteralTsDsl } from './literal'; import { ObjectTsDsl } from './object'; export const fromValue = ( input: unknown, options?: { layout?: 'pretty'; }, ): TsDsl => { if (isNode(input)) { return input as TsDsl; } if ( input === null || typeof input === 'number' || typeof input === 'boolean' || typeof input === 'string' || typeof input === 'bigint' ) { return new LiteralTsDsl(input); } if (input instanceof Array) { const arr = new ArrayTsDsl(...input.map((v) => fromValue(v, options))); if (options?.layout === 'pretty') arr.pretty(); return arr; } if (typeof input === 'object') { const obj = new ObjectTsDsl(); for (const [key, val] of Object.entries(input)) { const expr = fromValue(val, options); obj.prop(key, expr); } if (options?.layout === 'pretty') obj.pretty(); return obj; } throw new Error(`$.fromValue(): Unsupported input type ${String(input)}`); }; ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/id.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; const Mixed = TsDsl; export class IdTsDsl extends Mixed { readonly '~dsl' = 'IdTsDsl'; constructor(name: string) { super(); this.name.set(name); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } override toAst() { return ts.factory.createIdentifier(this.name.toString()); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/literal.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import tsOld from 'typescript'; import type { ts } from '../../ts-compiler'; import { TsDsl } from '../base'; import { PrefixTsDsl } from '../expr/prefix'; import { AsMixin } from '../mixins/as'; const Mixed = AsMixin( TsDsl< | tsOld.BigIntLiteral | tsOld.BooleanLiteral | tsOld.NullLiteral | tsOld.NumericLiteral | tsOld.PrefixUnaryExpression | tsOld.StringLiteral >, ); export class LiteralTsDsl extends Mixed { readonly '~dsl' = 'LiteralTsDsl'; protected value: ts.LiteralValue; constructor(value: ts.LiteralValue) { super(); this.value = value; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } override toAst() { if (typeof this.value === 'boolean') { return this.value ? tsOld.factory.createTrue() : tsOld.factory.createFalse(); } if (typeof this.value === 'number') { const expr = tsOld.factory.createNumericLiteral(Math.abs(this.value)); return this.value < 0 ? this.$node(new PrefixTsDsl(expr).neg()) : expr; } if (typeof this.value === 'string') { return tsOld.factory.createStringLiteral(this.value, true); } if (typeof this.value === 'bigint') { return tsOld.factory.createBigIntLiteral(this.value.toString()); } if (this.value === null) { return tsOld.factory.createNull(); } throw new Error(`Unsupported literal: ${String(this.value)}`); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/new.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { ArgsMixin } from '../mixins/args'; import { AsMixin } from '../mixins/as'; import { ExprMixin } from '../mixins/expr'; import { TypeArgsMixin } from '../mixins/type-args'; import { f } from '../utils/factories'; export type NewArgs = ReadonlyArray; export type NewExpr = NodeName | MaybeTsDsl; export type NewCtor = (expr: NewExpr, ...args: NewArgs) => NewTsDsl; const Mixed = ArgsMixin(AsMixin(ExprMixin(TypeArgsMixin(TsDsl)))); export class NewTsDsl extends Mixed { readonly '~dsl' = 'NewTsDsl'; protected _newExpr: Ref; constructor(expr: NewExpr, ...args: NewArgs) { super(); this._newExpr = ref(expr); this.args(...args); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._newExpr); } override toAst() { return ts.factory.createNewExpression( this.$node(this._newExpr), this.$generics(), this.$args(), ); } } f.new.set((...args) => new NewTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/object.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { AsMixin } from '../mixins/as'; import { ExprMixin } from '../mixins/expr'; import { HintMixin } from '../mixins/hint'; import { LayoutMixin } from '../mixins/layout'; import { ObjectPropTsDsl } from './prop'; type Expr = NodeName | MaybeTsDsl; type Stmt = NodeName | MaybeTsDsl; type ExprFn = Expr | ((p: ObjectPropTsDsl) => void); type StmtFn = Stmt | ((p: ObjectPropTsDsl) => void); const Mixed = AsMixin(ExprMixin(HintMixin(LayoutMixin(TsDsl)))); export class ObjectTsDsl extends Mixed { readonly '~dsl' = 'ObjectTsDsl'; protected _props = new Map(); protected _spreadCounter = 0; constructor(...props: Array) { super(); this.props(...props); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const prop of this._props.values()) { ctx.analyze(prop); } } /** Returns composite key for the property. */ private _propKey(prop: ObjectPropTsDsl): string { if (prop.kind === 'spread') { return `spread:${this._spreadCounter++}`; } return `${prop.kind}:${prop.propName}`; } /** Adds a computed property (e.g. `{ [expr]: value }`), or removes if null. */ computed(name: string, expr: ExprFn | null): this { if (expr === null) { this._props.delete(`computed:${name}`); } else { this._props.set( `computed:${name}`, new ObjectPropTsDsl({ kind: 'computed', name }).value(expr), ); } return this; } /** Adds a getter property (e.g. `{ get foo() { ... } }`), or removes if null. */ getter(name: string, stmt: StmtFn | null): this { if (stmt === null) { this._props.delete(`getter:${name}`); } else { this._props.set(`getter:${name}`, new ObjectPropTsDsl({ kind: 'getter', name }).value(stmt)); } return this; } /** Returns true if object has at least one property or spread. */ hasProps(): boolean { return this._props.size > 0; } /** Returns true if object has no properties or spreads. */ get isEmpty(): boolean { return this._props.size === 0; } /** Adds a property assignment, or removes if null. */ prop(name: string, expr: ExprFn | null): this { if (expr === null) { this._props.delete(`prop:${name}`); } else { this._props.set(`prop:${name}`, new ObjectPropTsDsl({ kind: 'prop', name }).value(expr)); } return this; } /** Adds multiple properties. */ props(...props: ReadonlyArray): this { for (const prop of props) { this._props.set(this._propKey(prop), prop); } return this; } /** Adds a setter property (e.g. `{ set foo(v) { ... } }`), or removes if null. */ setter(name: string, stmt: StmtFn | null): this { if (stmt === null) { this._props.delete(`setter:${name}`); } else { this._props.set(`setter:${name}`, new ObjectPropTsDsl({ kind: 'setter', name }).value(stmt)); } return this; } /** Adds a spread property (e.g. `{ ...options }`). */ spread(expr: ExprFn): this { const key = `spread:${this._spreadCounter++}`; this._props.set(key, new ObjectPropTsDsl({ kind: 'spread' }).value(expr)); return this; } override toAst() { const props = [...this._props.values()]; const node = ts.factory.createObjectLiteralExpression( this.$node(props), this.$multiline(props.length), ); return this.$hint(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/prefix.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; const Mixed = TsDsl; export class PrefixTsDsl extends Mixed { readonly '~dsl' = 'PrefixTsDsl'; protected _expr?: string | MaybeTsDsl; protected _op?: ts.PrefixUnaryOperator; constructor(expr?: string | MaybeTsDsl, op?: ts.PrefixUnaryOperator) { super(); this._expr = expr; this._op = op; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._expr); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the operand (the expression being prefixed). */ expr(expr: string | MaybeTsDsl): this { this._expr = expr; return this; } /** Sets the operator to MinusToken for negation (`-`). */ neg(): this { this._op = ts.SyntaxKind.MinusToken; return this; } /** Sets the operator to ExclamationToken for logical NOT (`!`). */ not(): this { this._op = ts.SyntaxKind.ExclamationToken; return this; } /** Sets the operator (e.g. `ts.SyntaxKind.ExclamationToken` for `!`). */ op(op: ts.PrefixUnaryOperator): this { this._op = op; return this; } override toAst() { this.$validate(); return ts.factory.createPrefixUnaryExpression(this._op, this.$node(this._expr)); } $validate(): asserts this is this & { _expr: string | MaybeTsDsl; _op: ts.PrefixUnaryOperator; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Prefix unary expression missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._expr) missing.push('.expr()'); if (!this._op) missing.push('operator (e.g., .not(), .neg())'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/prop.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { GetterTsDsl } from '../decl/getter'; import { SetterTsDsl } from '../decl/setter'; import { DocMixin } from '../mixins/doc'; import { safePropName } from '../utils/name'; import { IdTsDsl } from './id'; type Expr = NodeName | MaybeTsDsl; type Stmt = NodeName | MaybeTsDsl; export type ObjectPropKind = 'computed' | 'getter' | 'prop' | 'setter' | 'spread'; type Meta = | { kind: 'computed'; name: string } | { kind: 'getter'; name: string } | { kind: 'prop'; name: string } | { kind: 'setter'; name: string } | { kind: 'spread'; name?: undefined }; const Mixed = DocMixin(TsDsl); export class ObjectPropTsDsl extends Mixed { readonly '~dsl' = 'ObjectPropTsDsl'; protected _value?: Ref; protected _meta: Meta; constructor(meta: Meta) { super(); this._meta = meta; } get kind(): ObjectPropKind { return this._meta.kind; } get propName(): string | undefined { return this._meta.name; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._value); } get isValid(): boolean { return this.missingRequiredCalls().length === 0; } value(value: Expr | Stmt | ((p: ObjectPropTsDsl) => void)) { if (typeof value === 'function') { value(this); } else { this._value = ref(value); } return this; } override toAst() { this.$validate(); const node = this.$node(this._value); if (this._meta.kind === 'spread') { if (ts.isStatement(node)) { throw new Error('Invalid spread: object spread must be an expression, not a statement.'); } const result = ts.factory.createSpreadAssignment(node); return this.$docs(result); } if (this._meta.kind === 'getter') { const getter = new GetterTsDsl(this._meta.name).do(node); const result = this.$node(getter); return this.$docs(result); } if (this._meta.kind === 'setter') { const setter = new SetterTsDsl(this._meta.name).do(node); const result = this.$node(setter); return this.$docs(result); } if (ts.isIdentifier(node) && node.text === this._meta.name) { const result = ts.factory.createShorthandPropertyAssignment(this._meta.name); return this.$docs(result); } if (ts.isStatement(node)) { throw new Error( 'Invalid property: object property value must be an expression, not a statement.', ); } const result = ts.factory.createPropertyAssignment( this._meta.kind === 'computed' ? ts.factory.createComputedPropertyName(this.$node(new IdTsDsl(this._meta.name))) : this.$node(safePropName(this._meta.name)), node, ); return this.$docs(result); } $validate(): asserts this is this & { _value: Expr | Stmt; kind: ObjectPropKind; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error( `Object property${this._meta.name ? ` "${this._meta.name}"` : ''} missing ${missing.join(' and ')}`, ); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._value) missing.push('.value()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/regexp.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; type RegexFlag = 'g' | 'i' | 'm' | 's' | 'u' | 'y'; type RegexFlags = | '' | { [K in Avail]: `${K}${RegexFlags>}`; }[Avail]; const Mixed = TsDsl; export class RegExpTsDsl extends Mixed { readonly '~dsl' = 'RegExpTsDsl'; protected pattern: string; protected flags?: RegexFlags; constructor(pattern: string, flags?: RegexFlags) { super(); this.pattern = pattern; this.flags = flags; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } override toAst() { const patternContent = this.pattern.startsWith('/') && this.pattern.endsWith('/') ? this.pattern.slice(1, -1) : this.pattern; const escapedPattern = patternContent.replace(/(?; const Mixed = TsDsl; export class TemplateTsDsl extends Mixed { readonly '~dsl' = 'TemplateTsDsl'; protected parts: Array> = []; constructor(value?: TemplatePart) { super(); if (value !== undefined) this.add(value); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const part of this.parts) { ctx.analyze(part); } } add(value: TemplatePart): this { this.parts.push(ref(value)); return this; } override toAst() { const parts = this.$node( this.parts.map((p) => { const part = fromRef(p); return isSymbol(part) ? part.finalName : part; }), ); const normalized: Array = []; // merge consecutive string parts for (let index = 0; index < parts.length; index++) { const current = parts[index]!; if (typeof current === 'string') { let merged = current; while (index + 1 < parts.length && typeof parts[index + 1] === 'string') { merged += parts[index + 1]; index++; } normalized.push(merged); } else if (typeof current === 'number') { normalized.push(String(current)); } else { normalized.push(current); } } if (normalized.length === 0 || typeof normalized[0] !== 'string') { normalized.unshift(''); } if (normalized.length === 1 && typeof normalized[0] === 'string') { return ts.factory.createNoSubstitutionTemplateLiteral(normalized[0]); } if ( normalized.length === 2 && typeof normalized[0] === 'string' && typeof normalized[1] !== 'string' ) { return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(normalized[0]), [ ts.factory.createTemplateSpan(normalized[1]!, ts.factory.createTemplateTail('')), ]); } const head = ts.factory.createTemplateHead(normalized.shift() as string); const spans: Array = []; while (normalized.length) { const expr = normalized.shift() as ts.Expression; const next = typeof normalized[0] === 'string' ? (normalized.shift() as string) : ''; const isLast = normalized.length === 0; spans.push( ts.factory.createTemplateSpan( expr, isLast ? ts.factory.createTemplateTail(next) : ts.factory.createTemplateMiddle(next), ), ); } return ts.factory.createTemplateExpression(head, spans); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/ternary.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; const Mixed = TsDsl; export class TernaryTsDsl extends Mixed { readonly '~dsl' = 'TernaryTsDsl'; protected _condition?: string | MaybeTsDsl; protected _then?: string | MaybeTsDsl; protected _else?: string | MaybeTsDsl; constructor(condition?: string | MaybeTsDsl) { super(); if (condition) this.condition(condition); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._condition); ctx.analyze(this._then); ctx.analyze(this._else); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } condition(condition: string | MaybeTsDsl) { this._condition = condition; return this; } do(expr: string | MaybeTsDsl) { this._then = expr; return this; } otherwise(expr: string | MaybeTsDsl) { this._else = expr; return this; } override toAst() { this.$validate(); return ts.factory.createConditionalExpression( this.$node(this._condition), undefined, this.$node(this._then), undefined, this.$node(this._else), ); } $validate(): asserts this is this & { _condition: string | MaybeTsDsl; _else: string | MaybeTsDsl; _then: string | MaybeTsDsl; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Ternary expression missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._condition) missing.push('.condition()'); if (!this._then) missing.push('.do()'); if (!this._else) missing.push('.otherwise()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/expr/typeof.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { OperatorMixin } from '../mixins/operator'; import { f } from '../utils/factories'; export type TypeOfExpr = string | MaybeTsDsl; export type TypeOfExprCtor = (expr: TypeOfExpr) => TypeOfExprTsDsl; const Mixed = OperatorMixin(TsDsl); export class TypeOfExprTsDsl extends Mixed { readonly '~dsl' = 'TypeOfExprTsDsl'; protected _expr: TypeOfExpr; constructor(expr: TypeOfExpr) { super(); this._expr = expr; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._expr); } override toAst() { return ts.factory.createTypeOfExpression(this.$node(this._expr)); } } f.typeofExpr.set((...args) => new TypeOfExprTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/index.ts ================================================ import type ts from 'typescript'; import { ClassTsDsl } from './decl/class'; import { DecoratorTsDsl } from './decl/decorator'; import { EnumTsDsl } from './decl/enum'; import { FieldTsDsl } from './decl/field'; import { FuncTsDsl } from './decl/func'; import { GetterTsDsl } from './decl/getter'; import { InitTsDsl } from './decl/init'; import { EnumMemberTsDsl } from './decl/member'; import { MethodTsDsl } from './decl/method'; import { ParamTsDsl } from './decl/param'; import { PatternTsDsl } from './decl/pattern'; import { SetterTsDsl } from './decl/setter'; import { ArrayTsDsl } from './expr/array'; import { AsTsDsl } from './expr/as'; import { AttrTsDsl } from './expr/attr'; import { AwaitTsDsl } from './expr/await'; import { BinaryTsDsl } from './expr/binary'; import { CallTsDsl } from './expr/call'; import { ExprTsDsl } from './expr/expr'; import { fromValue as exprValue } from './expr/fromValue'; import { IdTsDsl } from './expr/id'; import { LiteralTsDsl } from './expr/literal'; import { NewTsDsl } from './expr/new'; import { ObjectTsDsl } from './expr/object'; import { PrefixTsDsl } from './expr/prefix'; import { ObjectPropTsDsl } from './expr/prop'; import { RegExpTsDsl } from './expr/regexp'; import { TemplateTsDsl } from './expr/template'; import { TernaryTsDsl } from './expr/ternary'; import { TypeOfExprTsDsl } from './expr/typeof'; import { DocTsDsl } from './layout/doc'; import { HintTsDsl } from './layout/hint'; import { NewlineTsDsl } from './layout/newline'; import { NoteTsDsl } from './layout/note'; import { BlockTsDsl } from './stmt/block'; import { IfTsDsl } from './stmt/if'; import { ReturnTsDsl } from './stmt/return'; import { StmtTsDsl } from './stmt/stmt'; import { ThrowTsDsl } from './stmt/throw'; import { TryTsDsl } from './stmt/try'; import { VarTsDsl } from './stmt/var'; import { TokenTsDsl } from './token'; import { TypeAliasTsDsl } from './type/alias'; import { TypeAndTsDsl } from './type/and'; import { TypeAttrTsDsl } from './type/attr'; import { TypeExprTsDsl } from './type/expr'; import { fromValue as typeValue } from './type/fromValue'; import { TypeFuncTsDsl } from './type/func'; import { TypeIdxTsDsl } from './type/idx'; import { TypeLiteralTsDsl } from './type/literal'; import { TypeMappedTsDsl } from './type/mapped'; import { TypeObjectTsDsl } from './type/object'; import { TypeOperatorTsDsl } from './type/operator'; import { TypeOrTsDsl } from './type/or'; import { TypeParamTsDsl } from './type/param'; import { TypeQueryTsDsl } from './type/query'; import { TypeTemplateTsDsl } from './type/template'; import { TypeTupleTsDsl } from './type/tuple'; import { LazyTsDsl } from './utils/lazy'; const tsDsl = { /** Creates an array literal expression (e.g. `[1, 2, 3]`). */ array: (...args: ConstructorParameters) => new ArrayTsDsl(...args), /** Creates an `as` type assertion expression (e.g. `value as Type`). */ as: (...args: ConstructorParameters) => new AsTsDsl(...args), /** Creates a property access expression (e.g. `obj.foo`). */ attr: (...args: ConstructorParameters) => new AttrTsDsl(...args), /** Creates an await expression (e.g. `await promise`). */ await: (...args: ConstructorParameters) => new AwaitTsDsl(...args), /** Creates a binary expression (e.g. `a + b`). */ binary: (...args: ConstructorParameters) => new BinaryTsDsl(...args), /** Creates a statement block (`{ ... }`). */ block: (...args: ConstructorParameters) => new BlockTsDsl(...args), /** Creates a function or method call expression (e.g. `fn(arg)`). */ call: (...args: ConstructorParameters) => new CallTsDsl(...args), /** Creates a class declaration or expression. */ class: (...args: ConstructorParameters) => new ClassTsDsl(...args), /** Creates a constant variable declaration (`const`). */ const: (...args: ConstructorParameters) => new VarTsDsl(...args).const(), /** Creates a decorator expression (e.g. `@decorator`). */ decorator: (...args: ConstructorParameters) => new DecoratorTsDsl(...args), /** Creates a JSDoc documentation block. */ doc: (...args: ConstructorParameters) => new DocTsDsl(...args), /** Creates an enum declaration. */ enum: (...args: ConstructorParameters) => new EnumTsDsl(...args), /** Creates a general expression node. */ expr: (...args: ConstructorParameters) => new ExprTsDsl(...args), /** Creates a field declaration in a class or object. */ field: (...args: ConstructorParameters) => new FieldTsDsl(...args), /** Converts a runtime value into a corresponding expression node. */ fromValue: (...args: Parameters) => exprValue(...args), /** Creates a function expression or declaration. */ func: ((nameOrFn?: any, fn?: any) => { if (nameOrFn === undefined) return new FuncTsDsl(); if (typeof nameOrFn !== 'string') return new FuncTsDsl(nameOrFn); if (fn === undefined) return new FuncTsDsl(nameOrFn); return new FuncTsDsl(nameOrFn, fn); }) as { (): FuncTsDsl<'arrow'>; (fn: (f: FuncTsDsl<'arrow'>) => void): FuncTsDsl<'arrow'>; (name: string): FuncTsDsl<'decl'>; (name: string, fn: (f: FuncTsDsl<'decl'>) => void): FuncTsDsl<'decl'>; (name?: string, fn?: (f: FuncTsDsl<'decl'>) => void): FuncTsDsl<'arrow'> | FuncTsDsl<'decl'>; }, /** Creates a getter method declaration. */ getter: (...args: ConstructorParameters) => new GetterTsDsl(...args), /** Creates a single-line comment (//). */ hint: (...args: ConstructorParameters) => new HintTsDsl(...args), /** Creates an identifier (e.g. `foo`). */ id: (...args: ConstructorParameters) => new IdTsDsl(...args), /** Creates an if statement. */ if: (...args: ConstructorParameters) => new IfTsDsl(...args), /** Creates an initialization block or statement. */ init: (...args: ConstructorParameters) => new InitTsDsl(...args), /** Creates a lazy, context-aware node with deferred evaluation. */ lazy: (...args: ConstructorParameters>) => new LazyTsDsl(...args), /** Creates a let variable declaration (`let`). */ let: (...args: ConstructorParameters) => new VarTsDsl(...args).let(), /** Creates a literal value (e.g. string, number, boolean). */ literal: (...args: ConstructorParameters) => new LiteralTsDsl(...args), /** Creates an enum member declaration. */ member: (...args: ConstructorParameters) => new EnumMemberTsDsl(...args), /** Creates a method declaration inside a class or object. */ method: (...args: ConstructorParameters) => new MethodTsDsl(...args), /** Creates a negation expression (`-x`). */ neg: (...args: ConstructorParameters) => new PrefixTsDsl(...args).neg(), /** Creates a new expression (e.g. `new ClassName()`). */ new: (...args: ConstructorParameters) => new NewTsDsl(...args), /** Creates a newline (for formatting purposes). */ newline: (...args: ConstructorParameters) => new NewlineTsDsl(...args), /** Creates a logical NOT expression (`!x`). */ not: (...args: ConstructorParameters) => new PrefixTsDsl(...args).not(), /** Creates a block comment (/* ... *\/). */ note: (...args: ConstructorParameters) => new NoteTsDsl(...args), /** Creates an object literal expression. */ object: (...args: ConstructorParameters) => new ObjectTsDsl(...args), /** Creates a parameter declaration for functions or methods. */ param: (...args: ConstructorParameters) => new ParamTsDsl(...args), /** Creates a pattern for destructuring or matching. */ pattern: (...args: ConstructorParameters) => new PatternTsDsl(...args), /** Creates a prefix unary expression (e.g. `-x`, `!x`, `~x`). */ prefix: (...args: ConstructorParameters) => new PrefixTsDsl(...args), /** Creates an object literal property (e.g. `{ foo: bar }`). */ prop: (...args: ConstructorParameters) => new ObjectPropTsDsl(...args), /** Creates a regular expression literal (e.g. `/foo/gi`). */ regexp: (...args: ConstructorParameters) => new RegExpTsDsl(...args), /** Creates a return statement. */ return: (...args: ConstructorParameters) => new ReturnTsDsl(...args), /** Creates a setter method declaration. */ setter: (...args: ConstructorParameters) => new SetterTsDsl(...args), /** Wraps an expression or statement-like value into a `StmtTsDsl`. */ stmt: (...args: ConstructorParameters) => new StmtTsDsl(...args), /** Creates a template literal expression. */ template: (...args: ConstructorParameters) => new TemplateTsDsl(...args), /** Creates a ternary conditional expression (if ? then : else). */ ternary: (...args: ConstructorParameters) => new TernaryTsDsl(...args), /** Creates a throw statement. */ throw: (...args: ConstructorParameters) => new ThrowTsDsl(...args), /** Creates a syntax token (e.g. `?`, `readonly`, `+`, `-`). */ token: (...args: ConstructorParameters) => new TokenTsDsl(...args), /** Creates a try/catch/finally statement. */ try: (...args: ConstructorParameters) => new TryTsDsl(...args), /** Creates a basic type reference or type expression (e.g. Foo or Foo). */ type: Object.assign( (...args: ConstructorParameters) => new TypeExprTsDsl(...args), { /** Creates a type alias declaration (e.g. `type Foo = Bar`). */ alias: (...args: ConstructorParameters) => new TypeAliasTsDsl(...args), /** Creates an intersection type (e.g. `A & B`). */ and: (...args: ConstructorParameters) => new TypeAndTsDsl(...args), /** Creates a qualified type reference (e.g. Foo.Bar). */ attr: (...args: ConstructorParameters) => new TypeAttrTsDsl(...args), /** Creates a basic type reference or type expression (e.g. Foo or Foo). */ expr: (...args: ConstructorParameters) => new TypeExprTsDsl(...args), /** Converts a runtime value into a corresponding type expression node. */ fromValue: (...args: Parameters) => typeValue(...args), /** Creates a function type node (e.g. `(a: string) => number`). */ func: (...args: ConstructorParameters) => new TypeFuncTsDsl(...args), /** Creates an indexed-access type (e.g. `Foo[K]`). */ idx: (...args: ConstructorParameters) => new TypeIdxTsDsl(...args), /** Creates a literal type node (e.g. 'foo', 42, or true). */ literal: (...args: ConstructorParameters) => new TypeLiteralTsDsl(...args), /** Creates a mapped type (e.g. `{ [K in keyof T]: U }`). */ mapped: (...args: ConstructorParameters) => new TypeMappedTsDsl(...args), /** Creates a type literal node (e.g. { foo: string }). */ object: (...args: ConstructorParameters) => new TypeObjectTsDsl(...args), /** Creates a type operator node (e.g. `readonly T`, `keyof T`, `unique T`). */ operator: (...args: ConstructorParameters) => new TypeOperatorTsDsl(...args), /** Represents a union type (e.g. `A | B | C`). */ or: (...args: ConstructorParameters) => new TypeOrTsDsl(...args), /** Creates a type parameter (e.g. ``). */ param: (...args: ConstructorParameters) => new TypeParamTsDsl(...args), /** Creates a type query node (e.g. `typeof Foo`). */ query: (...args: ConstructorParameters) => new TypeQueryTsDsl(...args), /** Builds a TypeScript template literal *type* (e.g. `${Foo}-${Bar}` as a type). */ template: (...args: ConstructorParameters) => new TypeTemplateTsDsl(...args), /** Creates a tuple type (e.g. [A, B, C]). */ tuple: (...args: ConstructorParameters) => new TypeTupleTsDsl(...args), }, ), /** Creates a `typeof` expression (e.g. `typeof value`). */ typeofExpr: (...args: ConstructorParameters) => new TypeOfExprTsDsl(...args), /** Creates a variable declaration (`var`). */ var: (...args: ConstructorParameters) => new VarTsDsl(...args), }; export const $ = Object.assign( (...args: ConstructorParameters) => new ExprTsDsl(...args), tsDsl, ); export type DollarTsDsl = { /** * Entry point to the TypeScript DSL. * * `$` creates a general expression node by default, but also exposes * builders for all other constructs such as `.type()`, `.call()`, * `.object()`, `.func()`, etc. * * Example: * ```ts * const node = $('console').attr('log').call($.literal('Hello')); * ``` * * Returns: * - A new `ExprTsDsl` instance when called directly. * - The `tsDsl` object for constructing more specific nodes. */ $: typeof $; }; export type { MaybeTsDsl, TypeTsDsl } from './base'; export { TsDsl } from './base'; export type { CallArgs } from './expr/call'; export type { ExampleOptions } from './utils/context'; export { ctx, TsDslContext } from './utils/context'; export { keywords } from './utils/keywords'; export { regexp } from './utils/regexp'; export { TypeScriptRenderer } from './utils/render'; export { reserved } from './utils/reserved'; ================================================ FILE: packages/openapi-ts/src/ts-dsl/layout/doc.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import ts from 'typescript'; import { TsDsl } from '../base'; import { IdTsDsl } from '../expr/id'; import type { TsDslContext } from '../utils/context'; import { ctx } from '../utils/context'; type DocMaybeLazy = ((ctx: TsDslContext) => T) | T; export type DocFn = (d: DocTsDsl) => void; export type DocLines = DocMaybeLazy>; export class DocTsDsl extends TsDsl { readonly '~dsl' = 'DocTsDsl'; protected _lines: Array = []; constructor(lines?: DocLines, fn?: DocFn) { super(); if (lines) this.add(lines); fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } add(lines: DocLines): this { this._lines.push(lines); return this; } apply(node: T): T { const lines = this._lines.reduce((lines: Array, line: DocLines) => { if (typeof line === 'function') line = line(ctx); for (const l of typeof line === 'string' ? [line] : line) { if (l || l === '') lines.push(l); } return lines; }, []); if (!lines.length) return node; const jsdocTexts = lines.map((line) => ts.factory.createJSDocText(`${line}\n`)); const jsdoc = ts.factory.createJSDocComment(ts.factory.createNodeArray(jsdocTexts), undefined); const cleanedJsdoc = ts .createPrinter() .printNode( ts.EmitHint.Unspecified, jsdoc, node.getSourceFile?.() ?? ts.createSourceFile('', '', ts.ScriptTarget.Latest), ) .replace('/*', '') .replace('* */', ''); ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, cleanedJsdoc, true); return node; } override toAst() { // this class does not build a standalone node; // it modifies other nodes via `apply()`. // Return a dummy comment node for compliance. return this.$node(new IdTsDsl('')); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/layout/hint.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import ts from 'typescript'; import { TsDsl } from '../base'; import { IdTsDsl } from '../expr/id'; import type { TsDslContext } from '../utils/context'; import { ctx } from '../utils/context'; type HintMaybeLazy = ((ctx: TsDslContext) => T) | T; export type HintFn = (d: HintTsDsl) => void; export type HintLines = HintMaybeLazy>; export class HintTsDsl extends TsDsl { readonly '~dsl' = 'HintTsDsl'; protected _lines: Array = []; constructor(lines?: HintLines, fn?: HintFn) { super(); if (lines) this.add(lines); fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } add(lines: HintLines): this { this._lines.push(lines); return this; } apply(node: T): T { const lines = this._lines.reduce((lines: Array, line: HintLines) => { if (typeof line === 'function') line = line(ctx); for (const l of typeof line === 'string' ? [line] : line) { if (l || l === '') lines.push(l); } return lines; }, []); if (!lines.length) return node; for (const line of lines) { ts.addSyntheticLeadingComment(node, ts.SyntaxKind.SingleLineCommentTrivia, ` ${line}`, false); } return node; } override toAst() { // this class does not build a standalone node; // it modifies other nodes via `apply()`. // Return a dummy comment node for compliance. return this.$node(new IdTsDsl('')); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/layout/newline.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type ts from 'typescript'; import { TsDsl } from '../base'; import { IdTsDsl } from '../expr/id'; export class NewlineTsDsl extends TsDsl { readonly '~dsl' = 'NewlineTsDsl'; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } override toAst() { return this.$node(new IdTsDsl('\n')); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/layout/note.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import ts from 'typescript'; import { TsDsl } from '../base'; import { IdTsDsl } from '../expr/id'; import type { TsDslContext } from '../utils/context'; import { ctx } from '../utils/context'; type NoteMaybeLazy = ((ctx: TsDslContext) => T) | T; export type NoteFn = (d: NoteTsDsl) => void; export type NoteLines = NoteMaybeLazy>; export class NoteTsDsl extends TsDsl { readonly '~dsl' = 'NoteTsDsl'; protected _lines: Array = []; constructor(lines?: NoteLines, fn?: NoteFn) { super(); if (lines) this.add(lines); fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } add(lines: NoteLines): this { this._lines.push(lines); return this; } apply(node: T): T { const lines = this._lines.reduce((lines: Array, line: NoteLines) => { if (typeof line === 'function') line = line(ctx); for (const l of typeof line === 'string' ? [line] : line) { if (l || l === '') lines.push(l); } return lines; }, []); if (!lines.length) return node; ts.addSyntheticLeadingComment( node, ts.SyntaxKind.MultiLineCommentTrivia, `\n${lines.join('\n')}\n`, true, ); return node; } override toAst() { // this class does not build a standalone node; // it modifies other nodes via `apply()`. // Return a dummy comment node for compliance. return this.$node(new IdTsDsl('')); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/args.ts ================================================ import type { AnalysisContext, Node, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import type { BaseCtor, MixinCtor } from './types'; type Arg = NodeName | MaybeTsDsl; export interface ArgsMethods extends Node { /** Renders the arguments into an array of `Expression`s. */ $args(): ReadonlyArray; /** Adds a single expression argument. */ arg(arg: Arg | undefined): this; /** Adds one or more expression arguments. */ args(...args: ReadonlyArray): this; } /** * Adds `.arg()` and `.args()` for managing expression arguments in call-like nodes. */ export function ArgsMixin>(Base: TBase) { abstract class Args extends Base { protected _args: Array> = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const arg of this._args) { ctx.analyze(arg); } } protected arg(arg: Arg | undefined): this { if (arg !== undefined) this._args.push(ref(arg)); return this; } protected args(...args: ReadonlyArray): this { this._args.push( ...args.filter((a): a is NonNullable => a !== undefined).map((a) => ref(a)), ); return this; } protected $args(): ReadonlyArray { return this.$node(this._args).map((arg) => this.$node(arg)); } } return Args as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/as.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import { f } from '../utils/factories'; import type { BaseCtor, DropFirst, MixinCtor } from './types'; export interface AsMethods extends Node { /** Creates an `as` type assertion expression (e.g. `value as Type`). */ as(...args: DropFirst>): ReturnType; } export function AsMixin>(Base: TBase) { abstract class As extends Base { override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected as(...args: DropFirst>): ReturnType { return f.as(this, ...args); } } return As as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/decorator.ts ================================================ import type { AnalysisContext, Node, NodeName } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { DecoratorTsDsl } from '../decl/decorator'; import type { BaseCtor, MixinCtor } from './types'; export interface DecoratorMethods extends Node { /** Renders the decorators into an array of `ts.Decorator`s. */ $decorators(): ReadonlyArray; /** Adds a decorator (e.g. `@sealed({ in: 'root' })`). */ decorator( name: NodeName | MaybeTsDsl, ...args: ReadonlyArray> ): this; } export function DecoratorMixin>(Base: TBase) { abstract class Decorator extends Base { protected decorators: Array = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const decorator of this.decorators) { ctx.analyze(decorator); } } protected decorator( name: NodeName, ...args: ReadonlyArray> ): this { this.decorators.push(new DecoratorTsDsl(name, ...args)); return this; } protected $decorators(): ReadonlyArray { return this.$node(this.decorators); } } return Decorator as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/do.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { StmtTsDsl } from '../stmt/stmt'; import type { BaseCtor, MixinCtor } from './types'; export type DoExpr = MaybeTsDsl; export interface DoMethods extends Node { /** Renders the collected `.do()` calls into an array of `Statement` nodes. */ $do(): ReadonlyArray; _do: Array; /** Adds one or more expressions/statements to the body. */ do(...items: ReadonlyArray): this; } /** * Adds `.do()` for appending statements or expressions to a body. */ export function DoMixin>(Base: TBase) { abstract class Do extends Base { protected _do: Array = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.pushScope(); try { for (const item of this._do) { ctx.analyze(item); } } finally { ctx.popScope(); } } protected do(...items: ReadonlyArray): this { this._do.push(...items); return this; } protected $do(): ReadonlyArray { return this.$node(this._do.map((item) => new StmtTsDsl(item))); } } return Do as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/doc.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { DocFn, DocLines } from '../layout/doc'; import { DocTsDsl } from '../layout/doc'; import type { BaseCtor, MixinCtor } from './types'; export interface DocMethods extends Node { $docs(node: T): T; doc(lines?: DocLines, fn?: DocFn): this; } export function DocMixin>(Base: TBase) { abstract class Doc extends Base { private _doc?: DocTsDsl; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected doc(lines?: DocLines, fn?: DocFn): this { this._doc = new DocTsDsl(lines, fn); return this; } protected $docs(node: T): T { return this._doc ? this._doc.apply(node) : node; } } return Doc as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/expr.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import { f } from '../utils/factories'; import type { BaseCtor, DropFirst, MixinCtor } from './types'; export interface ExprMethods extends Node { /** Accesses a property on the current expression (e.g. `this.foo`). */ attr(...args: DropFirst>): ReturnType; /** Awaits the current expression (e.g. `await expr`). */ await(): ReturnType; /** Calls the current expression (e.g. `fn(arg1, arg2)`). */ call(...args: DropFirst>): ReturnType; /** Produces a `return` statement returning the current expression. */ return(): ReturnType; } export function ExprMixin>(Base: TBase) { abstract class Expr extends Base { override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected attr(...args: DropFirst>): ReturnType { return f.attr(this, ...args); } protected await(): ReturnType { return f.await(this); } protected call(...args: DropFirst>): ReturnType { return f.call(this, ...args); } protected return(): ReturnType { return f.return(this); } } return Expr as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/hint.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { HintFn, HintLines } from '../layout/hint'; import { HintTsDsl } from '../layout/hint'; import type { BaseCtor, MixinCtor } from './types'; export interface HintMethods extends Node { $hint(node: T): T; hint(lines?: HintLines, fn?: HintFn): this; } export function HintMixin>(Base: TBase) { abstract class Hint extends Base { private _hint?: HintTsDsl; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected hint(lines?: HintLines, fn?: HintFn): this { this._hint = new HintTsDsl(lines, fn); return this; } protected $hint(node: T): T { return this._hint ? this._hint.apply(node) : node; } } return Hint as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/layout.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { BaseCtor, MixinCtor } from './types'; export interface LayoutMethods extends Node { /** Computes whether output should be multiline based on layout setting and element count. */ $multiline(count: number): boolean; /** Sets automatic line output with optional threshold (default: 3). */ auto(threshold?: number): this; /** Sets single line output. */ inline(): this; /** Sets multi line output. */ pretty(): this; } export function LayoutMixin>(Base: TBase) { abstract class Layout extends Base { protected static readonly DEFAULT_THRESHOLD = 3; protected layout: boolean | number | undefined; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected auto(threshold: number = Layout.DEFAULT_THRESHOLD): this { this.layout = threshold; return this; } protected inline(): this { this.layout = false; return this; } protected pretty(): this { this.layout = true; return this; } protected $multiline(count: number): boolean { if (this.layout === undefined) { this.layout = Layout.DEFAULT_THRESHOLD; } if (count === 0) return false; return typeof this.layout === 'number' ? count >= this.layout : this.layout; } } return Layout as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/modifiers.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { BaseCtor, MixinCtor } from './types'; export type Modifiers = { /** * Checks if the specified modifier is present. * * @param modifier - The modifier to check. * @returns True if the modifier is present, false otherwise. */ hasModifier(modifier: Modifier): boolean; modifiers: Array; }; type Modifier = | 'abstract' | 'async' | 'const' | 'declare' | 'default' | 'export' | 'override' | 'private' | 'protected' | 'public' | 'readonly' | 'static'; export interface ModifierMethods extends Modifiers { /** * Adds a modifier of the specified kind to the modifiers list if the condition is true. * * @param modifier - The modifier to add. * @param condition - Whether to add the modifier. * @returns The parent node for chaining. */ _m(modifier: Modifier, condition: boolean): this; } function modifierToKind(modifier: Modifier): ts.ModifierSyntaxKind { switch (modifier) { case 'abstract': return ts.SyntaxKind.AbstractKeyword; case 'async': return ts.SyntaxKind.AsyncKeyword; case 'const': return ts.SyntaxKind.ConstKeyword; case 'declare': return ts.SyntaxKind.DeclareKeyword; case 'default': return ts.SyntaxKind.DefaultKeyword; case 'export': return ts.SyntaxKind.ExportKeyword; case 'override': return ts.SyntaxKind.OverrideKeyword; case 'private': return ts.SyntaxKind.PrivateKeyword; case 'protected': return ts.SyntaxKind.ProtectedKeyword; case 'public': return ts.SyntaxKind.PublicKeyword; case 'readonly': return ts.SyntaxKind.ReadonlyKeyword; case 'static': return ts.SyntaxKind.StaticKeyword; } } function ModifiersMixin>(Base: TBase) { abstract class Modifiers extends Base { protected modifiers: Array = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected hasModifier(modifier: Modifier): boolean { const kind = modifierToKind(modifier); return Boolean(this.modifiers.find((mod) => mod.kind === kind)); } protected _m(modifier: Modifier, condition: boolean): this { if (condition) { const kind = modifierToKind(modifier); this.modifiers.push(ts.factory.createModifier(kind)); } return this; } } return Modifiers as unknown as MixinCtor; } export interface AbstractMethods extends Modifiers { /** * Adds the `abstract` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ abstract(condition?: boolean): this; } /** * Mixin that adds an `abstract` modifier to a node. */ export function AbstractMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Abstract extends Mixed { protected abstract(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('abstract', cond); } } return Abstract as unknown as MixinCtor; } export interface AsyncMethods extends Modifiers { /** * Adds the `async` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ async(condition?: boolean): this; } /** * Mixin that adds an `async` modifier to a node. */ export function AsyncMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Async extends Mixed { protected async(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('async', cond); } } return Async as unknown as MixinCtor; } export interface ConstMethods extends Modifiers { /** * Adds the `const` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ const(condition?: boolean): this; } /** * Mixin that adds a `const` modifier to a node. */ export function ConstMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Const extends Mixed { protected const(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('const', cond); } } return Const as unknown as MixinCtor; } export interface DeclareMethods extends Modifiers { /** * Adds the `declare` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ declare(condition?: boolean): this; } /** * Mixin that adds a `declare` modifier to a node. */ export function DeclareMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Declare extends Mixed { protected declare(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('declare', cond); } } return Declare as unknown as MixinCtor; } export interface DefaultMethods extends Modifiers { /** * Adds the `default` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ default(condition?: boolean): this; } /** * Mixin that adds a `default` modifier to a node. */ export function DefaultMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Default extends Mixed { /** * Adds the `default` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ protected default(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('default', cond); } } return Default as unknown as MixinCtor; } export interface ExportMethods extends Modifiers { /** * Adds the `export` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ export(condition?: boolean): this; } /** * Mixin that adds an `export` modifier to a node. */ export function ExportMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Export extends Mixed { /** * Adds the `export` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ protected export(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); this.exported = cond; // TODO: remove this side-effect once planner handles exported flag if (this.symbol) this.symbol.setExported(cond); return this._m('export', cond); } } return Export as unknown as MixinCtor; } export interface OverrideMethods extends Modifiers { /** * Adds the `override` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ override(condition?: boolean): this; } /** * Mixin that adds an `override` modifier to a node. */ export function OverrideMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Override extends Mixed { protected override(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('override', cond); } } return Override as unknown as MixinCtor; } export interface PrivateMethods extends Modifiers { /** * Adds the `private` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ private(condition?: boolean): this; } /** * Mixin that adds a `private` modifier to a node. */ export function PrivateMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Private extends Mixed { protected private(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('private', cond); } } return Private as unknown as MixinCtor; } export interface ProtectedMethods extends Modifiers { /** * Adds the `protected` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ protected(condition?: boolean): this; } /** * Mixin that adds a `protected` modifier to a node. */ export function ProtectedMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Protected extends Mixed { protected protected(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('protected', cond); } } return Protected as unknown as MixinCtor; } export interface PublicMethods extends Modifiers { /** * Adds the `public` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ public(condition?: boolean): this; } /** * Mixin that adds a `public` modifier to a node. */ export function PublicMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Public extends Mixed { protected public(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('public', cond); } } return Public as unknown as MixinCtor; } export interface ReadonlyMethods extends Modifiers { /** * Adds the `readonly` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ readonly(condition?: boolean): this; } /** * Mixin that adds a `readonly` modifier to a node. */ export function ReadonlyMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Readonly extends Mixed { protected readonly(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('readonly', cond); } } return Readonly as unknown as MixinCtor; } export interface StaticMethods extends Modifiers { /** * Adds the `static` keyword modifier if the condition is true. * * @param condition - Whether to add the modifier (default: true). * @returns The target object for chaining. */ static(condition?: boolean): this; } /** * Mixin that adds a `static` modifier to a node. */ export function StaticMixin>(Base: TBase) { const Mixed = ModifiersMixin(Base as BaseCtor); abstract class Static extends Mixed { protected static(condition?: boolean): this { const cond = arguments.length === 0 ? true : Boolean(condition); return this._m('static', cond); } } return Static as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/note.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { NoteFn, NoteLines } from '../layout/note'; import { NoteTsDsl } from '../layout/note'; import type { BaseCtor, MixinCtor } from './types'; export interface NoteMethods extends Node { $note(node: T): T; note(lines?: NoteLines, fn?: NoteFn): this; } export function NoteMixin>(Base: TBase) { abstract class Note extends Base { private _note?: NoteTsDsl; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected note(lines?: NoteLines, fn?: NoteFn): this { this._note = new NoteTsDsl(lines, fn); return this; } protected $note(node: T): T { return this._note ? this._note.apply(node) : node; } } return Note as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/operator.ts ================================================ import type { AnalysisContext, Node, NodeName } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { BinaryTsDsl } from '../expr/binary'; import type { BaseCtor, MixinCtor } from './types'; type Expr = NodeName | MaybeTsDsl; export interface OperatorMethods extends Node { /** Logical AND — `this && expr` */ and(expr: Expr): BinaryTsDsl; /** Creates an assignment expression (e.g. `this = expr`). */ assign(expr: Expr): BinaryTsDsl; /** Nullish coalescing — `this ?? expr` */ coalesce(expr: Expr): BinaryTsDsl; /** Division — `this / expr` */ div(expr: Expr): BinaryTsDsl; /** Strict equality — `this === expr` */ eq(expr: Expr): BinaryTsDsl; /** Greater than — `this > expr` */ gt(expr: Expr): BinaryTsDsl; /** Greater than or equal — `this >= expr` */ gte(expr: Expr): BinaryTsDsl; /** Loose equality — `this == expr` */ looseEq(expr: Expr): BinaryTsDsl; /** Loose inequality — `this != expr` */ looseNeq(expr: Expr): BinaryTsDsl; /** Less than — `this < expr` */ lt(expr: Expr): BinaryTsDsl; /** Less than or equal — `this <= expr` */ lte(expr: Expr): BinaryTsDsl; /** Subtraction — `this - expr` */ minus(expr: Expr): BinaryTsDsl; /** Strict inequality — `this !== expr` */ neq(expr: Expr): BinaryTsDsl; /** Nullish assignment — `this ??= expr` */ nullishAssign(expr: Expr): BinaryTsDsl; /** Logical OR — `this || expr` */ or(expr: Expr): BinaryTsDsl; /** Addition — `this + expr` */ plus(expr: Expr): BinaryTsDsl; /** Multiplication — `this * expr` */ times(expr: Expr): BinaryTsDsl; } export function OperatorMixin>(Base: TBase) { abstract class Operator extends Base { override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected and(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).and(expr); } protected assign(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this, '=', expr); } protected coalesce(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).coalesce(expr); } protected div(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).div(expr); } protected eq(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).eq(expr); } protected gt(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).gt(expr); } protected gte(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).gte(expr); } protected looseEq(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).looseEq(expr); } protected looseNeq(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).looseNeq(expr); } protected lt(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).lt(expr); } protected lte(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).lte(expr); } protected minus(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).minus(expr); } protected neq(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).neq(expr); } protected nullishAssign(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).nullishAssign(expr); } protected or(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).or(expr); } protected plus(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).plus(expr); } protected times(expr: Expr): BinaryTsDsl { return new BinaryTsDsl(this).times(expr); } } return Operator as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/optional.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { BaseCtor, MixinCtor } from './types'; export interface OptionalMethods extends Node { _optional?: boolean; /** Marks the node as optional when the condition is true. */ optional(condition?: boolean): this; /** Marks the node as required when the condition is true. */ required(condition?: boolean): this; } export function OptionalMixin>(Base: TBase) { abstract class Optional extends Base { protected _optional?: boolean; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected optional(condition?: boolean): this { this._optional = arguments.length === 0 ? true : Boolean(condition); return this; } protected required(condition?: boolean): this { this._optional = arguments.length === 0 ? false : !condition; return this; } } return Optional as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/param.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import type { ParamCtor, ParamFn, ParamName } from '../decl/param'; import { ParamTsDsl } from '../decl/param'; import type { BaseCtor, MixinCtor } from './types'; export interface ParamMethods extends Node { /** Renders the parameters into an array of `ParameterDeclaration`s. */ $params(): ReadonlyArray; /** Adds a parameter. */ param(...args: Parameters): this; /** Adds multiple parameters. */ params(...params: ReadonlyArray>): this; } export function ParamMixin>(Base: TBase) { abstract class Param extends Base { protected _params: Array> = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const param of this._params) { ctx.analyze(param); } } protected param(name: ParamName, fn?: ParamFn): this { const p = new ParamTsDsl(name, fn); this._params.push(p); return this; } protected params(...params: ReadonlyArray>): this { this._params.push(...params); return this; } protected $params(): ReadonlyArray { return this.$node(this._params); } } return Param as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/pattern.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type { MaybeArray } from '@hey-api/types'; import type ts from 'typescript'; import { PatternTsDsl } from '../decl/pattern'; import type { BaseCtor, MixinCtor } from './types'; export interface PatternMethods extends Node { /** Renders the pattern into a `BindingName`. */ $pattern(): ts.BindingName | undefined; /** Defines an array binding pattern. */ array(...props: ReadonlyArray | [ReadonlyArray]): this; /** Defines an object binding pattern. */ object(...props: ReadonlyArray | Record>): this; /** Adds a spread element (e.g. `...args`, `...options`) to the pattern. */ spread(name: string): this; } /** * Mixin providing `.array()`, `.object()`, and `.spread()` methods for defining destructuring patterns. */ export function PatternMixin>(Base: TBase) { abstract class Pattern extends Base { protected pattern?: PatternTsDsl; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.pattern); } protected array(...props: ReadonlyArray | [ReadonlyArray]): this { (this.pattern ??= new PatternTsDsl()).array(...props); return this; } protected object(...props: ReadonlyArray | Record>): this { (this.pattern ??= new PatternTsDsl()).object(...props); return this; } /** Adds a spread element (e.g. `...args`, `...options`) to the pattern. */ protected spread(name: string): this { (this.pattern ??= new PatternTsDsl()).spread(name); return this; } /** Renders the pattern into a `BindingName`. */ protected $pattern(): ts.BindingName | undefined { if (!this.pattern) return; return this.$node(this.pattern); } } return Pattern as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/type-args.ts ================================================ import type { AnalysisContext, Node, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl, TypeTsDsl } from '../base'; import type { BaseCtor, MixinCtor } from './types'; type Arg = NodeName | MaybeTsDsl; export interface TypeArgsMethods extends Node { /** Returns the type arguments as an array of ts.TypeNode nodes. */ $generics(): ReadonlyArray | undefined; /** Adds a single type argument (e.g. `string` in `Foo`). */ generic(arg: Arg): this; /** Adds type arguments (e.g. `Map`). */ generics(...args: ReadonlyArray): this; } export function TypeArgsMixin>(Base: TBase) { abstract class TypeArgs extends Base { protected _generics: Array> = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const g of this._generics) { ctx.analyze(g); } } protected generic(arg: Arg): this { this._generics.push(ref(arg)); return this; } protected generics(...args: ReadonlyArray): this { this._generics.push(...args.map((a) => ref(a))); return this; } protected $generics(): ReadonlyArray | undefined { return this.$type(this._generics); } } return TypeArgs as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/type-expr.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl, TypeTsDsl } from '../base'; import { f } from '../utils/factories'; import type { BaseCtor, DropFirst, MixinCtor } from './types'; export interface TypeExprMethods extends Node { /** Creates an indexed-access type (e.g. `Foo[K]`). */ idx( this: Parameters[0], ...args: DropFirst> ): ReturnType; /** Shorthand: builds `keyof T`. */ keyof(this: MaybeTsDsl): ReturnType; /** Shorthand: builds `readonly T`. */ readonly(this: MaybeTsDsl): ReturnType; /** Create a TypeExpr node representing ReturnType. */ returnType( this: Parameters[0], ...args: DropFirst> ): ReturnType; /** Create a TypeOfExpr node representing typeof this. */ typeofExpr( this: Parameters[0], ...args: DropFirst> ): ReturnType; /** Create a TypeQuery node representing typeof this. */ typeofType( this: Parameters[0], ...args: DropFirst> ): ReturnType; /** Shorthand: builds `unique T`. */ unique(this: MaybeTsDsl): ReturnType; } export function TypeExprMixin>(Base: TBase) { abstract class TypeExpr extends Base { override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } protected idx( this: Parameters[0], ...args: DropFirst> ): ReturnType { return f.type.idx(this, ...args); } protected keyof(this: TypeTsDsl): ReturnType { return f.type.operator().keyof(this); } protected readonly(this: TypeTsDsl): ReturnType { return f.type.operator().readonly(this); } protected returnType( this: Parameters[0], ...args: DropFirst> ): ReturnType { return f.type.expr('ReturnType').generic(f.type.query(this, ...args)); } protected typeofExpr( this: Parameters[0], ...args: DropFirst> ): ReturnType { return f.typeofExpr(this, ...args); } protected typeofType( this: Parameters[0], ...args: DropFirst> ): ReturnType { return f.type.query(this, ...args); } protected unique(this: TypeTsDsl): ReturnType { return f.type.operator().unique(this); } } return TypeExpr as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/type-params.ts ================================================ import type { AnalysisContext, Node, NodeName } from '@hey-api/codegen-core'; import { isRef, isSymbol } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TypeParamTsDsl } from '../type/param'; import type { BaseCtor, MixinCtor } from './types'; export interface TypeParamsMethods extends Node { /** Returns the type parameters as an array of ts.TypeParameterDeclaration nodes. */ $generics(): ReadonlyArray | undefined; /** Adds a single type parameter (e.g. `T` in `Array`). */ generic(...args: ConstructorParameters): this; /** Adds type parameters (e.g. `Map`). */ generics(...args: ReadonlyArray>): this; } export function TypeParamsMixin>(Base: TBase) { abstract class TypeParams extends Base { protected _generics: Array> = []; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const g of this._generics) { ctx.analyze(g); } } protected generic(...args: ConstructorParameters): this { const g = new TypeParamTsDsl(...args); this._generics.push(g); return this; } protected generics(...args: ReadonlyArray>): this { for (let arg of args) { if (typeof arg === 'string' || typeof arg === 'number' || isSymbol(arg) || isRef(arg)) { arg = new TypeParamTsDsl(arg); } this._generics.push(arg); } return this; } protected $generics(): ReadonlyArray | undefined { return this.$node(this._generics); } } return TypeParams as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/type-returns.ts ================================================ import type { AnalysisContext, Node, NodeName } from '@hey-api/codegen-core'; import type ts from 'typescript'; import { TypeTsDsl } from '../base'; import { TypeExprTsDsl } from '../type/expr'; import type { BaseCtor, MixinCtor } from './types'; export interface TypeReturnsMethods extends Node { /** Returns the return type node. */ $returns(): ts.TypeNode | undefined; /** Sets the return type. */ returns(type: NodeName | TypeTsDsl): this; } export function TypeReturnsMixin>(Base: TBase) { abstract class TypeReturns extends Base { protected _returns?: TypeTsDsl; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._returns); } protected returns(type: NodeName | TypeTsDsl): this { this._returns = type instanceof TypeTsDsl ? type : new TypeExprTsDsl(type); return this; } protected $returns(): ts.TypeNode | undefined { return this.$type(this._returns); } } return TypeReturns as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/types.ts ================================================ import type ts from 'typescript'; import type { TsDsl } from '../base'; export type BaseCtor = abstract new (...args: Array) => TsDsl; export type DropFirst> = T extends [any, ...infer Rest] ? Rest : never; export type MixinCtor, K> = abstract new ( ...args: Array ) => InstanceType & K; ================================================ FILE: packages/openapi-ts/src/ts-dsl/mixins/value.ts ================================================ import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import type { BaseCtor, MixinCtor } from './types'; export type ValueExpr = string | MaybeTsDsl; export interface ValueMethods extends Node { $value(): ts.Expression | undefined; /** Sets the initializer expression (e.g. `= expr`). */ assign(expr: ValueExpr): this; } export function ValueMixin>(Base: TBase) { abstract class Value extends Base { protected value?: ValueExpr; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.value); } protected assign(expr: ValueExpr): this { this.value = expr; return this; } protected $value(): ts.Expression | undefined { return this.$node(this.value); } } return Value as unknown as MixinCtor; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/stmt/block.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { DoMixin } from '../mixins/do'; import { LayoutMixin } from '../mixins/layout'; const Mixed = DoMixin(LayoutMixin(TsDsl)); export class BlockTsDsl extends Mixed { readonly '~dsl' = 'BlockTsDsl'; constructor(...items: Array) { super(); this.do(...items); } override analyze(ctx: AnalysisContext) { super.analyze(ctx); } override toAst() { const statements = this.$do(); return ts.factory.createBlock(statements, this.$multiline(statements.length)); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/stmt/if.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { DoMixin } from '../mixins/do'; import { BlockTsDsl } from './block'; export type IfCondition = string | MaybeTsDsl; const Mixed = DoMixin(TsDsl); export class IfTsDsl extends Mixed { readonly '~dsl' = 'IfTsDsl'; protected _condition?: IfCondition; protected _else?: Array; constructor(condition?: IfCondition) { super(); if (condition) this.condition(condition); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._condition); if (this._else) { ctx.pushScope(); try { for (const stmt of this._else) { ctx.analyze(stmt); } } finally { ctx.popScope(); } } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } condition(condition: IfCondition): this { this._condition = condition; return this; } otherwise(...items: Array): this { this._else = items; return this; } override toAst() { this.$validate(); return ts.factory.createIfStatement( this.$node(this._condition), this.$node(new BlockTsDsl(...this._do).pretty()), this._else ? this.$node(new BlockTsDsl(...this._else).pretty()) : undefined, ); } $validate(): asserts this is this & { _condition: IfCondition; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`If statement missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._condition) missing.push('.condition()'); if (this._do.length === 0) missing.push('.do()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/stmt/return.ts ================================================ import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { f } from '../utils/factories'; export type ReturnExpr = NodeName | MaybeTsDsl; export type ReturnCtor = (expr?: ReturnExpr) => ReturnTsDsl; const Mixed = TsDsl; export class ReturnTsDsl extends Mixed { readonly '~dsl' = 'ReturnTsDsl'; protected _returnExpr?: Ref; constructor(expr?: ReturnExpr) { super(); if (expr) this._returnExpr = ref(expr); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._returnExpr); } override toAst() { return ts.factory.createReturnStatement(this.$node(this._returnExpr)); } } f.return.set((...args) => new ReturnTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/stmt/stmt.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; const Mixed = TsDsl; export class StmtTsDsl extends Mixed { readonly '~dsl' = 'StmtTsDsl'; protected _inner: ts.Expression | ts.Statement | TsDsl; constructor(inner: ts.Expression | ts.Statement | TsDsl) { super(); this._inner = inner; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._inner); } override toAst() { const node = this.$node(this._inner); return ts.isStatement(node) ? node : ts.factory.createExpressionStatement(node); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/stmt/throw.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { LiteralTsDsl } from '../expr/literal'; const Mixed = TsDsl; export class ThrowTsDsl extends Mixed { readonly '~dsl' = 'ThrowTsDsl'; protected error: string | MaybeTsDsl; protected msg?: string | MaybeTsDsl; protected useNew: boolean; constructor(error: string | MaybeTsDsl, useNew = true) { super(); this.error = error; this.useNew = useNew; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.error); ctx.analyze(this.msg); } message(value: string | MaybeTsDsl): this { this.msg = value; return this; } override toAst() { const errorNode = this.$node(this.error); const messageNode = this.$node(this.msg ? [this.msg] : []).map((expr) => typeof expr === 'string' ? this.$node(new LiteralTsDsl(expr)) : expr, ); if (this.useNew) { return ts.factory.createThrowStatement( ts.factory.createNewExpression(errorNode, undefined, messageNode), ); } const args = messageNode.length ? [ts.factory.createCallExpression(errorNode, undefined, messageNode)] : [errorNode]; return ts.factory.createThrowStatement(args[0]!); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/stmt/try.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import type { DoExpr } from '../mixins/do'; import { BlockTsDsl } from './block'; const Mixed = TsDsl; export class TryTsDsl extends Mixed { readonly '~dsl' = 'TryTsDsl'; protected _catch?: Array; protected _catchArg?: NodeName; protected _finally?: Array; protected _try?: Array; constructor(...tryBlock: Array) { super(); this.try(...tryBlock); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); if (this._try) { ctx.pushScope(); try { for (const stmt of this._try) ctx.analyze(stmt); } finally { ctx.popScope(); } } if (this._catch || this._catchArg) { ctx.pushScope(); try { ctx.analyze(this._catchArg); if (this._catch) { for (const stmt of this._catch) ctx.analyze(stmt); } } finally { ctx.popScope(); } } if (this._finally) { ctx.pushScope(); try { for (const stmt of this._finally) ctx.analyze(stmt); } finally { ctx.popScope(); } } } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } catch(...items: Array): this { this._catch = items; return this; } catchArg(arg: NodeName): this { this._catchArg = arg; return this; } finally(...items: Array): this { this._finally = items; return this; } try(...items: Array): this { this._try = items; return this; } override toAst() { this.$validate(); const catchParam = this._catchArg ? (this.$node(this._catchArg) as ts.BindingName) : undefined; return ts.factory.createTryStatement( this.$node(new BlockTsDsl(...this._try).pretty()), ts.factory.createCatchClause( catchParam ? ts.factory.createVariableDeclaration(catchParam) : undefined, this.$node(new BlockTsDsl(...(this._catch ?? [])).pretty()), ), this._finally ? this.$node(new BlockTsDsl(...this._finally).pretty()) : undefined, ); } $validate(): asserts this is this & { _try: Array; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Try statement missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._try || this._try.length === 0) missing.push('.try()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/stmt/var.ts ================================================ import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; import { isSymbol } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl, TypeTsDsl } from '../base'; import { DocMixin } from '../mixins/doc'; import { HintMixin } from '../mixins/hint'; import { DefaultMixin, ExportMixin } from '../mixins/modifiers'; import { PatternMixin } from '../mixins/pattern'; import { ValueMixin } from '../mixins/value'; import { TypeExprTsDsl } from '../type/expr'; import { safeRuntimeName } from '../utils/name'; const Mixed = DefaultMixin( DocMixin(ExportMixin(HintMixin(PatternMixin(ValueMixin(TsDsl))))), ); export class VarTsDsl extends Mixed { readonly '~dsl' = 'VarTsDsl'; override readonly nameSanitizer = safeRuntimeName; protected kind: ts.NodeFlags = ts.NodeFlags.None; protected _type?: TypeTsDsl; constructor(name?: NodeName) { super(); if (name) this.name.set(name); if (isSymbol(name)) { name.setKind('var'); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.analyze(this._type); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } const(): this { this.kind = ts.NodeFlags.Const; return this; } let(): this { this.kind = ts.NodeFlags.Let; return this; } /** Sets the variable type. */ type(type: string | TypeTsDsl): this { this._type = type instanceof TypeTsDsl ? type : new TypeExprTsDsl(type); return this; } var(): this { this.kind = ts.NodeFlags.None; return this; } override toAst() { this.$validate(); const node = ts.factory.createVariableStatement( this.modifiers, ts.factory.createVariableDeclarationList( [ ts.factory.createVariableDeclaration( this.$pattern() ?? (this.$node(this.name) as ts.BindingName), undefined, this.$type(this._type), this.$value(), ), ], this.kind, ), ); return this.$docs(this.$hint(node)); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Variable declaration missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.$pattern() && !this.name.toString()) missing.push('name or pattern (.array()/.object())'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/token.ts ================================================ import ts from 'typescript'; import { TsDsl } from './base'; export class TokenTsDsl extends TsDsl> { readonly '~dsl' = 'TokenTsDsl'; protected _kind?: K; /** Sets the token kind */ kind(kind: K): this { this._kind = kind; return this; } /** Creates `-` */ minus(): TokenTsDsl { return (this as TokenTsDsl).kind(ts.SyntaxKind.MinusToken); } /** Creates `?` (optional) */ optional(): TokenTsDsl { return (this as TokenTsDsl).kind(ts.SyntaxKind.QuestionToken); } /** Creates `+` */ plus(): TokenTsDsl { return (this as TokenTsDsl).kind(ts.SyntaxKind.PlusToken); } /** Creates `?.` (optional chaining token) */ questionDot(): TokenTsDsl { return (this as TokenTsDsl).kind( ts.SyntaxKind.QuestionDotToken, ); } /** Creates `readonly` */ readonly(): TokenTsDsl { return (this as TokenTsDsl).kind(ts.SyntaxKind.ReadonlyKeyword); } /** Creates `...` (spread / rest) */ spread(): TokenTsDsl { return (this as TokenTsDsl).kind(ts.SyntaxKind.DotDotDotToken); } override toAst(): ts.Token { this.$validate(); // @ts-expect-error return ts.factory.createToken(this._kind); } $validate(): asserts this is this & { _kind: K; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Token missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._kind) missing.push('.kind()'); return missing; } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/alias.ts ================================================ import type { AnalysisContext, NodeName, NodeScope } from '@hey-api/codegen-core'; import { isSymbol } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { DocMixin } from '../mixins/doc'; import { ExportMixin } from '../mixins/modifiers'; import { TypeParamsMixin } from '../mixins/type-params'; import { safeTypeName } from '../utils/name'; type Value = MaybeTsDsl; const Mixed = DocMixin(ExportMixin(TypeParamsMixin(TsDsl))); export class TypeAliasTsDsl extends Mixed { readonly '~dsl' = 'TypeAliasTsDsl'; override readonly nameSanitizer = safeTypeName; override scope: NodeScope = 'type'; protected value?: Value; constructor(name: NodeName, fn?: (t: TypeAliasTsDsl) => void) { super(); this.name.set(name); if (isSymbol(name)) { name.setKind('type'); } fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.analyze(this.value); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the type expression on the right-hand side of `= ...`. */ type(node: Value): this { this.value = node; return this; } override toAst() { this.$validate(); const node = ts.factory.createTypeAliasDeclaration( this.modifiers, this.$node(this.name) as ts.Identifier, this.$generics(), this.$type(this.value), ); return this.$docs(node); } $validate(): asserts this is this & { value: Value; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; const name = this.name.toString(); throw new Error(`Type alias${name ? ` "${name}"` : ''} missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.value) missing.push('.type()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/and.ts ================================================ import type { AnalysisContext, NodeName, NodeScope, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { TypeTsDsl } from '../base'; import { TsDsl } from '../base'; type Type = NodeName | ts.TypeNode | TypeTsDsl; const Mixed = TsDsl; export class TypeAndTsDsl extends Mixed { readonly '~dsl' = 'TypeAndTsDsl'; override scope: NodeScope = 'type'; protected _types: Array> = []; constructor(...nodes: Array) { super(); this.types(...nodes); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const type of this._types) { ctx.analyze(type); } } types(...nodes: Array): this { this._types.push(...nodes.map((n) => ref(n))); return this; } override toAst() { const flat: Array = []; for (const node of this._types) { const type = this.$type(node); if (ts.isIntersectionTypeNode(type)) { flat.push(...type.types); } else { flat.push(type); } } return ts.factory.createIntersectionTypeNode(flat); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/attr.ts ================================================ import type { AnalysisContext, NodeName, NodeScope, Ref } from '@hey-api/codegen-core'; import { isRef, ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { TypeExprMixin } from '../mixins/type-expr'; type Base = NodeName | MaybeTsDsl; type Right = NodeName | ts.Identifier; const Mixed = TypeExprMixin(TsDsl); export class TypeAttrTsDsl extends Mixed { readonly '~dsl' = 'TypeAttrTsDsl'; override scope: NodeScope = 'type'; protected _base?: Ref; protected _right!: Ref; constructor(base: Base | Ref, right: string | ts.Identifier); constructor(right: Right); constructor(base: Base | Ref, right?: Right) { super(); if (right) { this.base(base); this.right(right); } else { this.base(); this.right(base as Right); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._base); ctx.analyze(this._right); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } base(base?: Base | Ref): this { if (isRef(base)) { this._base = base; } else { this._base = base ? ref(base) : undefined; } return this; } right(right: Right): this { this._right = ref(right); return this; } override toAst() { this.$validate(); const left = this.$node(this._base); if (!ts.isEntityName(left)) { throw new Error('TypeAttrTsDsl: base must be an EntityName'); } return ts.factory.createQualifiedName(left, this.$node(this._right) as ts.Identifier); } $validate(): asserts this is this & { _base: Ref; _right: Ref; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Type attribute missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._base) missing.push('.base()'); if (!this._right) missing.push('.right()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/expr.ts ================================================ import type { AnalysisContext, NodeName, NodeScope, Ref } from '@hey-api/codegen-core'; import { isNode, ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { TypeArgsMixin } from '../mixins/type-args'; import { TypeExprMixin } from '../mixins/type-expr'; import { f } from '../utils/factories'; import { TypeAttrTsDsl } from './attr'; export type TypeExprExpr = NodeName | TypeAttrTsDsl; export type TypeExprFn = (t: TypeExprTsDsl) => void; export type TypeExprCtor = (nameOrFn?: NodeName | TypeExprFn, fn?: TypeExprFn) => TypeExprTsDsl; const Mixed = TypeArgsMixin(TypeExprMixin(TsDsl)); export class TypeExprTsDsl extends Mixed { readonly '~dsl' = 'TypeExprTsDsl'; override scope: NodeScope = 'type'; protected _exprInput?: Ref; constructor(); constructor(fn: TypeExprFn); constructor(name: NodeName); constructor(name: NodeName, fn?: TypeExprFn); constructor(name?: NodeName | TypeExprFn, fn?: TypeExprFn) { super(); if (typeof name === 'function') { name(this); } else { this._exprInput = name ? ref(name) : undefined; fn?.(this); } } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._exprInput); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Accesses a nested type (e.g. `Foo.Bar`). */ attr(right: string | ts.Identifier | TypeAttrTsDsl): this { this._exprInput = isNode(right) ? ref(right.base(this._exprInput)) : ref(new TypeAttrTsDsl(this._exprInput!, right)); return this; } override toAst() { this.$validate(); return ts.factory.createTypeReferenceNode( this.$type(this._exprInput) as ts.EntityName, this.$generics(), ); } $validate(): asserts this is this & { _exprInput: Ref; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Type expression missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._exprInput) missing.push('name or .attr()'); return missing; } } f.type.expr.set( (...args) => new TypeExprTsDsl(...(args as ConstructorParameters)), ); ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/fromValue.ts ================================================ import { isNode } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { TsDsl } from '../base'; import { TypeLiteralTsDsl } from './literal'; import { TypeObjectTsDsl } from './object'; import { TypeTupleTsDsl } from './tuple'; export const fromValue = (input: unknown): TsDsl => { if (isNode(input)) { return input as TsDsl; } if (input === null) { return new TypeLiteralTsDsl(input); } if ( typeof input === 'number' || typeof input === 'boolean' || typeof input === 'string' || typeof input === 'bigint' ) { return new TypeLiteralTsDsl(input); } if (input instanceof Array) { const arr = new TypeTupleTsDsl(...input.map((v) => fromValue(v))); return arr; } if (typeof input === 'object') { const obj = new TypeObjectTsDsl(); for (const [key, val] of Object.entries(input)) { const type = fromValue(val); obj.prop(key, (p) => p.type(type)); } return obj; } throw new Error(`$.type.fromValue(): Unsupported input type ${String(input)}`); }; ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/func.ts ================================================ import type { AnalysisContext, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { DocMixin } from '../mixins/doc'; import { ParamMixin } from '../mixins/param'; import { TypeParamsMixin } from '../mixins/type-params'; import { TypeReturnsMixin } from '../mixins/type-returns'; const Mixed = DocMixin(ParamMixin(TypeParamsMixin(TypeReturnsMixin(TsDsl)))); export class TypeFuncTsDsl extends Mixed { readonly '~dsl' = 'TypeFuncTsDsl'; override scope: NodeScope = 'type'; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } override toAst() { this.$validate(); const node = ts.factory.createFunctionTypeNode( this.$generics(), this.$params(), this.$returns()!, ); return this.$docs(node); } $validate(): asserts this { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Function type missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (this.$returns() === undefined) missing.push('.returns()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/idx-sig.ts ================================================ import type { AnalysisContext, NodeName, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { DocMixin } from '../mixins/doc'; import { ReadonlyMixin } from '../mixins/modifiers'; export type TypeIdxSigType = string | MaybeTsDsl; export type TypeIdxSigKind = 'idxSig'; const Mixed = DocMixin(ReadonlyMixin(TsDsl)); export class TypeIdxSigTsDsl extends Mixed { readonly '~dsl' = 'TypeIdxSigTsDsl'; override scope: NodeScope = 'type'; protected _key?: TypeIdxSigType; protected _type?: TypeIdxSigType; constructor(name: NodeName, fn?: (i: TypeIdxSigTsDsl) => void) { super(); this.name.set(name); fn?.(this); } /** Element kind. */ get kind(): TypeIdxSigKind { return 'idxSig'; } /** Index signature parameter name. */ get propName(): string { return this.name.toString(); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._key); ctx.analyze(this._type); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the key type: `[name: T]` */ key(type: TypeIdxSigType): this { this._key = type; return this; } /** Sets the property type. */ type(type: TypeIdxSigType): this { this._type = type; return this; } override toAst() { this.$validate(); const node = ts.factory.createIndexSignature( this.modifiers, [ ts.factory.createParameterDeclaration( undefined, undefined, this.$node(this.name) as ts.BindingName, undefined, this.$type(this._key), ), ], this.$type(this._type), ); return this.$docs(node); } $validate(): asserts this is this & { _key: TypeIdxSigType; _type: TypeIdxSigType; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; const name = this.name.toString(); throw new Error(`Index signature${name ? ` "${name}"` : ''} missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._key) missing.push('.key()'); if (!this._type) missing.push('.\u200Btype()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/idx.ts ================================================ import type { AnalysisContext, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { TypeExprMixin } from '../mixins/type-expr'; import { f } from '../utils/factories'; type Base = string | MaybeTsDsl; type Index = string | number | MaybeTsDsl; export type TypeIdxCtor = (base: Base, index: Index) => TypeIdxTsDsl; const Mixed = TypeExprMixin(TsDsl); export class TypeIdxTsDsl extends Mixed { readonly '~dsl' = 'TypeIdxTsDsl'; override scope: NodeScope = 'type'; protected _base!: Base; protected _index!: Index; constructor(base: Base, index: Index) { super(); this.base(base); this.index(index); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._base); ctx.analyze(this._index); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } base(base: Base): this { this._base = base; return this; } index(index: Index): this { this._index = index; return this; } override toAst() { this.$validate(); return ts.factory.createIndexedAccessTypeNode(this.$type(this._base), this.$type(this._index)); } $validate(): asserts this is this & { _base: Base; _index: Index; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Indexed access type missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (this._base === undefined) missing.push('.base()'); if (this._index === undefined) missing.push('.index()'); return missing; } } f.type.idx.set((...args) => new TypeIdxTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/literal.ts ================================================ import type { AnalysisContext, NodeScope } from '@hey-api/codegen-core'; import tsOld from 'typescript'; import type { ts } from '../../ts-compiler'; import { TsDsl } from '../base'; import { LiteralTsDsl } from '../expr/literal'; const Mixed = TsDsl; export class TypeLiteralTsDsl extends Mixed { readonly '~dsl' = 'TypeLiteralTsDsl'; override scope: NodeScope = 'type'; protected value: ts.LiteralValue; constructor(value: ts.LiteralValue) { super(); this.value = value; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); } override toAst() { return tsOld.factory.createLiteralTypeNode(this.$node(new LiteralTsDsl(this.value))); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/mapped.ts ================================================ import type { AnalysisContext, NodeName, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { TokenTsDsl } from '../token'; const Mixed = TsDsl; export class TypeMappedTsDsl extends Mixed { readonly '~dsl' = 'TypeMappedTsDsl'; override scope: NodeScope = 'type'; protected questionToken?: TokenTsDsl< ts.SyntaxKind.QuestionToken | ts.SyntaxKind.PlusToken | ts.SyntaxKind.MinusToken >; protected readonlyToken?: TokenTsDsl< ts.SyntaxKind.ReadonlyKeyword | ts.SyntaxKind.MinusToken | ts.SyntaxKind.PlusToken >; protected _key?: string | MaybeTsDsl; protected _type?: string | MaybeTsDsl; constructor(name?: NodeName) { super(); if (name) this.name.set(name); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.questionToken); ctx.analyze(this.readonlyToken); ctx.analyze(this._key); ctx.analyze(this._type); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the key constraint: `[K in Constraint]` */ key(type: string | MaybeTsDsl): this { this._key = type; return this; } /** Removes `readonly` from the mapped members (`[K in X]-readonly`). */ mutable(): this { this.readonlyToken = new TokenTsDsl().minus(); return this; } /** Makes `[K in X]?:` optional. */ optional(): this { this.questionToken = new TokenTsDsl().optional(); return this; } /** Makes `[K in X]` readonly */ readonly(): this { this.readonlyToken = new TokenTsDsl().readonly(); return this; } /** Removes `?` from the mapped members (`[K in X]-?:`). */ required(): this { this.questionToken = new TokenTsDsl().minus(); return this; } /** Sets the mapped value type: `[K in X]: ValueType` */ type(type: string | MaybeTsDsl): this { this._type = type; return this; } override toAst() { this.$validate(); return ts.factory.createMappedTypeNode( this.$node(this.readonlyToken), ts.factory.createTypeParameterDeclaration( undefined, this.$node(this.name) as ts.Identifier, this.$type(this._key), undefined, ), undefined, this.$node(this.questionToken), this.$type(this._type), undefined, ); } $validate(): asserts this is this & { _key: string | MaybeTsDsl; _type: string | MaybeTsDsl; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; const name = this.name.toString(); throw new Error(`Mapped type${name ? ` "${name}"` : ''} missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._key) missing.push('.key()'); if (!this._type) missing.push('.\u200Btype()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/object.ts ================================================ import type { AnalysisContext, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import { TsDsl } from '../base'; import { TypeIdxSigTsDsl } from './idx-sig'; import { TypePropTsDsl } from './prop'; const Mixed = TsDsl; export class TypeObjectTsDsl extends Mixed { readonly '~dsl' = 'TypeObjectTsDsl'; override scope: NodeScope = 'type'; protected _props = new Map(); override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const prop of this._props.values()) { ctx.analyze(prop); } } /** Returns true if object has at least one property or index signature. */ hasProps(): boolean { return this._props.size > 0; } /** Adds an index signature to the object type, or removes if fn is null. */ idxSig(name: string, fn: ((i: TypeIdxSigTsDsl) => void) | null): this { const key = `idxSig:${name}`; if (fn === null) { this._props.delete(key); } else { this._props.set(key, new TypeIdxSigTsDsl(name, fn)); } return this; } /** Returns true if object has no properties or index signatures. */ get isEmpty(): boolean { return this._props.size === 0; } /** Adds a property signature, or removes if fn is null. */ prop(name: string, fn: ((p: TypePropTsDsl) => void) | null): this { const key = `prop:${name}`; if (fn === null) { this._props.delete(key); } else { this._props.set(key, new TypePropTsDsl(name, fn)); } return this; } /** Adds multiple properties/index signatures. */ props(...members: ReadonlyArray): this { for (const member of members) { this._props.set(`${member.kind}:${member.propName}`, member); } return this; } override toAst() { return ts.factory.createTypeLiteralNode(this.$node([...this._props.values()])); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/operator.ts ================================================ import type { AnalysisContext, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { f } from '../utils/factories'; type Op = ts.SyntaxKind.KeyOfKeyword | ts.SyntaxKind.ReadonlyKeyword | ts.SyntaxKind.UniqueKeyword; type Type = string | MaybeTsDsl; export type TypeOperatorCtor = () => TypeOperatorTsDsl; const Mixed = TsDsl; /** * Builds a TypeScript `TypeOperatorNode`, such as: * * - `keyof T` * - `readonly U` * - `unique V` * * This DSL provides both a generic `.operator()` API and convenient * shorthand methods (`.keyof()`, `.readonly()`, `.unique()`). * * The node will throw during render if required fields are missing. */ export class TypeOperatorTsDsl extends Mixed { readonly '~dsl' = 'TypeOperatorTsDsl'; override scope: NodeScope = 'type'; protected _op?: Op; protected _type?: Type; override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._type); } /** Shorthand: builds `keyof T`. */ keyof(type: Type): this { this.operator(ts.SyntaxKind.KeyOfKeyword); this.type(type); return this; } /** Sets the operator explicitly. */ operator(op: Op): this { this._op = op; return this; } /** Shorthand: builds `readonly T`. */ readonly(type: Type): this { this.operator(ts.SyntaxKind.ReadonlyKeyword); this.type(type); return this; } /** Sets the target type of the operator. */ type(type: Type): this { this._type = type; return this; } /** Shorthand: builds `unique T`. */ unique(type: Type): this { this.operator(ts.SyntaxKind.UniqueKeyword); this.type(type); return this; } override toAst() { this.$validate(); return ts.factory.createTypeOperatorNode(this._op, this.$type(this._type)); } /** Throws if required fields are not set. */ $validate(): asserts this is this & { _op: Op; _type: Type; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; throw new Error(`Type operator missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._op) missing.push('.operator()'); if (!this._type) missing.push('.\u200Btype()'); return missing; } } f.type.operator.set((...args) => new TypeOperatorTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/or.ts ================================================ import type { AnalysisContext, NodeName, NodeScope, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { TypeTsDsl } from '../base'; import { TsDsl } from '../base'; type Type = NodeName | ts.TypeNode | TypeTsDsl; const Mixed = TsDsl; export class TypeOrTsDsl extends Mixed { readonly '~dsl' = 'TypeOrTsDsl'; override scope: NodeScope = 'type'; protected _types: Array> = []; constructor(...nodes: Array) { super(); this.types(...nodes); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const type of this._types) { ctx.analyze(type); } } types(...nodes: Array): this { this._types.push(...nodes.map((n) => ref(n))); return this; } override toAst() { const flat: Array = []; for (const node of this._types) { const type = this.$type(node); if (ts.isUnionTypeNode(type)) { flat.push(...type.types); } else { flat.push(type); } } return ts.factory.createUnionTypeNode(flat); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/param.ts ================================================ import type { AnalysisContext, NodeName, NodeScope, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl, TypeTsDsl } from '../base'; import { TsDsl } from '../base'; export type TypeParamExpr = NodeName | boolean | MaybeTsDsl; const Mixed = TsDsl; export class TypeParamTsDsl extends Mixed { readonly '~dsl' = 'TypeParamTsDsl'; override scope: NodeScope = 'type'; protected constraint?: Ref; protected defaultValue?: Ref; constructor(name?: NodeName, fn?: (name: TypeParamTsDsl) => void) { super(); if (name) this.name.set(name); fn?.(this); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); ctx.analyze(this.constraint); ctx.analyze(this.defaultValue); } /** Sets the parameter default value. */ default(value: TypeParamExpr): this { this.defaultValue = ref(value); return this; } extends(constraint: TypeParamExpr): this { this.constraint = ref(constraint); return this; } override toAst() { const name = this.name.toString(); if (!name) throw new Error('Missing type name'); return ts.factory.createTypeParameterDeclaration( undefined, this.$node(this.name) as ts.Identifier, this.$type(this.constraint), this.$type(this.defaultValue), ); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/prop.ts ================================================ import type { AnalysisContext, NodeName, NodeScope, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; import { DocMixin } from '../mixins/doc'; import { ReadonlyMixin } from '../mixins/modifiers'; import { OptionalMixin } from '../mixins/optional'; import { TokenTsDsl } from '../token'; import { safePropName } from '../utils/name'; export type TypePropType = NodeName | MaybeTsDsl; export type TypePropKind = 'prop'; const Mixed = DocMixin(OptionalMixin(ReadonlyMixin(TsDsl))); export class TypePropTsDsl extends Mixed { readonly '~dsl' = 'TypePropTsDsl'; override scope: NodeScope = 'type'; protected _type?: Ref; constructor(name: NodeName, fn: (p: TypePropTsDsl) => void) { super(); this.name.set(name); fn(this); } /** Element kind. */ get kind(): TypePropKind { return 'prop'; } /** Property name. */ get propName(): string { return this.name.toString(); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._type); } /** Returns true when all required builder calls are present. */ get isValid(): boolean { return this.missingRequiredCalls().length === 0; } /** Sets the property type. */ type(type: TypePropType): this { this._type = ref(type); return this; } override toAst() { this.$validate(); const name = this.name.toString(); const node = ts.factory.createPropertySignature( this.modifiers, this.$node(safePropName(name)), this._optional ? this.$node(new TokenTsDsl().optional()) : undefined, this.$type(this._type), ); return this.$docs(node); } $validate(): asserts this is this & { _type: Ref; } { const missing = this.missingRequiredCalls(); if (missing.length === 0) return; const name = this.name.toString(); throw new Error(`Type property${name ? ` "${name}"` : ''} missing ${missing.join(' and ')}`); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this._type) missing.push('.type()'); return missing; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/query.ts ================================================ import type { AnalysisContext, NodeName, NodeScope, Ref } from '@hey-api/codegen-core'; import { ref } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl, TypeTsDsl } from '../base'; import { TsDsl } from '../base'; import { TypeExprMixin } from '../mixins/type-expr'; import { f } from '../utils/factories'; export type TypeQueryExpr = NodeName | MaybeTsDsl; export type TypeQueryCtor = (expr: TypeQueryExpr) => TypeQueryTsDsl; const Mixed = TypeExprMixin(TsDsl); export class TypeQueryTsDsl extends Mixed { readonly '~dsl' = 'TypeQueryTsDsl'; override scope: NodeScope = 'type'; protected _expr: Ref; constructor(expr: TypeQueryExpr) { super(); this._expr = ref(expr); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this._expr); } override toAst() { const expr = this.$node(this._expr); return ts.factory.createTypeQueryNode(expr as unknown as ts.EntityName); } } f.type.query.set((...args) => new TypeQueryTsDsl(...args)); ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/template.ts ================================================ import type { AnalysisContext, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { MaybeTsDsl } from '../base'; import { TsDsl } from '../base'; const Mixed = TsDsl; export class TypeTemplateTsDsl extends Mixed { readonly '~dsl' = 'TypeTemplateTsDsl'; override scope: NodeScope = 'type'; protected parts: Array> = []; constructor(value?: string | MaybeTsDsl) { super(); if (value !== undefined) this.add(value); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const part of this.parts) { ctx.analyze(part); } } /** Adds a raw string segment or embedded type expression. */ add(part: string | MaybeTsDsl): this { this.parts.push(part); return this; } override toAst() { const parts = this.$node(this.parts); const normalized: Array = []; // merge consecutive string parts for (let index = 0; index < parts.length; index++) { const current = parts[index]!; if (typeof current === 'string') { let merged = current; while (index + 1 < parts.length && typeof parts[index + 1] === 'string') { merged += parts[index + 1]!; index++; } normalized.push(merged); } else { normalized.push(current); } } if (normalized.length === 0 || typeof normalized[0] !== 'string') { normalized.unshift(''); } if (normalized.length === 1 && typeof normalized[0] === 'string') { return ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(normalized[0]), []); } if ( normalized.length === 2 && typeof normalized[0] === 'string' && typeof normalized[1] !== 'string' ) { return ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(normalized[0]), [ ts.factory.createTemplateLiteralTypeSpan(normalized[1]!, ts.factory.createTemplateTail('')), ]); } const head = ts.factory.createTemplateHead(normalized.shift() as string); const spans: Array = []; while (normalized.length) { const type = normalized.shift() as ts.TypeNode; const next = typeof normalized[0] === 'string' ? (normalized.shift() as string) : ''; const isLast = normalized.length === 0; spans.push( ts.factory.createTemplateLiteralTypeSpan( type, isLast ? ts.factory.createTemplateTail(next) : ts.factory.createTemplateMiddle(next), ), ); } return ts.factory.createTemplateLiteralType(head, spans); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/type/tuple.ts ================================================ import type { AnalysisContext, NodeScope } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { TypeTsDsl } from '../base'; import { TsDsl } from '../base'; const Mixed = TsDsl; export class TypeTupleTsDsl extends Mixed { readonly '~dsl' = 'TypeTupleTsDsl'; override scope: NodeScope = 'type'; protected _elements: Array = []; constructor(...nodes: Array) { super(); this.elements(...nodes); } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); for (const type of this._elements) { ctx.analyze(type); } } elements(...types: Array): this { this._elements.push(...types); return this; } override toAst() { return ts.factory.createTupleTypeNode(this._elements.map((t) => this.$type(t))); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/__tests__/name.test.ts ================================================ import { safeRuntimeName } from '../name'; describe('safeRuntimeName', () => { const scenarios: ReadonlyArray<{ name: string; output: string; }> = [ // browser globals { name: 'document', output: 'document_', }, { name: 'fetch', output: 'fetch_', }, { name: 'history', output: 'history_', }, { name: 'location', output: 'location_', }, { name: 'navigator', output: 'navigator_', }, { name: 'window', output: 'window_', }, { name: 'AbortController', output: 'AbortController_', }, { name: 'AbortSignal', output: 'AbortSignal_', }, { name: 'Blob', output: 'Blob_', }, { name: 'CustomEvent', output: 'CustomEvent_', }, { name: 'Event', output: 'Event_', }, { name: 'EventTarget', output: 'EventTarget_', }, { name: 'File', output: 'File_', }, { name: 'FileList', output: 'FileList_', }, { name: 'FileReader', output: 'FileReader_', }, { name: 'FormData', output: 'FormData_', }, { name: 'Headers', output: 'Headers_', }, { name: 'Request', output: 'Request_', }, { name: 'Response', output: 'Response_', }, { name: 'TextDecoder', output: 'TextDecoder_', }, { name: 'TextEncoder', output: 'TextEncoder_', }, { name: 'URL', output: 'URL_', }, { name: 'URLSearchParams', output: 'URLSearchParams_', }, // JavaScript globals { name: 'Array', output: 'Array_', }, { name: 'ArrayBuffer', output: 'ArrayBuffer_', }, { name: 'atob', output: 'atob_', }, { name: 'BigInt', output: 'BigInt_', }, { name: 'Boolean', output: 'Boolean_', }, { name: 'btoa', output: 'btoa_', }, { name: 'clearInterval', output: 'clearInterval_', }, { name: 'clearTimeout', output: 'clearTimeout_', }, { name: 'console', output: 'console_', }, { name: 'crypto', output: 'crypto_', }, { name: 'DataView', output: 'DataView_', }, { name: 'Date', output: 'Date_', }, { name: 'Error', output: 'Error_', }, { name: 'Function', output: 'Function_', }, { name: 'globalThis', output: 'globalThis_', }, { name: 'Infinity', output: 'Infinity_', }, { name: 'Intl', output: 'Intl_', }, { name: 'JSON', output: 'JSON_', }, { name: 'Map', output: 'Map_', }, { name: 'Math', output: 'Math_', }, { name: 'NaN', output: 'NaN_', }, { name: 'Number', output: 'Number_', }, { name: 'Object', output: 'Object_', }, { name: 'performance', output: 'performance_', }, { name: 'Promise', output: 'Promise_', }, { name: 'Proxy', output: 'Proxy_', }, { name: 'queueMicrotask', output: 'queueMicrotask_', }, { name: 'Reflect', output: 'Reflect_', }, { name: 'RegExp', output: 'RegExp_', }, { name: 'Set', output: 'Set_', }, { name: 'setInterval', output: 'setInterval_', }, { name: 'setTimeout', output: 'setTimeout_', }, { name: 'String', output: 'String_', }, { name: 'structuredClone', output: 'structuredClone_', }, { name: 'Symbol', output: 'Symbol_', }, { name: 'WeakMap', output: 'WeakMap_', }, { name: 'WeakSet', output: 'WeakSet_', }, // JavaScript keywords { name: 'arguments', output: 'arguments_', }, { name: 'async', output: 'async_', }, { name: 'await', output: 'await_', }, { name: 'break', output: 'break_', }, { name: 'case', output: 'case_', }, { name: 'catch', output: 'catch_', }, { name: 'class', output: 'class_', }, { name: 'const', output: 'const_', }, { name: 'continue', output: 'continue_', }, { name: 'debugger', output: 'debugger_', }, { name: 'default', output: 'default_', }, { name: 'delete', output: 'delete_', }, { name: 'do', output: 'do_', }, { name: 'else', output: 'else_', }, { name: 'enum', output: 'enum_', }, { name: 'eval', output: 'eval_', }, { name: 'export', output: 'export_', }, { name: 'extends', output: 'extends_', }, { name: 'false', output: 'false_', }, { name: 'finally', output: 'finally_', }, { name: 'for', output: 'for_', }, { name: 'from', output: 'from_', }, { name: 'function', output: 'function_', }, { name: 'if', output: 'if_', }, { name: 'implements', output: 'implements_', }, { name: 'import', output: 'import_', }, { name: 'in', output: 'in_', }, { name: 'instanceof', output: 'instanceof_', }, { name: 'interface', output: 'interface_', }, { name: 'let', output: 'let_', }, { name: 'new', output: 'new_', }, { name: 'null', output: 'null_', }, { name: 'package', output: 'package_', }, { name: 'private', output: 'private_', }, { name: 'protected', output: 'protected_', }, { name: 'public', output: 'public_', }, { name: 'return', output: 'return_', }, { name: 'static', output: 'static_', }, { name: 'super', output: 'super_', }, { name: 'switch', output: 'switch_', }, { name: 'this', output: 'this_', }, { name: 'throw', output: 'throw_', }, { name: 'true', output: 'true_', }, { name: 'try', output: 'try_', }, { name: 'typeof', output: 'typeof_', }, { name: 'var', output: 'var_', }, { name: 'void', output: 'void_', }, { name: 'while', output: 'while_', }, { name: 'with', output: 'with_', }, { name: 'yield', output: 'yield_', }, // Node.js globals { name: '__dirname', output: '__dirname_', }, { name: '__filename', output: '__filename_', }, { name: 'exports', output: 'exports_', }, { name: 'global', output: 'global_', }, { name: 'module', output: 'module_', }, { name: 'process', output: 'process_', }, { name: 'require', output: 'require_', }, { name: 'Buffer', output: 'Buffer_', }, // TypeScript keywords { name: 'any', output: 'any_', }, { name: 'as', output: 'as_', }, { name: 'bigint', output: 'bigint_', }, { name: 'boolean', output: 'boolean_', }, { name: 'namespace', output: 'namespace_', }, { name: 'never', output: 'never_', }, { name: 'null', output: 'null_', }, { name: 'number', output: 'number_', }, { name: 'string', output: 'string_', }, { name: 'symbol', output: 'symbol_', }, { name: 'type', output: 'type_', }, { name: 'undefined', output: 'undefined_', }, { name: 'unknown', output: 'unknown_', }, { name: 'void', output: 'void_', }, ]; it.each(scenarios)('transforms $name -> $output', async ({ name, output }) => { expect(safeRuntimeName(name)).toEqual(output); }); }); ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/__tests__/render.test.ts ================================================ import type { RenderContext } from '@hey-api/codegen-core'; import { Project } from '@hey-api/codegen-core'; import ts from 'typescript'; import type { TsDsl } from '../../../ts-dsl'; import { TypeScriptRenderer } from '../render'; import type { ModuleExport, ModuleImport } from '../render-utils'; describe('TypeScriptRenderer', () => { const renderer = new TypeScriptRenderer(); const mockFile = (overrides: any = {}) => ({ exports: [], imports: [], language: 'typescript', nodes: [], ...overrides, }); const mockCtx = (fileOverrides = {}, projectOverrides = {}): RenderContext => ({ file: mockFile(fileOverrides), project: new Project({ root: '/root', ...projectOverrides, }), }); it('supports() returns true only for typescript files', () => { expect(renderer.supports(mockCtx({ language: 'typescript' }))).toBe(true); expect(renderer.supports(mockCtx({ language: 'javascript' }))).toBe(false); }); it('renderImport() generates named and namespace imports correctly', () => { const group: ModuleImport = { imports: [ { isTypeOnly: false, localName: 'A', sourceName: 'A', }, ], isTypeOnly: false, kind: 'named', localName: undefined, modulePath: 'foo', }; const node = TypeScriptRenderer.toImportAst(group); expect(ts.isImportDeclaration(node)).toBe(true); }); it('renderExport() generates named and namespace exports correctly', () => { const group: ModuleExport = { canExportAll: false, exports: [ { exportedName: 'B', isTypeOnly: false, kind: 'named', sourceName: 'B', }, ], isTypeOnly: false, modulePath: 'bar', namespaceExport: undefined, }; const node = TypeScriptRenderer.toExportAst(group); expect(ts.isExportDeclaration(node)).toBe(true); }); }); ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/context.ts ================================================ import type { BindingKind, NodeScope, Symbol } from '@hey-api/codegen-core'; import { isSymbol } from '@hey-api/codegen-core'; import type { MaybeFunc } from '@hey-api/types'; import type ts from 'typescript'; import type { DollarTsDsl } from '../../ts-dsl'; import { $, TypeScriptRenderer } from '../../ts-dsl'; import type { TsDsl } from '../base'; import type { CallArgs } from '../expr/call'; export type NodeChain = ReadonlyArray; export interface AccessOptions { /** The access context. */ context?: 'example'; /** Enable debug mode. */ debug?: boolean; /** Transform function for each node in the access chain. */ transform?: (node: TsDsl, index: number, chain: NodeChain) => TsDsl; } export type AccessResult = ReturnType; export interface ExampleOptions { /** Import kind for the root node. */ importKind?: BindingKind; /** Import name for the root node. */ importName?: string; /** Setup to run before calling the example. */ importSetup?: MaybeFunc< ( ctx: DollarTsDsl & { /** The imported expression. */ node: TsDsl; }, ) => TsDsl >; /** Module to import from. */ moduleName?: string; /** Example request payload. */ payload?: MaybeFunc<(ctx: DollarTsDsl) => CallArgs | CallArgs[number]>; /** Variable name for setup node. */ setupName?: string; } function accessChainToNode(accessChain: NodeChain): T { let result!: AccessResult; accessChain.forEach((node, index) => { if (index === 0) { // assume correct node result = node as typeof result; } else { result = result.attr(node.name); } }); return result as T; } function getAccessChainForNode(node: TsDsl): NodeChain { const structuralChain = [...getStructuralChainForNode(node, new Set())]; const accessChain = structuralToAccessChain(structuralChain); if (accessChain.length === 0) { // I _think_ this should not happen, but it does and this fix works for now. // I assume this will cause issues with imports in some cases, investigate // when it actually happens. return [node.clone()]; } return accessChain.map((node) => node.clone()); } function getScope(node: TsDsl): NodeScope { return node.scope ?? 'value'; } function getStructuralChainForNode(node: TsDsl, visited: Set): NodeChain { if (visited.has(node)) return []; visited.add(node); if (isStopNode(node)) return []; if (node.structuralParents) { for (const [parent] of node.structuralParents) { if (getScope(parent) !== getScope(node)) continue; const chain = getStructuralChainForNode(parent, visited); if (chain.length > 0) return [...chain, node]; } } if (!node.root) return []; return [node]; } function isAccessorNode(node: TsDsl): boolean { return ( node['~dsl'] === 'FieldTsDsl' || node['~dsl'] === 'GetterTsDsl' || node['~dsl'] === 'MethodTsDsl' ); } function isStopNode(node: TsDsl): boolean { return node['~dsl'] === 'FuncTsDsl' || node['~dsl'] === 'TemplateTsDsl'; } /** * Fold a structural chain to an access chain by removing * non-accessor nodes. */ function structuralToAccessChain(structuralChain: NodeChain): NodeChain { const accessChain: Array = []; structuralChain.forEach((node, index) => { // assume first node is always included if (index === 0) { accessChain.push(node); } else if (isAccessorNode(node)) { accessChain.push(node); } }); return accessChain; } function transformAccessChain(accessChain: NodeChain, options: AccessOptions = {}): NodeChain { return accessChain.map((node, index) => { const transformedNode = options.transform?.(node, index, accessChain); if (transformedNode) return transformedNode; const accessNode = node.toAccessNode?.(node, options, { chain: accessChain, index, isLeaf: index === accessChain.length - 1, isRoot: index === 0, length: accessChain.length, }); if (accessNode) return accessNode; if (index === 0) { if (node['~dsl'] === 'ClassTsDsl') { const nextNode = accessChain[index + 1]; if (nextNode && isAccessorNode(nextNode)) { if ((nextNode as ReturnType).hasModifier('static')) { return $(node.name); } } return $.new(node.name).args(); } return $(node.name); } return node; }); } export class TsDslContext { /** * Build an expression for accessing the node. * * @param node - The node or symbol to build access for * @param options - Access options * @returns Expression for accessing the node * * @example * ```ts * ctx.access(node); // → Expression for accessing the node * ``` */ access(node: TsDsl | Symbol, options?: AccessOptions): T { const n = isSymbol(node) ? node.node : node; if (!n) { throw new Error(`Symbol ${node.name} is not resolved to a node.`); } const accessChain = getAccessChainForNode(n); const finalChain = transformAccessChain(accessChain, options); return accessChainToNode(finalChain); } /** * Build an example. * * @param node - The node to generate an example for * @param options - Example options * @returns Full example string * * @example * ```ts * ctx.example(node, { moduleName: 'my-sdk' }); // → Full example string * ``` */ example( node: TsDsl, options?: ExampleOptions, astOptions?: Parameters[0], ): string { if (astOptions) { return TypeScriptRenderer.astToString(astOptions); } options ||= {}; const accessChain = getAccessChainForNode(node); if (options.importName) { accessChain[0]!.name.set(options.importName); } const importNode = $(accessChain[0]!.name.toString()); // must store name before transform const finalChain = transformAccessChain(accessChain, { context: 'example', }); const setupNode = options.importSetup ? typeof options.importSetup === 'function' ? options.importSetup({ $, node: importNode }) : options.importSetup : (finalChain[0]! as TsDsl); const setupName = options.setupName; let payload = typeof options.payload === 'function' ? options.payload({ $ }) : options.payload; payload = payload instanceof Array ? payload : payload ? [payload] : []; let nodes: Array = []; if (setupName) { nodes = [ $.const(setupName).assign(setupNode), $.await(accessChainToNode([$(setupName), ...finalChain.slice(1)]).call(...payload)), ]; } else { nodes = [$.await(accessChainToNode([setupNode, ...finalChain.slice(1)]).call(...payload))]; } const localName = importNode.name.toString(); return TypeScriptRenderer.astToString({ imports: [ [ { imports: !options.importKind || options.importKind === 'named' ? [ { isTypeOnly: false, localName, sourceName: localName, }, ] : [], isTypeOnly: false, kind: options.importKind ?? 'named', localName: options.importKind !== 'named' ? localName : undefined, modulePath: options.moduleName ?? 'your-package', }, ], ], nodes, trailingNewline: false, }); } } export const ctx = new TsDslContext(); ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/factories.ts ================================================ import type { AsCtor } from '../expr/as'; import type { AttrCtor } from '../expr/attr'; import type { AwaitCtor } from '../expr/await'; import type { CallCtor } from '../expr/call'; import type { NewCtor } from '../expr/new'; import type { TypeOfExprCtor } from '../expr/typeof'; import type { ReturnCtor } from '../stmt/return'; import type { TypeExprCtor } from '../type/expr'; import type { TypeIdxCtor } from '../type/idx'; import type { TypeOperatorCtor } from '../type/operator'; import type { TypeQueryCtor } from '../type/query'; type Ctor = (...args: Array) => any; type Factory = { (...args: Parameters): ReturnType; /** Sets the implementation of this factory. */ set(fn: T): void; }; function createFactory(name: string): Factory { let impl: T | undefined; const slot = ((...args: Parameters) => { if (!impl) throw new Error(`${name} factory not registered`); return impl(...args); }) as Factory; slot.set = (fn: T) => { impl = fn; }; return slot; } export const f = { /** Factory for creating `as` type assertion expressions (e.g. `value as Type`). */ as: createFactory('as'), /** Factory for creating property access expressions (e.g. `obj.foo`). */ attr: createFactory('attr'), /** Factory for creating await expressions (e.g. `await promise`). */ await: createFactory('await'), /** Factory for creating function or method call expressions (e.g. `fn(arg)`). */ call: createFactory('call'), /** Factory for creating new expressions (e.g. `new ClassName()`). */ new: createFactory('new'), /** Factory for creating return statements. */ return: createFactory('return'), /** Factories for creating type nodes. */ type: { /** Factory for creating basic type references or type expressions (e.g. Foo or Foo). */ expr: createFactory('type.expr'), /** Factory for creating indexed-access types (e.g. `Foo[K]`). */ idx: createFactory('type.idx'), /** Factory for creating type operator nodes (e.g. `readonly T`, `keyof T`, `unique T`). */ operator: createFactory('type.operator'), /** Factory for creating type query nodes (e.g. `typeof Foo`). */ query: createFactory('type.query'), }, /** Factory for creating `typeof` expressions (e.g. `typeof value`). */ typeofExpr: createFactory('typeofExpr'), }; ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/keywords.ts ================================================ const browserGlobals = [ 'AbortController', 'AbortSignal', 'Blob', 'CustomEvent', 'document', 'Event', 'EventTarget', 'fetch', 'File', 'FileList', 'FileReader', 'FormData', 'Headers', 'history', 'location', 'navigator', 'Request', 'Response', 'TextDecoder', 'TextEncoder', 'URL', 'URLSearchParams', 'window', ]; const javaScriptGlobals = [ 'Array', 'ArrayBuffer', 'atob', 'BigInt', 'Boolean', 'btoa', 'clearInterval', 'clearTimeout', 'console', 'crypto', 'DataView', 'Date', 'Error', 'Function', 'globalThis', 'Infinity', 'Intl', 'JSON', 'Map', 'Math', 'NaN', 'Number', 'Object', 'performance', 'Promise', 'Proxy', 'queueMicrotask', 'Reflect', 'RegExp', 'Set', 'setInterval', 'setTimeout', 'String', 'structuredClone', 'Symbol', 'WeakMap', 'WeakSet', ]; const javaScriptKeywords = [ 'arguments', 'async', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'from', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', ]; const nodeGlobals = [ '__dirname', '__filename', 'Buffer', 'exports', 'global', 'module', 'process', 'require', ]; const typeScriptKeywords = [ 'any', 'as', 'bigint', 'boolean', 'namespace', 'never', 'null', 'number', 'string', 'symbol', 'type', 'undefined', 'unknown', 'void', ]; export const keywords = { browserGlobals, javaScriptGlobals, javaScriptKeywords, nodeGlobals, typeScriptKeywords, }; ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/lazy.ts ================================================ import type { AnalysisContext } from '@hey-api/codegen-core'; import type ts from 'typescript'; import { TsDsl } from '../base'; import type { TsDslContext } from './context'; import { ctx } from './context'; export type LazyThunk = (ctx: TsDslContext) => TsDsl; export class LazyTsDsl extends TsDsl { readonly '~dsl' = 'LazyTsDsl'; private _thunk: LazyThunk; constructor(thunk: LazyThunk) { super(); this._thunk = thunk; } override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.toResult()); } toResult(): TsDsl { return this._thunk(ctx); } override toAst() { return this.toResult().toAst(); } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/name.ts ================================================ import type ts from 'typescript'; import type { TsDsl } from '../base'; import { IdTsDsl } from '../expr/id'; import { LiteralTsDsl } from '../expr/literal'; import { regexp } from './regexp'; import type { ReservedList } from './reserved'; import { reserved } from './reserved'; export const safeAccessorName = (name: string): string => { regexp.number.lastIndex = 0; if (regexp.number.test(name)) { return name.startsWith('-') ? `'${name}'` : name; } regexp.typeScriptIdentifier.lastIndex = 0; if (regexp.typeScriptIdentifier.test(name)) { return name; } return `'${name}'`; }; export const safeMemberName = (name: string): TsDsl | IdTsDsl => { regexp.typeScriptIdentifier.lastIndex = 0; if (regexp.typeScriptIdentifier.test(name)) { return new IdTsDsl(name); } return new LiteralTsDsl(name) as TsDsl; }; export const safePropName = ( name: string, ): TsDsl | IdTsDsl => { regexp.number.lastIndex = 0; if (regexp.number.test(name)) { return name.startsWith('-') ? (new LiteralTsDsl(name) as TsDsl) : (new LiteralTsDsl(Number(name)) as TsDsl); } regexp.typeScriptIdentifier.lastIndex = 0; if (regexp.typeScriptIdentifier.test(name)) { return new IdTsDsl(name); } return new LiteralTsDsl(name) as TsDsl; }; const validTypeScriptChar = /^[\u200c\u200d\p{ID_Continue}]$/u; const safeName = (name: string, reserved: ReservedList): string => { let sanitized = ''; let index: number; const first = name[0] ?? ''; regexp.illegalStartCharacters.lastIndex = 0; if (regexp.illegalStartCharacters.test(first)) { // Check if character becomes valid when not in leading position (e.g., digits) if (validTypeScriptChar.test(first)) { sanitized += '_'; index = 0; } else { sanitized += '_'; index = 1; } } else { sanitized += first; index = 1; } while (index < name.length) { const char = name[index] ?? ''; sanitized += validTypeScriptChar.test(char) ? char : '_'; index += 1; } if (reserved['~values'].has(sanitized)) { sanitized = `${sanitized}_`; } return sanitized || '_'; }; export const safeRuntimeName = (name: string): string => safeName(name, reserved.runtime); export const safeTypeName = (name: string): string => safeName(name, reserved.type); ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/regexp.ts ================================================ /** * Matches characters from the start as long as they're not allowed. */ const illegalStartCharactersRegExp = /^[^$_\p{ID_Start}]+/u; /** * Matches string if it contains only digits and optionally decimal point or * leading minus sign. */ const numberRegExp = /^-?\d+(\.\d+)?$/; /** * Javascript identifier regexp pattern retrieved from * {@link} https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers */ const validTypescriptIdentifierRegExp = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u; export const regexp = { /** * Matches characters from the start as long as they're not allowed. */ illegalStartCharacters: illegalStartCharactersRegExp, /** * Matches string if it contains only digits and optionally decimal point or * leading minus sign. */ number: numberRegExp, /** * Javascript identifier regexp pattern retrieved from * {@link} https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers */ typeScriptIdentifier: validTypescriptIdentifierRegExp, }; ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/render-utils.ts ================================================ import path from 'node:path'; import type { ExportModule, File, ImportModule } from '@hey-api/codegen-core'; import ts from 'typescript'; const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed, removeComments: false, }); const blankFile = ts.createSourceFile('', '', ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS); /** Print a TypeScript node to a string. */ export function astToString(node: ts.Node): string { const result = printer.printNode(ts.EmitHint.Unspecified, node, blankFile); try { /** * TypeScript Compiler API escapes unicode characters by default and there * is no way to disable this behavior * {@link https://github.com/microsoft/TypeScript/issues/36174} */ return result.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)), ); } catch { return result; } } export const nodeBuiltins = new Set([ 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto', 'dgram', 'dns', 'domain', 'events', 'freelist', 'fs', 'http', 'https', 'module', 'net', 'os', 'path', 'process', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'timers', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'worker_threads', 'zlib', ]); export type SortGroup = number; export type SortDistance = number; export type SortModule = string; export type SortKey = [SortGroup, SortDistance, SortModule]; export type ModuleExport = Omit & { /** Module specifier for re-exports, e.g. `./foo`. */ modulePath: string; }; export type ModuleImport = Omit & { /** Module specifier for imports, e.g. `./foo`. */ modulePath: string; }; export function moduleSortKey({ file, fromFile, preferFileExtension, root, }: { file: Pick; fromFile: Pick; preferFileExtension: string; root: string; }): SortKey { const filePath = file.finalPath!.split(path.sep).join('/'); let modulePath = fromFile.finalPath!.split(path.sep).join('/'); // built-ins // TODO: based on nodeBuiltins set // external if (fromFile.external && !path.isAbsolute(modulePath)) { return [0, 0, modulePath]; } // outside project root if (!modulePath.startsWith(root.split(path.sep).join('/'))) { return [1, 0, modulePath]; } // local const rel = path .relative(path.dirname(filePath), path.dirname(modulePath)) .split(path.sep) .join('/'); let parentCount: number; // same folder if (!rel.startsWith('..')) { modulePath = `./${rel ? `${rel}/` : ''}${fromFile.name}${fromFile.extension ?? ''}`; parentCount = 0; } else { modulePath = `${rel}/${fromFile.name}${fromFile.extension ?? ''}`; parentCount = rel.split(path.sep).filter((segment) => segment === '..').length; } if (modulePath.endsWith('.ts')) { modulePath = modulePath.slice(0, -'.ts'.length); } if (preferFileExtension) { modulePath += preferFileExtension; } else if (modulePath.endsWith('/index')) { modulePath = modulePath.slice(0, -'/index'.length); } return [2, parentCount, modulePath]; } ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/render.ts ================================================ import type { RenderContext, Renderer } from '@hey-api/codegen-core'; import type { BaseOutput } from '@hey-api/shared'; import type { MaybeArray, MaybeFunc } from '@hey-api/types'; import ts from 'typescript'; import type { TsDsl } from '../../ts-dsl'; import { $ } from '../../ts-dsl'; import type { ModuleExport, ModuleImport, SortGroup, SortKey, SortModule } from './render-utils'; import { astToString, moduleSortKey } from './render-utils'; type Exports = ReadonlyArray>; type ExportsOptions = { preferExportAll?: boolean; }; type Header = MaybeArray | null | undefined; type HeaderArg = MaybeFunc<(ctx: RenderContext) => Header>; type Imports = ReadonlyArray>; function headerToLines(header: Header): ReadonlyArray { if (!header) return []; const lines: Array = []; if (typeof header === 'string') { lines.push(...header.split(/\r?\n/)); return lines; } for (const line of header) { lines.push(...line.split(/\r?\n/)); } return lines; } export class TypeScriptRenderer implements Renderer { /** * Function to generate a file header. * * @private */ private _header?: HeaderArg; /** * Options for module specifier resolution. * * @private */ private _module?: Partial['module']; /** * Whether `export * from 'module'` should be used when possible instead of named exports. * * @private */ private _preferExportAll: boolean; constructor( args: Pick, 'module'> & { header?: HeaderArg; preferExportAll?: boolean; } = {}, ) { this._header = args.header; this._module = args.module; this._preferExportAll = args.preferExportAll ?? false; } render(ctx: RenderContext): string { const header = typeof this._header === 'function' ? this._header(ctx) : this._header; return TypeScriptRenderer.astToString({ exports: this.getExports(ctx), exportsOptions: { preferExportAll: this._preferExportAll, }, header, imports: this.getImports(ctx), nodes: ctx.file.nodes, }); } supports(ctx: RenderContext): boolean { return ctx.file.language === 'typescript'; } static astToString(args: { exports?: Exports; exportsOptions?: ExportsOptions; header?: Header; imports?: Imports; nodes?: ReadonlyArray; /** * Whether to include a trailing newline at the end of the file. * * @default true */ trailingNewline?: boolean; }): string { let text = ''; for (const header of headerToLines(args.header)) { text += `${header}\n`; } let imports = ''; for (const group of args.imports ?? []) { if (imports) imports += '\n'; for (const imp of group) { imports += `${astToString(TypeScriptRenderer.toImportAst(imp))}\n`; } } text = `${text}${text && imports ? '\n' : ''}${imports}`; let nodes = ''; for (const node of args.nodes ?? []) { if (nodes) nodes += '\n'; nodes += `${astToString(node.toAst())}\n`; } text = `${text}${text && nodes ? '\n' : ''}${nodes}`; let exports = ''; for (const group of args.exports ?? []) { if ((!exports && nodes) || exports) exports += '\n'; for (const exp of group) { exports += `${astToString(TypeScriptRenderer.toExportAst(exp, args.exportsOptions))}\n`; } } text = `${text}${text && exports ? '\n' : ''}${exports}`; if (args.trailingNewline === false && text.endsWith('\n')) { text = text.slice(0, -1); } return text; } static toExportAst(group: ModuleExport, options?: ExportsOptions): ts.ExportDeclaration { const specifiers = group.exports.map((exp) => { const specifier = ts.factory.createExportSpecifier( exp.isTypeOnly, exp.sourceName !== exp.exportedName ? $.id(exp.sourceName).toAst() : undefined, $.id(exp.exportedName).toAst(), ); return specifier; }); const exportClause = group.namespaceExport ? ts.factory.createNamespaceExport($.id(group.namespaceExport).toAst()) : (!group.canExportAll || !options?.preferExportAll) && specifiers.length ? ts.factory.createNamedExports(specifiers) : undefined; return ts.factory.createExportDeclaration( undefined, group.isTypeOnly, exportClause, $.literal(group.modulePath).toAst(), ); } static toImportAst(group: ModuleImport): ts.ImportDeclaration { const specifiers = group.imports.map((imp) => { const specifier = ts.factory.createImportSpecifier( imp.isTypeOnly, imp.sourceName !== imp.localName ? $.id(imp.sourceName).toAst() : undefined, $.id(imp.localName).toAst(), ); return specifier; }); const importClause = ts.factory.createImportClause( group.isTypeOnly, group.kind === 'default' ? $.id(group.localName ?? '').toAst() : undefined, group.kind === 'namespace' ? ts.factory.createNamespaceImport($.id(group.localName ?? '').toAst()) : specifiers.length > 0 ? ts.factory.createNamedImports(specifiers) : undefined, ); return ts.factory.createImportDeclaration( undefined, importClause, $.literal(group.modulePath).toAst(), ); } private getExports(ctx: RenderContext): Exports { type ModuleEntry = { group: ModuleExport; sortKey: SortKey; }; const groups = new Map>(); for (const exp of ctx.file.exports) { const sortKey = moduleSortKey({ file: ctx.file, fromFile: exp.from, preferFileExtension: this._module?.extension || '', root: ctx.project.root, }); const modulePath = this._module?.resolve?.(sortKey[2], ctx) ?? sortKey[2]; const [groupIndex] = sortKey; if (!groups.has(groupIndex)) groups.set(groupIndex, new Map()); const moduleMap = groups.get(groupIndex)!; if (!moduleMap.has(modulePath)) { moduleMap.set(modulePath, { group: { canExportAll: exp.canExportAll, exports: exp.exports, isTypeOnly: exp.isTypeOnly, modulePath, namespaceExport: exp.namespaceExport, }, sortKey, }); } } const exports: Array> = Array.from(groups.entries()) .sort((a, b) => a[0] - b[0]) .map(([, moduleMap]) => { const entries = Array.from(moduleMap.values()); entries.sort((a, b) => { const d = a.sortKey[1] - b.sortKey[1]; return d !== 0 ? d : a.group.modulePath.localeCompare(b.group.modulePath); }); return entries.map((e) => { const group = e.group; if (group.namespaceExport) { group.exports = []; } else { const isTypeOnly = !group.exports.find((exp) => !exp.isTypeOnly); if (isTypeOnly) { group.isTypeOnly = true; for (const exp of group.exports) { exp.isTypeOnly = false; } } group.exports.sort((a, b) => a.exportedName.localeCompare(b.exportedName)); } return group; }); }); return exports; } private getImports(ctx: RenderContext): Imports { type ModuleEntry = { group: ModuleImport; sortKey: SortKey; }; const groups = new Map>(); for (const imp of ctx.file.imports) { const sortKey = moduleSortKey({ file: ctx.file, fromFile: imp.from, preferFileExtension: this._module?.extension || '', root: ctx.project.root, }); const modulePath = this._module?.resolve?.(sortKey[2], ctx) ?? sortKey[2]; const [groupIndex] = sortKey; if (!groups.has(groupIndex)) groups.set(groupIndex, new Map()); const moduleMap = groups.get(groupIndex)!; if (!moduleMap.has(modulePath)) { moduleMap.set(modulePath, { group: { imports: [], isTypeOnly: false, kind: imp.kind, modulePath, }, sortKey, }); } const entry = moduleMap.get(modulePath)!; const group = entry.group; if (imp.kind !== 'named') { group.isTypeOnly = imp.isTypeOnly; group.kind = imp.kind; group.localName = imp.localName; } else { group.imports.push(...imp.imports); } } const imports: Array> = Array.from(groups.entries()) .sort((a, b) => a[0] - b[0]) .map(([, moduleMap]) => { const entries = Array.from(moduleMap.values()); entries.sort((a, b) => { const d = a.sortKey[1] - b.sortKey[1]; return d !== 0 ? d : a.group.modulePath.localeCompare(b.group.modulePath); }); return entries.map((e) => { const group = e.group; if (group.kind === 'namespace') { group.imports = []; } else { const isTypeOnly = !group.imports.find((imp) => !imp.isTypeOnly); if (isTypeOnly) { group.isTypeOnly = true; for (const imp of group.imports) { imp.isTypeOnly = false; } } group.imports.sort((a, b) => a.localName.localeCompare(b.localName)); } return group; }); }); return imports; } } ================================================ FILE: packages/openapi-ts/src/ts-dsl/utils/reserved.ts ================================================ import { keywords } from './keywords'; type List = ReadonlyArray; export class ReservedList { private _array: List; private _set: Set; constructor(values: List) { this._array = values; this._set = new Set(values); } get '~values'() { return this._set; } /** * Updates the reserved list with new values. * * @param values New reserved values or a function that receives the previous * reserved values and returns the new ones. */ set(values: List | ((prev: List) => List)): void { const vals = typeof values === 'function' ? values(this._array) : values; this._array = vals; this._set = new Set(vals); } } const runtimeReserved = new ReservedList([ ...keywords.browserGlobals, ...keywords.javaScriptGlobals, ...keywords.javaScriptKeywords, ...keywords.nodeGlobals, ...keywords.typeScriptKeywords, ]); const typeReserved = new ReservedList([ ...keywords.javaScriptKeywords, ...keywords.typeScriptKeywords, ]); /** * Reserved names for identifiers. These names will not be used * for variables, functions, classes, or other identifiers in generated code. */ export const reserved = { /** * Reserved names for runtime identifiers. These names will not be used * for variables, functions, classes, or other runtime identifiers in * generated code. */ runtime: runtimeReserved, /** * Reserved names for type identifiers. These names will not be used * for type or interface identifiers in generated code. */ type: typeReserved, }; ================================================ FILE: packages/openapi-ts/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "composite": true, "rootDir": "src", "outDir": "dist", "types": ["vitest/globals", "node"] }, "include": ["src"], "references": [ { "path": "../types" }, { "path": "../codegen-core" }, { "path": "../shared" }, { "path": "../json-schema-ref-parser" } ] } ================================================ FILE: packages/openapi-ts/tsdown.config.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { defineConfig } from 'tsdown'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const replaceCoreImports = (filePath: string) => { let content = fs.readFileSync(filePath, 'utf8'); // Replace '../../client-core/bundle' with '../core' content = content.replace(/from ['"]\.\.\/\.\.\/client-core\/bundle/g, "from '../core"); fs.writeFileSync(filePath, content, 'utf8'); }; export default defineConfig({ clean: true, deps: { neverBundle: [ '@angular/common/http', '@angular/core', 'axios', 'ky', 'nuxt/app', 'ofetch', 'rxjs', 'vue', ], }, dts: true, entry: ['./src/{index,internal,run}.ts'], format: ['esm'], minify: false, onSuccess: async () => { // Copy client files to dist folder for runtime access const pluginNames = [ 'client-angular', 'client-axios', 'client-core', 'client-fetch', 'client-ky', 'client-next', 'client-nuxt', 'client-ofetch', ]; for (const pluginName of pluginNames) { const srcPath = path.resolve(__dirname, 'src', 'plugins', '@hey-api', pluginName, 'bundle'); const destPath = path.resolve( __dirname, 'dist', 'clients', pluginName.slice('client-'.length), ); if (fs.existsSync(srcPath)) { fs.mkdirSync(path.dirname(destPath), { recursive: true }); fs.cpSync(srcPath, destPath, { recursive: true }); // replace core imports in client bundle const clientFiles = fs.readdirSync(destPath); for (const file of clientFiles) { replaceCoreImports(path.resolve(destPath, file)); } } } }, sourcemap: true, treeshake: true, }); ================================================ FILE: packages/openapi-ts/turbo.json ================================================ { "$schema": "../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts/vitest.setup.ts ================================================ import 'zone.js'; // Angular needs zones import { fileURLToPath } from 'node:url'; import { TestBed } from '@angular/core/testing'; import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; import { beforeAll } from 'vitest'; TestBed.initTestEnvironment(BrowserTestingModule, platformBrowserTesting()); beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; import type { GetBarData, GetFooData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options), meta: { id: 'getFoo', method: 'get', path: '/foo' } }); export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); export const getBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getBarQueryKey(options), meta: { id: 'getBar', method: 'get', path: '/bar' } }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; import type { GetBarData, GetFooData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options), meta: { id: 'getFoo', method: 'get', path: '/foo' } }); export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); export const getBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getBarQueryKey(options), meta: { id: 'getBar', method: 'get', path: '/bar' } }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; import type { GetBarData, GetFooData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options), meta: { id: 'getFoo', method: 'get', path: '/foo' } }); export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); export const getBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getBarQueryKey(options), meta: { id: 'getBar', method: 'get', path: '/bar' } }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; import type { GetBarData, GetFooData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options), meta: { id: 'getFoo', method: 'get', path: '/foo' } }); export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); export const getBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getBarQueryKey(options), meta: { id: 'getBar', method: 'get', path: '/bar' } }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; import type { GetBarData, GetFooData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options), meta: { id: 'getFoo', method: 'get', path: '/foo' } }); export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); export const getBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getBarQueryKey(options), meta: { id: 'getBar', method: 'get', path: '/bar' } }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; import type { GetBarData, GetFooData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options), meta: { id: 'getFoo', method: 'get', path: '/foo' } }); export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); export const getBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getBarQueryKey(options), meta: { id: 'getBar', method: 'get', path: '/bar' } }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getBar, getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetBarData, GetBarResponses, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetBarData, GetBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ in: 'query', name: 'foo', type: 'apiKey' }], url: '/foo', ...options }); export const getBar = (options?: Options) => (options?.client ?? client).get({ security: [{ in: 'cookie', name: 'bar', type: 'apiKey' }], url: '/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; export type GetBarData = { body?: never; path?: never; query?: never; url: '/bar'; }; export type GetBarResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen test/generated generated/ ================================================ FILE: packages/openapi-ts-tests/main/package.json ================================================ { "name": "@test/openapi-ts", "version": "0.0.0", "private": true, "type": "module", "scripts": { "typecheck": "tsgo --noEmit" }, "devDependencies": { "@angular-devkit/build-angular": "21.1.2", "@angular/animations": "21.1.2", "@angular/cli": "21.1.2", "@angular/common": "21.1.2", "@angular/compiler": "21.1.2", "@angular/compiler-cli": "21.1.2", "@angular/core": "21.1.2", "@angular/forms": "21.1.2", "@angular/platform-browser": "21.1.2", "@angular/platform-browser-dynamic": "21.1.2", "@angular/router": "21.1.2", "@hey-api/codegen-core": "workspace:*", "@hey-api/custom-client": "workspace:*", "@hey-api/openapi-ts": "workspace:*", "@pinia/colada": "0.19.1", "@tanstack/angular-query-experimental": "5.90.25", "@tanstack/preact-query": "5.93.0", "@tanstack/react-query": "5.90.21", "@tanstack/solid-query": "5.90.23", "@tanstack/svelte-query": "5.90.2", "@tanstack/vue-query": "5.92.9", "@types/cross-spawn": "6.0.6", "ajv": "8.17.1", "arktype": "2.1.29", "axios": "1.13.4", "cross-spawn": "7.0.6", "eslint": "9.39.1", "fastify": "5.7.4", "ky": "1.14.3", "node-fetch": "3.3.2", "nuxt": "3.14.1592", "ofetch": "1.5.1", "rxjs": "7.8.2", "tslib": "2.8.1", "typescript": "5.9.3", "vue": "3.5.25", "zod": "4.3.6" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts-tests/main/test/2.0.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createClient, type UserConfig } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const version = '2.0.x'; const outputDir = path.join(__dirname, 'generated', version); describe(`OpenAPI ${version}`, () => { const createConfig = (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0] : userConfig.input; const inputPath = path.join( getSpecsPath(), version, typeof input === 'string' ? input : ((input?.path as string) ?? ''), ); return { plugins: ['@hey-api/typescript'], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', }, output: path.join(outputDir, typeof userConfig.output === 'string' ? userConfig.output : ''), } as const satisfies UserConfig; }; const scenarios = [ { config: createConfig({ input: 'external.yaml', output: 'external', }), description: 'handles external references', }, { config: createConfig({ input: 'additional-properties-false.json', output: 'additional-properties-false', }), description: 'forbids arbitrary properties on objects', }, { config: createConfig({ input: 'additional-properties-true.json', output: 'additional-properties-true', }), description: 'allows arbitrary properties on objects', }, { config: createConfig({ input: 'body-response-text-plain.yaml', output: 'body-response-text-plain', plugins: ['@hey-api/client-fetch', '@hey-api/typescript', '@hey-api/sdk'], }), description: 'handle text/plain content type', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values', }), description: 'handles various enum names and values', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-SCREAMING_SNAKE_CASE', plugins: [ { enums: { case: 'SCREAMING_SNAKE_CASE', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, SCREAMING_SNAKE_CASE)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-PascalCase', plugins: [ { enums: { case: 'PascalCase', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, PascalCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-camelCase', plugins: [ { enums: { case: 'camelCase', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, camelCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-snake_case', plugins: [ { enums: { case: 'snake_case', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, snake_case)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-preserve', plugins: [ { enums: { case: 'preserve', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, preserve)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-SCREAMING_SNAKE_CASE', plugins: [ { enums: { case: 'SCREAMING_SNAKE_CASE', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, SCREAMING_SNAKE_CASE)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-PascalCase', plugins: [ { enums: { case: 'PascalCase', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, PascalCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-camelCase', plugins: [ { enums: { case: 'camelCase', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, camelCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-snake_case', plugins: [ { enums: { case: 'snake_case', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, snake_case)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-preserve', plugins: [ { enums: { case: 'preserve', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, preserve)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-const', plugins: [ { enums: { case: 'camelCase', mode: 'typescript-const', }, name: '@hey-api/typescript', }, ], }), description: 'handles TypeScript const enum modifier', }, { config: createConfig({ input: 'exclude-deprecated.yaml', output: 'exclude-deprecated', parser: { filters: { deprecated: false, }, }, }), description: 'excludes deprecated fields', }, { config: createConfig({ input: 'form-data.json', output: 'form-data', plugins: ['@hey-api/client-fetch', '@hey-api/sdk'], }), description: 'handles form data', }, { config: createConfig({ input: 'ref-deep.yaml', output: 'ref-deep', plugins: ['@hey-api/typescript'], }), description: 'handles deep references', }, { config: createConfig({ input: 'transforms-read-write.yaml', output: 'transforms-read-write', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'handles read-only and write-only types', }, { config: createConfig({ input: 'transforms-schemas-name.yaml', output: 'transforms-schemas-name', parser: { transforms: { schemaName: (name: string) => { // Strip version markers: User_v1_0_0_User → User let clean = name.replace(/([A-Za-z\d]+)_v\d+_\d+_\d+_([A-Za-z\d]*)/g, (_, p1, p2) => p2.startsWith(p1) ? p2 : p1 + p2, ); // Deduplicate prefixes: Foo_Foo → Foo const m = clean.match(/^([A-Za-z\d]+)_\1([A-Za-z\d]*)$/); if (m) clean = m[1]! + m[2]!; return clean; }, }, }, plugins: ['@hey-api/typescript'], }), description: 'handles schema name transforms', }, { config: createConfig({ input: 'schema-unknown.yaml', output: 'schema-unknown', plugins: ['@hey-api/client-fetch', '@hey-api/sdk'], }), description: 'generates correct schemas instead of unknown', }, { config: createConfig({ input: 'security-api-key.yaml', output: 'security-api-key', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (api key)', }, { config: createConfig({ input: 'security-basic.json', output: 'security-basic', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (basic)', }, { config: createConfig({ input: 'security-oauth2.yaml', output: 'security-oauth2', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (oauth2)', }, { config: createConfig({ input: 'security-oauth2.yaml', output: 'security-false', plugins: [ '@hey-api/client-fetch', { auth: false, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions without auth', }, { config: createConfig({ input: 'servers.yaml', output: 'servers', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'generates baseUrl', }, { config: createConfig({ input: 'servers-base-path.yaml', output: 'servers-base-path', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'generates baseUrl from basePath', }, { config: createConfig({ input: 'servers-host.yaml', output: 'servers-host', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'generates baseUrl from host', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(__dirname, '__snapshots__', version, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/main/test/3.0.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createClient, type UserConfig } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const version = '3.0.x'; const outputDir = path.join(__dirname, 'generated', version); describe(`OpenAPI ${version}`, () => { const createConfig = (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0] : userConfig.input; const inputPath = path.join( getSpecsPath(), version, typeof input === 'string' ? input : ((input?.path as string) ?? ''), ); const output = userConfig.output instanceof Array ? userConfig.output[0] : userConfig.output; const outputPath = path.join( outputDir, typeof output === 'string' ? output : ((output?.path as string) ?? ''), ); const nameConflictResolver = typeof output === 'string' ? undefined : output?.nameConflictResolver; return { plugins: ['@hey-api/typescript'], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', }, output: { nameConflictResolver, path: outputPath, }, } as const satisfies UserConfig; }; const scenarios = [ { config: createConfig({ input: 'external.yaml', output: 'external', }), description: 'handles external references', }, { config: createConfig({ input: 'additional-properties-false.json', output: 'additional-properties-false', }), description: 'forbids arbitrary properties on objects', }, { config: createConfig({ input: 'additional-properties-true.json', output: 'additional-properties-true', }), description: 'allows arbitrary properties on objects', }, { config: createConfig({ input: 'additional-properties-undefined.json', output: 'additional-properties-undefined', }), description: 'allows arbitrary properties on objects', }, { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'array-nested-one-of.yaml', output: 'array-nested-one-of', }), description: 'generates union of arrays when items use nested oneOf', }, { config: createConfig({ input: 'body-response-text-plain.yaml', output: 'body-response-text-plain', plugins: ['@hey-api/client-fetch', '@hey-api/typescript', '@hey-api/sdk'], }), description: 'handle text/plain content type', }, { config: createConfig({ input: 'case.yaml', output: 'case-preserve', plugins: [ { case: 'preserve', name: '@hey-api/typescript', }, ], }), description: 'handles preserved identifier casing', }, { config: createConfig({ input: 'case.yaml', output: 'case-PascalCase', plugins: [ { case: 'PascalCase', name: '@hey-api/typescript', }, ], }), description: 'handles PascalCase identifier casing', }, { config: createConfig({ input: 'case.yaml', output: 'case-camelCase', plugins: [ { case: 'camelCase', name: '@hey-api/typescript', }, ], }), description: 'handles camelCase identifier casing', }, { config: createConfig({ input: 'case.yaml', output: 'case-snake_case', plugins: [ { case: 'snake_case', name: '@hey-api/typescript', }, ], }), description: 'handles snake_case identifier casing', }, { config: createConfig({ input: 'components-request-bodies.json', output: 'components-request-bodies', }), description: 'handles reusable request bodies', }, { config: createConfig({ input: 'content-binary.json', output: 'content-binary', }), description: 'handles binary content', }, { config: createConfig({ input: 'body-binary-format.yaml', output: 'body-binary-format', plugins: ['@hey-api/client-fetch', '@hey-api/typescript', '@hey-api/sdk'], }), description: 'handles binary format request body', }, { config: createConfig({ input: 'content-types.yaml', output: 'content-types', plugins: ['@hey-api/client-axios', '@hey-api/typescript', '@hey-api/sdk'], }), description: 'handles content types', }, { config: createConfig({ input: 'discriminator-all-of.yaml', output: 'discriminator-all-of', }), description: 'handles discriminator with and without mapping', }, { config: createConfig({ input: 'discriminator-any-of.yaml', output: 'discriminator-any-of', }), description: 'handles discriminator with and without mapping', }, { config: createConfig({ input: 'discriminator-mapped-many.yaml', output: 'discriminator-mapped-many', }), description: 'handles discriminator with multiple mappings', }, { config: createConfig({ input: 'discriminator-one-of.yaml', output: 'discriminator-one-of', }), description: 'handles discriminator with and without mapping', }, { config: createConfig({ input: 'discriminator-allof-nested.json', output: 'discriminator-allof-nested', }), description: 'handles nested allOf with discriminators', }, { config: createConfig({ input: 'discriminator-allof-inline.json', output: 'discriminator-allof-inline', }), description: 'handles allOf where inline schema discriminator mapping should take priority over $ref discriminator fallback', }, { config: createConfig({ input: 'discriminator-object-self-mapped.json', output: 'discriminator-object-self-mapped', }), description: 'handles object discriminator mappings that include the schema itself', }, { config: createConfig({ input: 'discriminator-non-string.yaml', output: 'discriminator-non-string', }), description: 'handles non-string discriminator property types', }, { config: createConfig({ input: 'enum-escape.json', output: 'enum-escape', }), description: 'escapes enum values', }, { config: createConfig({ input: 'enum-inline.json', output: 'enum-inline', parser: { transforms: { enums: 'root', }, }, }), description: 'exports inline enums', }, { config: createConfig({ input: 'enum-inline.json', output: 'enum-inline-javascript', parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'javascript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums (JavaScript)', }, { config: createConfig({ input: 'enum-inline.json', output: 'enum-inline-typescript', parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'typescript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums (TypeScript)', }, { config: createConfig({ input: 'enum-inline.json', output: { nameConflictResolver: ({ attempt, baseName }) => attempt === 0 ? baseName : `${baseName}_N${attempt + 1}`, path: 'enum-inline-name-resolver', }, parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'javascript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums with name conflict resolver', }, { config: createConfig({ input: 'enum-inline.json', output: { nameConflictResolver: () => null, path: 'enum-inline-name-resolver-null', }, parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'javascript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums with name conflict resolver returning null', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values', }), description: 'handles various enum names and values', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-SCREAMING_SNAKE_CASE', plugins: [ { enums: { case: 'SCREAMING_SNAKE_CASE', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, SCREAMING_SNAKE_CASE)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-PascalCase', plugins: [ { enums: { case: 'PascalCase', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, PascalCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-camelCase', plugins: [ { enums: { case: 'camelCase', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, camelCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-snake_case', plugins: [ { enums: { case: 'snake_case', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, snake_case)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-preserve', plugins: [ { enums: { case: 'preserve', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, preserve)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-javascript-ignore-null', plugins: [ { enums: { case: 'preserve', constantsIgnoreNull: true, mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, preserve, ignore null)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-SCREAMING_SNAKE_CASE', plugins: [ { enums: { case: 'SCREAMING_SNAKE_CASE', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, SCREAMING_SNAKE_CASE)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-PascalCase', plugins: [ { enums: { case: 'PascalCase', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, PascalCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-camelCase', plugins: [ { enums: { case: 'camelCase', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, camelCase)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-snake_case', plugins: [ { enums: { case: 'snake_case', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, snake_case)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-preserve', plugins: [ { enums: { case: 'preserve', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, preserve)', }, { config: createConfig({ input: 'enum-names-values.json', output: 'enum-names-values-typescript-const', plugins: [ { enums: { case: 'camelCase', mode: 'typescript-const', }, name: '@hey-api/typescript', }, ], }), description: 'handles TypeScript const enum modifier', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'exclude-deprecated.yaml', output: 'exclude-deprecated', parser: { filters: { deprecated: false, }, }, }), description: 'excludes deprecated fields', }, { config: createConfig({ input: 'internal-name-conflict.json', output: 'internal-name-conflict', plugins: ['@hey-api/client-fetch', '@tanstack/react-query'], }), description: 'handles conflict between generated code and internal artifacts', }, { config: createConfig({ input: 'operation-204.json', output: 'operation-204', }), description: 'handles empty response status codes', }, { config: createConfig({ input: 'parameter-explode-false.json', output: 'parameter-explode-false', plugins: ['@hey-api/client-fetch', '@hey-api/sdk'], }), description: 'handles non-exploded array query parameters', }, { config: createConfig({ input: 'parameter-explode-false.json', output: 'parameter-explode-false-axios', plugins: ['@hey-api/client-axios', '@hey-api/sdk'], }), description: 'handles non-exploded array query parameters (Axios)', }, { config: createConfig({ input: 'ref-deep.yaml', output: 'ref-deep', }), description: 'handles deep references', }, { config: createConfig({ input: 'transforms-read-write.yaml', output: 'transforms-read-write', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'handles read-only and write-only types', }, { config: createConfig({ input: 'transforms-schemas-name.yaml', output: 'transforms-schemas-name', parser: { transforms: { schemaName: (name: string) => { // Strip version markers: User_v1_0_0_User → User let clean = name.replace(/([A-Za-z\d]+)_v\d+_\d+_\d+_([A-Za-z\d]*)/g, (_, p1, p2) => p2.startsWith(p1) ? p2 : p1 + p2, ); // Deduplicate prefixes: Foo_Foo → Foo const m = clean.match(/^([A-Za-z\d]+)_\1([A-Za-z\d]*)$/); if (m) clean = m[1]! + m[2]!; return clean; }, }, }, }), description: 'handles schema name transforms', }, { config: createConfig({ input: 'transforms-schemas-name-collision.yaml', output: 'transforms-schemas-name-collision', parser: { transforms: { schemaName: (name: string) => // Try to rename all _vX_User schemas to "User" // This should cause collisions since "User" already exists name.replace(/_v\d+_User$/, ''), }, }, }), description: 'handles schema name collision prevention', }, { config: createConfig({ input: 'security-api-key.yaml', output: 'security-api-key', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (api key)', }, { config: createConfig({ input: 'security-http-bearer.json', output: 'security-http-bearer', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (Bearer token)', }, { config: createConfig({ input: 'security-oauth2.yaml', output: 'security-oauth2', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (oauth2)', }, { config: createConfig({ input: 'security-open-id-connect.yaml', output: 'security-open-id-connect', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (OpenID Connect)', }, { config: createConfig({ input: 'security-oauth2.yaml', output: 'security-false', plugins: [ '@hey-api/client-fetch', { auth: false, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions without auth', }, { config: createConfig({ input: 'servers.yaml', output: 'servers', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'generates baseUrl', }, { config: createConfig({ input: 'transformers-all-of.yaml', output: 'transformers-all-of', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms nested date in all of composition', }, { config: createConfig({ input: 'transformers-allof-response-wrapper.json', output: 'transformers-allof-response-wrapper', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms dates in allOf response wrapper (paginated response)', }, { config: createConfig({ input: 'transformers-any-of-null.json', output: 'transformers-any-of-null', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms nullable date property', }, { config: createConfig({ input: 'transformers-array.json', output: 'transformers-array', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms an array', }, { config: createConfig({ input: 'transformers-recursive.json', output: 'transformers-recursive', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms recursive/self-referential schemas', }, { config: createConfig({ input: 'dutchie.json', output: 'transforms-properties-required-by-default', parser: { transforms: { propertiesRequiredByDefault: true, }, }, }), description: 'makes all object properties required by default', }, { config: createConfig({ input: 'type-invalid.json', output: 'type-invalid', }), description: 'gracefully handles invalid type', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output.path); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(__dirname, '__snapshots__', version, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/main/test/3.1.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createClient, type UserConfig } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const version = '3.1.x'; const outputDir = path.join(__dirname, 'generated', version); describe(`OpenAPI ${version}`, () => { const createConfig = (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0] : userConfig.input; const inputPath = path.join( getSpecsPath(), version, typeof input === 'string' ? input : ((input?.path as string) ?? ''), ); const output = userConfig.output instanceof Array ? userConfig.output[0] : userConfig.output; const outputPath = path.join( outputDir, typeof output === 'string' ? output : ((output?.path as string) ?? ''), ); const nameConflictResolver = typeof output === 'string' ? undefined : output?.nameConflictResolver; return { plugins: ['@hey-api/typescript'], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', }, output: { nameConflictResolver, path: outputPath, }, } as const satisfies UserConfig; }; const scenarios = [ { config: createConfig({ input: 'external.yaml', output: 'external', }), description: 'handles external references', }, { config: createConfig({ input: 'pattern-properties.json', output: 'pattern-properties', }), description: 'handles pattern properties', }, { config: createConfig({ input: 'additional-properties-false.json', output: 'additional-properties-false', }), description: 'forbids arbitrary properties on objects', }, { config: createConfig({ input: 'additional-properties-true.json', output: 'additional-properties-true', }), description: 'allows arbitrary properties on objects (unknown top type)', }, { config: createConfig({ input: 'additional-properties-true.json', output: 'additional-properties-true-any', plugins: [ { name: '@hey-api/typescript', topType: 'any', }, ], }), description: 'allows arbitrary properties on objects (any top type)', }, { config: createConfig({ input: 'additional-properties-undefined.json', output: 'additional-properties-undefined', }), description: 'allows arbitrary properties on objects', }, { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'array-nested-one-of.yaml', output: 'array-nested-one-of', }), description: 'generates union of arrays when items use nested oneOf', }, { config: createConfig({ input: 'body-response-text-plain.yaml', output: 'body-response-text-plain', plugins: ['@hey-api/client-fetch', '@hey-api/typescript', '@hey-api/sdk'], }), description: 'handle text/plain content type', }, { config: createConfig({ input: 'case.yaml', output: 'case-preserve', plugins: [ { case: 'preserve', name: '@hey-api/typescript', }, ], }), description: 'handles preserved identifier casing', }, { config: createConfig({ input: 'case.yaml', output: 'case-PascalCase', plugins: [ { case: 'PascalCase', name: '@hey-api/typescript', }, ], }), description: 'handles PascalCase identifier casing', }, { config: createConfig({ input: 'case.yaml', output: 'case-camelCase', plugins: [ { case: 'camelCase', name: '@hey-api/typescript', }, ], }), description: 'handles camelCase identifier casing', }, { config: createConfig({ input: 'case.yaml', output: 'case-snake_case', plugins: [ { case: 'snake_case', name: '@hey-api/typescript', }, ], }), description: 'handles snake_case identifier casing', }, { config: createConfig({ input: 'components-request-bodies.json', output: 'components-request-bodies', }), description: 'handles reusable request bodies', }, { config: createConfig({ input: 'const.json', output: 'const', }), description: 'handles const keyword', }, { config: createConfig({ input: 'content-binary.json', output: 'content-binary', }), description: 'handles binary content', }, { config: createConfig({ input: 'content-media-type.yaml', output: 'content-media-type', }), description: 'handles contentMediaType schema property for file uploads', }, { config: createConfig({ input: 'content-types.yaml', output: 'content-types', plugins: ['@hey-api/client-axios', '@hey-api/typescript', '@hey-api/sdk'], }), description: 'handles content types', }, { config: createConfig({ input: 'discriminator-all-of.yaml', output: 'discriminator-all-of', }), description: 'handles discriminator with and without mapping', }, { config: createConfig({ input: 'discriminator-any-of.yaml', output: 'discriminator-any-of', }), description: 'handles discriminator with and without mapping', }, { config: createConfig({ input: 'discriminator-mapped-many.yaml', output: 'discriminator-mapped-many', }), description: 'handles discriminator with multiple mappings', }, { config: createConfig({ input: 'discriminator-one-of.yaml', output: 'discriminator-one-of', }), description: 'handles discriminator with and without mapping', }, { config: createConfig({ input: 'discriminator-allof-nested.json', output: 'discriminator-allof-nested', }), description: 'handles nested allOf with discriminators', }, { config: createConfig({ input: 'discriminator-allof-inline.json', output: 'discriminator-allof-inline', }), description: 'handles allOf where inline schema discriminator mapping should take priority over $ref discriminator fallback', }, { config: createConfig({ input: 'discriminator-object-self-mapped.json', output: 'discriminator-object-self-mapped', }), description: 'handles object discriminator mappings that include the schema itself', }, { config: createConfig({ input: 'discriminator-non-string.yaml', output: 'discriminator-non-string', }), description: 'handles non-string discriminator property types', }, { config: createConfig({ input: 'discriminator-one-of-read-write.yaml', output: 'discriminator-one-of-read-write', }), description: 'handles discriminator with oneOf and read/write transforms', }, { config: createConfig({ input: 'duplicate-null.json', output: 'duplicate-null', }), description: 'does not generate duplicate null', }, { config: createConfig({ input: 'enum-escape.json', output: 'enum-escape', }), description: 'escapes enum values', }, { config: createConfig({ input: 'enum-inline.yaml', output: 'enum-inline', parser: { transforms: { enums: 'root', }, }, }), description: 'exports inline enums', }, { config: createConfig({ input: 'enum-inline.yaml', output: 'enum-inline-javascript', parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'javascript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums (JavaScript)', }, { config: createConfig({ input: 'enum-inline.yaml', output: 'enum-inline-typescript', parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'typescript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums (TypeScript)', }, { config: createConfig({ input: 'enum-inline.yaml', output: { nameConflictResolver: ({ attempt, baseName }) => attempt === 0 ? baseName : `${baseName}_N${attempt + 1}`, path: 'enum-inline-name-resolver', }, parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'javascript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums with name conflict resolver', }, { config: createConfig({ input: 'enum-inline.yaml', output: { nameConflictResolver: () => null, path: 'enum-inline-name-resolver-null', }, parser: { transforms: { enums: 'root', }, }, plugins: [ { enums: 'javascript', name: '@hey-api/typescript', }, ], }), description: 'exports inline enums with name conflict resolver returning null', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values', }), description: 'handles various enum names and values', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-javascript-SCREAMING_SNAKE_CASE', plugins: [ { enums: { case: 'SCREAMING_SNAKE_CASE', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, SCREAMING_SNAKE_CASE)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-javascript-PascalCase', plugins: [ { enums: { case: 'PascalCase', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, PascalCase)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-javascript-camelCase', plugins: [ { enums: { case: 'camelCase', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, camelCase)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-javascript-snake_case', plugins: [ { enums: { case: 'snake_case', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, snake_case)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-javascript-preserve', plugins: [ { enums: { case: 'preserve', mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, preserve)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-javascript-ignore-null', plugins: [ { enums: { case: 'preserve', constantsIgnoreNull: true, mode: 'javascript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (JavaScript, preserve, ignore null)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-typescript-SCREAMING_SNAKE_CASE', plugins: [ { enums: { case: 'SCREAMING_SNAKE_CASE', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, SCREAMING_SNAKE_CASE)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-typescript-PascalCase', plugins: [ { enums: { case: 'PascalCase', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, PascalCase)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-typescript-camelCase', plugins: [ { enums: { case: 'camelCase', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, camelCase)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-typescript-snake_case', plugins: [ { enums: { case: 'snake_case', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, snake_case)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-typescript-preserve', plugins: [ { enums: { case: 'preserve', mode: 'typescript', }, name: '@hey-api/typescript', }, ], }), description: 'handles various enum names and values (TypeScript, preserve)', }, { config: createConfig({ input: 'enum-names-values.yaml', output: 'enum-names-values-typescript-const', plugins: [ { enums: { case: 'camelCase', mode: 'typescript-const', }, name: '@hey-api/typescript', }, ], }), description: 'handles TypeScript const enum modifier', }, { config: createConfig({ input: 'union-types.json', output: 'union-types', }), description: 'handles union of primitive types', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'exclude-deprecated.yaml', output: 'exclude-deprecated', parser: { filters: { deprecated: false, }, }, }), description: 'excludes deprecated fields', }, { config: createConfig({ input: 'headers.yaml', output: 'headers', plugins: ['@hey-api/client-fetch', '@hey-api/typescript', '@hey-api/sdk'], }), description: 'handles various headers', }, { config: createConfig({ input: 'internal-name-conflict.json', output: 'internal-name-conflict', plugins: ['@hey-api/client-fetch', '@tanstack/react-query'], }), description: 'handles conflict between generated code and internal artifacts', }, { config: createConfig({ input: 'negative-property-names.json', output: 'negative-property-names', }), description: 'handles negative property names correctly', }, { config: createConfig({ input: 'object-properties-all-of.json', output: 'object-properties-all-of', }), description: 'sets correct logical operator and brackets on object with properties and allOf composition', }, { config: createConfig({ input: 'object-properties-any-of.json', output: 'object-properties-any-of', }), description: 'sets correct logical operator and brackets on object with properties and anyOf composition', }, { config: createConfig({ input: 'object-properties-one-of.json', output: 'object-properties-one-of', }), description: 'sets correct logical operator and brackets on object with properties and oneOf composition', }, { config: createConfig({ input: 'object-property-names.yaml', output: 'object-property-names', }), description: 'sets correct index signature type on object with property names', }, { config: createConfig({ input: 'operation-204.json', output: 'operation-204', }), description: 'handles empty response status codes', }, { config: createConfig({ input: 'pagination-ref.yaml', output: 'pagination-ref', plugins: ['@hey-api/client-fetch', '@tanstack/react-query'], }), description: 'detects pagination fields', }, { config: createConfig({ input: 'parameter-explode-false.json', output: 'parameter-explode-false', plugins: ['@hey-api/client-fetch', '@hey-api/sdk'], }), description: 'handles non-exploded array query parameters', }, { config: createConfig({ input: 'parameter-explode-false.json', output: 'parameter-explode-false-axios', plugins: ['@hey-api/client-axios', '@hey-api/sdk'], }), description: 'handles non-exploded array query parameters (Axios)', }, { config: createConfig({ input: 'parameter-tuple.json', output: 'parameter-tuple', }), description: 'handles tuple query parameters', }, { config: createConfig({ input: 'ref-deep.yaml', output: 'ref-deep', }), description: 'handles deep references', }, { config: createConfig({ input: 'transforms-read-write.yaml', output: 'transforms-read-write', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'handles read-only and write-only types', }, { config: createConfig({ input: 'transforms-schemas-name.yaml', output: 'transforms-schemas-name', parser: { transforms: { schemaName: (name: string) => { // Strip version markers: User_v1_0_0_User → User let clean = name.replace(/([A-Za-z\d]+)_v\d+_\d+_\d+_([A-Za-z\d]*)/g, (_, p1, p2) => p2.startsWith(p1) ? p2 : p1 + p2, ); // Deduplicate prefixes: Foo_Foo → Foo const m = clean.match(/^([A-Za-z\d]+)_\1([A-Za-z\d]*)$/); if (m) clean = m[1]! + m[2]!; return clean; }, }, }, }), description: 'handles schema name transforms', }, { config: createConfig({ input: 'transforms-read-write-nested.yaml', output: 'transforms-read-write-nested', }), description: 'handles write-only types in nested schemas', }, { config: createConfig({ input: 'transforms-read-write-response.yaml', output: 'transforms-read-write-response', }), description: 'handles read-only types in nested response schemas', }, { config: createConfig({ input: 'transforms-read-write-unevaluated.yaml', output: 'transforms-read-write-unevaluated', }), description: 'preserves unevaluatedProperties in schemas with readOnly fields', }, { config: createConfig({ input: 'ref-type.json', output: 'ref-type', }), description: 'handles extended $ref with type keyword', }, { config: createConfig({ input: 'required-all-of-ref.json', output: 'required-all-of-ref', }), description: 'sets allOf composition ref model properties as required', }, { config: createConfig({ input: 'required-any-of-ref.json', output: 'required-any-of-ref', }), description: 'does not set anyOf composition ref model properties as required', }, { config: createConfig({ input: 'required-one-of-ref.json', output: 'required-one-of-ref', }), description: 'does not set oneOf composition ref model properties as required', }, { config: createConfig({ input: 'schema-const.yaml', output: 'schema-const', }), description: 'handles various constants', }, { config: createConfig({ input: 'security-api-key.yaml', output: 'security-api-key', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (api key)', }, { config: createConfig({ input: 'security-http-bearer.json', output: 'security-http-bearer', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (Bearer token)', }, { config: createConfig({ input: 'security-oauth2.yaml', output: 'security-oauth2', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (oauth2)', }, { config: createConfig({ input: 'security-open-id-connect.yaml', output: 'security-open-id-connect', plugins: [ '@hey-api/client-fetch', { auth: true, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions with auth (OpenID Connect)', }, { config: createConfig({ input: 'security-oauth2.yaml', output: 'security-false', plugins: [ '@hey-api/client-fetch', { auth: false, name: '@hey-api/sdk', }, ], }), description: 'generates SDK functions without auth', }, { config: createConfig({ input: 'servers.yaml', output: 'servers', plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], }), description: 'generates baseUrl', }, { config: createConfig({ input: 'transformers-all-of.yaml', output: 'transformers-all-of', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms nested date in all of composition', }, { config: createConfig({ input: 'transformers-allof-response-wrapper.json', output: 'transformers-allof-response-wrapper', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms dates in allOf response wrapper (paginated response)', }, { config: createConfig({ input: 'transformers-any-of-null.json', output: 'transformers-any-of-null', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms nullable date property', }, { config: createConfig({ input: 'transformers-array.json', output: 'transformers-array', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms an array', }, { config: createConfig({ input: 'transformers-recursive.json', output: 'transformers-recursive', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms recursive/self-referential schemas', }, { config: createConfig({ input: 'transformers-one-of-discriminated.yaml', output: 'transformers-one-of-discriminated', plugins: ['@hey-api/client-fetch', '@hey-api/transformers'], }), description: 'transforms discriminated oneOf without warning', }, { config: createConfig({ input: 'type-invalid.json', output: 'type-invalid', }), description: 'gracefully handles invalid type', }, { config: createConfig({ input: 'opencode.yaml', output: 'sse-angular', parser: { filters: { operations: { include: ['GET /event'], }, }, }, plugins: ['@hey-api/client-angular', '@hey-api/sdk'], }), description: 'client with SSE (Angular)', }, { config: createConfig({ input: 'opencode.yaml', output: 'sse-axios', parser: { filters: { operations: { include: ['GET /event'], }, }, }, plugins: ['@hey-api/client-axios', '@hey-api/sdk'], }), description: 'client with SSE (Axios)', }, { config: createConfig({ input: 'opencode.yaml', output: 'sse-fetch', parser: { filters: { operations: { include: ['GET /event'], }, }, }, plugins: ['@hey-api/client-fetch', '@hey-api/sdk'], }), description: 'client with SSE (Fetch)', }, { config: createConfig({ input: 'opencode.yaml', output: 'sse-ofetch', parser: { filters: { operations: { include: ['GET /event'], }, }, }, plugins: ['@hey-api/client-ofetch', '@hey-api/sdk'], }), description: 'client with SSE (ofetch)', }, { config: createConfig({ input: 'opencode.yaml', output: 'sse-next', parser: { filters: { operations: { include: ['GET /event'], }, }, }, plugins: ['@hey-api/client-next', '@hey-api/sdk'], }), description: 'client with SSE (Next.js)', }, { config: createConfig({ input: 'opencode.yaml', output: 'sse-nuxt', parser: { filters: { operations: { include: ['GET /event'], }, }, }, plugins: ['@hey-api/client-nuxt', '@hey-api/sdk'], }), description: 'client with SSE (Nuxt)', }, { config: createConfig({ input: 'sse-post.yaml', output: 'sse-tanstack-react-query', plugins: ['@hey-api/client-fetch', '@tanstack/react-query'], }), description: 'SSE POST endpoint is excluded from TanStack React Query mutations', }, { config: createConfig({ input: 'zoom-video-sdk.json', output: 'webhooks', }), description: 'webhook types', }, { config: createConfig({ input: 'string-with-format.yaml', output: 'string-with-format', }), description: 'anyOf string and binary string', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output.path); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(__dirname, '__snapshots__', version, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/additional-properties-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/additional-properties-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type Foo = { foo: string; }; export type Bar = Foo & {}; export type Baz = Foo & { bar: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/additional-properties-true/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/additional-properties-true/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type Foo = { foo: string; [key: string]: unknown; }; export type Bar = Foo & { [key: string]: unknown; }; export type Baz = Foo & { bar: string; [key: string]: unknown; }; export type Qux = { [key: string]: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { ClientOptions, PostFooData, PostFooResponse, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options: Options) => (options.client ?? client).post({ bodySerializer: null, url: '/foo', ...options, headers: { 'Content-Type': 'text/plain', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/body-response-text-plain/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type PostFooData = { body: string; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: string; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _110, Arrays, ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type _110 = '1-10' | '11-20'; export type MyFoo = 'myFoo' | 'myBar'; export type MyFoo2 = 'MyFoo' | 'MyBar'; export type Foo = 'foo' | 'bar' | '' | true | false; export type Numbers = 100 | 200 | 300 | -100 | -200 | -300; export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export const _110 = { 110: '1-10', 1120: '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { MyFoo: 'myFoo', MyBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { Foo: 'foo', Bar: 'bar', '': '', True: true, False: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-SCREAMING_SNAKE_CASE/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-SCREAMING_SNAKE_CASE/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export const _110 = { '1_10': '1-10', '11_20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { MY_FOO: 'myFoo', MY_BAR: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MY_FOO: 'MyFoo', MY_BAR: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { FOO: 'foo', BAR: 'bar', '': '', TRUE: true, FALSE: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export const _110 = { 110: '1-10', 1120: '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { myFoo: 'MyFoo', myBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export const _110 = { '1-10': '1-10', '11-20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-javascript-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export const _110 = { '1_10': '1-10', '11_20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { my_foo: 'myFoo', my_bar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { my_foo: 'MyFoo', my_bar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export enum _110 { _110 = '1-10', _1120 = '11-20' } export enum MyFoo { MyFoo = 'myFoo', MyBar = 'myBar' } export enum MyFoo2 { MyFoo = 'MyFoo', MyBar = 'MyBar' } export type Foo = 'foo' | 'bar' | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-SCREAMING_SNAKE_CASE/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-SCREAMING_SNAKE_CASE/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export enum _110 { '1_10' = '1-10', '11_20' = '11-20' } export enum MyFoo { MY_FOO = 'myFoo', MY_BAR = 'myBar' } export enum MyFoo2 { MY_FOO = 'MyFoo', MY_BAR = 'MyBar' } export type Foo = 'foo' | 'bar' | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export enum _110 { _110 = '1-10', _1120 = '11-20' } export enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export enum MyFoo2 { myFoo = 'MyFoo', myBar = 'MyBar' } export type Foo = 'foo' | 'bar' | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-const/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-const/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export const enum _110 { _110 = '1-10', _1120 = '11-20' } export const enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export const enum MyFoo2 { myFoo = 'MyFoo', myBar = 'MyBar' } export type Foo = 'foo' | 'bar' | '' | true | false; export const enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export enum _110 { '1-10' = '1-10', '11-20' = '11-20' } export enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export enum MyFoo2 { MyFoo = 'MyFoo', MyBar = 'MyBar' } export type Foo = 'foo' | 'bar' | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/enum-names-values-typescript-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export enum _110 { '1_10' = '1-10', '11_20' = '11-20' } export enum MyFoo { my_foo = 'myFoo', my_bar = 'myBar' } export enum MyFoo2 { my_foo = 'MyFoo', my_bar = 'MyBar' } export type Foo = 'foo' | 'bar' | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/exclude-deprecated/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/exclude-deprecated/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type Foo = string; export type PostFooData = { body: Foo; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/external/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _1, ClientOptions, Deep, ExternalAllOfSchema, ExternalAnyOfSchema, ExternalArraySchema, ExternalDoubleNestedNumeric, ExternalDoubleNestedProp, ExternalMixedProperties, ExternalNested, ExternalNestedNumeric, ExternalNestedNumericObjectA, ExternalNestedNumericObjectB, ExternalNestedObjectA, ExternalNestedObjectB, ExternalSchemaA, ExternalSchemaB, ExternalSchemaC, ExternalSchemaExternalProp, ExternalSchemaExternalPropAlias, ExternalSchemaPathA, ExternalSchemaPathB, ExternalSchemaPropertyA, ExternalSchemaPropertyB, ExternalSchemaPropertyC, ExternalSchemaPropertyD, ExternalSharedModel, ExternalSharedModelWithUuid, ExternalUnionSchema, GetExternalArrayData, GetExternalArrayResponse, GetExternalArrayResponses, GetExternalMixedData, GetExternalMixedResponse, GetExternalMixedResponses, GetExternalModelData, GetExternalModelError, GetExternalModelErrors, GetExternalModelResponse, GetExternalModelResponses, GetExternalNestedData, GetExternalNestedResponse, GetExternalNestedResponses, GetExternalPropertiesByIdData, GetExternalPropertiesByIdResponse, GetExternalPropertiesByIdResponses, GetExternalUnionData, GetExternalUnionResponses, GetExternalUuidData, GetExternalUuidResponse, GetExternalUuidResponses, Id, Name, PostExternalArrayData, PostExternalArrayResponse, PostExternalArrayResponses, PostExternalMixedData, PostExternalMixedResponse, PostExternalMixedResponses, PostExternalModelData, PostExternalModelErrors, PostExternalModelResponse, PostExternalModelResponses, PostExternalNestedData, PostExternalNestedResponse, PostExternalNestedResponses, PostExternalUnionData, PostExternalUnionResponses, PutExternalUuidData, PutExternalUuidResponse, PutExternalUuidResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/external/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type _1 = string; export type ExternalSchemaA = ExternalSharedModel; export type ExternalSchemaB = ExternalSharedModel; export type ExternalSchemaC = ExternalSharedModel; export type ExternalSchemaPathA = ExternalSharedModel; export type ExternalSchemaPathB = ExternalSharedModel; /** * External schema property (A) */ export type ExternalSchemaPropertyA = { uuid1?: ExternalSharedModelWithUuid; }; /** * External schema property (B) - second use of UUID */ export type ExternalSchemaPropertyB = { uuid2?: ExternalSharedModelWithUuid; }; /** * External schema property (C) - third use of UUID */ export type ExternalSchemaPropertyC = { uuid3?: ExternalSharedModelWithUuid; }; /** * External schema property with duplicate refs (D) */ export type ExternalSchemaPropertyD = { uuid4?: ExternalSharedModelWithUuid; uuid5?: ExternalSharedModelWithUuid; }; /** * External schema property via external property ref (id) */ export type ExternalSchemaExternalProp = { id3?: Id; id4?: Id; }; /** * Alias to external property via component property ref */ export type ExternalSchemaExternalPropAlias = { id5?: Id; id6?: Id; }; /** * External double nested prop via property ref */ export type ExternalDoubleNestedProp = { deep1?: Deep; deep2?: Deep; }; /** * External double nested numeric properties */ export type ExternalDoubleNestedNumeric = { numeric1?: _1; numeric2?: _1; }; export type ExternalNestedObjectA = ExternalNested; export type ExternalNestedObjectB = ExternalNested; export type ExternalNestedNumericObjectA = ExternalNestedNumeric; export type ExternalNestedNumericObjectB = ExternalNestedNumeric; /** * Mixed external property references */ export type ExternalMixedProperties = { id7?: Id; name1?: Name; uuid6?: ExternalSharedModelWithUuid; deep3?: Deep; numeric3?: _1; }; /** * Array containing external references */ export type ExternalArraySchema = { items?: Array; uuidItems?: Array; }; /** * Union type with external references */ export type ExternalUnionSchema = unknown; /** * AllOf with external references */ export type ExternalAllOfSchema = ExternalSharedModel & { additional?: ExternalSharedModelWithUuid; }; /** * AnyOf with external references */ export type ExternalAnyOfSchema = unknown; export type ExternalNested = { inner?: { deep?: string; }; }; export type Deep = string; export type ExternalNestedNumeric = { 0?: { 1?: string; }; }; export type ExternalSharedModel = { id: string; name?: string; }; export type Id = string; export type Name = string; export type ExternalSharedModelWithUuid = string; export type GetExternalModelData = { body?: never; path: { id: unknown; }; query?: { uuid?: unknown; }; url: '/external-model'; }; export type GetExternalModelErrors = { /** * Response using external UUID */ 400: ExternalSharedModelWithUuid; }; export type GetExternalModelError = GetExternalModelErrors[keyof GetExternalModelErrors]; export type GetExternalModelResponses = { /** * Response using external model */ 200: ExternalSharedModel; }; export type GetExternalModelResponse = GetExternalModelResponses[keyof GetExternalModelResponses]; export type PostExternalModelData = { /** * Request body using external model */ body: ExternalSharedModel; path?: never; query?: never; url: '/external-model'; }; export type PostExternalModelErrors = { /** * Response with union of external types */ 422: unknown; }; export type PostExternalModelResponses = { /** * Response using external model */ 201: ExternalSharedModel; }; export type PostExternalModelResponse = PostExternalModelResponses[keyof PostExternalModelResponses]; export type GetExternalUuidData = { body?: never; path?: never; query?: { uuid?: unknown; }; url: '/external-uuid'; }; export type GetExternalUuidResponses = { /** * Response using external UUID */ 200: ExternalSharedModelWithUuid; }; export type GetExternalUuidResponse = GetExternalUuidResponses[keyof GetExternalUuidResponses]; export type PutExternalUuidData = { /** * Request body using external UUID */ body?: ExternalSharedModelWithUuid; path?: never; query?: never; url: '/external-uuid'; }; export type PutExternalUuidResponses = { /** * Response using external UUID */ 200: ExternalSharedModelWithUuid; }; export type PutExternalUuidResponse = PutExternalUuidResponses[keyof PutExternalUuidResponses]; export type GetExternalNestedData = { body?: never; headers?: { deep?: unknown; }; path?: never; query?: never; url: '/external-nested'; }; export type GetExternalNestedResponses = { /** * Response using external nested object */ 200: ExternalNested; }; export type GetExternalNestedResponse = GetExternalNestedResponses[keyof GetExternalNestedResponses]; export type PostExternalNestedData = { /** * Request body using external nested object */ body?: ExternalNested; path?: never; query?: never; url: '/external-nested'; }; export type PostExternalNestedResponses = { /** * Response using external nested object */ 201: ExternalNested; }; export type PostExternalNestedResponse = PostExternalNestedResponses[keyof PostExternalNestedResponses]; export type GetExternalMixedData = { body?: never; headers?: { deep?: unknown; }; path: { id: unknown; }; query?: { uuid?: unknown; numeric?: unknown; }; url: '/external-mixed'; }; export type GetExternalMixedResponses = { /** * Response with array of external models */ 200: Array; }; export type GetExternalMixedResponse = GetExternalMixedResponses[keyof GetExternalMixedResponses]; export type PostExternalMixedData = { /** * Request body with mixed external properties */ body?: { id?: Id; name?: Name; uuid?: ExternalSharedModelWithUuid; deep?: Deep; }; path?: never; query?: never; url: '/external-mixed'; }; export type PostExternalMixedResponses = { /** * Response using external model */ 201: ExternalSharedModel; }; export type PostExternalMixedResponse = PostExternalMixedResponses[keyof PostExternalMixedResponses]; export type GetExternalArrayData = { body?: never; path?: never; query?: never; url: '/external-array'; }; export type GetExternalArrayResponses = { /** * Response with array of external models */ 200: Array; }; export type GetExternalArrayResponse = GetExternalArrayResponses[keyof GetExternalArrayResponses]; export type PostExternalArrayData = { body: Array; path?: never; query?: never; url: '/external-array'; }; export type PostExternalArrayResponses = { /** * Response with array of external models */ 201: Array; }; export type PostExternalArrayResponse = PostExternalArrayResponses[keyof PostExternalArrayResponses]; export type GetExternalUnionData = { body?: never; path?: never; query?: never; url: '/external-union'; }; export type GetExternalUnionResponses = { /** * Response with union of external types */ 200: unknown; }; export type PostExternalUnionData = { body: unknown; path?: never; query?: never; url: '/external-union'; }; export type PostExternalUnionResponses = { /** * Response with union of external types */ 201: unknown; }; export type GetExternalPropertiesByIdData = { body?: never; headers?: { deep?: unknown; }; path: { id: unknown; }; query?: { uuid?: unknown; }; url: '/external-properties/{id}'; }; export type GetExternalPropertiesByIdResponses = { 200: { id?: Id; name?: Name; uuid?: ExternalSharedModelWithUuid; deep?: Deep; numeric?: _1; }; }; export type GetExternalPropertiesByIdResponse = GetExternalPropertiesByIdResponses[keyof GetExternalPropertiesByIdResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postV1Foo } from './sdk.gen'; export type { ClientOptions, Foo, PostV1FooData, PostV1FooResponse, PostV1FooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client'; import { client } from './client.gen'; import type { PostV1FooData, PostV1FooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postV1Foo = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/v1/foo', ...options, headers: { 'Content-Type': null, ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/form-data/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type Foo = { status?: number; }; export type PostV1FooData = { body: { file: Blob | File; info: string; }; path?: never; query?: never; url: '/v1/foo'; }; export type PostV1FooResponses = { /** * OK */ 200: Foo; }; export type PostV1FooResponse = PostV1FooResponses[keyof PostV1FooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/@angular/common.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type HttpRequest, httpResource } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { client } from '../client.gen'; import type { Options } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; @Injectable({ providedIn: 'root' }) export class DefaultServiceRequests { public serviceWithEmptyTag(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/no+tag', ...options }); } public patchApiVbyApiVersionNoTag(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PATCH', url: '/api/v{api-version}/no+tag', ...options }); } public fooWow(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/no+tag', ...options }); } /** * Body should not be unknown * * Body should not be unknown */ public postApiVbyApiVersionBody(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/body', ...options }); } } @Injectable({ providedIn: 'root' }) export class SimpleServiceRequests { public deleteCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/simple', ...options }); } public getCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/simple', ...options }); } public headCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'HEAD', url: '/api/v{api-version}/simple', ...options }); } public optionsCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'OPTIONS', url: '/api/v{api-version}/simple', ...options }); } public patchCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PATCH', url: '/api/v{api-version}/simple', ...options }); } public postCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/simple', ...options }); } public putCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/simple', ...options }); } } @Injectable({ providedIn: 'root' }) export class DescriptionsServiceRequests { public callWithDescriptions(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/descriptions/', ...options }); } } @Injectable({ providedIn: 'root' }) export class ParametersServiceRequests { public callWithParameters(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); } public callWithWeirdParameterNames(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options }); } } @Injectable({ providedIn: 'root' }) export class DefaultsServiceRequests { public callWithDefaultParameters(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/defaults', ...options }); } public callWithDefaultOptionalParameters(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/defaults', ...options }); } public callToTestOrderOfParams(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/defaults', ...options }); } } @Injectable({ providedIn: 'root' }) export class DuplicateServiceRequests { public duplicateName(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName2(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName3(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName4(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/duplicate', ...options }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceRequests { public callWithNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/no-content', ...options }); } public callWithResponseAndNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); } } @Injectable({ providedIn: 'root' }) export class ResponseServiceRequests { public callWithResponseAndNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); } public callWithResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/response', ...options }); } public callWithDuplicateResponses(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/response', ...options }); } public callWithResponses(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/response', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags1ServiceRequests { public dummyA(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/a', ...options }); } public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags2ServiceRequests { public dummyA(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/a', ...options }); } public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags3ServiceRequests { public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class CollectionFormatServiceRequests { public collectionFormat(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/collectionFormat', ...options }); } } @Injectable({ providedIn: 'root' }) export class TypesServiceRequests { public types(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/types', ...options }); } } @Injectable({ providedIn: 'root' }) export class ComplexServiceRequests { public complexTypes(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/complex', ...options }); } } @Injectable({ providedIn: 'root' }) export class HeaderServiceRequests { public callWithResultFromHeader(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/header', ...options }); } } @Injectable({ providedIn: 'root' }) export class ErrorServiceRequests { public testErrorCode(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/error', ...options }); } } @Injectable({ providedIn: 'root' }) export class NonAsciiÆøåÆøÅöôêÊServiceRequests { public nonAsciiæøåÆøÅöôêÊ字符串(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); } } @Injectable({ providedIn: 'root' }) export class DefaultServiceResources { public serviceWithEmptyTag(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).serviceWithEmptyTag(opts) : undefined; }); } public patchApiVbyApiVersionNoTag(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).patchApiVbyApiVersionNoTag(opts) : undefined; }); } public fooWow(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).fooWow(opts) : undefined; }); } /** * Body should not be unknown * * Body should not be unknown */ public postApiVbyApiVersionBody(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).postApiVbyApiVersionBody(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class SimpleServiceResources { public deleteCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).deleteCallWithoutParametersAndResponse(opts) : undefined; }); } public getCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).getCallWithoutParametersAndResponse(opts) : undefined; }); } public headCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).headCallWithoutParametersAndResponse(opts) : undefined; }); } public optionsCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).optionsCallWithoutParametersAndResponse(opts) : undefined; }); } public patchCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).patchCallWithoutParametersAndResponse(opts) : undefined; }); } public postCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).postCallWithoutParametersAndResponse(opts) : undefined; }); } public putCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).putCallWithoutParametersAndResponse(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DescriptionsServiceResources { public callWithDescriptions(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DescriptionsServiceRequests).callWithDescriptions(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ParametersServiceResources { public callWithParameters(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).callWithParameters(opts) : undefined; }); } public callWithWeirdParameterNames(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).callWithWeirdParameterNames(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DefaultsServiceResources { public callWithDefaultParameters(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callWithDefaultParameters(opts) : undefined; }); } public callWithDefaultOptionalParameters(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callWithDefaultOptionalParameters(opts) : undefined; }); } public callToTestOrderOfParams(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callToTestOrderOfParams(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DuplicateServiceResources { public duplicateName(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName(opts) : undefined; }); } public duplicateName2(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName2(opts) : undefined; }); } public duplicateName3(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName3(opts) : undefined; }); } public duplicateName4(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName4(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceResources { public callWithNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NoContentServiceRequests).callWithNoContentResponse(opts) : undefined; }); } public callWithResponseAndNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NoContentServiceRequests).callWithResponseAndNoContentResponse(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ResponseServiceResources { public callWithResponseAndNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NoContentServiceRequests).callWithResponseAndNoContentResponse(opts) : undefined; }); } public callWithResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponse(opts) : undefined; }); } public callWithDuplicateResponses(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithDuplicateResponses(opts) : undefined; }); } public callWithResponses(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponses(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags1ServiceResources { public dummyA(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyA(opts) : undefined; }); } public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags2ServiceResources { public dummyA(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyA(opts) : undefined; }); } public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags3ServiceResources { public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class CollectionFormatServiceResources { public collectionFormat(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(CollectionFormatServiceRequests).collectionFormat(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class TypesServiceResources { public types(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(TypesServiceRequests).types(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ComplexServiceResources { public complexTypes(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ComplexServiceRequests).complexTypes(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class HeaderServiceResources { public callWithResultFromHeader(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(HeaderServiceRequests).callWithResultFromHeader(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ErrorServiceResources { public testErrorCode(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ErrorServiceRequests).testErrorCode(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class NonAsciiÆøåÆøÅöôêÊServiceResources { public nonAsciiæøåÆøÅöôêÊ字符串(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NonAsciiÆøåÆøÅöôêÊServiceRequests).nonAsciiæøåÆøÅöôêÊ字符串(opts) : undefined; }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@angular/common/default-class/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://api.example.com/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Business, Business2, Business3, Business4, Business5, Domains, Domains2, Domains3, Domains4, Locations, type Options, Providers, Providers2, Providers3, Providers4 } from './sdk.gen'; export type { BusinessGetData, BusinessGetResponse, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponse, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponse, BusinessProvidersDomainsPostResponses, ClientOptions, GetData, GetResponse, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponse, PutBusinessProvidersDomainsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { BusinessGetData, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponses, GetData, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class Domains { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers { static domains = Domains; } export class Business { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations/businesses', ...options }); } static providers = Providers; } export class Business2 { static business = Business; } export class Domains2 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers2 { static domains = Domains2; } export class Business3 { static providers = Providers2; } export class Providers3 { static business = Business3; } export class Domains3 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers4 { static domains = Domains3; } export class Business4 { static providers = Providers4; } export class Domains4 { public static putBusinessProvidersDomains(options?: Options) { return (options?.client ?? client).put({ url: '/business/providers/domains', ...options }); } static business = Business4; } export class Business5 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations/businesses', ...options }); } } export class Locations { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations', ...options }); } static business = Business5; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://api.example.com/v1' | (string & {}); }; export type BusinessProvidersDomainsGetData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsGetResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsGetResponse = BusinessProvidersDomainsGetResponses[keyof BusinessProvidersDomainsGetResponses]; export type BusinessProvidersDomainsPostData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsPostResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsPostResponse = BusinessProvidersDomainsPostResponses[keyof BusinessProvidersDomainsPostResponses]; export type PutBusinessProvidersDomainsData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type PutBusinessProvidersDomainsResponses = { /** * OK */ 200: string; }; export type PutBusinessProvidersDomainsResponse = PutBusinessProvidersDomainsResponses[keyof PutBusinessProvidersDomainsResponses]; export type BusinessGetData = { body?: never; path?: never; query?: never; url: '/locations/businesses'; }; export type BusinessGetResponses = { /** * OK */ 200: string; }; export type BusinessGetResponse = BusinessGetResponses[keyof BusinessGetResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/locations'; }; export type GetResponses = { /** * OK */ 200: string; }; export type GetResponse = GetResponses[keyof GetResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://api.example.com/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Business, Domains, NestedSdkWithInstance, type Options, Providers } from './sdk.gen'; export type { BusinessGetData, BusinessGetResponse, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponse, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponse, BusinessProvidersDomainsPostResponses, ClientOptions, GetData, GetResponse, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponse, PutBusinessProvidersDomainsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { BusinessGetData, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponses, GetData, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new NestedSdkWithInstance()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class Domains extends HeyApiClient { public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/business/providers/domains', ...options }); } public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/business/providers/domains', ...options }); } } export class Providers extends HeyApiClient { private _domains?: Domains; get domains(): Domains { return this._domains ??= new Domains({ client: this.client }); } } export class Business extends HeyApiClient { public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/locations/businesses', ...options }); } private _providers?: Providers; get providers(): Providers { return this._providers ??= new Providers({ client: this.client }); } } export class NestedSdkWithInstance extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); NestedSdkWithInstance.__registry.set(this, args?.key); } public putBusinessProvidersDomains(options?: Options) { return (options?.client ?? this.client).put({ url: '/business/providers/domains', ...options }); } public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/locations', ...options }); } private _business?: Business; get business(): Business { return this._business ??= new Business({ client: this.client }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://api.example.com/v1' | (string & {}); }; export type BusinessProvidersDomainsGetData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsGetResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsGetResponse = BusinessProvidersDomainsGetResponses[keyof BusinessProvidersDomainsGetResponses]; export type BusinessProvidersDomainsPostData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsPostResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsPostResponse = BusinessProvidersDomainsPostResponses[keyof BusinessProvidersDomainsPostResponses]; export type PutBusinessProvidersDomainsData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type PutBusinessProvidersDomainsResponses = { /** * OK */ 200: string; }; export type PutBusinessProvidersDomainsResponse = PutBusinessProvidersDomainsResponses[keyof PutBusinessProvidersDomainsResponses]; export type BusinessGetData = { body?: never; path?: never; query?: never; url: '/locations/businesses'; }; export type BusinessGetResponses = { /** * OK */ 200: string; }; export type BusinessGetResponse = BusinessGetResponses[keyof BusinessGetResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/locations'; }; export type GetResponses = { /** * OK */ 200: string; }; export type GetResponse = GetResponses[keyof GetResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/schemas/default/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const ExternalRefASchema = { description: 'External ref to shared model (A)', $ref: '#/definitions/ExternalSharedModel' } as const; export const ExternalRefBSchema = { description: 'External ref to shared model (B)', $ref: '#/definitions/ExternalSharedModel' } as const; export const CommentWithBreaksSchema = { description: 'Testing multiline comments in string: First line\nSecond line\n\nFourth line', type: 'integer' } as const; export const CommentWithBackticksSchema = { description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work', type: 'integer' } as const; export const CommentWithBackticksAndQuotesSchema = { description: 'Testing backticks and quotes in string: `backticks`, \'quotes\', "double quotes" and ```multiple backticks``` should work', type: 'integer' } as const; export const CommentWithSlashesSchema = { description: 'Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work', type: 'integer' } as const; export const CommentWithExpressionPlaceholdersSchema = { description: 'Testing expression placeholders in string: ${expression} should work', type: 'integer' } as const; export const CommentWithQuotesSchema = { description: 'Testing quotes in string: \'single quote\'\'\' and "double quotes""" should work', type: 'integer' } as const; export const CommentWithReservedCharactersSchema = { description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work', type: 'integer' } as const; export const SimpleIntegerSchema = { description: 'This is a simple number', type: 'integer' } as const; export const SimpleBooleanSchema = { description: 'This is a simple boolean', type: 'boolean' } as const; export const SimpleStringSchema = { description: 'This is a simple string', type: 'string' } as const; export const NonAsciiStringæøåÆØÅöôêÊ字符串Schema = { description: 'A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串)', type: 'string' } as const; export const SimpleFileSchema = { description: 'This is a simple file', format: 'binary', type: 'string' } as const; export const SimpleReferenceSchema = { description: 'This is a simple reference', $ref: '#/definitions/ModelWithString' } as const; export const SimpleStringWithPatternSchema = { description: 'This is a simple string', type: 'string', maxLength: 64, pattern: '^[a-zA-Z0-9_]*$' } as const; export const EnumWithStringsSchema = { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ] } as const; export const EnumWithNumbersSchema = { description: 'This is a simple enum with numbers', enum: [ 1, 2, 3, 1.1, 1.2, 1.3, 100, 200, 300, -100, -200, -300, -1.1, -1.2, -1.3 ] } as const; export const EnumFromDescriptionSchema = { description: 'Success=1,Warning=2,Error=3', type: 'number' } as const; export const EnumWithExtensionsSchema = { description: 'This is a simple enum with numbers', enum: [ 200, 400, 500 ], 'x-enum-varnames': [ 'CUSTOM_SUCCESS', 'CUSTOM_WARNING', 'CUSTOM_ERROR' ], 'x-enum-descriptions': [ 'Used when the status of something is successful', 'Used when the status of something has a warning', 'Used when the status of something has an error' ] } as const; export const ArrayWithNumbersSchema = { description: 'This is a simple array with numbers', type: 'array', items: { type: 'integer' } } as const; export const ArrayWithBooleansSchema = { description: 'This is a simple array with booleans', type: 'array', items: { type: 'boolean' } } as const; export const ArrayWithStringsSchema = { description: 'This is a simple array with strings', type: 'array', items: { type: 'string' } } as const; export const ArrayWithReferencesSchema = { description: 'This is a simple array with references', type: 'array', items: { $ref: '#/definitions/ModelWithString' } } as const; export const ArrayWithArraySchema = { description: 'This is a simple array containing an array', type: 'array', items: { type: 'array', items: { $ref: '#/definitions/ModelWithString' } } } as const; export const ArrayWithPropertiesSchema = { description: 'This is a simple array with properties', type: 'array', items: { type: 'object', properties: { foo: { type: 'string' }, bar: { type: 'string' } } } } as const; export const DictionaryWithStringSchema = { description: 'This is a string dictionary', type: 'object', additionalProperties: { type: 'string' } } as const; export const DictionaryWithReferenceSchema = { description: 'This is a string reference', type: 'object', additionalProperties: { $ref: '#/definitions/ModelWithString' } } as const; export const DictionaryWithArraySchema = { description: 'This is a complex dictionary', type: 'object', additionalProperties: { type: 'array', items: { $ref: '#/definitions/ModelWithString' } } } as const; export const DictionaryWithDictionarySchema = { description: 'This is a string dictionary', type: 'object', additionalProperties: { type: 'object', additionalProperties: { type: 'string' } } } as const; export const DictionaryWithPropertiesSchema = { description: 'This is a complex dictionary', type: 'object', additionalProperties: { type: 'object', properties: { foo: { type: 'string' }, bar: { type: 'string' } } } } as const; export const DateSchema = { description: 'This is a type-only model that defines Date as a string', type: 'string' } as const; export const ModelWithIntegerSchema = { description: 'This is a model with one number property', type: 'object', properties: { prop: { description: 'This is a simple number property', type: 'integer' } } } as const; export const ModelWithBooleanSchema = { description: 'This is a model with one boolean property', type: 'object', properties: { prop: { description: 'This is a simple boolean property', type: 'boolean' } } } as const; export const ModelWithStringSchema = { description: 'This is a model with one string property', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } } } as const; export const ModelWithStringErrorSchema = { description: 'This is a model with one string property', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } } } as const; export const ModelWithNullableStringSchema = { description: 'This is a model with one string property', type: 'object', required: [ 'nullableRequiredProp' ], properties: { nullableProp: { description: 'This is a simple string property', type: 'string', 'x-nullable': true }, nullableRequiredProp: { description: 'This is a simple string property', type: 'string', 'x-nullable': true } } } as const; export const ModelWithEnumSchema = { description: 'This is a model with one enum', type: 'object', properties: { test: { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ] }, statusCode: { description: 'These are the HTTP error code enums', enum: [ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ] }, bool: { description: 'Simple boolean enum', type: 'boolean', enum: [ true ] } } } as const; export const ModelWithEnumFromDescriptionSchema = { description: 'This is a model with one enum', type: 'object', properties: { test: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } } } as const; export const ModelWithNestedEnumsSchema = { description: 'This is a model with nested enums', type: 'object', properties: { dictionaryWithEnum: { type: 'object', additionalProperties: { enum: [ 'Success', 'Warning', 'Error' ] } }, dictionaryWithEnumFromDescription: { type: 'object', additionalProperties: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } }, arrayWithEnum: { type: 'array', items: { enum: [ 'Success', 'Warning', 'Error' ] } }, arrayWithDescription: { type: 'array', items: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } } } } as const; export const ModelWithReferenceSchema = { description: 'This is a model with one property containing a reference', type: 'object', properties: { prop: { $ref: '#/definitions/ModelWithProperties' } } } as const; export const ModelWithArraySchema = { description: 'This is a model with one property containing an array', type: 'object', properties: { prop: { type: 'array', items: { $ref: '#/definitions/ModelWithString' } }, propWithFile: { type: 'array', items: { format: 'binary', type: 'string' } }, propWithNumber: { type: 'array', items: { type: 'number' } } } } as const; export const ModelWithDictionarySchema = { description: 'This is a model with one property containing a dictionary', type: 'object', properties: { prop: { type: 'object', additionalProperties: { type: 'string' } } } } as const; export const ModelWithCircularReferenceSchema = { description: 'This is a model with one property containing a circular reference', type: 'object', properties: { prop: { $ref: '#/definitions/ModelWithCircularReference' } } } as const; export const ModelWithPropertiesSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'required', 'requiredAndReadOnly' ], properties: { required: { type: 'string' }, requiredAndReadOnly: { type: 'string', readOnly: true }, string: { type: 'string' }, number: { type: 'number' }, boolean: { type: 'boolean' }, reference: { $ref: '#/definitions/ModelWithString' }, 'property with space': { type: 'string' }, default: { type: 'string' }, try: { type: 'string' }, '@namespace.string': { type: 'string', readOnly: true }, '@namespace.integer': { type: 'integer', readOnly: true } } } as const; export const ModelWithNestedPropertiesSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'first' ], properties: { first: { type: 'object', required: [ 'second' ], readOnly: true, properties: { second: { type: 'object', required: [ 'third' ], readOnly: true, properties: { third: { type: 'string', readOnly: true } } } } } } } as const; export const ModelWithDuplicatePropertiesSchema = { description: 'This is a model with duplicated properties', type: 'object', properties: { prop: { $ref: '#/definitions/ModelWithString' } } } as const; export const ModelWithOrderedPropertiesSchema = { description: 'This is a model with ordered properties', type: 'object', properties: { zebra: { type: 'string' }, apple: { type: 'string' }, hawaii: { type: 'string' } } } as const; export const ModelWithDuplicateImportsSchema = { description: 'This is a model with duplicated imports', type: 'object', properties: { propA: { $ref: '#/definitions/ModelWithString' }, propB: { $ref: '#/definitions/ModelWithString' }, propC: { $ref: '#/definitions/ModelWithString' } } } as const; export const ModelThatExtendsSchema = { description: 'This is a model that extends another model', type: 'object', allOf: [ { $ref: '#/definitions/ModelWithString' }, { type: 'object', properties: { propExtendsA: { type: 'string' }, propExtendsB: { $ref: '#/definitions/ModelWithString' } } } ] } as const; export const ModelThatExtendsExtendsSchema = { description: 'This is a model that extends another model', type: 'object', allOf: [ { $ref: '#/definitions/ModelWithString' }, { $ref: '#/definitions/ModelThatExtends' }, { type: 'object', properties: { propExtendsC: { type: 'string' }, propExtendsD: { $ref: '#/definitions/ModelWithString' } } } ] } as const; export const defaultSchema = { type: 'object', properties: { name: { type: 'string' } } } as const; export const ModelWithPatternSchema = { description: 'This is a model that contains a some patterns', type: 'object', required: [ 'key', 'name' ], properties: { key: { maxLength: 64, pattern: '^[a-zA-Z0-9_]*$', type: 'string' }, name: { maxLength: 255, type: 'string' }, enabled: { type: 'boolean', readOnly: true }, modified: { type: 'string', format: 'date-time', readOnly: true }, id: { type: 'string', pattern: '^\\d{2}-\\d{3}-\\d{4}$' }, text: { type: 'string', pattern: '^\\w+$' }, patternWithSingleQuotes: { type: 'string', pattern: '^[a-zA-Z0-9\']*$' }, patternWithNewline: { type: 'string', pattern: 'aaa\\nbbb' }, patternWithBacktick: { type: 'string', pattern: 'aaa`bbb' }, patternWithUnicode: { type: 'string', pattern: '^\\p{L}+$' } } } as const; export const parameter_ActivityParamsSchema = { type: 'object', properties: { description: { type: 'string' }, graduate_id: { type: 'integer' }, organization_id: { type: 'integer' }, parent_activity: { type: 'integer' }, post_id: { type: 'integer' } } } as const; export const response_PostActivityResponseSchema = { type: 'object', properties: { description: { type: 'string' }, graduate_id: { type: 'integer' }, organization_id: { type: 'integer' }, parent_activity_id: { type: 'integer' }, post_id: { type: 'integer' } } } as const; export const failure_FailureSchema = { type: 'object', properties: { error: { type: 'string' }, message: { type: 'string' }, reference_code: { type: 'string' } } } as const; export const ExternalSharedModelSchema = { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: [ 'id' ] } as const; export const ModelWithReferenceWritableSchema = { description: 'This is a model with one property containing a reference', type: 'object', properties: { prop: { $ref: '#/definitions/ModelWithPropertiesWritable' } } } as const; export const ModelWithPropertiesWritableSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'required' ], properties: { required: { type: 'string' }, string: { type: 'string' }, number: { type: 'number' }, boolean: { type: 'boolean' }, reference: { $ref: '#/definitions/ModelWithString' }, 'property with space': { type: 'string' }, default: { type: 'string' }, try: { type: 'string' } } } as const; export const ModelWithPatternWritableSchema = { description: 'This is a model that contains a some patterns', type: 'object', required: [ 'key', 'name' ], properties: { key: { maxLength: 64, pattern: '^[a-zA-Z0-9_]*$', type: 'string' }, name: { maxLength: 255, type: 'string' }, id: { type: 'string', pattern: '^\\d{2}-\\d{3}-\\d{4}$' }, text: { type: 'string', pattern: '^\\w+$' }, patternWithSingleQuotes: { type: 'string', pattern: '^[a-zA-Z0-9\']*$' }, patternWithNewline: { type: 'string', pattern: 'aaa\\nbbb' }, patternWithBacktick: { type: 'string', pattern: 'aaa`bbb' }, patternWithUnicode: { type: 'string', pattern: '^\\p{L}+$' } } } as const; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Bar, Foo, type Options, Sdk } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new Sdk()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class Bar extends HeyApiClient { public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/foo/bar', ...options }); } public put(options?: Options) { return (options?.client ?? this.client).put({ url: '/foo/bar', ...options }); } } export class Foo extends HeyApiClient { public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/foo', ...options }); } public put(options?: Options) { return (options?.client ?? this.client).put({ url: '/foo', ...options }); } private _bar?: Bar; get bar(): Bar { return this._bar ??= new Bar({ client: this.client }); } } export class Sdk extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); Sdk.__registry.set(this, args?.key); } public getFoo(options?: Options) { return (options?.client ?? this.client).get({ url: '/foo', ...options }); } public getFooBar(options?: Options) { return (options?.client ?? this.client).get({ url: '/foo/bar', ...options }); } private _foo?: Foo; get foo(): Foo { return this._foo ??= new Foo({ client: this.client }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/instance/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base', throwOnError: true })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/sdk/throwOnError/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Baz, ClientOptions, PostFooReadData, PostFooReadResponse, PostFooReadResponses, QuxAllRead, ReadableBarRead, ReadableCorge, ReadableFooRead, ReadableQuux, WritableBarRead, WritableCorge, WritableFooRead, WritableQuux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type Baz = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type ReadableFooRead = ReadableBarRead & { readonly foo?: string; }; export type WritableFooRead = WritableBarRead; export type ReadableBarRead = Baz & { readonly bar?: string; }; export type WritableBarRead = Baz; export type ReadableQuux = { baz?: Array; qux?: QuxAllRead; }; export type WritableQuux = { baz?: Array; }; export type ReadableCorge = { foo?: string; bar?: { readonly baz?: boolean; }; }; export type WritableCorge = { foo?: string; }; export type PostFooReadData = { body: WritableFooRead; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: ReadableFooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BarRead, Baz, ClientOptions, Corge, FooRead, PostFooReadData, PostFooReadResponse, PostFooReadResponses, Quux, QuxAllRead } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type FooRead = BarRead & { readonly foo?: string; }; export type BarRead = Baz & { readonly bar?: string; }; export type Baz = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type Quux = { baz?: Array; qux?: QuxAllRead; }; export type Corge = { foo?: string; bar?: { readonly baz?: boolean; }; }; export type PostFooReadData = { body: FooRead; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: FooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/@pinia/colada.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'; import { serializeQueryKeyValue } from '../client'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; baseUrl?: _JSONValue; body?: _JSONValue; query?: _JSONValue; tags?: _JSONValue; } ]; const createQueryKey = (id: string, options?: TOptions, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (tags) { params.tags = tags as unknown as _JSONValue; } if (options?.body !== undefined) { const normalizedBody = serializeQueryKeyValue(options.body); if (normalizedBody !== undefined) { params.body = normalizedBody; } } if (options?.path) { params.path = options.path; } if (options?.query !== undefined) { const normalizedQuery = serializeQueryKeyValue(options.query); if (normalizedQuery !== undefined) { params.query = normalizedQuery; } } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooQuery = defineQueryOptions, GetFooResponse, Error>((options?: Options) => ({ key: getFooQueryKey(options), query: async (context) => { const { data } = await FooBazService.getFoo({ ...options, ...context, throwOnError: true }); return data; } })); export const fooPostMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await FooService.post({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooPutMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await FooService.put({ ...options, ...vars, throwOnError: true }); return data; } }); export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarQuery = defineQueryOptions, GetFooBarResponse, Error>((options?: Options) => ({ key: getFooBarQueryKey(options), query: async (context) => { const { data } = await BarBazService.getFooBar({ ...options, ...context, throwOnError: true }); return data; } })); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await BarService.post({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooBarPutMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await BarService.put({ ...options, ...vars, throwOnError: true }); return data; } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/@pinia/colada.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'; import { serializeQueryKeyValue } from '../client'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; baseUrl?: _JSONValue; body?: _JSONValue; query?: _JSONValue; tags?: _JSONValue; } ]; const createQueryKey = (id: string, options?: TOptions, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (tags) { params.tags = tags as unknown as _JSONValue; } if (options?.body !== undefined) { const normalizedBody = serializeQueryKeyValue(options.body); if (normalizedBody !== undefined) { params.body = normalizedBody; } } if (options?.path) { params.path = options.path; } if (options?.query !== undefined) { const normalizedQuery = serializeQueryKeyValue(options.query); if (normalizedQuery !== undefined) { params.query = normalizedQuery; } } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: serviceWithEmptyTagQueryKey(options), query: async (context) => { const { data } = await serviceWithEmptyTag({ ...options, ...context, throwOnError: true }); return data; } })); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooWowMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await fooWow({ ...options, ...vars, throwOnError: true }); return data; } }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: getCallWithoutParametersAndResponseQueryKey(options), query: async (context) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithDescriptions({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithParameters({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithWeirdParameterNames({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersQuery = defineQueryOptions, unknown, Error>((options: Options) => ({ key: callWithDefaultParametersQueryKey(options), query: async (context) => { const { data } = await callWithDefaultParameters({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...vars, throwOnError: true }); return data; } }); export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callToTestOrderOfParams({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Query = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: duplicateName2QueryKey(options), query: async (context) => { const { data } = await duplicateName2({ ...options, ...context, throwOnError: true }); return data; } })); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName3({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName4({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: callWithNoContentResponseQueryKey(options), query: async (context) => { const { data } = await callWithNoContentResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseQuery = defineQueryOptions, CallWithResponseAndNoContentResponseResponse, Error>((options?: Options) => ({ key: callWithResponseAndNoContentResponseQueryKey(options), query: async (context) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: dummyAQueryKey(options), query: async (context) => { const { data } = await dummyA({ ...options, ...context, throwOnError: true }); return data; } })); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: dummyBQueryKey(options), query: async (context) => { const { data } = await dummyB({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseQuery = defineQueryOptions, CallWithResponseResponse, Error>((options?: Options) => ({ key: callWithResponseQueryKey(options), query: async (context) => { const { data } = await callWithResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, CallWithDuplicateResponsesError> => ({ mutation: async (vars) => { const { data } = await callWithDuplicateResponses({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, CallWithResponsesError> => ({ mutation: async (vars) => { const { data } = await callWithResponses({ ...options, ...vars, throwOnError: true }); return data; } }); export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatQuery = defineQueryOptions, unknown, Error>((options: Options) => ({ key: collectionFormatQueryKey(options), query: async (context) => { const { data } = await collectionFormat({ ...options, ...context, throwOnError: true }); return data; } })); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesQuery = defineQueryOptions, TypesResponse, Error>((options: Options) => ({ key: typesQueryKey(options), query: async (context) => { const { data } = await types({ ...options, ...context, throwOnError: true }); return data; } })); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesQuery = defineQueryOptions, ComplexTypesResponse, Error>((options: Options) => ({ key: complexTypesQueryKey(options), query: async (context) => { const { data } = await complexTypes({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithResultFromHeader({ ...options, ...vars, throwOnError: true }); return data; } }); export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await testErrorCode({ ...options, ...vars, throwOnError: true }); return data; } }); export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...vars, throwOnError: true }); return data; } }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions, PostApiVbyApiVersionBodyError> => ({ mutation: async (vars) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...vars, throwOnError: true }); return data; } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@pinia/colada/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, useMutation, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePatchApiVbyApiVersionNoTagMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...patchApiVbyApiVersionNoTagMutation(), ...mutationOptions }); export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useFooWowMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...fooWowMutation(), ...mutationOptions }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDeleteCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...deleteCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePatchCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...patchCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePutCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...putCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDescriptionsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDescriptionsMutation(), ...mutationOptions }); export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithParametersMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithParametersMutation(), ...mutationOptions }); export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithWeirdParameterNamesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithWeirdParameterNamesMutation(), ...mutationOptions }); export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDefaultOptionalParametersMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDefaultOptionalParametersMutation(), ...mutationOptions }); export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallToTestOrderOfParamsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callToTestOrderOfParamsMutation(), ...mutationOptions }); export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateNameMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateNameMutation(), ...mutationOptions }); export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateName3Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateName3Mutation(), ...mutationOptions }); export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateName4Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateName4Mutation(), ...mutationOptions }); export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDuplicateResponsesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDuplicateResponsesMutation(), ...mutationOptions }); export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithResponsesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithResponsesMutation(), ...mutationOptions }); export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithResultFromHeaderMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithResultFromHeaderMutation(), ...mutationOptions }); export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useTestErrorCodeMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...testErrorCodeMutation(), ...mutationOptions }); export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useNonAsciiæøåÆøÅöôêÊ字符串Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...nonAsciiæøåÆøÅöôêÊ字符串Mutation(), ...mutationOptions }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const usePostApiVbyApiVersionBodyMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postApiVbyApiVersionBodyMutation(), ...mutationOptions }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: serviceWithEmptyTagQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArrayCSV: { array: { explode: false } }, parameterArraySSV: { array: { explode: false } }, parameterArrayTSV: { array: { explode: false } }, parameterArrayPipes: { array: { explode: false } } } }, url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/types', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Body should not be unknown * * Body should not be unknown */ export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/body', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/fastify/default/fastify.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { RouteHandler } from 'fastify'; import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseResponses, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DummyAResponses, DummyBResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; export type RouteHandlers = { callWithDescriptions: RouteHandler<{ Querystring?: CallWithDescriptionsData['query']; }>; callWithParameters: RouteHandler<{ Headers: CallWithParametersData['headers']; Params: CallWithParametersData['path']; Querystring: CallWithParametersData['query']; }>; callWithWeirdParameterNames: RouteHandler<{ Body: CallWithWeirdParameterNamesData['body']; Headers: CallWithWeirdParameterNamesData['headers']; Params: CallWithWeirdParameterNamesData['path']; Querystring: CallWithWeirdParameterNamesData['query']; }>; callWithDefaultParameters: RouteHandler<{ Querystring: CallWithDefaultParametersData['query']; }>; callWithDefaultOptionalParameters: RouteHandler<{ Querystring?: CallWithDefaultOptionalParametersData['query']; }>; callToTestOrderOfParams: RouteHandler<{ Querystring: CallToTestOrderOfParamsData['query']; }>; callWithNoContentResponse: RouteHandler<{ Reply: CallWithNoContentResponseResponses; }>; callWithResponseAndNoContentResponse: RouteHandler<{ Reply: CallWithResponseAndNoContentResponseResponses; }>; dummyA: RouteHandler<{ Reply: DummyAResponses; }>; dummyB: RouteHandler<{ Reply: DummyBResponses; }>; callWithDuplicateResponses: RouteHandler<{ Reply: Omit & CallWithDuplicateResponsesResponses; }>; callWithResponses: RouteHandler<{ Reply: Omit & CallWithResponsesResponses; }>; collectionFormat: RouteHandler<{ Querystring: CollectionFormatData['query']; }>; types: RouteHandler<{ Params?: TypesData['path']; Querystring: TypesData['query']; Reply: TypesResponses; }>; complexTypes: RouteHandler<{ Querystring: ComplexTypesData['query']; Reply: ComplexTypesErrors & ComplexTypesResponses; }>; callWithResultFromHeader: RouteHandler<{ Reply: CallWithResultFromHeaderErrors & CallWithResultFromHeaderResponses; }>; testErrorCode: RouteHandler<{ Querystring: TestErrorCodeData['query']; Reply: TestErrorCodeErrors & TestErrorCodeResponses; }>; nonAsciiæøåÆøÅöôêÊ字符串: RouteHandler<{ Querystring: NonAsciiæøåÆøÅöôêÊ字符串Data['query']; Reply: NonAsciiæøåÆøÅöôêÊ字符串Responses; }>; postApiVbyApiVersionBody: RouteHandler<{ Body: PostApiVbyApiVersionBodyData['body']; Reply: PostApiVbyApiVersionBodyErrors & PostApiVbyApiVersionBodyResponses; }>; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/fastify/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/fastify/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/ref-deep/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo, GetFooData, GetFooResponses, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/ref-deep/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type Foo = { foo?: Array<{ baz?: string; }>; bar?: Array<{ baz?: string; }>; }; export type Bar = { foo?: Array<{ baz?: string; }>; bar?: Array<{ baz?: string; }>; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, sendEmail } from './sdk.gen'; export type { Attachment, AttachmentCollection, ClientOptions, HeaderCollection, MessageHeader, SendEmailData, SendEmailError, SendEmailErrors, SendEmailRequest, SendEmailResponse, SendEmailResponse2, SendEmailResponses, StandardPostmarkResponse } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { SendEmailData, SendEmailErrors, SendEmailResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Send a single email */ export const sendEmail = (options: Options) => (options.client ?? client).post({ url: '/email', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/schema-unknown/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://api.postmarkapp.com` | (string & {}); }; export type SendEmailRequest = { /** * The sender email address. Must have a registered and confirmed Sender Signature. */ From?: string; /** * Recipient email address. Multiple addresses are comma seperated. Max 50. */ To?: string; /** * Recipient email address. Multiple addresses are comma seperated. Max 50. */ Cc?: string; /** * Bcc recipient email address. Multiple addresses are comma seperated. Max 50. */ Bcc?: string; /** * Email Subject */ Subject?: string; /** * Email tag that allows you to categorize outgoing emails and get detailed statistics. */ Tag?: string; /** * If no TextBody specified HTML email message */ HtmlBody?: string; /** * If no HtmlBody specified Plain text email message */ TextBody?: string; /** * Reply To override email address. Defaults to the Reply To set in the sender signature. */ ReplyTo?: string; /** * Activate open tracking for this email. */ TrackOpens?: boolean; /** * Replace links in content to enable "click tracking" stats. Default is 'null', which uses the server's LinkTracking setting'. */ TrackLinks?: 'None' | 'HtmlAndText' | 'HtmlOnly' | 'TextOnly'; Headers?: HeaderCollection; Attachments?: AttachmentCollection; }; /** * A single header for an email message. */ export type MessageHeader = { /** * The header's name. */ Name?: string; /** * The header's value. */ Value?: string; }; export type HeaderCollection = Array; /** * An attachment for an email message. */ export type Attachment = { Name?: string; Content?: string; ContentType?: string; ContentID?: string; }; export type AttachmentCollection = Array; /** * The standard response when a postmark message is sent */ export type SendEmailResponse = { To?: string; SubmittedAt?: string; MessageID?: string; ErrorCode?: number; Message?: string; }; /** * A Postmark API error. */ export type StandardPostmarkResponse = { ErrorCode?: number; Message?: string; }; export type SendEmailData = { body?: SendEmailRequest; headers: { /** * The token associated with the Server on which this request will operate. */ 'X-Postmark-Server-Token': string; }; path?: never; query?: never; url: '/email'; }; export type SendEmailErrors = { /** * An error was generated due to incorrect use of the API. See the Message associated with this response for more information. */ 422: StandardPostmarkResponse; /** * Indicates an internal server error occurred. */ 500: unknown; }; export type SendEmailError = SendEmailErrors[keyof SendEmailErrors]; export type SendEmailResponses = { /** * OK */ 200: SendEmailResponse; }; export type SendEmailResponse2 = SendEmailResponses[keyof SendEmailResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ in: 'query', name: 'foo', type: 'apiKey' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-api-key/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'basic', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-basic/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/security-oauth2/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://foo.com/v1' | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: '/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-base-path/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}/v1` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/servers-host/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://foo.com` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BarRead, BarReadWritable, Baz, ClientOptions, Corge, CorgeWritable, FooRead, FooReadWritable, PostFooReadData, PostFooReadResponse, PostFooReadResponses, Quux, QuuxWritable, QuxAllRead } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-read-write/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type FooRead = BarRead & { readonly foo?: string; }; export type BarRead = Baz & { readonly bar?: string; }; export type Baz = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type Quux = { baz?: Array; qux?: QuxAllRead; }; export type Corge = { foo?: string; bar?: { readonly baz?: boolean; }; }; export type FooReadWritable = BarReadWritable; export type BarReadWritable = Baz; export type QuuxWritable = { baz?: Array; }; export type CorgeWritable = { foo?: string; }; export type PostFooReadData = { body: FooReadWritable; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: FooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-schemas-name/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Comment, GetUsersData, GetUsersResponse, GetUsersResponses, Post, PostPostsData, PostPostsResponse, PostPostsResponses, User, UserProfile } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/transforms-schemas-name/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type User = { id?: string; name?: string; profile?: UserProfile; }; export type UserProfile = { bio?: string; avatar?: string; }; export type Post = { id?: string; title?: string; author?: User; comments?: Array; }; export type Comment = { id?: string; text?: string; author?: User; }; export type GetUsersData = { body?: never; path?: never; query?: never; url: '/users'; }; export type GetUsersResponses = { /** * Success */ 200: User; }; export type GetUsersResponse = GetUsersResponses[keyof GetUsersResponses]; export type PostPostsData = { body?: Post; path?: never; query?: never; url: '/posts'; }; export type PostPostsResponses = { /** * Created */ 201: Post; }; export type PostPostsResponse = PostPostsResponses[keyof PostPostsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/additional-properties-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/additional-properties-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: string; }; export type Bar = Foo & {}; export type Baz = Foo & { bar: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/additional-properties-true/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/additional-properties-true/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: string; [key: string]: unknown; }; export type Bar = Foo & { [key: string]: unknown; }; export type Baz = Foo & { bar: string; [key: string]: unknown; }; export type Qux = { [key: string]: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/additional-properties-undefined/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/additional-properties-undefined/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: { [key: string]: unknown; }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/array-items-one-of-length-1/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/array-items-one-of-length-1/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: Array; }; export type Bar = string; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/array-nested-one-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/array-nested-one-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = Array<{ foo?: string; bar?: string; } | { baz?: string; qux?: string; }> | Array<{ foo?: string; bar?: string; }>; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, uploadBinary, uploadPdf, uploadZip } from './sdk.gen'; export type { ClientOptions, UploadBinaryData, UploadBinaryResponse, UploadBinaryResponses, UploadPdfData, UploadPdfResponse, UploadPdfResponses, UploadZipData, UploadZipResponse, UploadZipResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { UploadBinaryData, UploadBinaryResponses, UploadPdfData, UploadPdfResponses, UploadZipData, UploadZipResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Upload a zip file */ export const uploadZip = (options: Options) => (options.client ?? client).post({ bodySerializer: null, url: '/upload-zip', ...options, headers: { 'Content-Type': 'application/zip', ...options.headers } }); /** * Upload a PDF file */ export const uploadPdf = (options: Options) => (options.client ?? client).post({ bodySerializer: null, url: '/upload-pdf', ...options, headers: { 'Content-Type': 'application/pdf', ...options.headers } }); /** * Upload binary data */ export const uploadBinary = (options: Options) => (options.client ?? client).post({ bodySerializer: null, url: '/upload-binary', ...options, headers: { 'Content-Type': 'application/octet-stream', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-binary-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type UploadZipData = { body: Blob | File; path?: never; query?: never; url: '/upload-zip'; }; export type UploadZipResponses = { /** * Successfully uploaded */ 204: void; }; export type UploadZipResponse = UploadZipResponses[keyof UploadZipResponses]; export type UploadPdfData = { body: Blob | File; path?: never; query?: never; url: '/upload-pdf'; }; export type UploadPdfResponses = { /** * Successfully uploaded */ 204: void; }; export type UploadPdfResponse = UploadPdfResponses[keyof UploadPdfResponses]; export type UploadBinaryData = { body: Blob | File; path?: never; query?: never; url: '/upload-binary'; }; export type UploadBinaryResponses = { /** * Successfully uploaded */ 204: void; }; export type UploadBinaryResponse = UploadBinaryResponses[keyof UploadBinaryResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { ClientOptions, PostFooData, PostFooResponse, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options: Options) => (options.client ?? client).post({ bodySerializer: null, url: '/foo', ...options, headers: { 'Content-Type': 'text/plain', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/body-response-text-plain/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PostFooData = { body: string; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: string; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, ClientOptions, Foo, FooBar, FooBar2, FooBar3, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type Foo = { /** * original name: fooBar */ fooBar: FooBar; /** * original name: BarBaz */ BarBaz: Foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: FooBar2; /** * original name: BarBaz */ BarBaz: FooBar3; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type FooBar = boolean; /** * original name: fooBar */ export type FooBar2 = number; /** * original name: FooBar */ export type FooBar3 = string; export type GetFooData = { body: Foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Foo; /** * OK */ 201: _201; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, clientOptions, foo, fooBar, fooBar2, fooBar3, getFooData, getFooResponse, getFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type clientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type foo = { /** * original name: fooBar */ fooBar: fooBar; /** * original name: BarBaz */ BarBaz: foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: fooBar2; /** * original name: BarBaz */ BarBaz: fooBar3; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type fooBar = boolean; /** * original name: fooBar */ export type fooBar2 = number; /** * original name: FooBar */ export type fooBar3 = string; export type getFooData = { body: foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type getFooResponses = { /** * OK */ 200: foo; /** * OK */ 201: _201; }; export type getFooResponse = getFooResponses[keyof getFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, ClientOptions, Foo, foo_bar, fooBar, FooBar, getFooData, getFooResponse, getFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type Foo = { /** * original name: fooBar */ fooBar: foo_bar; /** * original name: BarBaz */ BarBaz: Foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: fooBar; /** * original name: BarBaz */ BarBaz: FooBar; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type foo_bar = boolean; /** * original name: fooBar */ export type fooBar = number; /** * original name: FooBar */ export type FooBar = string; export type getFooData = { body: Foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type getFooResponses = { /** * OK */ 200: Foo; /** * OK */ 201: _201; }; export type getFooResponse = getFooResponses[keyof getFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, client_options, foo, foo_bar, foo_bar2, foo_bar3, get_foo_data, get_foo_response, get_foo_responses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/case-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type client_options = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type foo = { /** * original name: fooBar */ fooBar: foo_bar; /** * original name: BarBaz */ BarBaz: foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: foo_bar2; /** * original name: BarBaz */ BarBaz: foo_bar3; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type foo_bar = boolean; /** * original name: fooBar */ export type foo_bar2 = number; /** * original name: FooBar */ export type foo_bar3 = string; export type get_foo_data = { body: foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type get_foo_responses = { /** * OK */ 200: foo; /** * OK */ 201: _201; }; export type get_foo_response = get_foo_responses[keyof get_foo_responses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/components-request-bodies/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/components-request-bodies/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * Foo */ export type Foo = { page?: number; }; export type PostFooData = { /** * Foo */ body: Foo; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-binary/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetBarData, GetBarResponse, GetBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-binary/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type GetBarData = { body?: never; path?: never; query?: never; url: '/bar'; }; export type GetBarResponses = { 200: Blob | File; }; export type GetBarResponse = GetBarResponses[keyof GetBarResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/content-types/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-all-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, BarMapped, BarUnion, Baz, BazMapped, BazUnion, ClientOptions, Foo, FooMapped, FooUnion, Qux, QuxExtend, QuxMapped } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-all-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { id: string; }; export type Bar = Omit & { bar?: string; id: 'Bar'; }; export type Baz = Omit & { baz?: string; id: 'Baz'; }; export type Qux = Omit & { qux?: boolean; id: 'Qux'; }; export type FooMapped = { id: string; }; export type BarMapped = Omit & { bar?: string; id: 'bar'; }; export type BazMapped = Omit & { baz?: string; id: 'baz'; }; export type QuxMapped = Omit & { qux?: boolean; id: 'QuxMapped'; }; export type FooUnion = ({ id: 'bar'; } & BarUnion) | ({ id: 'baz'; } & BazUnion); export type BarUnion = { id?: string; bar?: string; }; export type BazUnion = { id?: string; baz?: string; }; export type QuxExtend = FooUnion; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-allof-inline/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, GetFoosData, GetFoosResponse, GetFoosResponses, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-allof-inline/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { $type: string; foo?: string; }; export type Bar = Omit & { $type: 'FooBar'; bar?: string; }; export type Baz = Omit & { baz?: string; $type: 'FooBaz'; }; export type Qux = Omit & { qux?: string; $type: 'BarQux'; }; export type GetFoosData = { body?: never; path?: never; query?: never; url: '/foos'; }; export type GetFoosResponses = { /** * OK */ 200: Bar | Baz | Qux; }; export type GetFoosResponse = GetFoosResponses[keyof GetFoosResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-allof-nested/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { CarDto, ClientOptions, GetCarsData, GetCarsResponse, GetCarsResponses, VehicleDto, VolvoDto } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-allof-nested/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type VehicleDto = { $type: string; id: number; }; export type CarDto = Omit & { modelName: string; $type: 'Car'; }; export type VolvoDto = Omit & { seatbeltCount: number; $type: 'Volvo'; }; export type GetCarsData = { body?: never; path?: never; query?: never; url: '/cars'; }; export type GetCarsResponses = { /** * List of cars */ 200: Array; }; export type GetCarsResponse = GetCarsResponses[keyof GetCarsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-any-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Quux, Quuz, Qux, Spæcial } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-any-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ type?: 'Bar'; } & Bar) | ({ type?: 'Baz'; } & Baz); export type Baz = Qux; export type Bar = Qux; export type Spæcial = Qux; export type Qux = { id: string; type: Quux; }; export type Quux = 'Bar' | 'Baz'; export type Quuz = ({ type?: 'bar'; } & Bar) | ({ type?: 'baz'; } & Baz) | ({ type?: 'non-ascii'; } & Spæcial); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-mapped-many/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Spæcial } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-mapped-many/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ foo: 'one' | 'two'; } & Bar) | ({ foo: 'three'; } & Baz) | ({ foo: 'four'; } & Spæcial); export type Bar = { foo?: 'one' | 'two'; }; export type Baz = { foo?: 'three'; }; export type Spæcial = { foo?: 'four'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-non-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { AutoConfig, BooleanAnyOf, BooleanOneOf, ClientOptions, CustomConfig, IntegerAllOfBase, IntegerAllOfChildA, IntegerAllOfChildB, IntegerOneOf, NumberOneOf, TypeOne, TypeTwo, VersionAlpha, VersionBeta } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-non-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type BooleanOneOf = ({ use_custom: false; } & AutoConfig) | ({ use_custom: true; } & CustomConfig); export type AutoConfig = { use_custom: boolean; auto_setting: string; }; export type CustomConfig = { use_custom: boolean; custom_value: number; }; export type BooleanAnyOf = ({ use_custom?: false; } & AutoConfig) | ({ use_custom?: true; } & CustomConfig); export type IntegerOneOf = ({ type_id: 1; } & TypeOne) | ({ type_id: 2; } & TypeTwo); export type TypeOne = { type_id: number; one_data: string; }; export type TypeTwo = { type_id: number; two_data: string; }; export type NumberOneOf = ({ version: 1; } & VersionAlpha) | ({ version: 2.5; } & VersionBeta); export type VersionAlpha = { version: number; alpha_field: string; }; export type VersionBeta = { version: number; beta_field: string; }; export type IntegerAllOfBase = { kind: number; }; export type IntegerAllOfChildA = Omit & { child_a_field: string; kind: 1; }; export type IntegerAllOfChildB = Omit & { child_b_field: string; kind: 2; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-object-self-mapped/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BlogPostDto, BlogPostWithImageDto, ClientOptions, GetBlogPostsData, GetBlogPostsResponse, GetBlogPostsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-object-self-mapped/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type BlogPostDto = { $type: 'BlogPost'; id: number; title: string; }; export type BlogPostWithImageDto = Omit & { imageUrl: string; $type: 'BlogPostWithImage'; }; export type GetBlogPostsData = { body?: never; path?: never; query?: never; url: '/blog-posts'; }; export type GetBlogPostsResponses = { /** * List of blog posts */ 200: Array; }; export type GetBlogPostsResponse = GetBlogPostsResponses[keyof GetBlogPostsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-one-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Quux, Quuz, Qux, Spæcial } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/discriminator-one-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ type: 'Bar'; } & Bar) | ({ type: 'Baz'; } & Baz); export type Baz = Qux; export type Bar = Qux; export type Spæcial = Qux; export type Qux = { id: string; type: Quux; }; export type Quux = 'Bar' | 'Baz'; export type Quuz = ({ type: 'bar'; } & Bar) | ({ type: 'baz'; } & Baz) | ({ type: 'non-ascii'; } & Spæcial); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-escape/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-escape/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: 'foo\'bar' | 'foo"bar'; }; export type Bar = 'foo\'bar' | 'foo"bar'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export type TypeEnum = 'foo' | 'bar' | 'FooBar' | 'fooBar' | 'foo bar'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-javascript/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type ClientOptions, type Foo, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-javascript/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export const TypeEnum = { FOO: 'foo', BAR: 'bar', FOO_BAR: 'FooBar', FOO_BAR2: 'fooBar', FOO_BAR3: 'foo bar' } as const; export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-name-resolver/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type ClientOptions, type Foo, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-name-resolver/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export const TypeEnum = { FOO: 'foo', BAR: 'bar', FOO_BAR: 'FooBar', FOO_BAR_N2: 'fooBar', FOO_BAR_N3: 'foo bar' } as const; export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-name-resolver-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type ClientOptions, type Foo, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-name-resolver-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export const TypeEnum = { FOO: 'foo', BAR: 'bar', FOO_BAR: 'FooBar', FOO_BAR2: 'fooBar', FOO_BAR3: 'foo bar' } as const; export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-typescript/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type ClientOptions, type Foo, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-inline-typescript/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export enum TypeEnum { FOO = 'foo', BAR = 'bar', FOO_BAR = 'FooBar', FOO_BAR2 = 'fooBar', FOO_BAR3 = 'foo bar' } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _110, Arrays, ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type _110 = '1-10' | '11-20'; export type MyFoo = 'myFoo' | 'myBar'; export type MyFoo2 = 'MyFoo' | 'MyBar'; export type Foo = 'foo' | 'bar' | null | '' | true | false; export type Numbers = 100 | 200 | 300 | -100 | -200 | -300; export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { 110: '1-10', 1120: '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { MyFoo: 'myFoo', MyBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { Foo: 'foo', Bar: 'bar', Null: null, '': '', True: true, False: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-SCREAMING_SNAKE_CASE/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-SCREAMING_SNAKE_CASE/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1_10': '1-10', '11_20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { MY_FOO: 'myFoo', MY_BAR: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MY_FOO: 'MyFoo', MY_BAR: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { FOO: 'foo', BAR: 'bar', NULL: null, '': '', TRUE: true, FALSE: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { 110: '1-10', 1120: '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { myFoo: 'MyFoo', myBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', null: null, '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-ignore-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-ignore-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1-10': '1-10', '11-20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1-10': '1-10', '11-20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', null: null, '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-javascript-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1_10': '1-10', '11_20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { my_foo: 'myFoo', my_bar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { my_foo: 'MyFoo', my_bar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', null: null, '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { _110 = '1-10', _1120 = '11-20' } export enum MyFoo { MyFoo = 'myFoo', MyBar = 'myBar' } export enum MyFoo2 { MyFoo = 'MyFoo', MyBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-SCREAMING_SNAKE_CASE/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-SCREAMING_SNAKE_CASE/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { '1_10' = '1-10', '11_20' = '11-20' } export enum MyFoo { MY_FOO = 'myFoo', MY_BAR = 'myBar' } export enum MyFoo2 { MY_FOO = 'MyFoo', MY_BAR = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { _110 = '1-10', _1120 = '11-20' } export enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export enum MyFoo2 { myFoo = 'MyFoo', myBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-const/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-const/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const enum _110 { _110 = '1-10', _1120 = '11-20' } export const enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export const enum MyFoo2 { myFoo = 'MyFoo', myBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export const enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { '1-10' = '1-10', '11-20' = '11-20' } export enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export enum MyFoo2 { MyFoo = 'MyFoo', MyBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-names-values-typescript-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { '1_10' = '1-10', '11_20' = '11-20' } export enum MyFoo { my_foo = 'myFoo', my_bar = 'myBar' } export enum MyFoo2 { my_foo = 'MyFoo', my_bar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/enum-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = 'foo' | 'bar' | null; export type Bar = 'foo' | 'bar'; export type Baz = 'foo' | 'bar'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/exclude-deprecated/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/exclude-deprecated/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = string; export type PostFooData = { body: Foo; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/external/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _1, ClientOptions, Deep, ExternalAllOfSchema, ExternalAnyOfSchema, ExternalArraySchema, ExternalDeepParam, ExternalDoubleNestedNumeric, ExternalDoubleNestedProp, ExternalIdParam, ExternalMixedBody, ExternalMixedProperties, ExternalModelBody, ExternalNested, ExternalNestedBody, ExternalNestedNumeric, ExternalNestedNumericObjectA, ExternalNestedNumericObjectB, ExternalNestedObjectA, ExternalNestedObjectB, ExternalNumericParam, ExternalSchemaA, ExternalSchemaB, ExternalSchemaC, ExternalSchemaExternalProp, ExternalSchemaExternalPropAlias, ExternalSchemaPathA, ExternalSchemaPathB, ExternalSchemaPropertyA, ExternalSchemaPropertyB, ExternalSchemaPropertyC, ExternalSchemaPropertyD, ExternalSharedModel, ExternalSharedModelWithUuid, ExternalUnionSchema, ExternalUuidBody, ExternalUuidParam, GetExternalArrayData, GetExternalArrayResponse, GetExternalArrayResponses, GetExternalMixedData, GetExternalMixedResponse, GetExternalMixedResponses, GetExternalModelData, GetExternalModelError, GetExternalModelErrors, GetExternalModelResponse, GetExternalModelResponses, GetExternalNestedData, GetExternalNestedResponse, GetExternalNestedResponses, GetExternalPropertiesByIdData, GetExternalPropertiesByIdResponse, GetExternalPropertiesByIdResponses, GetExternalUnionData, GetExternalUnionResponse, GetExternalUnionResponses, GetExternalUuidData, GetExternalUuidResponse, GetExternalUuidResponses, Id, Name, PostExternalArrayData, PostExternalArrayResponse, PostExternalArrayResponses, PostExternalMixedData, PostExternalMixedResponse, PostExternalMixedResponses, PostExternalModelData, PostExternalModelError, PostExternalModelErrors, PostExternalModelResponse, PostExternalModelResponses, PostExternalNestedData, PostExternalNestedResponse, PostExternalNestedResponses, PostExternalUnionData, PostExternalUnionResponse, PostExternalUnionResponses, PutExternalUuidData, PutExternalUuidResponse, PutExternalUuidResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/external/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type _1 = string; export type ExternalSchemaA = ExternalSharedModel; export type ExternalSchemaB = ExternalSharedModel; export type ExternalSchemaC = ExternalSharedModel; export type ExternalSchemaPathA = ExternalSharedModel; export type ExternalSchemaPathB = ExternalSharedModel; /** * External schema property (A) */ export type ExternalSchemaPropertyA = { uuid1?: ExternalSharedModelWithUuid; }; /** * External schema property (B) - second use of UUID */ export type ExternalSchemaPropertyB = { uuid2?: ExternalSharedModelWithUuid; }; /** * External schema property (C) - third use of UUID */ export type ExternalSchemaPropertyC = { uuid3?: ExternalSharedModelWithUuid; }; /** * External schema property with duplicate refs (D) */ export type ExternalSchemaPropertyD = { uuid4?: ExternalSharedModelWithUuid; uuid5?: ExternalSharedModelWithUuid; }; /** * External schema property via external property ref (id) */ export type ExternalSchemaExternalProp = { id3?: Id; id4?: Id; }; /** * Alias to external property via component property ref */ export type ExternalSchemaExternalPropAlias = { id5?: Id; id6?: Id; }; /** * External double nested prop via property ref */ export type ExternalDoubleNestedProp = { deep1?: Deep; deep2?: Deep; }; /** * External double nested numeric properties */ export type ExternalDoubleNestedNumeric = { numeric1?: _1; numeric2?: _1; }; export type ExternalNestedObjectA = ExternalNested; export type ExternalNestedObjectB = ExternalNested; export type ExternalNestedNumericObjectA = ExternalNestedNumeric; export type ExternalNestedNumericObjectB = ExternalNestedNumeric; /** * Mixed external property references */ export type ExternalMixedProperties = { id7?: Id; name1?: Name; uuid6?: ExternalSharedModelWithUuid; deep3?: Deep; numeric3?: _1; }; /** * Array containing external references */ export type ExternalArraySchema = { items?: Array; uuidItems?: Array; }; /** * Union type with external references */ export type ExternalUnionSchema = ExternalSharedModel | ExternalSharedModelWithUuid; /** * AllOf with external references */ export type ExternalAllOfSchema = ExternalSharedModel & { additional?: ExternalSharedModelWithUuid; }; /** * AnyOf with external references */ export type ExternalAnyOfSchema = ExternalNested | ExternalNestedNumeric; export type ExternalNested = { inner?: { deep?: string; }; }; export type Deep = string; export type ExternalNestedNumeric = { 0?: { 1?: string; }; }; export type ExternalSharedModel = { id: string; name?: string; }; export type Id = string; export type Name = string; export type ExternalSharedModelWithUuid = string; export type ExternalIdParam = Id; export type ExternalUuidParam = ExternalSharedModelWithUuid; export type ExternalDeepParam = Deep; export type ExternalNumericParam = _1; export type ExternalModelBody = ExternalSharedModel; export type ExternalUuidBody = ExternalSharedModelWithUuid; export type ExternalNestedBody = ExternalNested; /** * Request body with mixed external properties */ export type ExternalMixedBody = { id?: Id; name?: Name; uuid?: ExternalSharedModelWithUuid; deep?: Deep; }; export type GetExternalModelData = { body?: never; path: { id: Id; }; query?: { uuid?: ExternalSharedModelWithUuid; }; url: '/external-model'; }; export type GetExternalModelErrors = { /** * Response using external UUID */ 400: ExternalSharedModelWithUuid; }; export type GetExternalModelError = GetExternalModelErrors[keyof GetExternalModelErrors]; export type GetExternalModelResponses = { /** * Response using external model */ 200: ExternalSharedModel; }; export type GetExternalModelResponse = GetExternalModelResponses[keyof GetExternalModelResponses]; export type PostExternalModelData = { /** * Request body using external model */ body: ExternalModelBody; path?: never; query?: never; url: '/external-model'; }; export type PostExternalModelErrors = { /** * Response with union of external types */ 422: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; }; export type PostExternalModelError = PostExternalModelErrors[keyof PostExternalModelErrors]; export type PostExternalModelResponses = { /** * Response using external model */ 201: ExternalSharedModel; }; export type PostExternalModelResponse = PostExternalModelResponses[keyof PostExternalModelResponses]; export type GetExternalUuidData = { body?: never; path?: never; query?: { uuid?: ExternalSharedModelWithUuid; }; url: '/external-uuid'; }; export type GetExternalUuidResponses = { /** * Response using external UUID */ 200: ExternalSharedModelWithUuid; }; export type GetExternalUuidResponse = GetExternalUuidResponses[keyof GetExternalUuidResponses]; export type PutExternalUuidData = { /** * Request body using external UUID */ body?: ExternalUuidBody; path?: never; query?: never; url: '/external-uuid'; }; export type PutExternalUuidResponses = { /** * Response using external UUID */ 200: ExternalSharedModelWithUuid; }; export type PutExternalUuidResponse = PutExternalUuidResponses[keyof PutExternalUuidResponses]; export type GetExternalNestedData = { body?: never; headers?: { deep?: Deep; }; path?: never; query?: never; url: '/external-nested'; }; export type GetExternalNestedResponses = { /** * Response using external nested object */ 200: ExternalNested; }; export type GetExternalNestedResponse = GetExternalNestedResponses[keyof GetExternalNestedResponses]; export type PostExternalNestedData = { /** * Request body using external nested object */ body?: ExternalNestedBody; path?: never; query?: never; url: '/external-nested'; }; export type PostExternalNestedResponses = { /** * Response using external nested object */ 201: ExternalNested; }; export type PostExternalNestedResponse = PostExternalNestedResponses[keyof PostExternalNestedResponses]; export type GetExternalMixedData = { body?: never; headers?: { deep?: Deep; }; path: { id: Id; }; query?: { uuid?: ExternalSharedModelWithUuid; numeric?: _1; }; url: '/external-mixed'; }; export type GetExternalMixedResponses = { /** * Response with array of external models */ 200: Array; }; export type GetExternalMixedResponse = GetExternalMixedResponses[keyof GetExternalMixedResponses]; export type PostExternalMixedData = { /** * Request body with mixed external properties */ body?: ExternalMixedBody; path?: never; query?: never; url: '/external-mixed'; }; export type PostExternalMixedResponses = { /** * Response using external model */ 201: ExternalSharedModel; }; export type PostExternalMixedResponse = PostExternalMixedResponses[keyof PostExternalMixedResponses]; export type GetExternalArrayData = { body?: never; path?: never; query?: never; url: '/external-array'; }; export type GetExternalArrayResponses = { /** * Response with array of external models */ 200: Array; }; export type GetExternalArrayResponse = GetExternalArrayResponses[keyof GetExternalArrayResponses]; export type PostExternalArrayData = { body: Array; path?: never; query?: never; url: '/external-array'; }; export type PostExternalArrayResponses = { /** * Response with array of external models */ 201: Array; }; export type PostExternalArrayResponse = PostExternalArrayResponses[keyof PostExternalArrayResponses]; export type GetExternalUnionData = { body?: never; path?: never; query?: never; url: '/external-union'; }; export type GetExternalUnionResponses = { /** * Response with union of external types */ 200: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; }; export type GetExternalUnionResponse = GetExternalUnionResponses[keyof GetExternalUnionResponses]; export type PostExternalUnionData = { body: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; path?: never; query?: never; url: '/external-union'; }; export type PostExternalUnionResponses = { /** * Response with union of external types */ 201: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; }; export type PostExternalUnionResponse = PostExternalUnionResponses[keyof PostExternalUnionResponses]; export type GetExternalPropertiesByIdData = { body?: never; headers?: { deep?: Deep; }; path: { id: Id; }; query?: { uuid?: ExternalSharedModelWithUuid; }; url: '/external-properties/{id}'; }; export type GetExternalPropertiesByIdResponses = { 200: { id?: Id; name?: Name; uuid?: ExternalSharedModelWithUuid; deep?: Deep; numeric?: _1; }; }; export type GetExternalPropertiesByIdResponse = GetExternalPropertiesByIdResponses[keyof GetExternalPropertiesByIdResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { create, create2, create3, type Options } from '../sdk.gen'; import type { Create2Data, Create3Data, CreateData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const createQueryKey2 = (options?: Options) => createQueryKey('create', options); export const createOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await create({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: createQueryKey2(options) }); export const create2Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await create2({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const create3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await create3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { create, create2, create3, type Options } from './sdk.gen'; export type { ClientOptions, Create2Data, Create2Responses, Create3Data, Create3Responses, CreateData, CreateResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { Create2Data, Create2Responses, Create3Data, Create3Responses, CreateData, CreateResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const create = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const create2 = (options?: Options) => (options?.client ?? client).patch({ url: '/foo', ...options }); export const create3 = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type CreateData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type CreateResponses = { /** * OK */ 200: unknown; }; export type Create2Data = { body?: never; path?: never; query?: never; url: '/foo'; }; export type Create2Responses = { /** * OK */ 200: unknown; }; export type Create3Data = { body?: never; path?: never; query?: never; url: '/foo'; }; export type Create3Responses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/operation-204/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, PostFooData, PostFooResponse, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/operation-204/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: string; /** * Created */ 204: void; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { ClientOptions, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ querySerializer: { parameters: { foo: { array: { explode: false } } } }, url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PostFooData = { body?: never; path?: never; query?: { foo?: Array; }; url: '/foo'; }; export type PostFooResponses = { /** * OK */ default: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { ClientOptions, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ querySerializer: { parameters: { foo: { array: { explode: false } } } }, url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/parameter-explode-false-axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: `${string}://${string}` | (string & {}); }; export type PostFooData = { body?: never; path?: never; query?: { foo?: Array; }; url: '/foo'; }; export type PostFooResponses = { /** * OK */ default: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/@angular/common.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type HttpRequest, httpResource } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { client } from '../client.gen'; import type { Options } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; @Injectable({ providedIn: 'root' }) export class DefaultServiceRequests { public export(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/no+tag', ...options }); } public patchApiVbyApiVersionNoTag(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PATCH', url: '/api/v{api-version}/no+tag', ...options }); } public import(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/no+tag', ...options }); } public fooWow(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/no+tag', ...options }); } public getApiVbyApiVersionSimpleOperation(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/simple:operation', ...options }); } } export class ODataControllerService { public count(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/simple/$count', ...options }); } } export class VVersionService { private _oDataControllerService?: ODataControllerService; get oDataControllerService(): ODataControllerService { return this._oDataControllerService ??= new ODataControllerService(); } } export class ApiService { private _vVersionService?: VVersionService; get vVersionService(): VVersionService { return this._vVersionService ??= new VVersionService(); } } @Injectable({ providedIn: 'root' }) export class SimpleServiceRequests { public deleteCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/simple', ...options }); } public getCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/simple', ...options }); } public headCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'HEAD', url: '/api/v{api-version}/simple', ...options }); } public optionsCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'OPTIONS', url: '/api/v{api-version}/simple', ...options }); } public patchCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PATCH', url: '/api/v{api-version}/simple', ...options }); } public postCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/simple', ...options }); } public putCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/simple', ...options }); } private _apiService?: ApiService; get apiService(): ApiService { return this._apiService ??= new ApiService(); } } @Injectable({ providedIn: 'root' }) export class ParametersServiceRequests { public deleteFoo(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); } public callWithParameters(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); } public callWithWeirdParameterNames(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options }); } public getCallWithOptionalParam(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/parameters', ...options }); } public postCallWithOptionalParam(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters', ...options }); } } @Injectable({ providedIn: 'root' }) export class DescriptionsServiceRequests { public callWithDescriptions(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/descriptions', ...options }); } } @Injectable({ providedIn: 'root' }) export class DeprecatedServiceRequests { /** * @deprecated */ public deprecatedCall(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/deprecated', ...options }); } } @Injectable({ providedIn: 'root' }) export class RequestBodyServiceRequests { public postApiVbyApiVersionRequestBody(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/requestBody', ...options }); } } @Injectable({ providedIn: 'root' }) export class FormDataServiceRequests { public postApiVbyApiVersionFormData(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/formData', ...options }); } } @Injectable({ providedIn: 'root' }) export class DefaultsServiceRequests { public callWithDefaultParameters(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/defaults', ...options }); } public callWithDefaultOptionalParameters(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/defaults', ...options }); } public callToTestOrderOfParams(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/defaults', ...options }); } } @Injectable({ providedIn: 'root' }) export class DuplicateServiceRequests { public duplicateName(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName2(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName3(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName4(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/duplicate', ...options }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceRequests { public callWithNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/no-content', ...options }); } public callWithResponseAndNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); } } @Injectable({ providedIn: 'root' }) export class ResponseServiceRequests { public callWithResponseAndNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); } public callWithResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/response', ...options }); } public callWithDuplicateResponses(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/response', ...options }); } public callWithResponses(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/response', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags1ServiceRequests { public dummyA(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/a', ...options }); } public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags2ServiceRequests { public dummyA(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/a', ...options }); } public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags3ServiceRequests { public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class CollectionFormatServiceRequests { public collectionFormat(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/collectionFormat', ...options }); } } @Injectable({ providedIn: 'root' }) export class TypesServiceRequests { public types(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/types', ...options }); } } @Injectable({ providedIn: 'root' }) export class UploadServiceRequests { public uploadFile(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/upload', ...options }); } } @Injectable({ providedIn: 'root' }) export class FileResponseServiceRequests { public fileResponse(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/file/{id}', ...options }); } } @Injectable({ providedIn: 'root' }) export class ComplexServiceRequests { public complexTypes(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/complex', ...options }); } public complexParams(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/complex/{id}', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipartServiceRequests { public multipartResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multipart', ...options }); } public multipartRequest(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/multipart', ...options }); } } @Injectable({ providedIn: 'root' }) export class HeaderServiceRequests { public callWithResultFromHeader(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/header', ...options }); } } @Injectable({ providedIn: 'root' }) export class ErrorServiceRequests { public testErrorCode(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/error', ...options }); } } @Injectable({ providedIn: 'root' }) export class NonAsciiÆøåÆøÅöôêÊServiceRequests { public nonAsciiæøåÆøÅöôêÊ字符串(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); } /** * Login User */ public putWithFormUrlEncoded(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); } } @Injectable({ providedIn: 'root' }) export class DefaultServiceResources { public export(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).export(opts) : undefined; }); } public patchApiVbyApiVersionNoTag(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).patchApiVbyApiVersionNoTag(opts) : undefined; }); } public import(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).import(opts) : undefined; }); } public fooWow(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).fooWow(opts) : undefined; }); } public getApiVbyApiVersionSimpleOperation(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).getApiVbyApiVersionSimpleOperation(opts) : undefined; }); } } export class ODataControllerService2 { public count(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).apiService.vVersionService.oDataControllerService.count(opts) : undefined; }); } } export class VVersionService2 { private _oDataControllerService?: ODataControllerService2; get oDataControllerService(): ODataControllerService2 { return this._oDataControllerService ??= new ODataControllerService2(); } } export class ApiService2 { private _vVersionService?: VVersionService2; get vVersionService(): VVersionService2 { return this._vVersionService ??= new VVersionService2(); } } @Injectable({ providedIn: 'root' }) export class SimpleServiceResources { public deleteCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).deleteCallWithoutParametersAndResponse(opts) : undefined; }); } public getCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).getCallWithoutParametersAndResponse(opts) : undefined; }); } public headCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).headCallWithoutParametersAndResponse(opts) : undefined; }); } public optionsCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).optionsCallWithoutParametersAndResponse(opts) : undefined; }); } public patchCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).patchCallWithoutParametersAndResponse(opts) : undefined; }); } public postCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).postCallWithoutParametersAndResponse(opts) : undefined; }); } public putCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).putCallWithoutParametersAndResponse(opts) : undefined; }); } private _apiService?: ApiService2; get apiService(): ApiService2 { return this._apiService ??= new ApiService2(); } } @Injectable({ providedIn: 'root' }) export class ParametersServiceResources { public deleteFoo(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).deleteFoo(opts) : undefined; }); } public callWithParameters(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).callWithParameters(opts) : undefined; }); } public callWithWeirdParameterNames(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).callWithWeirdParameterNames(opts) : undefined; }); } public getCallWithOptionalParam(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).getCallWithOptionalParam(opts) : undefined; }); } public postCallWithOptionalParam(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).postCallWithOptionalParam(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DescriptionsServiceResources { public callWithDescriptions(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DescriptionsServiceRequests).callWithDescriptions(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DeprecatedServiceResources { /** * @deprecated */ public deprecatedCall(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DeprecatedServiceRequests).deprecatedCall(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class RequestBodyServiceResources { public postApiVbyApiVersionRequestBody(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(RequestBodyServiceRequests).postApiVbyApiVersionRequestBody(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class FormDataServiceResources { public postApiVbyApiVersionFormData(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(FormDataServiceRequests).postApiVbyApiVersionFormData(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DefaultsServiceResources { public callWithDefaultParameters(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callWithDefaultParameters(opts) : undefined; }); } public callWithDefaultOptionalParameters(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callWithDefaultOptionalParameters(opts) : undefined; }); } public callToTestOrderOfParams(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callToTestOrderOfParams(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DuplicateServiceResources { public duplicateName(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName(opts) : undefined; }); } public duplicateName2(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName2(opts) : undefined; }); } public duplicateName3(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName3(opts) : undefined; }); } public duplicateName4(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName4(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceResources { public callWithNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NoContentServiceRequests).callWithNoContentResponse(opts) : undefined; }); } public callWithResponseAndNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NoContentServiceRequests).callWithResponseAndNoContentResponse(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ResponseServiceResources { public callWithResponseAndNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NoContentServiceRequests).callWithResponseAndNoContentResponse(opts) : undefined; }); } public callWithResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponse(opts) : undefined; }); } public callWithDuplicateResponses(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithDuplicateResponses(opts) : undefined; }); } public callWithResponses(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponses(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags1ServiceResources { public dummyA(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyA(opts) : undefined; }); } public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags2ServiceResources { public dummyA(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyA(opts) : undefined; }); } public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags3ServiceResources { public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class CollectionFormatServiceResources { public collectionFormat(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(CollectionFormatServiceRequests).collectionFormat(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class TypesServiceResources { public types(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(TypesServiceRequests).types(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class UploadServiceResources { public uploadFile(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(UploadServiceRequests).uploadFile(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class FileResponseServiceResources { public fileResponse(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(FileResponseServiceRequests).fileResponse(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ComplexServiceResources { public complexTypes(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ComplexServiceRequests).complexTypes(opts) : undefined; }); } public complexParams(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ComplexServiceRequests).complexParams(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipartServiceResources { public multipartResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipartServiceRequests).multipartResponse(opts) : undefined; }); } public multipartRequest(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipartServiceRequests).multipartRequest(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class HeaderServiceResources { public callWithResultFromHeader(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(HeaderServiceRequests).callWithResultFromHeader(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ErrorServiceResources { public testErrorCode(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ErrorServiceRequests).testErrorCode(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class NonAsciiÆøåÆøÅöôêÊServiceResources { public nonAsciiæøåÆøÅöôêÊ字符串(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NonAsciiÆøåÆøÅöôêÊServiceRequests).nonAsciiæøåÆøÅöôêÊ字符串(opts) : undefined; }); } /** * Login User */ public putWithFormUrlEncoded(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NonAsciiÆøåÆøÅöôêÊServiceRequests).putWithFormUrlEncoded(opts) : undefined; }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@angular/common/default-class/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://api.example.com/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Business, Business2, Business3, Business4, Business5, Domains, Domains2, Domains3, Domains4, Locations, type Options, Providers, Providers2, Providers3, Providers4 } from './sdk.gen'; export type { BusinessGetData, BusinessGetResponse, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponse, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponse, BusinessProvidersDomainsPostResponses, ClientOptions, GetData, GetResponse, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponse, PutBusinessProvidersDomainsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { BusinessGetData, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponses, GetData, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class Domains { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers { static domains = Domains; } export class Business { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations/businesses', ...options }); } static providers = Providers; } export class Business2 { static business = Business; } export class Domains2 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers2 { static domains = Domains2; } export class Business3 { static providers = Providers2; } export class Providers3 { static business = Business3; } export class Domains3 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers4 { static domains = Domains3; } export class Business4 { static providers = Providers4; } export class Domains4 { public static putBusinessProvidersDomains(options?: Options) { return (options?.client ?? client).put({ url: '/business/providers/domains', ...options }); } static business = Business4; } export class Business5 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations/businesses', ...options }); } } export class Locations { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations', ...options }); } static business = Business5; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://api.example.com/v1' | (string & {}); }; export type BusinessProvidersDomainsGetData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsGetResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsGetResponse = BusinessProvidersDomainsGetResponses[keyof BusinessProvidersDomainsGetResponses]; export type BusinessProvidersDomainsPostData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsPostResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsPostResponse = BusinessProvidersDomainsPostResponses[keyof BusinessProvidersDomainsPostResponses]; export type PutBusinessProvidersDomainsData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type PutBusinessProvidersDomainsResponses = { /** * OK */ 200: string; }; export type PutBusinessProvidersDomainsResponse = PutBusinessProvidersDomainsResponses[keyof PutBusinessProvidersDomainsResponses]; export type BusinessGetData = { body?: never; path?: never; query?: never; url: '/locations/businesses'; }; export type BusinessGetResponses = { /** * OK */ 200: string; }; export type BusinessGetResponse = BusinessGetResponses[keyof BusinessGetResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/locations'; }; export type GetResponses = { /** * OK */ 200: string; }; export type GetResponse = GetResponses[keyof GetResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://api.example.com/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Business, Domains, NestedSdkWithInstance, type Options, Providers } from './sdk.gen'; export type { BusinessGetData, BusinessGetResponse, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponse, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponse, BusinessProvidersDomainsPostResponses, ClientOptions, GetData, GetResponse, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponse, PutBusinessProvidersDomainsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { BusinessGetData, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponses, GetData, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new NestedSdkWithInstance()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class Domains extends HeyApiClient { public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/business/providers/domains', ...options }); } public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/business/providers/domains', ...options }); } } export class Providers extends HeyApiClient { private _domains?: Domains; get domains(): Domains { return this._domains ??= new Domains({ client: this.client }); } } export class Business extends HeyApiClient { public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/locations/businesses', ...options }); } private _providers?: Providers; get providers(): Providers { return this._providers ??= new Providers({ client: this.client }); } } export class NestedSdkWithInstance extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); NestedSdkWithInstance.__registry.set(this, args?.key); } public putBusinessProvidersDomains(options?: Options) { return (options?.client ?? this.client).put({ url: '/business/providers/domains', ...options }); } public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/locations', ...options }); } private _business?: Business; get business(): Business { return this._business ??= new Business({ client: this.client }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://api.example.com/v1' | (string & {}); }; export type BusinessProvidersDomainsGetData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsGetResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsGetResponse = BusinessProvidersDomainsGetResponses[keyof BusinessProvidersDomainsGetResponses]; export type BusinessProvidersDomainsPostData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsPostResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsPostResponse = BusinessProvidersDomainsPostResponses[keyof BusinessProvidersDomainsPostResponses]; export type PutBusinessProvidersDomainsData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type PutBusinessProvidersDomainsResponses = { /** * OK */ 200: string; }; export type PutBusinessProvidersDomainsResponse = PutBusinessProvidersDomainsResponses[keyof PutBusinessProvidersDomainsResponses]; export type BusinessGetData = { body?: never; path?: never; query?: never; url: '/locations/businesses'; }; export type BusinessGetResponses = { /** * OK */ 200: string; }; export type BusinessGetResponse = BusinessGetResponses[keyof BusinessGetResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/locations'; }; export type GetResponses = { /** * OK */ 200: string; }; export type GetResponse = GetResponses[keyof GetResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/schemas/default/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const _400Schema = { description: 'Model with number-only name', type: 'string' } as const; export const ExternalRefASchema = { description: 'External ref to shared model (A)', $ref: '#/components/schemas/ExternalSharedModel' } as const; export const ExternalRefBSchema = { description: 'External ref to shared model (B)', $ref: '#/components/schemas/ExternalSharedModel' } as const; export const camelCaseCommentWithBreaksSchema = { description: 'Testing multiline comments in string: First line\nSecond line\n\nFourth line', type: 'integer' } as const; export const CommentWithBreaksSchema = { description: 'Testing multiline comments in string: First line\nSecond line\n\nFourth line', type: 'integer' } as const; export const CommentWithBackticksSchema = { description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work', type: 'integer' } as const; export const CommentWithBackticksAndQuotesSchema = { description: 'Testing backticks and quotes in string: `backticks`, \'quotes\', "double quotes" and ```multiple backticks``` should work', type: 'integer' } as const; export const CommentWithSlashesSchema = { description: 'Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work', type: 'integer' } as const; export const CommentWithExpressionPlaceholdersSchema = { description: 'Testing expression placeholders in string: ${expression} should work', type: 'integer' } as const; export const CommentWithQuotesSchema = { description: 'Testing quotes in string: \'single quote\'\'\' and "double quotes""" should work', type: 'integer' } as const; export const CommentWithReservedCharactersSchema = { description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work', type: 'integer' } as const; export const SimpleIntegerSchema = { description: 'This is a simple number', type: 'integer' } as const; export const SimpleBooleanSchema = { description: 'This is a simple boolean', type: 'boolean' } as const; export const SimpleStringSchema = { description: 'This is a simple string', type: 'string' } as const; export const NonAsciiStringæøåÆØÅöôêÊ字符串Schema = { description: 'A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串)', type: 'string' } as const; export const SimpleFileSchema = { description: 'This is a simple file', format: 'binary', type: 'string' } as const; export const SimpleReferenceSchema = { description: 'This is a simple reference', allOf: [ { $ref: '#/components/schemas/ModelWithString' } ] } as const; export const SimpleStringWithPatternSchema = { description: 'This is a simple string', type: 'string', nullable: true, maxLength: 64, pattern: '^[a-zA-Z0-9_]*$' } as const; export const EnumWithStringsSchema = { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ] } as const; export const EnumWithReplacedCharactersSchema = { enum: [ '\'Single Quote\'', '"Double Quotes"', 'øæåôöØÆÅÔÖ字符串', 3.1, '' ], type: 'string' } as const; export const EnumWithNumbersSchema = { description: 'This is a simple enum with numbers', enum: [ 1, 2, 3, 1.1, 1.2, 1.3, 100, 200, 300, -100, -200, -300, -1.1, -1.2, -1.3 ], default: 200 } as const; export const EnumFromDescriptionSchema = { description: 'Success=1,Warning=2,Error=3', type: 'number' } as const; export const EnumWithExtensionsSchema = { description: 'This is a simple enum with numbers', enum: [ 200, 400, 500 ], 'x-enum-varnames': [ 'CUSTOM_SUCCESS', 'CUSTOM_WARNING', 'CUSTOM_ERROR' ], 'x-enum-descriptions': [ 'Used when the status of something is successful', 'Used when the status of something has a warning', 'Used when the status of something has an error' ] } as const; export const EnumWithXEnumNamesSchema = { enum: [ 0, 1, 2 ], 'x-enumNames': [ 'zero', 'one', 'two' ] } as const; export const ArrayWithNumbersSchema = { description: 'This is a simple array with numbers', type: 'array', items: { type: 'integer' } } as const; export const ArrayWithBooleansSchema = { description: 'This is a simple array with booleans', type: 'array', items: { type: 'boolean' } } as const; export const ArrayWithStringsSchema = { description: 'This is a simple array with strings', type: 'array', items: { type: 'string' }, default: [ 'test' ] } as const; export const ArrayWithReferencesSchema = { description: 'This is a simple array with references', type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } } as const; export const ArrayWithArraySchema = { description: 'This is a simple array containing an array', type: 'array', items: { type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const ArrayWithPropertiesSchema = { description: 'This is a simple array with properties', type: 'array', items: { type: 'object', properties: { '16x16': { $ref: '#/components/schemas/camelCaseCommentWithBreaks' }, bar: { type: 'string' } } } } as const; export const ArrayWithAnyOfPropertiesSchema = { description: 'This is a simple array with any of properties', type: 'array', items: { anyOf: [ { type: 'object', properties: { foo: { type: 'string', default: 'test' } } }, { type: 'object', properties: { bar: { type: 'string' } } } ] } } as const; export const AnyOfAnyAndNullSchema = { type: 'object', properties: { data: { anyOf: [ {}, { nullable: true } ] } } } as const; export const AnyOfArraysSchema = { description: 'This is a simple array with any of properties', type: 'object', properties: { results: { items: { anyOf: [ { type: 'object', properties: { foo: { type: 'string' } } }, { type: 'object', properties: { bar: { type: 'string' } } } ] }, type: 'array' } } } as const; export const DictionaryWithStringSchema = { description: 'This is a string dictionary', type: 'object', additionalProperties: { type: 'string' } } as const; export const DictionaryWithPropertiesAndAdditionalPropertiesSchema = { type: 'object', properties: { foo: { type: 'number' }, bar: { type: 'boolean' } }, additionalProperties: { type: 'string' } } as const; export const DictionaryWithReferenceSchema = { description: 'This is a string reference', type: 'object', additionalProperties: { $ref: '#/components/schemas/ModelWithString' } } as const; export const DictionaryWithArraySchema = { description: 'This is a complex dictionary', type: 'object', additionalProperties: { type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const DictionaryWithDictionarySchema = { description: 'This is a string dictionary', type: 'object', additionalProperties: { type: 'object', additionalProperties: { type: 'string' } } } as const; export const DictionaryWithPropertiesSchema = { description: 'This is a complex dictionary', type: 'object', additionalProperties: { type: 'object', properties: { foo: { type: 'string' }, bar: { type: 'string' } } } } as const; export const ModelWithIntegerSchema = { description: 'This is a model with one number property', type: 'object', properties: { prop: { description: 'This is a simple number property', type: 'integer' } } } as const; export const ModelWithBooleanSchema = { description: 'This is a model with one boolean property', type: 'object', properties: { prop: { description: 'This is a simple boolean property', type: 'boolean' } } } as const; export const ModelWithStringSchema = { description: 'This is a model with one string property', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } } } as const; export const ModelWithStringErrorSchema = { description: 'This is a model with one string property', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } } } as const; export const Model_From_ZendeskSchema = { description: '`Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets)', type: 'string' } as const; export const ModelWithNullableStringSchema = { description: 'This is a model with one string property', type: 'object', required: [ 'nullableRequiredProp1', 'nullableRequiredProp2' ], properties: { nullableProp1: { description: 'This is a simple string property', type: 'string', nullable: true }, nullableRequiredProp1: { description: 'This is a simple string property', type: 'string', nullable: true }, nullableProp2: { description: 'This is a simple string property', nullable: true, type: 'string' }, nullableRequiredProp2: { description: 'This is a simple string property', nullable: true, type: 'string' }, 'foo_bar-enum': { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ] } } } as const; export const ModelWithEnumSchema = { description: 'This is a model with one enum', type: 'object', properties: { 'foo_bar-enum': { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ] }, statusCode: { description: 'These are the HTTP error code enums', enum: [ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ] }, bool: { description: 'Simple boolean enum', type: 'boolean', enum: [ true ] } } } as const; export const ModelWithEnumWithHyphenSchema = { description: 'This is a model with one enum with escaped name', type: 'object', properties: { 'foo-bar-baz-qux': { type: 'string', enum: [ '3.0' ], title: 'Foo-Bar-Baz-Qux', default: '3.0' } } } as const; export const ModelWithEnumFromDescriptionSchema = { description: 'This is a model with one enum', type: 'object', properties: { test: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } } } as const; export const ModelWithNestedEnumsSchema = { description: 'This is a model with nested enums', type: 'object', properties: { dictionaryWithEnum: { type: 'object', additionalProperties: { enum: [ 'Success', 'Warning', 'Error' ] } }, dictionaryWithEnumFromDescription: { type: 'object', additionalProperties: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } }, arrayWithEnum: { type: 'array', items: { enum: [ 'Success', 'Warning', 'Error' ] } }, arrayWithDescription: { type: 'array', items: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } }, 'foo_bar-enum': { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ] } } } as const; export const ModelWithReferenceSchema = { description: 'This is a model with one property containing a reference', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithProperties' } } } as const; export const ModelWithArrayReadOnlyAndWriteOnlySchema = { description: 'This is a model with one property containing an array', type: 'object', properties: { prop: { type: 'array', items: { $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' } }, propWithFile: { type: 'array', items: { format: 'binary', type: 'string' } }, propWithNumber: { type: 'array', items: { type: 'number' } } } } as const; export const ModelWithArraySchema = { description: 'This is a model with one property containing an array', type: 'object', properties: { prop: { type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } }, propWithFile: { type: 'array', items: { format: 'binary', type: 'string' } }, propWithNumber: { type: 'array', items: { type: 'number' } } } } as const; export const ModelWithDictionarySchema = { description: 'This is a model with one property containing a dictionary', type: 'object', properties: { prop: { type: 'object', additionalProperties: { type: 'string' } } } } as const; export const DeprecatedModelSchema = { deprecated: true, description: 'This is a deprecated model with a deprecated property', type: 'object', properties: { prop: { deprecated: true, description: 'This is a deprecated property', type: 'string' } } } as const; export const ModelWithCircularReferenceSchema = { description: 'This is a model with one property containing a circular reference', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithCircularReference' } } } as const; export const CompositionWithOneOfSchema = { description: 'This is a model with one property with a \'one of\' relationship', type: 'object', properties: { propA: { type: 'object', oneOf: [ { $ref: '#/components/schemas/ModelWithString' }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithOneOfAnonymousSchema = { description: 'This is a model with one property with a \'one of\' relationship where the options are not $ref', type: 'object', properties: { propA: { type: 'object', oneOf: [ { description: 'Anonymous object type', type: 'object', properties: { propA: { type: 'string' } } }, { description: 'Anonymous string type', type: 'string' }, { description: 'Anonymous integer type', type: 'integer' } ] } } } as const; export const ModelCircleSchema = { description: 'Circle', type: 'object', required: [ 'kind' ], properties: { kind: { type: 'string' }, radius: { type: 'number' } } } as const; export const ModelSquareSchema = { description: 'Square', type: 'object', required: [ 'kind' ], properties: { kind: { type: 'string' }, sideLength: { type: 'number' } } } as const; export const CompositionWithOneOfDiscriminatorSchema = { description: 'This is a model with one property with a \'one of\' relationship where the options are not $ref', type: 'object', oneOf: [ { $ref: '#/components/schemas/ModelCircle' }, { $ref: '#/components/schemas/ModelSquare' } ], discriminator: { propertyName: 'kind', mapping: { circle: '#/components/schemas/ModelCircle', square: '#/components/schemas/ModelSquare' } } } as const; export const CompositionWithAnyOfSchema = { description: 'This is a model with one property with a \'any of\' relationship', type: 'object', properties: { propA: { type: 'object', anyOf: [ { $ref: '#/components/schemas/ModelWithString' }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithAnyOfAnonymousSchema = { description: 'This is a model with one property with a \'any of\' relationship where the options are not $ref', type: 'object', properties: { propA: { type: 'object', anyOf: [ { description: 'Anonymous object type', type: 'object', properties: { propA: { type: 'string' } } }, { description: 'Anonymous string type', type: 'string' }, { description: 'Anonymous integer type', type: 'integer' } ] } } } as const; export const CompositionWithNestedAnyAndTypeNullSchema = { description: 'This is a model with nested \'any of\' property with a type null', type: 'object', properties: { propA: { type: 'object', anyOf: [ { items: { nullable: true, allOf: [ { $ref: '#/components/schemas/ModelWithDictionary' } ] }, type: 'array' }, { items: { nullable: true, allOf: [ { $ref: '#/components/schemas/ModelWithArray' } ] }, type: 'array' } ] } } } as const; export const _3e_num_1ПериодSchema = { enum: [ 'Bird', 'Dog' ], type: 'string' } as const; export const ConstValueSchema = { enum: [ 'ConstValue' ], type: 'string' } as const; export const CompositionWithNestedAnyOfAndNullSchema = { description: 'This is a model with one property with a \'any of\' relationship where the options are not $ref', type: 'object', properties: { propA: { nullable: true, allOf: [ { items: { anyOf: [ { $ref: '#/components/schemas/3e-num_1Период' }, { $ref: '#/components/schemas/ConstValue' } ] }, type: 'array' } ], title: 'Scopes' } } } as const; export const CompositionWithOneOfAndNullableSchema = { description: 'This is a model with one property with a \'one of\' relationship', type: 'object', properties: { propA: { nullable: true, type: 'object', oneOf: [ { type: 'object', properties: { boolean: { type: 'boolean' } } }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithOneOfAndSimpleDictionarySchema = { description: 'This is a model that contains a simple dictionary within composition', type: 'object', properties: { propA: { oneOf: [ { type: 'boolean' }, { type: 'object', additionalProperties: { type: 'number' } } ] } } } as const; export const CompositionWithOneOfAndSimpleArrayDictionarySchema = { description: 'This is a model that contains a dictionary of simple arrays within composition', type: 'object', properties: { propA: { oneOf: [ { type: 'boolean' }, { type: 'object', additionalProperties: { type: 'array', items: { type: 'boolean' } } } ] } } } as const; export const CompositionWithOneOfAndComplexArrayDictionarySchema = { description: 'This is a model that contains a dictionary of complex arrays (composited) within composition', type: 'object', properties: { propA: { oneOf: [ { type: 'boolean' }, { type: 'object', additionalProperties: { type: 'array', items: { oneOf: [ { type: 'number' }, { type: 'string' } ] } } } ] } } } as const; export const CompositionWithAllOfAndNullableSchema = { description: 'This is a model with one property with a \'all of\' relationship', type: 'object', properties: { propA: { nullable: true, type: 'object', allOf: [ { type: 'object', properties: { boolean: { type: 'boolean' } } }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithAnyOfAndNullableSchema = { description: 'This is a model with one property with a \'any of\' relationship', type: 'object', properties: { propA: { nullable: true, type: 'object', anyOf: [ { type: 'object', properties: { boolean: { type: 'boolean' } } }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionBaseModelSchema = { description: 'This is a base model with two simple optional properties', type: 'object', properties: { firstName: { type: 'string' }, lastname: { type: 'string' } } } as const; export const CompositionExtendedModelSchema = { description: 'This is a model that extends the base model', type: 'object', allOf: [ { $ref: '#/components/schemas/CompositionBaseModel' } ], properties: { age: { type: 'number' } }, required: [ 'firstName', 'lastname', 'age' ] } as const; export const ModelWithPropertiesSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'required', 'requiredAndReadOnly', 'requiredAndNullable' ], properties: { required: { type: 'string' }, requiredAndReadOnly: { type: 'string', readOnly: true }, requiredAndNullable: { type: 'string', nullable: true }, string: { type: 'string' }, number: { type: 'number' }, boolean: { type: 'boolean' }, reference: { $ref: '#/components/schemas/ModelWithString' }, 'property with space': { type: 'string' }, default: { type: 'string' }, try: { type: 'string' }, '@namespace.string': { type: 'string', readOnly: true }, '@namespace.integer': { type: 'integer', readOnly: true } } } as const; export const ModelWithNestedPropertiesSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'first' ], properties: { first: { type: 'object', required: [ 'second' ], readOnly: true, nullable: true, properties: { second: { type: 'object', required: [ 'third' ], readOnly: true, nullable: true, properties: { third: { type: 'string', required: true, readOnly: true, nullable: true } } } } } } } as const; export const ModelWithDuplicatePropertiesSchema = { description: 'This is a model with duplicated properties', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const ModelWithOrderedPropertiesSchema = { description: 'This is a model with ordered properties', type: 'object', properties: { zebra: { type: 'string' }, apple: { type: 'string' }, hawaii: { type: 'string' } } } as const; export const ModelWithDuplicateImportsSchema = { description: 'This is a model with duplicated imports', type: 'object', properties: { propA: { $ref: '#/components/schemas/ModelWithString' }, propB: { $ref: '#/components/schemas/ModelWithString' }, propC: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const ModelThatExtendsSchema = { description: 'This is a model that extends another model', type: 'object', allOf: [ { $ref: '#/components/schemas/ModelWithString' }, { type: 'object', properties: { propExtendsA: { type: 'string' }, propExtendsB: { $ref: '#/components/schemas/ModelWithString' } } } ] } as const; export const ModelThatExtendsExtendsSchema = { description: 'This is a model that extends another model', type: 'object', allOf: [ { $ref: '#/components/schemas/ModelWithString' }, { $ref: '#/components/schemas/ModelThatExtends' }, { type: 'object', properties: { propExtendsC: { type: 'string' }, propExtendsD: { $ref: '#/components/schemas/ModelWithString' } } } ] } as const; export const ModelWithPatternSchema = { description: 'This is a model that contains a some patterns', type: 'object', required: [ 'key', 'name' ], properties: { key: { maxLength: 64, pattern: '^[a-zA-Z0-9_]*$', type: 'string' }, name: { maxLength: 255, type: 'string' }, enabled: { type: 'boolean', readOnly: true }, modified: { type: 'string', format: 'date-time', readOnly: true }, id: { type: 'string', pattern: '^\\d{2}-\\d{3}-\\d{4}$' }, text: { type: 'string', pattern: '^\\w+$' }, patternWithSingleQuotes: { type: 'string', pattern: '^[a-zA-Z0-9\']*$' }, patternWithNewline: { type: 'string', pattern: 'aaa\\nbbb' }, patternWithBacktick: { type: 'string', pattern: 'aaa`bbb' }, patternWithUnicode: { type: 'string', pattern: '^\\p{L}+$' } } } as const; export const FileSchema = { required: [ 'mime' ], type: 'object', properties: { id: { title: 'Id', type: 'string', readOnly: true, minLength: 1 }, updated_at: { title: 'Updated at', type: 'string', format: 'date-time', readOnly: true }, created_at: { title: 'Created at', type: 'string', format: 'date-time', readOnly: true }, mime: { title: 'Mime', type: 'string', maxLength: 24, minLength: 1 }, file: { title: 'File', type: 'string', readOnly: true, format: 'uri' } } } as const; export const defaultSchema = { type: 'object', properties: { name: { type: 'string' } } } as const; export const PageableSchema = { type: 'object', properties: { page: { minimum: 0, type: 'integer', format: 'int32', default: 0 }, size: { minimum: 1, type: 'integer', format: 'int32' }, sort: { type: 'array', items: { type: 'string' } } } } as const; export const FreeFormObjectWithoutAdditionalPropertiesSchema = { description: 'This is a free-form object without additionalProperties.', type: 'object' } as const; export const FreeFormObjectWithAdditionalPropertiesEqTrueSchema = { description: 'This is a free-form object with additionalProperties: true.', type: 'object', additionalProperties: true } as const; export const FreeFormObjectWithAdditionalPropertiesEqEmptyObjectSchema = { description: 'This is a free-form object with additionalProperties: {}.', type: 'object', additionalProperties: {} } as const; export const ModelWithConstSchema = { type: 'object', properties: { String: { enum: [ 'String' ], type: 'string' }, number: { enum: [ 0 ], type: 'number' }, null: { nullable: true }, withType: { enum: [ 'Some string' ], type: 'string' } } } as const; export const ModelWithAdditionalPropertiesEqTrueSchema = { description: 'This is a model with one property and additionalProperties: true', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } }, additionalProperties: true } as const; export const NestedAnyOfArraysNullableSchema = { properties: { nullableArray: { nullable: true, allOf: [ { items: { anyOf: [ { type: 'string' }, { type: 'boolean' } ] }, type: 'array' } ] } }, type: 'object' } as const; export const CompositionWithOneOfAndPropertiesSchema = { type: 'object', oneOf: [ { type: 'object', required: [ 'foo' ], properties: { foo: { $ref: '#/components/parameters/SimpleParameter' } }, additionalProperties: false }, { type: 'object', required: [ 'bar' ], properties: { bar: { $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' } }, additionalProperties: false } ], required: [ 'baz', 'qux' ], properties: { baz: { type: 'integer', format: 'uint16', minimum: 0, nullable: true }, qux: { type: 'integer', format: 'uint8', minimum: 0 } } } as const; export const NullableObjectSchema = { description: 'An object that can be null', nullable: true, type: 'object', properties: { foo: { type: 'string' } }, default: null } as const; export const CharactersInDescriptionSchema = { type: 'string', description: 'Some % character' } as const; export const ModelWithNullableObjectSchema = { type: 'object', properties: { data: { $ref: '#/components/schemas/NullableObject' } } } as const; export const ModelWithAdditionalPropertiesRefSchema = { type: 'object', description: 'An object with additional properties that can be null', additionalProperties: { nullable: true, allOf: [ { $ref: '#/components/schemas/NullableObject' } ] } } as const; export const ModelWithOneOfEnumSchema = { oneOf: [ { type: 'object', required: [ 'foo' ], properties: { foo: { type: 'string', enum: [ 'Bar' ] } } }, { type: 'object', required: [ 'foo' ], properties: { foo: { type: 'string', enum: [ 'Baz' ] } } }, { type: 'object', required: [ 'foo' ], properties: { foo: { type: 'string', enum: [ 'Qux' ] } } }, { type: 'object', required: [ 'content', 'foo' ], properties: { content: { type: 'string', format: 'date-time' }, foo: { type: 'string', enum: [ 'Quux' ] } } }, { type: 'object', required: [ 'content', 'foo' ], properties: { content: { type: 'array', items: { type: 'string', format: 'date-time' }, maxItems: 2, minItems: 2 }, foo: { type: 'string', enum: [ 'Corge' ] } } } ] } as const; export const ModelWithNestedArrayEnumsDataFooSchema = { enum: [ 'foo', 'bar' ], type: 'string' } as const; export const ModelWithNestedArrayEnumsDataBarSchema = { enum: [ 'baz', 'qux' ], type: 'string' } as const; export const ModelWithNestedArrayEnumsDataSchema = { type: 'object', properties: { foo: { type: 'array', items: { $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' } }, bar: { type: 'array', items: { $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataBar' } } } } as const; export const ModelWithNestedArrayEnumsSchema = { type: 'object', properties: { array_strings: { type: 'array', items: { type: 'string' } }, data: { allOf: [ { $ref: '#/components/schemas/ModelWithNestedArrayEnumsData' } ] } } } as const; export const ModelWithNestedCompositionEnumsSchema = { type: 'object', properties: { foo: { allOf: [ { $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' } ] } } } as const; export const ModelWithReadOnlyAndWriteOnlySchema = { type: 'object', required: [ 'foo', 'bar' ], properties: { foo: { type: 'string' }, bar: { readOnly: true, type: 'string' } } } as const; export const ModelWithConstantSizeArraySchema = { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 } as const; export const ModelWithAnyOfConstantSizeArraySchema = { type: 'array', items: { oneOf: [ { type: 'number' }, { type: 'string' } ] }, minItems: 3, maxItems: 3 } as const; export const ModelWithPrefixItemsConstantSizeArraySchema = { type: 'array', items: { oneOf: [ { $ref: '#/components/schemas/ModelWithInteger' }, { type: 'number' }, { type: 'string' } ] } } as const; export const ModelWithAnyOfConstantSizeArrayNullableSchema = { type: 'array', items: { oneOf: [ { type: 'number', nullable: true }, { type: 'string' } ] }, minItems: 3, maxItems: 3 } as const; export const ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsSchema = { type: 'array', items: { oneOf: [ { type: 'number' }, { $ref: '#/components/schemas/import' } ] }, minItems: 2, maxItems: 2 } as const; export const ModelWithAnyOfConstantSizeArrayAndIntersectSchema = { type: 'array', items: { allOf: [ { type: 'number' }, { type: 'string' } ] }, minItems: 2, maxItems: 2 } as const; export const ModelWithNumericEnumUnionSchema = { type: 'object', properties: { value: { type: 'number', description: 'Период', enum: [ -10, -1, 0, 1, 3, 6, 12 ] } } } as const; export const ModelWithBackticksInDescriptionSchema = { description: 'Some description with `back ticks`', type: 'object', properties: { template: { type: 'string', description: 'The template `that` should be used for parsing and importing the contents of the CSV file.\n\n

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    \n
    \n[\n  {\n    "resourceType": "Asset",\n    "identifier": {\n      "name": "${1}",\n      "domain": {\n        "name": "${2}",\n        "community": {\n          "name": "Some Community"\n        }\n      }\n    },\n    "attributes" : {\n      "00000000-0000-0000-0000-000000003115" : [ {\n        "value" : "${3}"\n      } ],\n      "00000000-0000-0000-0000-000000000222" : [ {\n        "value" : "${4}"\n      } ]\n    }\n  }\n]\n
    ' } } } as const; export const ModelWithOneOfAndPropertiesSchema = { type: 'object', oneOf: [ { $ref: '#/components/parameters/SimpleParameter' }, { $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' } ], required: [ 'baz', 'qux' ], properties: { baz: { type: 'integer', format: 'uint16', minimum: 0, nullable: true }, qux: { type: 'integer', format: 'uint8', minimum: 0 } } } as const; export const ParameterSimpleParameterUnusedSchema = { description: 'Model used to test deduplication strategy (unused)', type: 'string' } as const; export const PostServiceWithEmptyTagResponseSchema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const PostServiceWithEmptyTagResponse2Schema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const DeleteFooDataSchema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const DeleteFooData2Schema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const importSchema = { description: 'Model with restricted keyword name', type: 'string' } as const; export const SchemaWithFormRestrictedKeysSchema = { properties: { description: { type: 'string' }, 'x-enum-descriptions': { type: 'string' }, 'x-enum-varnames': { type: 'string' }, 'x-enumNames': { type: 'string' }, title: { type: 'string' }, object: { type: 'object', properties: { description: { type: 'string' }, 'x-enum-descriptions': { type: 'string' }, 'x-enum-varnames': { type: 'string' }, 'x-enumNames': { type: 'string' }, title: { type: 'string' } } }, array: { type: 'array', items: { type: 'object', properties: { description: { type: 'string' }, 'x-enum-descriptions': { type: 'string' }, 'x-enum-varnames': { type: 'string' }, 'x-enumNames': { type: 'string' }, title: { type: 'string' } } } } } } as const; export const io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptionsSchema = { description: 'This schema was giving PascalCase transformations a hard time', properties: { preconditions: { allOf: [ { $ref: '#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions' } ], description: 'Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.' } }, type: 'object' } as const; export const io_k8s_apimachinery_pkg_apis_meta_v1_PreconditionsSchema = { description: 'This schema was giving PascalCase transformations a hard time', properties: { resourceVersion: { description: 'Specifies the target ResourceVersion', type: 'string' }, uid: { description: 'Specifies the target UID.', type: 'string' } }, type: 'object' } as const; export const AdditionalPropertiesUnknownIssueSchema = { type: 'object', additionalProperties: { anyOf: [ { type: 'string' }, { type: 'number' } ] } } as const; export const AdditionalPropertiesUnknownIssue2Schema = { type: 'object', additionalProperties: { anyOf: [ { type: 'string' }, { type: 'number' } ] } } as const; export const AdditionalPropertiesUnknownIssue3Schema = { type: 'object', allOf: [ { type: 'string' }, { type: 'object', required: [ 'entries' ], properties: { entries: { type: 'object', additionalProperties: { $ref: '#/components/schemas/AdditionalPropertiesUnknownIssue' } } } } ] } as const; export const AdditionalPropertiesIntegerIssueSchema = { type: 'object', required: [ 'value' ], properties: { value: { type: 'integer' } }, additionalProperties: { type: 'integer' } } as const; export const OneOfAllOfIssueSchema = { oneOf: [ { allOf: [ { oneOf: [ { $ref: '#/components/schemas/ConstValue' }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' } ] }, { $ref: '#/components/schemas/3e-num_1Период' } ] }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' } ] } as const; export const Generic_Schema_Duplicate_Issue_1_System_Boolean_Schema = { type: 'object', properties: { item: { type: 'boolean' }, error: { type: 'string', nullable: true }, hasError: { type: 'boolean', readOnly: true }, data: { type: 'object', additionalProperties: false } }, additionalProperties: false } as const; export const Generic_Schema_Duplicate_Issue_1_System_String_Schema = { type: 'object', properties: { item: { type: 'string', nullable: true }, error: { type: 'string', nullable: true }, hasError: { type: 'boolean', readOnly: true } }, additionalProperties: false } as const; export const ExternalSharedModelSchema = { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: [ 'id' ] } as const; export const ModelWithReferenceWritableSchema = { description: 'This is a model with one property containing a reference', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithPropertiesWritable' } } } as const; export const ModelWithArrayReadOnlyAndWriteOnlyWritableSchema = { description: 'This is a model with one property containing an array', type: 'object', properties: { prop: { type: 'array', items: { $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnlyWritable' } }, propWithFile: { type: 'array', items: { format: 'binary', type: 'string' } }, propWithNumber: { type: 'array', items: { type: 'number' } } } } as const; export const ModelWithPropertiesWritableSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'required', 'requiredAndNullable' ], properties: { required: { type: 'string' }, requiredAndNullable: { type: 'string', nullable: true }, string: { type: 'string' }, number: { type: 'number' }, boolean: { type: 'boolean' }, reference: { $ref: '#/components/schemas/ModelWithString' }, 'property with space': { type: 'string' }, default: { type: 'string' }, try: { type: 'string' } } } as const; export const ModelWithPatternWritableSchema = { description: 'This is a model that contains a some patterns', type: 'object', required: [ 'key', 'name' ], properties: { key: { maxLength: 64, pattern: '^[a-zA-Z0-9_]*$', type: 'string' }, name: { maxLength: 255, type: 'string' }, id: { type: 'string', pattern: '^\\d{2}-\\d{3}-\\d{4}$' }, text: { type: 'string', pattern: '^\\w+$' }, patternWithSingleQuotes: { type: 'string', pattern: '^[a-zA-Z0-9\']*$' }, patternWithNewline: { type: 'string', pattern: 'aaa\\nbbb' }, patternWithBacktick: { type: 'string', pattern: 'aaa`bbb' }, patternWithUnicode: { type: 'string', pattern: '^\\p{L}+$' } } } as const; export const FileWritableSchema = { required: [ 'mime' ], type: 'object', properties: { mime: { title: 'Mime', type: 'string', maxLength: 24, minLength: 1 } } } as const; export const ModelWithReadOnlyAndWriteOnlyWritableSchema = { type: 'object', required: [ 'foo', 'baz' ], properties: { foo: { type: 'string' }, baz: { type: 'string', writeOnly: true } } } as const; export const ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritableSchema = { type: 'array', items: { oneOf: [ { type: 'number' }, { $ref: '#/components/schemas/import' } ] }, minItems: 2, maxItems: 2 } as const; export const AdditionalPropertiesUnknownIssueWritableSchema = { type: 'object', additionalProperties: { anyOf: [ { type: 'string' }, { type: 'number' } ] } } as const; export const OneOfAllOfIssueWritableSchema = { oneOf: [ { allOf: [ { oneOf: [ { $ref: '#/components/schemas/ConstValue' }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' } ] }, { $ref: '#/components/schemas/3e-num_1Период' } ] }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' } ] } as const; export const Generic_Schema_Duplicate_Issue_1_System_Boolean_WritableSchema = { type: 'object', properties: { item: { type: 'boolean' }, error: { type: 'string', nullable: true }, data: { type: 'object', additionalProperties: false } }, additionalProperties: false } as const; export const Generic_Schema_Duplicate_Issue_1_System_String_WritableSchema = { type: 'object', properties: { item: { type: 'string', nullable: true }, error: { type: 'string', nullable: true } }, additionalProperties: false } as const; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Bar, Foo, type Options, Sdk } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new Sdk()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class Bar extends HeyApiClient { public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/foo/bar', ...options }); } public put(options?: Options) { return (options?.client ?? this.client).put({ url: '/foo/bar', ...options }); } } export class Foo extends HeyApiClient { public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/foo', ...options }); } public put(options?: Options) { return (options?.client ?? this.client).put({ url: '/foo', ...options }); } private _bar?: Bar; get bar(): Bar { return this._bar ??= new Bar({ client: this.client }); } } export class Sdk extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); Sdk.__registry.set(this, args?.key); } public getFoo(options?: Options) { return (options?.client ?? this.client).get({ url: '/foo', ...options }); } public getFooBar(options?: Options) { return (options?.client ?? this.client).get({ url: '/foo/bar', ...options }); } private _foo?: Foo; get foo(): Foo { return this._foo ??= new Foo({ client: this.client }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/instance/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base', throwOnError: true })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/sdk/throwOnError/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Baz, ClientOptions, PostFooReadData, PostFooReadResponse, PostFooReadResponses, PostFooReadWriteData, PostFooReadWriteResponse, PostFooReadWriteResponses, PostFooWriteData, PostFooWriteResponse, PostFooWriteResponses, QuxAllRead, ReadableBarRead, ReadableBarWrite, ReadableCorge, ReadableFooRead, ReadableFooReadWrite, ReadableFooWrite, ReadableQuux, WritableBarRead, WritableBarWrite, WritableCorge, WritableFooRead, WritableFooReadWrite, WritableFooWrite, WritableQuux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Baz = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type ReadableFooReadWrite = ReadableBarRead; export type WritableFooReadWrite = WritableBarRead & { foo?: string; }; export type ReadableFooRead = ReadableBarRead & { readonly foo?: string; }; export type WritableFooRead = WritableBarRead; export type ReadableFooWrite = ReadableBarWrite; export type WritableFooWrite = WritableBarWrite & { foo?: string; }; export type ReadableBarRead = Baz | { readonly bar?: string; }; export type WritableBarRead = Baz; export type ReadableBarWrite = Baz; export type WritableBarWrite = Baz | { bar?: string; }; export type ReadableQuux = { baz?: Array; qux?: QuxAllRead; }; export type WritableQuux = { baz?: Array; }; export type ReadableCorge = { bar?: { readonly baz?: boolean; }; }; export type WritableCorge = { foo?: { baz?: boolean; }; }; export type PostFooReadWriteData = { body: WritableFooReadWrite; path?: never; query?: never; url: '/foo-read-write'; }; export type PostFooReadWriteResponses = { /** * OK */ 200: ReadableFooReadWrite; }; export type PostFooReadWriteResponse = PostFooReadWriteResponses[keyof PostFooReadWriteResponses]; export type PostFooReadData = { body: WritableFooRead; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: ReadableFooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; export type PostFooWriteData = { body: WritableFooWrite; path?: never; query?: never; url: '/foo-write'; }; export type PostFooWriteResponses = { /** * OK */ 200: ReadableFooWrite; }; export type PostFooWriteResponse = PostFooWriteResponses[keyof PostFooWriteResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BarRead, BarWrite, Baz, ClientOptions, Corge, FooRead, FooReadWrite, FooWrite, PostFooReadData, PostFooReadResponse, PostFooReadResponses, PostFooReadWriteData, PostFooReadWriteResponse, PostFooReadWriteResponses, PostFooWriteData, PostFooWriteResponse, PostFooWriteResponses, Quux, QuxAllRead } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@hey-api/typescript/transforms-read-write-ignore/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type FooReadWrite = BarRead & { foo?: string; }; export type FooRead = BarRead & { readonly foo?: string; }; export type FooWrite = BarWrite & { foo?: string; }; export type BarRead = Baz | { readonly bar?: string; }; export type BarWrite = Baz | { bar?: string; }; export type Baz = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type Quux = { baz?: Array; qux?: QuxAllRead; }; export type Corge = { foo?: { baz?: boolean; }; bar?: { readonly baz?: boolean; }; }; export type PostFooReadWriteData = { body: FooReadWrite; path?: never; query?: never; url: '/foo-read-write'; }; export type PostFooReadWriteResponses = { /** * OK */ 200: FooReadWrite; }; export type PostFooReadWriteResponse = PostFooReadWriteResponses[keyof PostFooReadWriteResponses]; export type PostFooReadData = { body: FooRead; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: FooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; export type PostFooWriteData = { body: FooWrite; path?: never; query?: never; url: '/foo-write'; }; export type PostFooWriteResponses = { /** * OK */ 200: FooWrite; }; export type PostFooWriteResponse = PostFooWriteResponses[keyof PostFooWriteResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/@pinia/colada.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'; import { serializeQueryKeyValue } from '../client'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; baseUrl?: _JSONValue; body?: _JSONValue; query?: _JSONValue; tags?: _JSONValue; } ]; const createQueryKey = (id: string, options?: TOptions, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (tags) { params.tags = tags as unknown as _JSONValue; } if (options?.body !== undefined) { const normalizedBody = serializeQueryKeyValue(options.body); if (normalizedBody !== undefined) { params.body = normalizedBody; } } if (options?.path) { params.path = options.path; } if (options?.query !== undefined) { const normalizedQuery = serializeQueryKeyValue(options.query); if (normalizedQuery !== undefined) { params.query = normalizedQuery; } } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooQuery = defineQueryOptions, GetFooResponse, Error>((options?: Options) => ({ key: getFooQueryKey(options), query: async (context) => { const { data } = await FooBazService.getFoo({ ...options, ...context, throwOnError: true }); return data; } })); export const fooPostMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await FooService.post({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooPutMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await FooService.put({ ...options, ...vars, throwOnError: true }); return data; } }); export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarQuery = defineQueryOptions, GetFooBarResponse, Error>((options?: Options) => ({ key: getFooBarQueryKey(options), query: async (context) => { const { data } = await BarBazService.getFooBar({ ...options, ...context, throwOnError: true }); return data; } })); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await BarService.post({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooBarPutMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await BarService.put({ ...options, ...vars, throwOnError: true }); return data; } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/@pinia/colada.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'; import { serializeQueryKeyValue } from '../client'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; baseUrl?: _JSONValue; body?: _JSONValue; query?: _JSONValue; tags?: _JSONValue; } ]; const createQueryKey = (id: string, options?: TOptions, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (tags) { params.tags = tags as unknown as _JSONValue; } if (options?.body !== undefined) { const normalizedBody = serializeQueryKeyValue(options.body); if (normalizedBody !== undefined) { params.body = normalizedBody; } } if (options?.path) { params.path = options.path; } if (options?.query !== undefined) { const normalizedQuery = serializeQueryKeyValue(options.query); if (normalizedQuery !== undefined) { params.query = normalizedQuery; } } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: exportQueryKey(options), query: async (context) => { const { data } = await export_({ ...options, ...context, throwOnError: true }); return data; } })); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...vars, throwOnError: true }); return data; } }); export const importMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await import_({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooWowMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await fooWow({ ...options, ...vars, throwOnError: true }); return data; } }); export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountQuery = defineQueryOptions, ApiVVersionODataControllerCountResponse, Error>((options?: Options) => ({ key: apiVVersionODataControllerCountQueryKey(options), query: async (context) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...context, throwOnError: true }); return data; } })); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationQuery = defineQueryOptions, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationError>((options: Options) => ({ key: getApiVbyApiVersionSimpleOperationQueryKey(options), query: async (context) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...context, throwOnError: true }); return data; } })); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: getCallWithoutParametersAndResponseQueryKey(options), query: async (context) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deleteFoo({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithDescriptions({ ...options, ...vars, throwOnError: true }); return data; } }); /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deprecatedCall({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithParameters({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithWeirdParameterNames({ ...options, ...vars, throwOnError: true }); return data; } }); export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamQuery = defineQueryOptions, unknown, Error>((options: Options) => ({ key: getCallWithOptionalParamQueryKey(options), query: async (context) => { const { data } = await getCallWithOptionalParam({ ...options, ...context, throwOnError: true }); return data; } })); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postCallWithOptionalParam({ ...options, ...vars, throwOnError: true }); return data; } }); export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...vars, throwOnError: true }); return data; } }); export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: callWithDefaultParametersQueryKey(options), query: async (context) => { const { data } = await callWithDefaultParameters({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...vars, throwOnError: true }); return data; } }); export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callToTestOrderOfParams({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Query = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: duplicateName2QueryKey(options), query: async (context) => { const { data } = await duplicateName2({ ...options, ...context, throwOnError: true }); return data; } })); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName3({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName4({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseQuery = defineQueryOptions, CallWithNoContentResponseResponse, Error>((options?: Options) => ({ key: callWithNoContentResponseQueryKey(options), query: async (context) => { const { data } = await callWithNoContentResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseQuery = defineQueryOptions, CallWithResponseAndNoContentResponseResponse, Error>((options?: Options) => ({ key: callWithResponseAndNoContentResponseQueryKey(options), query: async (context) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAQuery = defineQueryOptions, DummyAResponse, Error>((options?: Options) => ({ key: dummyAQueryKey(options), query: async (context) => { const { data } = await dummyA({ ...options, ...context, throwOnError: true }); return data; } })); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBQuery = defineQueryOptions, DummyBResponse, Error>((options?: Options) => ({ key: dummyBQueryKey(options), query: async (context) => { const { data } = await dummyB({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseQuery = defineQueryOptions, CallWithResponseResponse, Error>((options?: Options) => ({ key: callWithResponseQueryKey(options), query: async (context) => { const { data } = await callWithResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, CallWithDuplicateResponsesError> => ({ mutation: async (vars) => { const { data } = await callWithDuplicateResponses({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, CallWithResponsesError> => ({ mutation: async (vars) => { const { data } = await callWithResponses({ ...options, ...vars, throwOnError: true }); return data; } }); export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatQuery = defineQueryOptions, unknown, Error>((options: Options) => ({ key: collectionFormatQueryKey(options), query: async (context) => { const { data } = await collectionFormat({ ...options, ...context, throwOnError: true }); return data; } })); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesQuery = defineQueryOptions, TypesResponse, Error>((options: Options) => ({ key: typesQueryKey(options), query: async (context) => { const { data } = await types({ ...options, ...context, throwOnError: true }); return data; } })); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await uploadFile({ ...options, ...vars, throwOnError: true }); return data; } }); export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseQuery = defineQueryOptions, FileResponseResponse, Error>((options: Options) => ({ key: fileResponseQueryKey(options), query: async (context) => { const { data } = await fileResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesQuery = defineQueryOptions, ComplexTypesResponse, Error>((options: Options) => ({ key: complexTypesQueryKey(options), query: async (context) => { const { data } = await complexTypes({ ...options, ...context, throwOnError: true }); return data; } })); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseQuery = defineQueryOptions, MultipartResponseResponse, Error>((options?: Options) => ({ key: multipartResponseQueryKey(options), query: async (context) => { const { data } = await multipartResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await multipartRequest({ ...options, ...vars, throwOnError: true }); return data; } }); export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await complexParams({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithResultFromHeader({ ...options, ...vars, throwOnError: true }); return data; } }); export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await testErrorCode({ ...options, ...vars, throwOnError: true }); return data; } }); export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...vars, throwOnError: true }); return data; } }); /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await putWithFormUrlEncoded({ ...options, ...vars, throwOnError: true }); return data; } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@pinia/colada/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, useMutation, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePatchApiVbyApiVersionNoTagMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...patchApiVbyApiVersionNoTagMutation(), ...mutationOptions }); export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useImportMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...importMutation(), ...mutationOptions }); export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useFooWowMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...fooWowMutation(), ...mutationOptions }); export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDeleteCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...deleteCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePatchCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...patchCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePutCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...putCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDeleteFooMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...deleteFooMutation(), ...mutationOptions }); export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDescriptionsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDescriptionsMutation(), ...mutationOptions }); /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const useDeprecatedCallMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...deprecatedCallMutation(), ...mutationOptions }); export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithParametersMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithParametersMutation(), ...mutationOptions }); export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithWeirdParameterNamesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithWeirdParameterNamesMutation(), ...mutationOptions }); export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostCallWithOptionalParamMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postCallWithOptionalParamMutation(), ...mutationOptions }); export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostApiVbyApiVersionRequestBodyMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postApiVbyApiVersionRequestBodyMutation(), ...mutationOptions }); export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostApiVbyApiVersionFormDataMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postApiVbyApiVersionFormDataMutation(), ...mutationOptions }); export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDefaultOptionalParametersMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDefaultOptionalParametersMutation(), ...mutationOptions }); export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallToTestOrderOfParamsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callToTestOrderOfParamsMutation(), ...mutationOptions }); export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateNameMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateNameMutation(), ...mutationOptions }); export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateName3Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateName3Mutation(), ...mutationOptions }); export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateName4Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateName4Mutation(), ...mutationOptions }); export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDuplicateResponsesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDuplicateResponsesMutation(), ...mutationOptions }); export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithResponsesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithResponsesMutation(), ...mutationOptions }); export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useUploadFileMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...uploadFileMutation(), ...mutationOptions }); export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useMultipartRequestMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...multipartRequestMutation(), ...mutationOptions }); export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useComplexParamsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...complexParamsMutation(), ...mutationOptions }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithResultFromHeaderMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithResultFromHeaderMutation(), ...mutationOptions }); export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useTestErrorCodeMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...testErrorCodeMutation(), ...mutationOptions }); export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useNonAsciiæøåÆøÅöôêÊ字符串Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...nonAsciiæøåÆøÅöôêÊ字符串Mutation(), ...mutationOptions }); /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const usePutWithFormUrlEncodedMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...putWithFormUrlEncodedMutation(), ...mutationOptions }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/fastify/default/fastify.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { RouteHandler } from 'fastify'; import type { ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseResponses, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteFooData3, DeprecatedCallData, DummyAResponses, DummyBResponses, FileResponseData, FileResponseResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type RouteHandlers = { import: RouteHandler<{ Body: ImportData['body']; Reply: Omit; }>; apiVVersionODataControllerCount: RouteHandler<{ Reply: ApiVVersionODataControllerCountResponses; }>; getApiVbyApiVersionSimpleOperation: RouteHandler<{ Params: GetApiVbyApiVersionSimpleOperationData['path']; Reply: GetApiVbyApiVersionSimpleOperationResponses; }>; deleteFoo: RouteHandler<{ Headers: DeleteFooData3['headers']; Params: DeleteFooData3['path']; }>; callWithDescriptions: RouteHandler<{ Querystring?: CallWithDescriptionsData['query']; }>; deprecatedCall: RouteHandler<{ Headers: DeprecatedCallData['headers']; }>; callWithParameters: RouteHandler<{ Body: CallWithParametersData['body']; Headers: CallWithParametersData['headers']; Params: CallWithParametersData['path']; Querystring: CallWithParametersData['query']; }>; callWithWeirdParameterNames: RouteHandler<{ Body: CallWithWeirdParameterNamesData['body']; Headers: CallWithWeirdParameterNamesData['headers']; Params: CallWithWeirdParameterNamesData['path']; Querystring: CallWithWeirdParameterNamesData['query']; }>; getCallWithOptionalParam: RouteHandler<{ Body: GetCallWithOptionalParamData['body']; Querystring?: GetCallWithOptionalParamData['query']; }>; postCallWithOptionalParam: RouteHandler<{ Body?: PostCallWithOptionalParamData['body']; Querystring: PostCallWithOptionalParamData['query']; Reply: PostCallWithOptionalParamResponses; }>; postApiVbyApiVersionRequestBody: RouteHandler<{ Body?: PostApiVbyApiVersionRequestBodyData['body']; Querystring?: PostApiVbyApiVersionRequestBodyData['query']; }>; postApiVbyApiVersionFormData: RouteHandler<{ Body?: PostApiVbyApiVersionFormDataData['body']; Querystring?: PostApiVbyApiVersionFormDataData['query']; }>; callWithDefaultParameters: RouteHandler<{ Querystring?: CallWithDefaultParametersData['query']; }>; callWithDefaultOptionalParameters: RouteHandler<{ Querystring?: CallWithDefaultOptionalParametersData['query']; }>; callToTestOrderOfParams: RouteHandler<{ Querystring: CallToTestOrderOfParamsData['query']; }>; callWithNoContentResponse: RouteHandler<{ Reply: CallWithNoContentResponseResponses; }>; callWithResponseAndNoContentResponse: RouteHandler<{ Reply: CallWithResponseAndNoContentResponseResponses; }>; dummyA: RouteHandler<{ Reply: DummyAResponses; }>; dummyB: RouteHandler<{ Reply: DummyBResponses; }>; callWithDuplicateResponses: RouteHandler<{ Reply: Omit & CallWithDuplicateResponsesResponses; }>; callWithResponses: RouteHandler<{ Reply: Omit & CallWithResponsesResponses; }>; collectionFormat: RouteHandler<{ Querystring: CollectionFormatData['query']; }>; types: RouteHandler<{ Params?: TypesData['path']; Querystring: TypesData['query']; Reply: TypesResponses; }>; uploadFile: RouteHandler<{ Body: UploadFileData['body']; Params: UploadFileData['path']; Reply: UploadFileResponses; }>; fileResponse: RouteHandler<{ Params: FileResponseData['path']; Reply: FileResponseResponses; }>; complexTypes: RouteHandler<{ Querystring: ComplexTypesData['query']; Reply: ComplexTypesErrors & ComplexTypesResponses; }>; multipartResponse: RouteHandler<{ Reply: MultipartResponseResponses; }>; multipartRequest: RouteHandler<{ Body?: MultipartRequestData['body']; }>; complexParams: RouteHandler<{ Body?: ComplexParamsData['body']; Params: ComplexParamsData['path']; Reply: ComplexParamsResponses; }>; callWithResultFromHeader: RouteHandler<{ Reply: CallWithResultFromHeaderErrors & CallWithResultFromHeaderResponses; }>; testErrorCode: RouteHandler<{ Querystring: TestErrorCodeData['query']; Reply: TestErrorCodeErrors & TestErrorCodeResponses; }>; nonAsciiæøåÆøÅöôêÊ字符串: RouteHandler<{ Querystring: NonAsciiæøåÆøÅöôêÊ字符串Data['query']; Reply: NonAsciiæøåÆøÅöôêÊ字符串Responses; }>; putWithFormUrlEncoded: RouteHandler<{ Body: PutWithFormUrlEncodedData['body']; }>; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/fastify/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/fastify/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/ref-deep/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses, PostFooData, PostFooResponse, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/ref-deep/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: Array<{ baz?: string; }>; bar?: Array<{ baz?: string; }>; }; export type Bar = { foo?: Array<{ baz?: string; }>; bar?: Array<{ baz?: string; }>; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Array<{ foo?: number; bar?: string; }>; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: { foo?: { foo?: number; bar?: string; }; bar?: string; }; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getBar, getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetBarData, GetBarResponses, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetBarData, GetBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ in: 'query', name: 'foo', type: 'apiKey' }], url: '/foo', ...options }); export const getBar = (options?: Options) => (options?.client ?? client).get({ security: [{ in: 'cookie', name: 'bar', type: 'apiKey' }], url: '/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-api-key/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; export type GetBarData = { body?: never; path?: never; query?: never; url: '/bar'; }; export type GetBarResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-http-bearer/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-oauth2/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/security-open-id-connect/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/servers/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://foo.com/v1' | `${string}://${string}/v1` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetFooResponse } from './types.gen'; const quxSchemaResponseTransformer = (data: any) => { if (data.baz) { data.baz = new Date(data.baz); } return data; }; const bazSchemaResponseTransformer = (data: any) => { data = quxSchemaResponseTransformer(data); data.bar = new Date(data.bar); return data; }; const barSchemaResponseTransformer = (data: any) => { data.foo = data.foo.map((item: any) => bazSchemaResponseTransformer(item)); return data; }; const fooSchemaResponseTransformer = (data: any) => { data.foo = data.foo.map((item: any) => barSchemaResponseTransformer(item)); return data; }; export const getFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-all-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: Array; }; export type Bar = { foo: Array; bar: 'foo' | 'bar' | 'baz'; }; export type Baz = Omit & { foo: number; bar: Date; baz: 'foo' | 'bar' | 'baz'; qux: number; id: 'Baz'; }; export type Qux = { foo: number; bar: number; baz?: Date; id: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Foo; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, CreateSecretData, CreateSecretResponse, CreateSecretResponses, ListSecretsData, ListSecretsResponse, ListSecretsResponses, PaginatedResponse, RepositorySecret } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { CreateSecretResponse, ListSecretsResponse } from './types.gen'; const repositorySecretSchemaResponseTransformer = (data: any) => { data.createdAt = new Date(data.createdAt); data.updatedAt = new Date(data.updatedAt); return data; }; export const listSecretsResponseTransformer = async (data: any): Promise => { if (data.data) { data.data = data.data.map((item: any) => repositorySecretSchemaResponseTransformer(item)); } return data; }; export const createSecretResponseTransformer = async (data: any): Promise => { data = repositorySecretSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-allof-response-wrapper/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: '{protocol}://specs' | (string & {}); }; export type PaginatedResponse = { meta?: { page?: number; limit?: number; total?: number; totalPages?: number; }; }; export type RepositorySecret = { id: number; name: string; createdAt: Date; updatedAt: Date; }; export type ListSecretsData = { body?: never; path?: never; query?: never; url: '/secrets'; }; export type ListSecretsResponses = { /** * PaginatedResponseRepositorySecret * * OK */ 200: PaginatedResponse & { data?: Array; }; }; export type ListSecretsResponse = ListSecretsResponses[keyof ListSecretsResponses]; export type CreateSecretData = { body?: never; path?: never; query?: never; url: '/secrets/{id}'; }; export type CreateSecretResponses = { /** * Created */ 201: RepositorySecret; }; export type CreateSecretResponse = CreateSecretResponses[keyof CreateSecretResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses, GetNullablePollData, GetNullablePollResponse, GetNullablePollResponses, GetPollData, GetPollResponse, GetPollResponses, Poll } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetFooResponse, GetNullablePollResponse, GetPollResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { if (data.foo) { data.foo = new Date(data.foo); } if (data.bar) { data.bar = new Date(data.bar); } if (data.requiredBaz) { data.requiredBaz = new Date(data.requiredBaz); } return data; }; export const getFooResponseTransformer = async (data: any): Promise => { data = data.map((item: any) => fooSchemaResponseTransformer(item)); return data; }; const pollSchemaResponseTransformer = (data: any) => { data.createdAt = new Date(data.createdAt); return data; }; export const getPollResponseTransformer = async (data: any): Promise => { data = pollSchemaResponseTransformer(data); return data; }; export const getNullablePollResponseTransformer = async (data: any): Promise => { if (data) { data = pollSchemaResponseTransformer(data); } return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-any-of-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Poll = { id: number; createdAt: Date; }; export type Foo = { foo?: Date; bar?: Date | null; requiredBaz: Date | null; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Array; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type GetPollData = { body?: never; path?: never; query?: never; url: '/polls'; }; export type GetPollResponses = { /** * OK */ 200: Poll; }; export type GetPollResponse = GetPollResponses[keyof GetPollResponses]; export type GetNullablePollData = { body?: never; path?: never; query?: never; url: '/polls/nullable'; }; export type GetNullablePollResponses = { /** * OK */ 200: Poll | null; }; export type GetNullablePollResponse = GetNullablePollResponses[keyof GetNullablePollResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetFooResponse } from './types.gen'; export const getFooResponseTransformer = async (data: any): Promise => { data.foo = data.foo.map((item: any) => { item.baz = new Date(item.baz); return item; }); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-array/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: { foo: Array<{ baz: Date; }>; }; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetTreeData, GetTreeResponse, GetTreeResponses, TreeNode } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetTreeResponse } from './types.gen'; const treeNodeSchemaResponseTransformer = (data: any) => { if (data.createdAt) { data.createdAt = new Date(data.createdAt); } if (data.children) { data.children = data.children.map((item: any) => treeNodeSchemaResponseTransformer(item)); } return data; }; export const getTreeResponseTransformer = async (data: any): Promise => { data = data.map((item: any) => treeNodeSchemaResponseTransformer(item)); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transformers-recursive/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TreeNode = { id?: string; name?: string; createdAt?: Date; children?: Array; }; export type GetTreeData = { body?: never; path?: never; query?: never; url: '/tree'; }; export type GetTreeResponses = { /** * Success */ 200: Array; }; export type GetTreeResponse = GetTreeResponses[keyof GetTreeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-properties-required-by-default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Address, AllocatedDeliveryItem, AllocatedPreOrderItem, AnonymousTransaction, AnonymousTransactionWritable, AppliedDiscount, AppliedDiscountWritable, AssignPlantsToGroupRequest, BadRequestPropertyError, BadRequestResponse, BatchDetails, BatchLabResultsPostData, BatchLabResultsPostError, BatchLabResultsPostErrors, BatchLabResultsPostResponses, BooleanNullableOptional, BooleanOptional, Brand, BrandEditRequest, BrandGetData, BrandGetErrors, BrandGetResponse, BrandGetResponses, BrandPostData, BrandPostError, BrandPostErrors, BrandPostResponse, BrandPostResponses, BroadcastedResponses, BroadcastedResponsesWritable, BulkCreateOrUpdateHarvest, BulkCreateOrUpdateHarvestResponse, BulkHarvestDetail, CalculationMethod, CancelPreorderRequest, CannabinoidTerpeneValue, CartItemPrice, CartPrice, ChangeGrowthPhaseRequest, ClientOptions, ClosingReportCategorySummary, ClosingReportCategorySummaryWritable, ClosingReportCustomerTypeSummary, ClosingReportCustomerTypeSummaryWritable, ClosingReportOrderSourceSummary, ClosingReportOrderSourceSummaryWritable, ClosingReportOrderTypeSummary, ClosingReportOrderTypeSummaryWritable, ClosingReportPayByBankBatchFileSums, ClosingReportPaymentSummary, ClosingReportTaxRateSummary, ClosingReportV2, ClosingReportV2Writable, ConvertBatchDetails, ConvertImmatureBatchRequest, ConvertImmaturePlantResponse, ConvertImmaturePlantResponseApiResult, CreateAnonymousTransactionRequest, CreatedImmaturePlantBatch, CreatedMaturePlant, CreateImmaturePlantBatchResponse, CreateImmaturePlantBatchResponseApiResult, CreateJournalEntryRequest, CreateMatureBatchRequest, CreateMaturePlantsResponse, CreateMaturePlantsResponseApiResult, CreateOrUpdateHarvest, CreatePlantRequest, CreatePreOrderRequest, CreateUpdatePurchaseOrderItemRequest, CreateUpdatePurchaseOrderRequest, CreateUpdatePurchaseOrderResponse, CreateUpdatePurchaseOrdersRequest, Customer, CustomerByExternalIdGetData, CustomerByExternalIdGetError, CustomerByExternalIdGetErrors, CustomerByExternalIdGetResponse, CustomerByExternalIdGetResponses, CustomerCustomerLookupPostData, CustomerCustomerLookupPostError, CustomerCustomerLookupPostErrors, CustomerCustomerLookupPostResponse, CustomerCustomerLookupPostResponses, CustomerCustomerPostData, CustomerCustomerPostError, CustomerCustomerPostErrors, CustomerCustomerPostResponse, CustomerCustomerPostResponses, CustomerCustomersGetData, CustomerCustomersGetError, CustomerCustomersGetErrors, CustomerCustomersGetResponse, CustomerCustomersGetResponses, CustomerCustomersPaginatedGetData, CustomerCustomersPaginatedGetError, CustomerCustomersPaginatedGetErrors, CustomerCustomersPaginatedGetResponse, CustomerCustomersPaginatedGetResponses, CustomerCustomerTypesGetData, CustomerCustomerTypesGetErrors, CustomerCustomerTypesGetResponse, CustomerCustomerTypesGetResponses, CustomerJournalCreatePostData, CustomerJournalCreatePostError, CustomerJournalCreatePostErrors, CustomerJournalCreatePostResponse, CustomerJournalCreatePostResponses, CustomerJournalGetData, CustomerJournalGetError, CustomerJournalGetErrors, CustomerJournalGetResponse, CustomerJournalGetResponses, CustomerJournalUpdatePostData, CustomerJournalUpdatePostError, CustomerJournalUpdatePostErrors, CustomerJournalUpdatePostResponse, CustomerJournalUpdatePostResponses, CustomerReferralSourcesGetData, CustomerReferralSourcesGetErrors, CustomerReferralSourcesGetResponse, CustomerReferralSourcesGetResponses, CustomerSearchPostData, CustomerSearchPostError, CustomerSearchPostErrors, CustomerSearchPostResponse, CustomerSearchPostResponses, CustomerSearchRequest, CustomerSearchResult, CustomerSearchResultWritable, CustomerType, CustomerWritable, DateTimeNullableOptional, DecimalNullableOptional, DeleteImageRequest, DeliveriesGetData, DeliveriesGetError, DeliveriesGetErrors, DeliveriesGetResponse, DeliveriesGetResponses, DeliveriesSetRouteDetailPostData, DeliveriesSetRouteDetailPostError, DeliveriesSetRouteDetailPostErrors, DeliveriesSetRouteDetailPostResponses, DeliveryOrderStatus, DeliveryPayment, DeliveryScheduleType, Discount, DiscountApiResponse, DiscountApiResponseWritable, DiscountApplicationMethod, DiscountConstraintApiResponse, DiscountConstraintApiResponseWritable, DiscountFirstTimeCustomer, DiscountGroup, DiscountItemGroupType, DiscountMenuDisplayApiResponse, DiscountPaymentRestrictionApiResponse, DiscountRestriction, DiscountRewardApiResponse, DiscountRewardApiResponseWritable, DiscountsGetData, DiscountsGetErrors, DiscountsGetResponse, DiscountsGetResponses, DiscountsV2ListGetData, DiscountsV2ListGetErrors, DiscountsV2ListGetResponse, DiscountsV2ListGetResponses, DiscountThresholdType, DriverDetail, DriversGetData, DriversGetErrors, DriversGetResponse, DriversGetResponses, DriversPostData, DriversPostError, DriversPostErrors, DriversPostResponses, EcomCustomerEdit, Employee, EmployeesGetData, EmployeesGetErrors, EmployeesGetResponse, EmployeesGetResponses, FeeDonation, FeeDonationInfo, FinishOrUnfinishBatchDetails, GuestListEntry, GuestlistGetData, GuestlistGetErrors, GuestlistGetResponse, GuestlistGetResponses, Harvest, HarvestBulkPostData, HarvestBulkPostError, HarvestBulkPostErrors, HarvestBulkPostResponse, HarvestBulkPostResponses, HarvestedPlant, HarvestGetData, HarvestGetErrors, HarvestGetResponse, HarvestGetResponses, HarvestPlantRequest, HarvestPostData, HarvestPostErrors, HarvestPostResponse, HarvestPostResponses, HarvestWasteDetail, HarvestWasteDetailWaste, Int32iEnumerableOptional, Int32NullableOptional, IntegratedPayment, IntegrationIntegrationReconGetData, IntegrationIntegrationReconGetErrors, IntegrationIntegrationReconGetResponse, IntegrationIntegrationReconGetResponses, InventoryDiscrepancy, InventoryDiscrepancyWritable, InventoryGetData, InventoryGetErrors, InventoryGetResponse, InventoryGetResponses, InventoryIntegrationReconResponse, InventoryIntegrationReconResponseWritable, InventoryInventorytransactionGetData, InventoryInventorytransactionGetErrors, InventoryInventorytransactionGetResponse, InventoryInventorytransactionGetResponses, InventoryItem, InventoryItemWritable, InventoryLabresultsGetData, InventoryLabresultsGetErrors, InventoryLabresultsGetResponse, InventoryLabresultsGetResponses, InventoryReceivedinventoryGetData, InventoryReceivedinventoryGetErrors, InventoryReceivedinventoryGetResponse, InventoryReceivedinventoryGetResponses, InventoryReceiveinventoryPostData, InventoryReceiveinventoryPostError, InventoryReceiveinventoryPostErrors, InventoryReceiveinventoryPostResponse, InventoryReceiveinventoryPostResponses, InventoryRoomQuantity, InventorySnapshot, InventorySnapshotGetData, InventorySnapshotGetErrors, InventorySnapshotGetResponse, InventorySnapshotGetResponses, InventoryTag, InventoryTransaction, IRestrictionApiResponse, JournalEntry, LabResult, LabResultUnit, LabResultUnitData, LabResultWritable, Lineage, LineagesGetData, LineagesGetErrors, LineagesGetResponse, LineagesGetResponses, LineItemTaxInfo, LineItemTaxInfoWritable, LocationIdentity, LocationIdentityWritable, LocationMapping, LocationProductOverride, LocationProductOverrideRequest, LocationResponse, LocationResponseWritable, LoyaltySnapshot, ManualPayment, MatureBatchDetails, MovePlantRequest, ObjectWaste, OkcomputerGetData, OkcomputerGetErrors, OkcomputerGetResponse, OkcomputerGetResponses, PackageAddTagsPostData, PackageAddTagsPostErrors, PackageAddTagsPostResponses, PackageLineage, PackageRemoveTagsPostData, PackageRemoveTagsPostErrors, PackageRemoveTagsPostResponses, PackageSetTagsPostData, PackageSetTagsPostError, PackageSetTagsPostErrors, PackageSetTagsPostResponses, Plant, PlantAssignPlantsToGroupPostData, PlantAssignPlantsToGroupPostError, PlantAssignPlantsToGroupPostErrors, PlantAssignPlantsToGroupPostResponses, PlantChangePhasePostData, PlantChangePhasePostErrors, PlantChangePhasePostResponses, PlantGetData, PlantGetErrors, PlantGetReasonCodesGetData, PlantGetReasonCodesGetErrors, PlantGetReasonCodesGetResponse, PlantGetReasonCodesGetResponses, PlantGetResponse, PlantGetResponses, PlantHarvestPostData, PlantHarvestPostErrors, PlantHarvestPostResponses, PlantMovePostData, PlantMovePostErrors, PlantMovePostResponses, PlantNonstsBatchConvertImmatureplantsPostData, PlantNonstsBatchConvertImmatureplantsPostError, PlantNonstsBatchConvertImmatureplantsPostErrors, PlantNonstsBatchConvertImmatureplantsPostResponse, PlantNonstsBatchConvertImmatureplantsPostResponses, PlantNonstsBatchFinishHarvestPostData, PlantNonstsBatchFinishHarvestPostError, PlantNonstsBatchFinishHarvestPostErrors, PlantNonstsBatchFinishHarvestPostResponses, PlantNonstsBatchImmatureplantsPostData, PlantNonstsBatchImmatureplantsPostError, PlantNonstsBatchImmatureplantsPostErrors, PlantNonstsBatchImmatureplantsPostResponse, PlantNonstsBatchImmatureplantsPostResponses, PlantNonstsBatchMatureplantsPostData, PlantNonstsBatchMatureplantsPostError, PlantNonstsBatchMatureplantsPostErrors, PlantNonstsBatchMatureplantsPostResponse, PlantNonstsBatchMatureplantsPostResponses, PlantNonstsBatchPostData, PlantNonstsBatchPostError, PlantNonstsBatchPostErrors, PlantNonstsBatchPostResponses, PlantNonstsBatchRetirePostData, PlantNonstsBatchRetirePostError, PlantNonstsBatchRetirePostErrors, PlantNonstsBatchRetirePostResponses, PlantNonstsRetagPostData, PlantNonstsRetagPostError, PlantNonstsRetagPostErrors, PlantNonstsRetagPostResponses, PlantNonstsSplitPostData, PlantNonstsSplitPostError, PlantNonstsSplitPostErrors, PlantNonstsSplitPostResponse, PlantNonstsSplitPostResponses, PlantNonstsUpdatePostData, PlantNonstsUpdatePostError, PlantNonstsUpdatePostErrors, PlantNonstsUpdatePostResponse, PlantNonstsUpdatePostResponses, PlantPostData, PlantPostError, PlantPostErrors, PlantPostResponse, PlantPostResponses, PlantRetirePostData, PlantRetirePostError, PlantRetirePostErrors, PlantRetirePostResponses, PlantWasteDetail, PlantWasteDetailWaste, PlantWritable, PostImmatureBatchRequest, PrecartItem, PreorderCancelPostData, PreorderCancelPostError, PreorderCancelPostErrors, PreorderCancelPostResponse, PreorderCancelPostResponses, PreOrderItem, PreorderPriceCartPostData, PreorderPriceCartPostError, PreorderPriceCartPostErrors, PreorderPriceCartPostResponse, PreorderPriceCartPostResponses, PreOrderRedemption, PreOrderRedemptionIEnumerableOptional, PreOrderStatus, PreorderStatusGetData, PreorderStatusGetErrors, PreorderStatusGetResponse, PreorderStatusGetResponses, PreorderSubmitPostData, PreorderSubmitPostError, PreorderSubmitPostErrors, PreorderSubmitPostResponse, PreorderSubmitPostResponses, PreorderUpdatePostData, PreorderUpdatePostErrors, PreorderUpdatePostResponses, PriceCartRequest, PriceEstimates, PricingDetail, PricingTier, PricingTierData, PricingTiersGetData, PricingTiersGetErrors, PricingTiersGetResponse, PricingTiersGetResponses, Producer, ProducersGetData, ProducersGetErrors, ProducersGetResponse, ProducersGetResponses, ProductCategory, ProductCategoryGetData, ProductCategoryGetErrors, ProductCategoryGetResponse, ProductCategoryGetResponses, ProductDetail, ProductDetailUpload, ProductDetailWritable, ProductEffect, ProductsExternalCategoriesGetData, ProductsExternalCategoriesGetError, ProductsExternalCategoriesGetErrors, ProductsExternalCategoriesGetResponse, ProductsExternalCategoriesGetResponses, ProductsGetData, ProductsGetErrors, ProductsGetResponse, ProductsGetResponses, ProductsLocationOverridesGetData, ProductsLocationOverridesGetErrors, ProductsLocationOverridesGetResponse, ProductsLocationOverridesGetResponses, ProductsLocationOverridesPostData, ProductsLocationOverridesPostErrors, ProductsLocationOverridesPostResponses, ProductsProductPostData, ProductsProductPostError, ProductsProductPostErrors, ProductsProductPostResponse, ProductsProductPostResponses, ProductsProductsPostData, ProductsProductsPostError, ProductsProductsPostErrors, ProductsProductsPostResponse, ProductsProductsPostResponses, ProductsRemoveImagePostData, ProductsRemoveImagePostError, ProductsRemoveImagePostErrors, ProductsRemoveImagePostResponse, ProductsRemoveImagePostResponses, ProductsSetImagePostData, ProductsSetImagePostError, ProductsSetImagePostErrors, ProductsSetImagePostResponse, ProductsSetImagePostResponses, ProductsStrainsGetData, ProductsStrainsGetErrors, ProductsStrainsGetResponse, ProductsStrainsGetResponses, ProductTag, PublishedDiscount, PurchaseOrderData, PurchaseOrderGetData, PurchaseOrderGetError, PurchaseOrderGetErrors, PurchaseOrderGetResponse, PurchaseOrderGetResponses, PurchaseOrderItemDetail, PurchaseOrderPostData, PurchaseOrderPostError, PurchaseOrderPostErrors, PurchaseOrderPostResponse, PurchaseOrderPostResponses, ReceivedInventory, ReceivedInventoryItem, ReceiveInventoryItemSave, ReceiveInventorySave, ReferenceLabResultsNamesGetData, ReferenceLabResultsNamesGetErrors, ReferenceLabResultsNamesGetResponse, ReferenceLabResultsNamesGetResponses, ReferenceLabResultUnitsGetData, ReferenceLabResultUnitsGetErrors, ReferenceLabResultUnitsGetResponse, ReferenceLabResultUnitsGetResponses, ReferenceUnitsGetData, ReferenceUnitsGetErrors, ReferenceUnitsGetResponse, ReferenceUnitsGetResponses, ReferenceUnitTypesGetData, ReferenceUnitTypesGetErrors, ReferenceUnitTypesGetResponse, ReferenceUnitTypesGetResponses, RegisterAdjustment, RegisterCashSummary, RegisterTransaction, RegulatoryCategory, RegulatoryCategoryGetData, RegulatoryCategoryGetErrors, RegulatoryCategoryGetResponse, RegulatoryCategoryGetResponses, ReportingCashSummaryGetData, ReportingCashSummaryGetError, ReportingCashSummaryGetErrors, ReportingCashSummaryGetResponse, ReportingCashSummaryGetResponses, ReportingClosingReportGetData, ReportingClosingReportGetError, ReportingClosingReportGetErrors, ReportingClosingReportGetResponse, ReportingClosingReportGetResponses, ReportingCustomersGetData, ReportingCustomersGetErrors, ReportingCustomersGetResponse, ReportingCustomersGetResponses, ReportingCustomersPaginatedGetData, ReportingCustomersPaginatedGetError, ReportingCustomersPaginatedGetErrors, ReportingCustomersPaginatedGetResponse, ReportingCustomersPaginatedGetResponses, ReportingDiscountDetail, ReportingDiscountsGetData, ReportingDiscountsGetErrors, ReportingDiscountsGetResponse, ReportingDiscountsGetResponses, ReportingInventoryGetData, ReportingInventoryGetErrors, ReportingInventoryGetResponse, ReportingInventoryGetResponses, ReportingInventoryItem, ReportingInventoryItemWritable, ReportingLoyaltySnapshotGetData, ReportingLoyaltySnapshotGetErrors, ReportingLoyaltySnapshotGetResponse, ReportingLoyaltySnapshotGetResponses, ReportingProductsGetData, ReportingProductsGetErrors, ReportingProductsGetResponse, ReportingProductsGetResponses, ReportingRegisterAdjustmentsGetData, ReportingRegisterAdjustmentsGetErrors, ReportingRegisterAdjustmentsGetResponse, ReportingRegisterAdjustmentsGetResponses, ReportingRegisterTransactionsGetData, ReportingRegisterTransactionsGetErrors, ReportingRegisterTransactionsGetResponse, ReportingRegisterTransactionsGetResponses, ReportingTransactionsGetData, ReportingTransactionsGetError, ReportingTransactionsGetErrors, ReportingTransactionsGetResponse, ReportingTransactionsGetResponses, RetagPlantRequest, RetireImmaturePlantsDetails, RetireImmaturePlantsRequest, RetirePlantRequest, Room, RoomPostData, RoomPostErrors, RoomPostResponse, RoomPostResponses, RoomRoomsGetData, RoomRoomsGetErrors, RoomRoomsGetResponse, RoomRoomsGetResponses, RoomWaste, SavedReceive, SetImageRequest, SetImageRequestWritable, SetImageResponse, Severity, Size, SizesGetData, SizesGetErrors, SizesGetResponse, SizesGetResponses, SplitBatchDetails, SplitImmaturePlantResult, SplitImmaturePlantResultApiResult, SplitImmaturePlantResultDetail, SplitImmaturePlantsRequest, SplitPlantDetails, StandardAllergensDetails, StrainDetail, StrainsGetData, StrainsGetErrors, StrainsGetResponse, StrainsGetResponses, StrainsPostData, StrainsPostError, StrainsPostErrors, StrainsPostResponse, StrainsPostResponses, StrainsTypesGetData, StrainsTypesGetErrors, StrainsTypesGetResponse, StrainsTypesGetResponses, StringIEnumerableOptional, StringOptional, SuccessResult, Table, TablePostData, TablePostErrors, TablePostResponse, TablePostResponses, TableTablesGetData, TableTablesGetErrors, TableTablesGetResponse, TableTablesGetResponses, Tag, TagGetData, TagGetErrors, TagGetResponse, TagGetResponses, TaxSummaryInfo, Terminal, TerminalsGetData, TerminalsGetErrors, TerminalsGetResponse, TerminalsGetResponses, Transaction, TransactionCreateAnonymousPostData, TransactionCreateAnonymousPostErrors, TransactionCreateAnonymousPostResponse, TransactionCreateAnonymousPostResponses, TransactionItem, TransactionItemWritable, TransactionWritable, Unit, UnitType, UpdateBatchLabResultsRequest, UpdateBatchRequest, UpdateDeliveryRouteDetailRequest, UpdateJournalEntryRequest, UpdatePackageTagsRequest, UpdatePlantDetails, UpdatePlantsRequest, UpdatePreOrderRequest, UpdateStrain, UploadFileType, UtilAuthorizationHeaderByApiKeyGetData, UtilAuthorizationHeaderByApiKeyGetResponse, UtilAuthorizationHeaderByApiKeyGetResponses, ValidationFailure, ValidationResult, ValidationResultWritable, VehicleDetail, VehiclesGetData, VehiclesGetErrors, VehiclesGetResponse, VehiclesGetResponses, VehiclesPostData, VehiclesPostError, VehiclesPostErrors, VehiclesPostResponses, Vendor, VendorPostData, VendorPostErrors, VendorPostResponse, VendorPostResponses, VendorVendorsGetData, VendorVendorsGetErrors, VendorVendorsGetResponse, VendorVendorsGetResponses, WasteGetData, WasteGetErrors, WasteGetResponse, WasteGetResponses, WasteHarvestWastePostData, WasteHarvestWastePostError, WasteHarvestWastePostErrors, WasteHarvestWastePostResponse, WasteHarvestWastePostResponses, WastePlantWastePostData, WastePlantWastePostError, WastePlantWastePostErrors, WastePlantWastePostResponse, WastePlantWastePostResponses, WasteSummary, WeeklyRecurrenceInfo, WhoamiGetData, WhoamiGetErrors, WhoamiGetResponse, WhoamiGetResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-properties-required-by-default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | 'https://api.pos.dutchie.com' | (string & {}); }; export type Address = { addressId: number | null; customerId: number; street: string | null; street2: string | null; city: string | null; state: string | null; postal_code: string | null; country_Code: string | null; latitude: number | null; longitude: number | null; county: string | null; additionalStateIdentifiers: string | null; }; export type AllocatedDeliveryItem = { transactionId: number; productName: string | null; quantity: number; totalPrice: number; totalDiscount: number; totalTax: number; }; export type AllocatedPreOrderItem = { productName: string | null; quantity: number; totalPrice: number; totalDiscount: number; totalTax: number; }; /** * Anonymous transaction response model containing transaction identifiers for guest checkout operations. */ export type AnonymousTransaction = { /** * Unique identifier for the customer record associated with this anonymous transaction. */ customerId: number; /** * Unique identifier for the transaction record. */ transactionId: number; /** * String representation of the unique identifier for API responses. */ readonly uniqueId: string | null; }; /** * Discount information applied to a specific transaction item in cannabis retail operations. */ export type AppliedDiscount = { /** * Unique identifier for the discount program or campaign applied. */ discountId: number; /** * Display name of the discount for customer receipts and reporting. */ discountName: string | null; /** * Reason or justification for the discount application (e.g., "Loyalty Reward", "Medical Patient"). */ discountReason: string | null; /** * Discount amount applied to the transaction item (in USD, positive value represents savings). */ amount: number; /** * Reference identifier linking this discount back to the specific transaction line item. * Not guaranteed to be unique outside of a single transaction. */ readonly transactionItemId: number; }; /** * Request model for assigning existing cannabis plants to a specific plant group for batch management and cultivation workflow organization. * * **Plant Group Assignment:** * - Assigns existing plants to target plant group using serial numbers * - Supports batch organization for cultivation workflow management * - Plants identified by serial numbers for precise assignment * - Validates target plant group exists before assignment * * **Serial Number Identification:** * - Plants identified by their unique serial numbers rather than IDs * - All serial numbers must correspond to existing plants in the facility * - Plants must be accessible to the authenticated location * - Serial numbers must match exact plant tracking identifiers * * **Batch Management:** * - Plant groups enable batch-based cultivation tracking and compliance * - Supports harvest planning and cultivation scheduling optimization * - Facilitates cultivation management and operational efficiency */ export type AssignPlantsToGroupRequest = { /** * Name of target plant group for batch organization and cultivation tracking */ plantGroupName: string | null; /** * Collection of plant serial numbers to assign to the specified plant group */ plantSerialNumbers: Array | null; }; /** * Field-specific validation error details for BadRequest responses. */ export type BadRequestPropertyError = { /** * Name of the property that failed validation. */ propertyName: string | null; /** * Description of the validation error for the specified property. */ propertyError: string | null; }; /** * Standardized error response model for HTTP 400 Bad Request responses across the API. */ export type BadRequestResponse = { /** * General error message describing the nature of the bad request. */ message: string | null; /** * Collection of field-specific validation errors for detailed feedback. */ propertyErrors: Array | null; }; /** * Detailed specification for creating individual immature plant batches with cultivation and compliance information. */ export type BatchDetails = { /** * Display name for the immature plant batch for identification and organization. */ batchName: string | null; /** * Plant type designation for the batch (e.g., "Seedling", "Clone", "Cutting"). */ plantType: string | null; /** * Number of plants in the immature batch for inventory tracking and compliance. */ plantCount: number; /** * Strain identifier for the cannabis strain being cultivated in this batch. */ strainId: number; /** * Room identifier for the immature batch location assignment. */ roomId: number; /** * Table identifier within the room for precise location tracking (optional). */ tableId: number | null; /** * Mother plant identifier for tracking genetic lineage (required for clone batches). */ motherPlantId: number | null; /** * Date when the immature batch was created for cultivation timeline documentation. */ dateCreated: string | null; }; export type BooleanNullableOptional = boolean; export type BooleanOptional = boolean; export type Brand = { brandId: number; brandName: string | null; brandCatalogBrandId: string | null; }; export type BrandEditRequest = { brandId: number | null; brandName: string | null; }; export type BroadcastedResponses = { responses: Array | null; }; export type BulkCreateOrUpdateHarvest = { harvests: Array | null; }; export type BulkCreateOrUpdateHarvestResponse = { createdHarvestIds: Array | null; updatedHarvestIds: Array | null; }; export type BulkHarvestDetail = { harvestId: number | null; harvestName: string | null; harvestRoomId: number; harvestDate: string | null; strainId: number; }; export type CalculationMethod = 1 | 2 | 3 | 4 | 5 | 6 | 15; /** * Request model for canceling existing customer pre-orders before fulfillment. */ export type CancelPreorderRequest = { /** * Unique identifier of the pre-order to be canceled. */ orderId: number; /** * Required reason for canceling the order (used for business analytics and customer service). */ cancellationReason: string | null; }; /** * Laboratory test result value model for cannabinoid and terpene measurements in cannabis products. */ export type CannabinoidTerpeneValue = { /** * Name of the laboratory test result (e.g., "THC", "CBD", "Limonene") - must match predefined compound list. */ labResultName: string; /** * Measured value of the compound in the cannabis sample (decimal precision for accurate reporting). */ value: number; /** * Unit identifier for the measurement (references LabResultUnit enum - mg/g, percentage, etc.). */ labResultUnitId: number; }; export type CartItemPrice = { productName: string | null; productId: number; quantity: number; subtotal: number; pricingTierAdjustment: number | null; discounts: Array | null; tax: number; }; export type CartPrice = { cartItemPrices: Array | null; subTotal: number; taxes: number; discount: number; total: number; originalTotal: number; roundedDifference: number; }; /** * Request model for updating the cultivation growth phase of cannabis plants to track development stages. * * **Growth Phase Management:** * - Updates plant cultivation phase for proper development tracking * - Supports bulk processing of multiple plants in single operation * - Validates growth phase against allowed phase values * - Automatically sets phase start date if not provided * * **Valid Growth Phases:** * - `Propagation`: Initial plant development and cloning phase * - `Vegetative`: Active vegetative growth before flowering initiation * - `Flowering`: Reproductive growth phase leading to harvest * * **Phase Transition Rules:** * - Phase start date defaults to current UTC time if not specified * - Phase changes are logged for cultivation timeline tracking * - Integration with external cultivation systems for environmental control */ export type ChangeGrowthPhaseRequest = { /** * Collection of LeafLogix plant IDs to update to the new growth phase */ plantIds: Array | null; /** * Target cultivation growth phase. Must be one of: `Propagation`, `Vegetative`, `Flowering` */ growthPhase: string | null; /** * Date when new growth phase begins (optional, defaults to current UTC time if not specified) */ phaseStartDate: string | null; }; /** * Product category sales summary for cannabis retail closing reports and financial analysis. */ export type ClosingReportCategorySummary = { /** * Product category name (e.g., "Flower", "Edibles", "Concentrates"). */ category: string | null; /** * Total net sales for the category (calculated property returning CategoryNetTotal). */ readonly categoryTotal: number; /** * Gross sales total for the category before discounts (in USD). */ categoryGrossTotal: number; /** * Total discount amount applied to products in this category (in USD). */ categoryDiscountTotal: number; /** * Net sales total for the category after discounts (in USD). */ categoryNetTotal: number; /** * Total cost of goods sold for products in this category (in USD). */ categoryCost: number; }; /** * Customer type sales summary for cannabis retail closing reports and customer segment analysis. */ export type ClosingReportCustomerTypeSummary = { /** * Customer type classification (e.g., "Recreational", "Medical", "Industry"). */ customerType: string | null; /** * Total net sales for this customer type (calculated property returning NetTotal). */ readonly total: number; /** * Gross sales total for this customer type before discounts (in USD). */ grossTotal: number; /** * Net sales total for this customer type after discounts (in USD). */ netTotal: number; /** * Total discount amount applied to this customer type (in USD). */ discountTotal: number; /** * Total cost of goods sold for this customer type (in USD). */ customerTypeCost: number; /** * Cannabis product sales total for this customer type (in USD). */ cannabisSales: number; /** * Non-cannabis product sales total for this customer type (accessories, etc.) (in USD). */ nonCannabisSales: number; }; /** * Order source sales summary for cannabis retail closing reports and marketing channel analysis. */ export type ClosingReportOrderSourceSummary = { /** * Order origination source (e.g., "Website", "Mobile App", "Weedmaps", "Walk-In"). */ orderSource: string | null; /** * Total net sales for this order source (calculated property returning NetTotal). */ readonly total: number; /** * Gross sales total for this order source before discounts (in USD). */ grossTotal: number; /** * Net sales total for this order source after discounts (in USD). */ netTotal: number; /** * Total discount amount applied to this order source (in USD). */ discountTotal: number; orderSourceCost: number; }; /** * Order type sales summary for cannabis retail closing reports and fulfillment channel analysis. */ export type ClosingReportOrderTypeSummary = { /** * Order fulfillment type (e.g., "In-Store", "Pickup", "Delivery", "Curbside"). */ orderType: string | null; /** * Total net sales for this order type (calculated property returning NetTotal). */ readonly total: number; /** * Gross sales total for this order type before discounts (in USD). */ grossTotal: number; /** * Net sales total for this order type after discounts (in USD). */ netTotal: number; /** * Total discount amount applied to this order type (in USD). */ discountTotal: number; /** * Total cost of goods sold for this order type (in USD). */ orderTypeCost: number; }; /** * Pay-by-Bank batch file summary for cannabis payment processing reconciliation. */ export type ClosingReportPayByBankBatchFileSums = { /** * Batch file name for payment processor identification and tracking. */ batchFileName: string | null; /** * Adjustment amount for the batch file for financial reconciliation. */ payByBankBatchFileAdjustmentAmount: number; }; /** * Payment method summary for cannabis retail closing reports and financial reconciliation. */ export type ClosingReportPaymentSummary = { /** * Payment method type (e.g., "Cash", "Credit Card", "CanPay", "Hypur"). */ paymentType: string | null; /** * Total amount paid using this payment method (in USD). */ totalPaid: number; }; /** * Tax rate summary for cannabis retail closing reports and tax liability tracking. */ export type ClosingReportTaxRateSummary = { /** * Tax rate name or type (e.g., "State Excise Tax", "City Cannabis Tax", "Sales Tax"). */ taxRate: string | null; /** * Total tax amount collected for this tax rate (in USD). */ totalTax: number; }; /** * Enhanced closing report model for cannabis dispensary daily financial operations with payment processing integration. */ export type ClosingReportV2 = { /** * Total tips aggregated for the closing period for staff distribution. */ readonly totalTips: number | null; /** * Tips processed through Pay-by-Bank system for electronic tip distribution. */ payByBankTips: number; /** * Transaction fees charged by Pay-by-Bank system for cost accounting. */ payByBankTransactionFees: number; /** * Batch file summaries for Pay-by-Bank transaction reconciliation. */ payByBankBatchFile: Array | null; /** * Fees and donations collected during the closing period for compliance reporting. */ feesDonations: Array | null; /** * DutchiePay tips processed for cannabis payment integration. */ readonly dutchiePayTips: number | null; /** * DutchiePay transaction adjustments for cannabis payment processing. */ readonly dutchiePayTotalAdjustmentAmount: number | null; /** * DutchiePay batch file summaries for cannabis payment reconciliation. */ readonly dutchiePayBatchFileSums: Array | null; grossSales: number | null; discount: number | null; loyalty: number | null; totalTax: number | null; cost: number | null; coupons: number | null; itemTotal: number | null; transactionCount: number; itemCount: number; customerCount: number; newCustomerCount: number; voidCount: number; voidTotal: number | null; returnTotal: number | null; startingBalance: number | null; endingBalance: number | null; deposits: number | null; adjustments: number | null; totalPayments: number | null; invoiceTotal: number | null; cannabisSales: number | null; nonCannabisSales: number | null; netSales: number | null; revenueFeesDonations: number | null; nonRevenueFeesDonations: number | null; rounding: number | null; totalIncome: number | null; averageCartNetSales: number | null; readonly overShort: number | null; categorySummary: Array | null; paymentSummary: Array | null; taxSummary: Array | null; customerTypeSummary: Array | null; orderTypeSummary: Array | null; orderSourceSummary: Array | null; }; /** * Detailed specification for converting individual plant batches during cultivation growth phase transitions. */ export type ConvertBatchDetails = { /** * Batch identifier for the plant batch being converted to mature growth phase. */ batchId: number; /** * Collection of individual plant serial numbers within the batch for state tracking compliance. */ serialNumbers: Array | null; /** * Target growth stage for the batch conversion (e.g., "Vegetative", "Flowering"). */ batchStage: string | null; /** * Destination room identifier for the converted batch location tracking. */ roomId: number; /** * Destination table identifier within the room for precise location tracking (optional). */ tableId: number | null; /** * Date when the batch conversion was performed for cultivation timeline documentation. */ dateCreated: string | null; }; /** * Request model for converting immature plant batches to mature growth phases in cannabis cultivation operations. */ export type ConvertImmatureBatchRequest = { /** * Collection of plant batches to be converted from immature to mature growth phases. */ batches: Array | null; }; /** * Response model for immature plant batch conversion operations containing converted mature plant identifiers. */ export type ConvertImmaturePlantResponse = { /** * Collection of mature plants created from immature batch conversion. */ convertedPlants: Array | null; }; export type ConvertImmaturePlantResponseApiResult = { result: boolean; message: string | null; data: ConvertImmaturePlantResponse; }; /** * Request model for creating anonymous transactions for guest customer operations. */ export type CreateAnonymousTransactionRequest = { /** * Optional reference identifier for the transaction (for external system integration). */ transactionReference: string | null; }; /** * Response model for immature plant batch creation operations containing created batch and plant identifiers. */ export type CreateImmaturePlantBatchResponse = { /** * Collection of created immature plant batches with associated plant identifiers. */ batches: Array | null; }; export type CreateImmaturePlantBatchResponseApiResult = { result: boolean; message: string | null; data: CreateImmaturePlantBatchResponse; }; /** * Request model for creating new customer journal entries with interaction details and notes. */ export type CreateJournalEntryRequest = { /** * The customer ID to create the journal entry for. */ customerId: number; /** * Brief title or summary of the journal entry. */ subject: string; /** * Detailed content and notes for the journal entry. */ body: string; /** * Date and time when the journal entry should be dated. */ date: string; }; /** * Request model for creating mature plant batches in cannabis cultivation operations. */ export type CreateMatureBatchRequest = { /** * Collection of mature plant batch specifications for bulk batch creation operations. */ batches: Array | null; }; /** * Response model for mature plant batch creation operations containing created mature plant identifiers. */ export type CreateMaturePlantsResponse = { /** * Collection of mature plants created ready for flowering phase cultivation. */ createdPlants: Array | null; }; export type CreateMaturePlantsResponseApiResult = { result: boolean; message: string | null; data: CreateMaturePlantsResponse; }; export type CreateOrUpdateHarvest = { harvestId: number | null; harvestName: string | null; strainName: string | null; harvestRoomId: number; harvestDate: string; }; export type CreatePlantRequest = { serialNumber: string | null; plantGroupName: string | null; growthPhase: string | null; phaseStartDate: string | null; dateCreated: string | null; bornDate: string | null; strain: string | null; room: string | null; table: string | null; isMother: boolean; bypassStateIntegration: boolean; }; export type CreatePreOrderRequest = { customerId: number; items?: Array | null; redemptions?: Array | null; isDelivery?: boolean; /** * @deprecated */ orderSource?: string | null; orderType?: string | null; deliveryStreet?: string | null; deliveryStreet2?: string | null; deliveryCity?: string | null; deliveryState?: string | null; deliveryPostalCode?: string | null; idempotencyKey?: string | null; notes?: string | null; status?: string | null; transactionReference?: string | null; timeWindowStartDateUtc?: string | null; timeWindowEndDateUtc?: string | null; deliveryScheduleId?: DeliveryScheduleType; }; export type CreateUpdatePurchaseOrderItemRequest = { productId: number; unitId: Int32NullableOptional; quantity: Int32NullableOptional; subtotal: DecimalNullableOptional; tax: DecimalNullableOptional; }; export type CreateUpdatePurchaseOrderRequest = { purchaseOrderId: number | null; expectedArrivalDate: DateTimeNullableOptional; title: StringOptional; dateReceived: DateTimeNullableOptional; shippingInformation: StringOptional; vendorContact: StringOptional; status: StringOptional; vendorId: Int32NullableOptional; purchaseOrderNumber: Int32NullableOptional; purchaseOrderItems: Array | null; }; export type CreateUpdatePurchaseOrderResponse = { createdPurchaseOrderIds: Array | null; updatedPurchaseOrderIds: Array | null; }; export type CreateUpdatePurchaseOrdersRequest = { purchaseOrders: Array | null; }; /** * Individual created immature plant batch containing batch identifier and associated plant IDs. */ export type CreatedImmaturePlantBatch = { /** * Unique identifier assigned to the created immature plant batch. */ batchId: number; /** * Collection of unique plant identifiers created within this batch. */ plantIds: Array | null; }; export type CreatedMaturePlant = { batchId: number; plantId: number; plantSerialNumber: string | null; }; /** * Represents a customer profile with personal information, contact details, and cannabis compliance data. */ export type Customer = { /** * Unique internal identifier for the customer record. */ customerId: number; /** * String representation of UniqueId for external API consumption. */ readonly uniqueId: string | null; /** * Deprecated name field (use FirstName and LastName instead). * * @deprecated */ name: string | null; /** * Customer's first name. */ firstName: string | null; /** * Customer's last name. */ lastName: string | null; /** * Customer's middle name. */ middleName: string | null; /** * Name suffix (Jr., Sr., III, etc.). */ nameSuffix: string | null; /** * Name prefix (Mr., Mrs., Dr., etc.). */ namePrefix: string | null; /** * Primary street address line. */ address1: string | null; /** * Secondary address line (apartment, suite, etc.). */ address2: string | null; /** * City name. */ city: string | null; /** * State or province. */ state: string | null; /** * Postal or ZIP code. */ postalCode: string | null; /** * Primary phone number. */ phone: string | null; /** * Cell phone number. */ cellPhone: string | null; /** * Email address. */ emailAddress: string | null; /** * Customer account status. */ status: string | null; /** * Medical marijuana identification number. */ mmjidNumber: string | null; /** * Medical marijuana ID expiration date. */ mmjidExpirationDate: string | null; /** * Last modification timestamp in UTC format. */ lastModifiedDateUTC: string | null; /** * Customer record creation date. */ creationDate: string | null; /** * Customer type classification. */ customerType: string | null; /** * Customer's gender. */ gender: string | null; /** * SHA2_256 hash of the Driver License ID */ driversLicenseHash: string | null; /** * Customer's date of birth. */ dateOfBirth: string | null; /** * External system customer identifier. */ externalCustomerId: string | null; /** * Name of the integration system that created this customer. */ createdByIntegrator: string | null; /** * Indicates if this is an anonymous customer record. */ isAnonymous: boolean; /** * How the customer heard about the dispensary. */ referralSource: string | null; /** * Additional details about referral source when "Other" is selected. */ otherReferralSource: string | null; /** * SpringBig loyalty system member identifier. */ springBigMemberId: number; /** * Custom identifier for external system integration. */ customIdentifier: string | null; /** * Collection of active discount groups for this customer. */ readonly discountGroups: Array | null; /** * Location where this customer record was created. */ createdAtLocation: string | null; /** * Additional notes about the customer. */ notes: string | null; /** * Indicates if customer is enrolled in loyalty program. */ isLoyaltyMember: boolean | null; /** * Primary medical condition for medical marijuana patients. */ primaryQualifyingCondition: string | null; /** * Additional medical conditions for medical marijuana patients. */ secondaryQualifyingConditions: Array | null; /** * Customer ID this record was merged into (if applicable). */ mergedIntoCustomerId: number | null; /** * Customer's marketing communication preference. */ optedIntoMarketing: boolean | null; /** * Customer's current loyalty program tier. */ loyaltyTier: string | null; }; /** * Search criteria model for customer lookup operations with flexible matching options. */ export type CustomerSearchRequest = { /** * Customer's last name for name-based search matching. */ lastName: string | null; /** * Customer's date of birth for identity verification and precise matching. */ dateOfBirth: string | null; /** * Customer's phone number for contact-based search matching. */ phone: string | null; /** * Customer's email address for account-based search matching. */ emailAddress: string | null; /** * Medical marijuana identification number for regulatory compliance search. */ mmjidNumber: string | null; /** * Driver's license identifier for government ID-based search matching. */ driversLicenseId: string | null; }; /** * Extended customer model that includes search match type information for customer lookup operations. */ export type CustomerSearchResult = { /** * Indicates how the customer record was matched during the search operation. */ matchType: string | null; /** * Unique internal identifier for the customer record. */ customerId: number; /** * String representation of UniqueId for external API consumption. */ readonly uniqueId: string | null; /** * Deprecated name field (use FirstName and LastName instead). * * @deprecated */ name: string | null; /** * Customer's first name. */ firstName: string | null; /** * Customer's last name. */ lastName: string | null; /** * Customer's middle name. */ middleName: string | null; /** * Name suffix (Jr., Sr., III, etc.). */ nameSuffix: string | null; /** * Name prefix (Mr., Mrs., Dr., etc.). */ namePrefix: string | null; /** * Primary street address line. */ address1: string | null; /** * Secondary address line (apartment, suite, etc.). */ address2: string | null; /** * City name. */ city: string | null; /** * State or province. */ state: string | null; /** * Postal or ZIP code. */ postalCode: string | null; /** * Primary phone number. */ phone: string | null; /** * Cell phone number. */ cellPhone: string | null; /** * Email address. */ emailAddress: string | null; /** * Customer account status. */ status: string | null; /** * Medical marijuana identification number. */ mmjidNumber: string | null; /** * Medical marijuana ID expiration date. */ mmjidExpirationDate: string | null; /** * Last modification timestamp in UTC format. */ lastModifiedDateUTC: string | null; /** * Customer record creation date. */ creationDate: string | null; /** * Customer type classification. */ customerType: string | null; /** * Customer's gender. */ gender: string | null; /** * SHA2_256 hash of the Driver License ID */ driversLicenseHash: string | null; /** * Customer's date of birth. */ dateOfBirth: string | null; /** * External system customer identifier. */ externalCustomerId: string | null; /** * Name of the integration system that created this customer. */ createdByIntegrator: string | null; /** * Indicates if this is an anonymous customer record. */ isAnonymous: boolean; /** * How the customer heard about the dispensary. */ referralSource: string | null; /** * Additional details about referral source when "Other" is selected. */ otherReferralSource: string | null; /** * SpringBig loyalty system member identifier. */ springBigMemberId: number; /** * Custom identifier for external system integration. */ customIdentifier: string | null; /** * Collection of active discount groups for this customer. */ readonly discountGroups: Array | null; /** * Location where this customer record was created. */ createdAtLocation: string | null; /** * Additional notes about the customer. */ notes: string | null; /** * Indicates if customer is enrolled in loyalty program. */ isLoyaltyMember: boolean | null; /** * Primary medical condition for medical marijuana patients. */ primaryQualifyingCondition: string | null; /** * Additional medical conditions for medical marijuana patients. */ secondaryQualifyingConditions: Array | null; /** * Customer ID this record was merged into (if applicable). */ mergedIntoCustomerId: number | null; /** * Customer's marketing communication preference. */ optedIntoMarketing: boolean | null; /** * Customer's current loyalty program tier. */ loyaltyTier: string | null; }; /** * Represents a customer type classification for cannabis dispensary operations and compliance. */ export type CustomerType = { /** * Unique identifier for the customer type. */ id: number; /** * Display name of the customer type. */ name: string | null; /** * Indicates whether this customer type is for medical marijuana patients. */ isMedical: boolean; /** * Indicates whether this customer type is for retail (adult-use) customers. */ isRetail: boolean; }; export type DateTimeNullableOptional = string; export type DecimalNullableOptional = number; /** * Request model for deleting a product image through the product image management API. */ export type DeleteImageRequest = { /** * The unique identifier of the product that owns the image to be deleted. */ productId: number; /** * The unique identifier of the specific image to be deleted from the product. */ imageId: number; }; export type DeliveryOrderStatus = { preOrderId: number | null; transactionId: number; status: string | null; orderDate: string; customerFirstName: string | null; customerLastName: string | null; customerId: number; orderType: string | null; orderSource: string | null; rejectedReason: string | null; total: number | null; subTotal: number | null; totalTax: number | null; streetAddress1: string | null; streetAddress2: string | null; city: string | null; deliveryState: string | null; postalCode: string | null; customerPhone: string | null; customerExpectedTimeStart: string; customerExpectedTimeEnd: string; dispatchDepartTime: string; dispatchArriveTime: string; items: Array | null; payments: Array | null; deliveryStatus: string | null; }; export type DeliveryPayment = { name: string | null; amount: number; }; export type DeliveryScheduleType = 1 | 2; export type Discount = { name: string | null; amount: number; discountId: number | null; }; export type DiscountApiResponse = { id: number | null; externalId: string | null; validDateFrom: string | null; validDateTo: string | null; maxRedemptions: number | null; redemptionLimit: number | null; firstTimeCustomerOnly: DiscountFirstTimeCustomer; discountDescription: string | null; discountCode: string | null; applicationMethodId: DiscountApplicationMethod; readonly applicationMethod: string | null; canStackAutomatically: boolean; onlineName: string | null; locationRestrictions: Array | null; restrictToGroupIds: Array | null; monday: boolean | null; tuesday: boolean | null; wednesday: boolean | null; thursday: boolean | null; friday: boolean | null; saturday: boolean | null; sunday: boolean | null; isActive: boolean; isBundledDiscount: boolean; constraints: Array | null; reward: DiscountRewardApiResponse; menuDisplay: DiscountMenuDisplayApiResponse; paymentRestrictions: DiscountPaymentRestrictionApiResponse; }; export type DiscountApplicationMethod = 1 | 2 | 3 | 4 | 5 | 6; export type DiscountConstraintApiResponse = { discountConstraintId: number | null; discountId: number; thresholdMin: number | null; includeNonCannabis: boolean; thresholdTypeId: DiscountThresholdType; readonly thresholdType: string | null; readonly hasThreshold: boolean; discountItemGroupTypeId: DiscountItemGroupType; readonly itemGroupType: string | null; restrictions: { [key: string]: IRestrictionApiResponse; } | null; }; export type DiscountFirstTimeCustomer = 0 | 1 | 2; /** * Discount group model for organizing and categorizing related discounts. */ export type DiscountGroup = { /** * Unique identifier for the discount group. */ discountGroupId: number; /** * Display name of the discount group for management and organization. */ discountGroupName: string | null; }; export type DiscountItemGroupType = 5 | 6; export type DiscountMenuDisplayApiResponse = { menuDisplayDescription: string | null; menuDisplayImageUrl: string | null; menuDisplayName: string | null; menuDisplayRank: number; }; export type DiscountPaymentRestrictionApiResponse = { payByBankSignupIncentive: boolean; }; /** * Discount restriction model defining entity inclusion or exclusion rules for discount application. */ export type DiscountRestriction = { /** * Collection of entity identifiers subject to the restriction rule. */ ids: Array | null; /** * Indicates if this is an exclusion rule (true) or inclusion rule (false). */ isExclusion: boolean; }; export type DiscountRewardApiResponse = { discountRewardId: number | null; discountId: number; calculationMethodId: CalculationMethod; readonly calculationMethod: string | null; discountValue: number; includeNonCannabis: boolean; highestOrLowest: string | null; thresholdTypeId: DiscountThresholdType; readonly thresholdType: string | null; readonly hasThreshold: boolean; itemGroupTypeId: DiscountItemGroupType; readonly itemGroupType: string | null; thresholdMin: number | null; thresholdMax: number | null; applyToOnlyOneItem: boolean; restrictions: { [key: string]: IRestrictionApiResponse; } | null; }; export type DiscountThresholdType = 1 | 2 | 3; export type DriverDetail = { driverId: number; name: string | null; stateId: string | null; driversLicense: string | null; }; /** * E-commerce customer data model for creating or updating customer profiles via API integration. */ export type EcomCustomerEdit = { /** * When specified, it updates the record, if the ID exists * null / unspecified will create a new customer */ customerId?: number | null; /** * Unique identifier for external system integration. */ uniqueId?: string | null; /** * Deprecated full name field (use FirstName and LastName instead). * * @deprecated */ name?: string | null; /** * Customer's first name (required). */ firstName: string; /** * Customer's last name. */ lastName?: string | null; /** * Customer's middle name. */ middleName?: string | null; /** * Name suffix (Jr., Sr., III, etc.). */ nameSuffix?: string | null; /** * Name prefix (Mr., Mrs., Dr., etc.). */ namePrefix?: string | null; /** * Primary street address line (required). */ address1: string; /** * Secondary address line (apartment, suite, etc.). */ address2?: string | null; /** * City name (required). */ city: string; /** * State or province (required). */ state: string; /** * Postal or ZIP code (required). */ postalCode: string; /** * Phone number. */ phone?: string | null; /** * Email address. */ emailAddress?: string | null; /** * Active; Cancelled; Hold; Banned */ status: string; /** * Medical marijuana identification number. */ mmjidNumber?: string | null; /** * Driver's license ID. */ driversLicenseID?: string | null; /** * Driver's license expiration date. */ driversLicenseExpiration?: string | null; /** * Medical marijuana ID expiration date. */ mmjidExpirationDate?: string | null; /** * Customer type classification (required). Use CustomerTypes endpoint to retrieve active customer types for a given location. */ customerType: string; /** * Customer's date of birth. */ dateOfBirth?: string | null; /** * External system customer identifier. */ externalCustomerId?: string | null; /** * Customer's gender. */ gender?: string | null; /** * Optional idempotency key for duplicate prevention. When provided with a ConsumerKey header, ensures the same customer creation request is not processed multiple times. */ idempotencyKey?: string | null; /** * How the customer heard about the dispensary. Use ReferralSources endpoint to retrieve values. */ referralSource?: string | null; /** * Custom identifier for external system integration. */ customIdentifier?: string | null; /** * Additional notes about the customer. */ notes?: string | null; /** * Indicates if customer is enrolled in loyalty program. */ isLoyaltyMember?: boolean | null; }; export type Employee = { userId: number; loginId: string | null; fullName: string | null; defaultLocation: string | null; status: string | null; stateId: string | null; mmjExpiration: string; permissionsLocation: string | null; groups: string | null; }; /** * Fee and donation tracking model for cannabis dispensary compliance and accounting. */ export type FeeDonation = { /** * Name of the fee or donation for identification and reporting purposes. */ name: string | null; /** * Cash value of the fee or donation for financial accounting. */ cashValue: number; /** * Flag indicating whether the fee or donation counts as revenue for accounting purposes. */ isRevenue: boolean; }; /** * Fee and donation information associated with cannabis retail transactions. */ export type FeeDonationInfo = { /** * Unique identifier for the specific fee or donation program. */ feeDonationId: number; /** * Description of the fee or donation for customer receipts and reporting. */ description: string | null; /** * Amount of the fee or donation (in USD). */ amount: number; /** * Indicates whether this fee counts as business revenue for accounting purposes. */ isRevenue: boolean; }; export type FinishOrUnfinishBatchDetails = { batchId: number; harvestCompletedOn: string | null; }; export type GuestListEntry = { name: string | null; checkinDateUTC: string; status: string | null; customerId: number; transactionId: number; transactionReferenceNumber: string | null; terminalName: string | null; customerType: string | null; phone: string | null; cellPhone: string | null; preOrderSource: string | null; }; export type Harvest = { harvestId: number; harvestName: string | null; harvestDate: string; harvestRoom: string | null; plantCount: number; plantWeight: number | null; wetWeight: number | null; wetWaste: number | null; dryBudWeight: number | null; dryShakeWeight: number | null; dryWaste: number | null; packageCount: number; packagedWeight: number | null; lastModifiedDateUTC: string; strainName: string | null; }; /** * Request model for moving cannabis plants from cultivation to harvest status with optional weight tracking. * * **Request Behavior:** * - Moves specified plants from cultivation status to harvesting status * - Supports bulk processing of multiple plants in single operation * - Optional weight tracking for harvest yield management * - Integrates with external cultivation systems when configured * * **Validation:** * - All plant IDs must exist and be accessible to the authenticated location * - Plants must be in valid status for harvesting (typically Active status) * - Harvest ID must correspond to existing harvest record */ export type HarvestPlantRequest = { /** * Collection of plants to be harvested with optional weight measurements */ plants: Array | null; /** * Target harvest record ID for associating harvested plants */ harvestId: number; /** * Date and time when harvest occurred (optional, defaults to current UTC time if not specified) */ harvestedOn: string | null; }; /** * Harvest waste detail model for tracking waste generated from specific harvest operations. */ export type HarvestWasteDetail = { /** * Identifier for the harvest batch generating this waste. */ harvestId: number; /** * Type or category of waste material from the harvest. */ wasteType: string | null; /** * Quantity of waste material generated from the harvest. */ wasteAmount: number; /** * Unit of measurement identifier for the waste amount. */ unitId: number; }; /** * Generic waste record model containing waste disposal information and associated detail records for cannabis compliance and waste tracking. */ export type HarvestWasteDetailWaste = { /** * Unique identifier for the waste record (null for new waste creation). */ wasteId: number | null; /** * Reference number for waste tracking and documentation. */ referenceNo: string | null; /** * Additional comments or notes about the waste disposal. */ comments: string | null; /** * Date when the waste disposal occurred. */ wasteDate: string | null; /** * Collection of waste detail records containing specific item information. */ wasteDetail: Array | null; /** * Licensed Service Provider identifier (internal use only). */ lspId: number | null; /** * Location identifier (internal use only). */ locId: number | null; /** * Indicates if room identification is required for this waste type (internal use only). */ roomRequired: boolean | null; /** * Indicates if this waste integrates with BioTrack system (internal use only). */ isBioTrack: boolean | null; }; /** * Individual plant harvest information with optional weight tracking for yield management. * * **Weight Tracking:** * - Weight is optional but recommended for harvest yield analysis * - Typically represents wet weight at time of harvest * - Used for compliance reporting and operational analytics */ export type HarvestedPlant = { /** * Unique LeafLogix plant identifier for the plant being harvested */ plantId: number; /** * Optional harvest weight measurement (typically wet weight in grams) */ weight: number | null; }; export type IRestrictionApiResponse = { isExclusion: boolean; }; export type Int32iEnumerableOptional = Array; export type Int32NullableOptional = number; /** * Integrated payment processing information for cannabis transactions processed through connected payment systems. */ export type IntegratedPayment = { /** * Type of integrated payment processor used for the transaction (e.g., "CreditCard", "CanPay", "ACH"). */ integrationType: string | null; /** * Amount paid through the integrated payment system (in USD). */ integratedPaid: number; /** * External payment identifier from the integrated payment processor for transaction tracking. */ externalPaymentId: string | null; }; export type InventoryDiscrepancy = { inventoryId: number | null; packageId: string | null; quantity: number; roomId: number; unitId: number; externalQuantity: number; externalUnitId: number; equivalentExternalQuantity: number | null; readonly difference: number; productName: string | null; room: string | null; externalRoom: string | null; batchModeQuantity: number | null; bioTrackCategoryName: string | null; externalBioTrackCategoryName: string | null; sku: string | null; unitErrorMsg: string | null; rooms: Array | null; serialNumber: string | null; }; export type InventoryIntegrationReconResponse = { lastUpdated: string | null; discrepancies: Array | null; }; /** * Inventory item model representing current stock and product details for available inventory. */ export type InventoryItem = { /** * Unit of measurement for unit weight, always "g" (grams). */ unitWeightUnit: string | null; /** * Unique inventory record identifier for this specific inventory item. */ inventoryId: number; /** * Product identifier linking this inventory to the product catalog. */ productId: number; /** * Stock Keeping Unit (SKU) code for inventory tracking and identification. */ sku: string | null; /** * Display name of the product for customer-facing applications. */ productName: string | null; /** * Detailed product description including effects, characteristics, and usage information. */ description: string | null; /** * Category identifier for product classification (optional). */ categoryId: number | null; /** * Category name for product classification and filtering. */ category: string | null; /** * URL path to product image for display purposes. */ imageUrl: string | null; /** * Current available quantity for sale or transfer. */ quantityAvailable: number; /** * Unit of measurement for the available quantity (e.g., "g", "mg", "ea"). */ quantityUnits: string | null; /** * Weight per unit in grams for dosing and compliance calculations. */ unitWeight: number; /** * Flower equivalent amount in grams for compliance tracking. */ flowerEquivalent: number; /** * Recreational flower equivalent amount in grams (optional). */ recFlowerEquivalent: number | null; /** * Unit of measurement for flower equivalent, always "g" (grams). */ readonly flowerEquivalentUnits: string | null; /** * Batch identifier for lot tracking and quality control. */ batchId: number; /** * Human-readable batch name or lot number for tracking. */ batchName: string | null; /** * Package identifier for compliance tracking and traceability. */ packageId: string | null; /** * Current status of the package (e.g., "Active", "Testing", "Quarantine"). */ packageStatus: string | null; /** * Base unit price for retail sales. */ unitPrice: number; /** * Medical program pricing (optional, different from retail). */ medUnitPrice: number | null; /** * Recreational program pricing (optional, different from medical). */ recUnitPrice: number | null; /** * Strain identifier for cannabis products (optional). */ strainId: number | null; /** * Strain name for cannabis products. */ strain: string | null; /** * Cannabis strain classification (Hybrid, Indica, Sativa, CBD). */ strainType: string | null; /** * Product size designation for packaging and dosing information. */ size: string | null; /** * Collection of laboratory test results for this batch (included when includeLabResults=true). */ labResults: Array | null; /** * Date when laboratory testing was completed (optional). */ testedDate: string | null; /** * Date when sample was collected for laboratory testing (optional). */ sampleDate: string | null; /** * Date when product was packaged for distribution (optional). */ packagedDate: string | null; /** * Date when product was manufactured or produced (optional). */ manufacturingDate: string | null; /** * Last modification timestamp in UTC for data synchronization. */ lastModifiedDateUtc: string | null; /** * Current status of laboratory testing (e.g., "Passed", "Failed", "Pending"). */ labTestStatus: string | null; /** * Vendor identifier for the supplier of this inventory (optional). */ vendorId: number | null; /** * Vendor name for the supplier of this inventory. */ vendor: string | null; /** * Product expiration date for compliance and quality control (optional). */ expirationDate: string | null; /** * Quantity breakdown by storage room/location (included when includeRoomQuantities=true). */ roomQuantities: Array | null; /** * Pricing tier classification for bulk pricing strategies. */ pricingTierName: string | null; /** * Alternative product name for display purposes. */ alternateName: string | null; /** * Collection of compliance tags associated with this inventory package. */ tags: Array | null; /** * Brand identifier for branded products (optional). */ brandId: number | null; /** * Brand name for branded products. */ brandName: string | null; /** * Indicates if product is restricted to medical program only. */ medicalOnly: boolean; /** * External compliance system ID (METRC or BioTrack) for regulatory tracking. */ externalPackageId: string | null; /** * Producer name for cultivation and manufacturing tracking. */ producer: string | null; /** * Producer identifier for cultivation and manufacturing tracking (optional). */ producerId: number | null; /** * Package lineage information for traceability and compliance tracking. */ lineage: Array | null; /** * Potency classification indicator for dosing guidance. */ potencyIndicator: string | null; /** * Master category classification for product grouping. */ masterCategory: string | null; /** * Effective potency in milligrams for dosing calculations (optional). */ effectivePotencyMg: number | null; /** * Indicates if product contains cannabis or is cannabis-related. */ isCannabis: boolean; /** * National Drug Code for pharmaceutical tracking (optional). */ packageNDC: string | null; /** * URL to certificate of analysis or lab testing document. */ labResultUrl: string | null; }; /** * Cannabis inventory quantity tracking model by room location for facility management and compliance. */ export type InventoryRoomQuantity = { /** * Room identifier for the storage location. */ roomId: number; /** * Room name or description for the storage location. */ room: string | null; /** * Quantity of cannabis product available in this specific room location. */ quantityAvailable: number; }; /** * Historical inventory snapshot model representing inventory levels at a specific point in time. */ export type InventorySnapshot = { /** * Stock Keeping Unit (SKU) code for product identification. */ sku: string; /** * Product name as it existed at the snapshot date. */ product: string; /** * Product identifier linking to the product catalog. */ productId: number; /** * Storage room name where inventory was located at snapshot time. */ room: string; /** * Storage room identifier for location tracking. */ roomId: number; /** * Vendor name for the supplier of this inventory (optional). */ vendor?: string | null; /** * Package identifier for compliance tracking and traceability. */ packageId: string; /** * Batch name or lot number for quality tracking (optional). */ batchName?: string | null; /** * Batch identifier for lot tracking (optional). */ batchId?: number | null; /** * Inventory quantity as it existed at the snapshot date. */ quantity: number; /** * Total cost value of the inventory quantity (optional). */ totalCost?: number | null; /** * Unit of measurement for the quantity. */ unit: string; /** * Unit identifier for the measurement type. */ unitId: number; /** * Inventory status at the time of snapshot (e.g., "Active", "Quarantine"). */ status?: string | null; /** * Date and time when this inventory snapshot was captured. */ snapshotDate: string; /** * Inventory record identifier linking to the specific inventory item. */ inventoryId: number; }; export type InventoryTag = { tagId: number; tagName: string | null; packageId: string | null; }; /** * Inventory transaction record model representing historical inventory movement and modification operations. */ export type InventoryTransaction = { /** * Unique identifier for the inventory transaction record. */ inventoryTransactionId: number; /** * Type of inventory transaction performed. * **Options**: Move, Convert, Adjust, Combine, Receive, Change Product, Discontinue, Detail Update, Reconciliation, Create Package */ transactionType?: string | null; /** * Product name at the time of transaction. */ product?: string | null; /** * Stock Keeping Unit (SKU) code for the product. */ sku?: string | null; /** * Product identifier linking to the product catalog. */ productId?: number; /** * Unit of measurement for the transaction quantities. */ unit?: string | null; /** * Package identifier for compliance tracking and traceability. */ packageId?: string | null; /** * External package identifier from integrated compliance systems. */ externalPackageId?: string | null; /** * Batch identifier for lot tracking (optional). */ batchId?: number | null; /** * Batch name or lot number for quality tracking (optional). */ batchName?: string | null; /** * Transaction quantity for non-adjustment operations (Move, Convert, Receive, etc.). */ quantity?: number | null; /** * Original quantity before adjustment (used for Adjust transaction type). */ fromQuantity?: number | null; /** * New quantity after adjustment (used for Adjust transaction type). */ toQuantity?: number | null; /** * Reason for adjustment (used for Adjust transaction type). */ reason?: string | null; /** * Receive inventory history identifier for received inventory linkage (optional). */ receiveInventoryHistoryId?: number | null; /** * Source location name for Move transactions. */ fromLocation?: string | null; /** * Source room name for Move transactions. */ fromRoom?: string | null; /** * Destination location name for Move transactions. */ toLocation?: string | null; /** * Destination room name for Move transactions. */ toRoom?: string | null; /** * Conversion transaction identifier for Convert operations (optional). */ conversionTransactionID?: number | null; /** * Username or identifier of the person who performed the transaction. */ transactionBy?: string | null; /** * Date and time when the transaction was performed. */ transactionDate?: string; /** * Unit cost of the package at the time of transaction (optional). */ unitCost?: number | null; /** * Purchase order identifier for received inventory linkage (optional). */ purchaseOrderId?: number | null; /** * Unique inventory item identifier affected by this transaction. */ inventoryId?: number; }; /** * Represents a customer journal entry containing notes and interaction history for customer service tracking. */ export type JournalEntry = { /** * Unique identifier for the journal entry. */ journalEntryId: number; /** * Brief title or summary of the journal entry. */ subject: string | null; /** * Detailed content and notes for the journal entry. */ body: string | null; /** * Date and time when the journal entry was created or should be dated. */ date: string; }; /** * Laboratory testing result model for cannabis and cannabis product analysis. */ export type LabResult = { /** * Name of the laboratory test performed (e.g., "THC", "CBD", "Myrcene", "Total Aerobic Count"). */ labTest: string | null; /** * Numeric test result value (null if not detected or not applicable). */ value: number | null; labResultUnitId: LabResultUnit; /** * Human-readable unit name corresponding to the LabResultUnitId. */ readonly labResultUnit: string | null; }; export type LabResultUnit = 1 | 2 | 3 | 4 | 5 | 6; /** * Laboratory result unit data model for cannabis testing measurements and reporting. */ export type LabResultUnitData = { /** * Unique identifier for the lab result unit type. */ labResultUnitId: number; /** * Display name of the lab result unit (e.g., "mg", "%", "mg/g", "ND", "LOQ", "Pass/Fail"). */ labResultUnit: string | null; }; /** * Tax information applied to individual transaction line items in cannabis retail operations. */ export type LineItemTaxInfo = { /** * Name of the tax rate applied (e.g., "State Excise Tax", "City Cannabis Tax", "Sales Tax"). */ rateName: string | null; /** * Tax rate as a decimal percentage (e.g., 0.0875 for 8.75% tax rate). */ rate: number; /** * Calculated tax amount applied to the line item (in USD). */ amount: number; /** * Reference identifier linking this tax information back to the specific transaction line item. * Not guaranteed to be unique outside of a single transaction. */ readonly transactionItemId: number; }; /** * Cannabis genetic lineage model containing hereditary classification information for product categorization and genetic tracking. */ export type Lineage = { /** * Unique identifier for the genetic lineage. */ lineageId: number; /** * Display name for the genetic lineage (e.g., "Indica", "Sativa", "Hybrid"). */ lineageName: string | null; }; /** * Location identity model containing complete location and parent company information for API key verification and context identification. */ export type LocationIdentity = { /** * Unique identifier for the cannabis dispensary location. */ locationId: number; /** * Unique identifier for the parent company (LSP - Licensed Service Provider). */ lspId: number; /** * Business name of the cannabis dispensary location. */ locationName: string | null; /** * Company name of the parent organization (Licensed Service Provider). */ lspName: string | null; /** * Primary street address of the dispensary location. */ address: string | null; /** * Secondary address line (suite, unit, etc.) if applicable. */ address2: string | null; /** * City where the dispensary is located. */ city: string | null; /** * State or province where the dispensary is licensed to operate. */ state: string | null; /** * Postal code (ZIP code) for the dispensary location. */ postalCode: string | null; /** * State-issued cannabis business license number for regulatory compliance. */ licenseNumber: string | null; /** * "Doing Business As" name if different from the legal business name. */ doingBusinessAs: string | null; /** * Indicates whether customer profiles are shared across locations within the organization. */ shareCustomerProfiles: boolean; /** * Legacy global unique identifier for the location (deprecated). * * @deprecated */ globalId: string | null; /** * Global unique identifier for the location across all systems and integrations. */ locationGlobalId: string | null; /** * Global unique identifier for the parent company (LSP) across all systems. */ lspGlobalId: string | null; /** * Regional identifier for compliance and API routing (internal use only). */ region: string | null; /** * Base64-encoded SHA256 hash of the region identifier for secure regional routing. */ readonly regionId: string | null; }; /** * Location mapping model for associating discounts with specific business locations. */ export type LocationMapping = { /** * Name of the location where the discount applies. */ locationName: string | null; }; export type LocationProductOverride = { productId: number; price: number | null; recPrice: number | null; cost: number | null; onlineAvailable: boolean | null; posAvailable: boolean | null; maxPurchasable: number | null; lowInventoryThreshold: number | null; customMetadata: string | null; }; export type LocationProductOverrideRequest = { /** * Product identifier for the product being configured with location-specific overrides. */ productId: number; price: DecimalNullableOptional; recPrice: DecimalNullableOptional; cost: DecimalNullableOptional; onlineAvailable: BooleanNullableOptional; posAvailable: BooleanNullableOptional; maxPurchasable: DecimalNullableOptional; lowInventoryThreshold: DecimalNullableOptional; customMetadata: StringOptional; }; export type LocationResponse = { locationName: string | null; locId: number; licenseNumber: string | null; readonly outcome: string | null; readonly outcomeId: number; broadcastedTo: string | null; errorDetail: string | null; }; /** * Represents a customer's loyalty program balance and activity snapshot for reporting purposes. * * Contains current point balances and historical activity for individual customers within the * loyalty program. Used for daily balance reporting, customer service inquiries, and loyalty * program analytics. Data reflects nightly batch processing and may not include real-time changes. */ export type LoyaltySnapshot = { /** * Unique identifier for the customer in the loyalty program. * Links this loyalty snapshot to the specific customer account. */ customerId: number; /** * Current available loyalty points balance for the customer. * Represents points that can be redeemed for rewards or discounts. */ loyaltyBalance: number; /** * Total loyalty points redeemed/spent by the customer over their lifetime. * Historical record of all point redemptions and rewards claimed. */ loyaltySpent: number; /** * Total loyalty points earned by the customer over their lifetime. * Historical record of all points awarded through purchases and activities. */ loyaltyEarned: number; }; /** * Manual payment information for cannabis transactions processed outside integrated payment systems. */ export type ManualPayment = { /** * Name of the manual payment processor or handling method (e.g., "Cash", "Check", "Money Order"). */ manualPaymentProcessorName: string | null; /** * Amount paid through the manual payment method (in USD). */ manualPaid: number; }; /** * Detailed specification for creating individual mature plant batches with compliance tracking information. */ export type MatureBatchDetails = { /** * Batch identifier for the mature plant batch being created. */ batchId: number; /** * Collection of individual plant serial numbers within the mature batch for state tracking compliance. */ serialNumbers: Array | null; /** * Growth stage designation for the mature batch (e.g., "Vegetative", "Flowering"). */ batchStage: string | null; /** * Room identifier for the mature batch location assignment. */ roomId: number; /** * Table identifier within the room for precise location tracking (optional). */ tableId: number | null; /** * Date when the mature batch was created for cultivation timeline documentation. */ dateCreated: string | null; }; /** * Request model for moving cannabis plants to a different cultivation room or table within the same facility. * * **Movement Behavior:** * - Moves specified plants to target room within same facility * - Optional table assignment for precise cultivation area management * - Validates target room belongs to same facility for security * - Automatically updates plant cultivation stage if room has associated stage * * **Facility Restrictions:** * - Target room must belong to same facility as requesting user * - Cross-facility plant movements are prohibited for security and compliance * - All plant IDs must be accessible to the authenticated location * * **Integration:** * - Movement synchronized with external cultivation systems when configured * - Supports cultivation workflow automation and environmental optimization */ export type MovePlantRequest = { /** * Collection of LeafLogix plant IDs to move to the target room */ plantIds: Array | null; /** * Target cultivation room ID within the same facility where plants will be moved */ roomId: number; /** * Optional table ID within the target room for precise plant positioning (optional) */ tableId: number | null; }; /** * Generic waste record model containing waste disposal information and associated detail records for cannabis compliance and waste tracking. */ export type ObjectWaste = { /** * Unique identifier for the waste record (null for new waste creation). */ wasteId: number | null; /** * Reference number for waste tracking and documentation. */ referenceNo: string | null; /** * Additional comments or notes about the waste disposal. */ comments: string | null; /** * Date when the waste disposal occurred. */ wasteDate: string | null; /** * Collection of waste detail records containing specific item information. */ wasteDetail: Array<{ [key: string]: unknown; }> | null; /** * Licensed Service Provider identifier (internal use only). */ lspId: number | null; /** * Location identifier (internal use only). */ locId: number | null; /** * Indicates if room identification is required for this waste type (internal use only). */ roomRequired: boolean | null; /** * Indicates if this waste integrates with BioTrack system (internal use only). */ isBioTrack: boolean | null; }; /** * Package lineage tracking model for cannabis product traceability and regulatory compliance. */ export type PackageLineage = { /** * Package identifier for the current package in the lineage chain. */ packageId: string | null; /** * Number of generations between current package and antecedent package in the lineage chain. */ antecedentPackageDistance: number; /** * Flag indicating whether the antecedent package originated from a harvest operation. */ antecedentIsHarvest: boolean; /** * Batch name for the current package for lot tracking and quality control. */ batchName: string | null; /** * Batch name of the antecedent package for lineage and quality tracking. */ antecedentBatchName: string | null; }; export type Plant = { plantId: number; serialNumber: string | null; growthPhase: string | null; type: string | null; harvestedWeight: number | null; status: string | null; plantCount: number | null; isMother: boolean; motherPlantId: number | null; plantedOn: string | null; addedToHarvestOn: string | null; harvestDate: string | null; destroyedDate: string | null; plantGroupName: string | null; strain: string | null; room: string | null; table: string | null; vegetationStartedOn: string | null; vegetationEndedOn: string | null; floweringStartedOn: string | null; floweringEndedOn: string | null; currentPhaseStartDate: string | null; lastModifiedDate: string | null; daysInCurrentPhase: number | null; floweringRoom: string | null; floweringTable: string | null; vegetationRoom: string | null; vegetationTable: string | null; daysInFlowering: number | null; daysInVegetation: number | null; batchId: number; readonly harvestId: number; }; /** * Plant waste detail model for tracking waste generated from specific plant disposal operations. */ export type PlantWasteDetail = { /** * Identifier for the plant generating this waste. */ plantId: number; /** * Type or category of waste material from the plant. */ wasteType: string | null; /** * Quantity of waste material generated from the plant. */ wasteAmount: number; /** * Unit of measurement identifier for the waste amount. */ unitId: number; }; /** * Generic waste record model containing waste disposal information and associated detail records for cannabis compliance and waste tracking. */ export type PlantWasteDetailWaste = { /** * Unique identifier for the waste record (null for new waste creation). */ wasteId: number | null; /** * Reference number for waste tracking and documentation. */ referenceNo: string | null; /** * Additional comments or notes about the waste disposal. */ comments: string | null; /** * Date when the waste disposal occurred. */ wasteDate: string | null; /** * Collection of waste detail records containing specific item information. */ wasteDetail: Array | null; /** * Licensed Service Provider identifier (internal use only). */ lspId: number | null; /** * Location identifier (internal use only). */ locId: number | null; /** * Indicates if room identification is required for this waste type (internal use only). */ roomRequired: boolean | null; /** * Indicates if this waste integrates with BioTrack system (internal use only). */ isBioTrack: boolean | null; }; /** * Request model for creating immature plant batches in cannabis cultivation operations. */ export type PostImmatureBatchRequest = { /** * Collection of immature plant batch specifications for bulk batch creation operations. */ batches: Array | null; }; export type PreOrderItem = { productId: number; quantity: number; }; export type PreOrderRedemption = { productId?: number | null; redemptionType: string; redemptionId: string; redemptionDescription?: string | null; redemptionCallbackUrl?: string | null; }; export type PreOrderRedemptionIEnumerableOptional = Array; export type PreOrderStatus = { preOrderId: number; status: string | null; transactionId: number | null; orderDate: string; customerFirstName: string | null; customerLastName: string | null; customerId: number; orderType: string | null; orderSource: string | null; rejectedReason: string | null; isCancellable: boolean; isUpdateable: boolean; total: number | null; subTotal: number | null; totalTax: number | null; sourceSystem: string | null; items: Array | null; }; export type PrecartItem = { productId: number; quantity: number; }; /** * Request model for calculating pricing, taxes, and discounts for a customer's shopping cart before creating a pre-order. */ export type PriceCartRequest = { /** * Collection of products in the customer's shopping cart with quantities and specifications. */ cart: Array | null; /** * Customer type identifier for pricing tier and discount eligibility (e.g., medical, recreational). */ customerTypeId: number | null; /** * Unique customer identifier for personalized pricing and loyalty program benefits. */ customerId: number | null; /** * Primary street address for delivery orders (used for tax calculation and delivery fee estimation). */ deliveryStreet: string | null; /** * Secondary address information (apartment, suite, unit number) for delivery orders. */ deliveryStreet2: string | null; /** * City name for delivery address (used for tax jurisdiction determination). */ deliveryCity: string | null; /** * State or province for delivery address (used for tax calculation and compliance verification). */ deliveryState: string | null; /** * Postal or ZIP code for delivery address (used for precise tax calculation and delivery zones). */ deliveryPostalCode: string | null; /** * Indicates whether this is a delivery order (true) or pickup order (false) for tax and fee calculation. */ isDelivery: boolean; }; export type PriceEstimates = { discountAmount: number; taxAmount: number; feeAmount: number; subtotal: number; grandTotal: number; }; /** * Pricing detail information for cannabis products with medical and recreational pricing tiers. */ export type PricingDetail = { /** * Medical cannabis patient pricing (typically lower due to tax benefits and patient programs). */ medPrice: number | null; /** * Recreational adult-use cannabis pricing (standard retail pricing with full taxes). */ recPrice: number | null; /** * Pricing tier name for customer segmentation (e.g., "Standard", "VIP", "Bulk", "Employee"). */ pricingTierName: string | null; }; export type PricingTier = { pricingTierId: number; pricingTierName: string | null; }; export type PricingTierData = { startWeight: number | null; endWeight: number | null; price: number; medicalPrice: number; }; /** * Producer identification model containing basic producer information for product attribution and reference data needs. */ export type Producer = { /** * Unique identifier for the producer. */ producerId: number; /** * Display name of the producer for product attribution and branding. */ producerName: string | null; }; /** * Product category model containing cannabis product classification information for menu organization and product management. */ export type ProductCategory = { /** * Unique identifier for the product category. */ productCategoryId: number; /** * Display name of the product category (e.g., "Flower", "Edibles", "Concentrates"). */ productCategoryName: string | null; /** * Higher-level master category classification for broader product grouping. */ masterCategory: string | null; }; export type ProductDetail = { productId: number; sku: string | null; internalName: string | null; productName: string | null; description: string | null; masterCategory: string | null; categoryId: number | null; category: string | null; imageUrl: string | null; imageUrls: Array | null; strainId: number | null; strain: string | null; strainType: string | null; size: string | null; netWeight: number | null; netWeightUnitId: number | null; readonly netWeightUnit: string | null; brandId: number | null; brandName: string | null; vendorId: number | null; vendorName: string | null; isCannabis: boolean; isActive: boolean; isCoupon: boolean; thcContent: number | null; thcContentUnit: string | null; cbdContent: number | null; cbdContentUnit: string | null; productGrams: number | null; flowerEquivalent: number | null; recFlowerEquivalent: number | null; price: number | null; medPrice: number | null; recPrice: number | null; unitCost: number | null; unitType: string | null; onlineTitle: string | null; onlineDescription: string | null; readonly onlineProduct: boolean | null; posProducts: boolean | null; pricingTier: number | null; onlineAvailable: boolean | null; lowInventoryThreshold: number | null; pricingTierName: string | null; pricingTierDescription: string | null; pricingTierData: Array | null; flavor: string | null; alternateName: string | null; lineageName: string | null; distillationName: string | null; maxPurchaseablePerTransaction: number | null; tags: Array | null; effects: Array | null; dosage: string | null; instructions: string | null; allergens: string | null; standardAllergens: StandardAllergensDetails; defaultUnit: string | null; producerId: number | null; producerName: string | null; createdDate: string | null; isMedicalOnly: boolean; lastModifiedDateUTC: string | null; grossWeight: number | null; isTaxable: boolean | null; taxCategories: Array | null; upc: string | null; regulatoryCategory: string | null; ndc: string | null; daysSupply: number | null; readonly illinoisTaxCategory: string | null; externalCategory: string | null; externalId: string | null; syncExternally: boolean; regulatoryName: string | null; broadcastedResponses: BroadcastedResponses; administrationMethod: string | null; unitCBDContentDose: number | null; unitTHCContentDose: number | null; oilVolume: number | null; ingredientList: string | null; expirationDays: number | null; abbreviation: string | null; isTestProduct: boolean; isFinished: boolean; allowAutomaticDiscounts: boolean; servingSize: string | null; servingSizePerUnit: number | null; isNutrient: boolean; approvalDateUTC: string | null; ecomCategory: string | null; ecomSubcategory: string | null; customMetadata: string | null; }; /** * Product upload model for creating and updating products. * * ⚠️ **DATA LOSS WARNING**: Most fields will be overwritten with null/zero if not provided. * **RECOMMENDED**: Use GET /products first, modify needed fields, then POST the complete object. */ export type ProductDetailUpload = { /** * The unique identifier for a product in the system. * * **IMPORTANT**: This field determines whether a product is created or updated: * - To CREATE a new product: Omit this field or set to null * - To UPDATE an existing product: You MUST provide the ProductId of the existing product */ productId?: number | null; /** * Product SKU - REQUIRED for CREATE operations */ sku: string; /** * Product Name - REQUIRED for CREATE operations */ productName: string; /** * Deprecated in favor of AlternateName */ description?: string | null; alternateName?: string | null; masterCategory?: string | null; category?: string | null; strain?: string | null; /** * Strain type of the specified strain. * Used to disambiguate strains, if duplicates exist. * If no duplicates exist in the location's strain list, this field is not useful. * If duplicates DO exist and this field is not specified, the strain will be chosen by the first one created. */ strainType?: string | null; size?: string | null; netWeight?: number | null; /** * Optional. Abbreviation of the unit of the product's net weight. */ netWeightUnit?: string | null; grossWeight?: number | null; brandName?: string | null; vendorName?: string | null; isCannabis?: boolean; isActive?: boolean; thcContent?: number | null; /** * mg; %; mg/g; n.d. */ thcContentUnit?: string | null; cbdContent?: number | null; /** * mg; %; mg/g; n.d. */ cbdContentUnit?: string | null; productGrams?: number | null; flowerEquivalent?: number | null; recFlowerEquivalent?: number | null; price?: number | null; unitCost?: number | null; unitType?: string | null; onlineTitle?: string | null; onlineDescription?: string | null; onlineProduct?: boolean | null; posProducts?: boolean | null; tags?: Array | null; defaultUnit?: string | null; isMedicalOnly?: boolean | null; isTaxable?: boolean | null; regulatoryCategory?: string | null; ndc?: string | null; daysSupply?: number | null; illinoisTaxCategory?: string | null; externalCategory?: string | null; externalId?: StringOptional; syncExternally?: boolean | null; bypassExternalUpdate?: boolean | null; administrationMethod?: StringOptional; unitCBDContentDose?: DecimalNullableOptional; unitTHCContentDose?: DecimalNullableOptional; oilVolume?: DecimalNullableOptional; ingredientList?: StringOptional; expirationDays?: Int32NullableOptional; abbreviation?: StringOptional; isTestProduct?: BooleanOptional; isFinished?: BooleanOptional; allowAutomaticDiscounts?: BooleanOptional; servingSize?: StringOptional; servingSizePerUnit?: Int32NullableOptional; isNutrient?: BooleanOptional; approvalDateUTC?: DateTimeNullableOptional; customMetadata?: StringOptional; /** * List of strings of tax categories that the product belongs to. */ taxCategories?: Array | null; pricingDetails?: PricingDetail; /** * UserName of the user making the product change * This will be used when authorizing with traceability systems (METRC/BioTrack) - if not included or NULL is specified, the traceability integration's "master key" will be used, if possible. * This field is only relevant if the request is setting SyncExternally to true */ userName?: string | null; instructions?: string | null; upc?: string | null; regulatoryName?: StringOptional; broadcast?: BooleanOptional; }; export type ProductEffect = { effectId: number; effectName: string | null; productId: number; }; export type ProductTag = { tagId: number; tagName: string | null; productId: number; }; /** * Published discount model containing complete discount configuration and constraint information for customer-facing applications. */ export type PublishedDiscount = { /** * Unique identifier for the discount. */ discountId: number; /** * Display name of the discount for customer-facing applications. */ discountName: string | null; /** * Monetary discount amount or percentage value. */ discountAmount: number; /** * Promotional code required to apply the discount (optional). */ discountCode: string | null; /** * Type classification of the discount (e.g., percentage, fixed amount). */ discountType: string | null; /** * Method used to apply the discount (e.g., automatic, code required). */ discountMethod: string | null; /** * Indicates if the discount is currently active and available. */ isActive: boolean; /** * Start date and time when discount becomes valid (UTC converted from Eastern Time). */ validFrom: string | null; /** * End date and time when discount expires (UTC converted from Eastern Time). */ validUntil: string | null; /** * Type of threshold requirement for discount eligibility (optional). */ thresholdType: string | null; /** * Minimum number of qualifying items required for discount application (optional). */ minimumItemsRequired: number | null; /** * Maximum number of items that can receive the discount (optional). */ maximumItemsAllowed: number | null; /** * Maximum number of times this discount can be used (optional). */ maximumUsageCount: number | null; /** * Indicates if discount applies to non-cannabis products. */ includeNonCannabis: boolean; /** * Indicates if discount is restricted to first-time customers only. */ firstTimeCustomerOnly: boolean; /** * Indicates if discount can be combined with other discounts. */ stackOnOtherDiscounts: boolean; weeklyRecurrenceInfo: WeeklyRecurrenceInfo; products: DiscountRestriction; productCategories: DiscountRestriction; brands: DiscountRestriction; vendors: DiscountRestriction; strains: DiscountRestriction; tiers: DiscountRestriction; tags: DiscountRestriction; inventoryTags: DiscountRestriction; customerTypes: DiscountRestriction; /** * Associated discount groups for bundling and organization (loaded conditionally). */ discountGroups: Array | null; }; export type PurchaseOrderData = { purchaseOrderId: number; expectedArrivalDate: string | null; title: string | null; dateReceived: string | null; dateSubmitted: string | null; shippingInformation: string | null; vendorId: number; vendorName: string | null; vendorContact: string | null; status: string | null; purchaseOrderNumber: number; createdByUser: string | null; dateCreated: string | null; purchaseOrderItems: Array | null; }; export type PurchaseOrderItemDetail = { purchaseOrderId: number; purchaseOrderItemId: number; productId: number; productName: string | null; quantity: number; unitId: number; unitName: string | null; unitNameAbbreviation: string | null; subtotal: number; tax: number; }; /** * Request model for receiving and recording new cannabis inventory items into the facility management system. */ export type ReceiveInventoryItemSave = { /** * Product identifier for the cannabis product being received into inventory (required). */ productId: number; /** * Quantity of the product being received into inventory (required). */ quantity: number; /** * Unit type for the received quantity (qty; ml; g; Gal; L; lb; mg; oz; fl oz; kg). */ unitType?: string | null; /** * Flower equivalent weight for regulatory compliance and limit calculations. */ flowerEquivalent?: number | null; /** * Recreational flower equivalent weight for regulatory compliance tracking. */ recFlowerEquivalent?: number | null; /** * Vendor identifier for supply chain tracking and vendor management. */ vendorId?: number | null; /** * Room identifier for facility location assignment and space management. */ roomId?: number | null; /** * Package identifier from state tracking system for compliance documentation. */ packageId?: string | null; /** * Lot number for batch tracking and quality control management. */ lot?: string | null; /** * Unit cost for inventory valuation and cost accounting. */ cost?: number | null; /** * General retail price for the received inventory item. */ price?: number | null; /** * Recreational market price for dual-license operations. */ recPrice?: number | null; /** * Tax amount for financial compliance and tax reporting. */ tax?: number | null; /** * Product expiration date for inventory rotation and compliance management. */ expirationDate?: string | null; /** * Collection of tag identifiers for product categorization and organization. */ tags?: Array | null; /** * Cultivation tax amount for cannabis-specific tax compliance. */ cultivationTax?: number | null; /** * Table identifier within the room for precise location tracking. */ tableId?: number | null; /** * Source allocated inventory identifier for traceability and audit trails. */ sourceAllocatedInventoryId?: number | null; /** * Total package cost for comprehensive cost allocation and accounting. */ totalPackageCost?: number | null; /** * Flag to retrieve lab results from Metrc for compliance integration. */ getMetrcLabResults?: boolean | null; /** * Product name for inventory identification and display purposes. */ productName?: string | null; /** * Date when the product was packaged for shelf life tracking. */ packagingDate?: string | null; /** * Date when the product was manufactured for quality control tracking. */ manufacturingDate?: string | null; /** * Producer identifier for supply chain tracking and compliance documentation. */ producerId?: number | null; /** * External package identifier for cross-system integration and tracking. */ externalPackageId?: string | null; /** * Potency indicator for product strength classification and customer information. */ potencyIndicator?: string | null; }; /** * Request model for creating inventory receive orders for incoming transfers, purchase orders, or direct inventory additions. */ export type ReceiveInventorySave = { /** * Vendor identifier for the supplier (optional, can be resolved from VendorLicense). */ vendorId?: number | null; /** * Name of the person who delivered the inventory shipment. */ deliveredBy?: string | null; /** * Date and time when the inventory was delivered (required). */ deliveredOn: string; /** * Vendor license code for compliance tracking and vendor identification. */ vendorLicense?: string | null; /** * External transaction reference ID for tracking and reconciliation. */ transactionId?: string | null; /** * Descriptive title for the receive order for identification purposes. */ orderTitle?: string | null; /** * External system ID for preventing duplicate receives (must be unique). */ externalId?: string | null; /** * Additional notes or comments about the receive transaction. */ note?: string | null; /** * Collection of inventory items being received in this transaction. */ items?: Array | null; /** * Indicates whether to immediately process items into inventory (true) or save as draft (false). */ receiveIntoInventory?: boolean | null; /** * User ID for processing the receive (required when ReceiveIntoInventory=true). */ userId?: number | null; /** * Username for processing the receive (alternative to UserId, required when ReceiveIntoInventory=true). */ userName?: string | null; }; /** * Received inventory record model representing completed or pending inventory receive orders and their processing status. */ export type ReceivedInventory = { /** * Unique identifier for the receive inventory transaction. */ receiveInventoryHistoryId: number; /** * Descriptive title for the receive order for identification purposes. */ title: string | null; /** * Current processing status of the receive order (e.g., "Pending", "Completed", "Failed"). */ status: string | null; /** * Error message if the receive order failed processing (optional). */ failureMessage: string | null; /** * Date and time when the inventory was delivered by the vendor (optional). */ deliveredOn: string | null; /** * Date and time when the receive order was created in the system (optional). */ addedOn: string | null; /** * Name of the vendor who supplied the inventory. */ vendor: string | null; /** * Vendor license code for compliance tracking and verification. */ vendorLicense: string | null; /** * Collection of inventory items included in this receive order. */ items: Array | null; }; /** * Response model representing received cannabis inventory items with complete tracking and financial information. */ export type ReceivedInventoryItem = { /** * Product name for inventory item identification and display. */ product: string | null; /** * Stock Keeping Unit (SKU) for product identification and retail operations. */ sku: string | null; /** * Product identifier for database references and system integration. */ productId: number | null; /** * Product type classification for cannabis product categorization. */ type: string | null; /** * Quantity of the received inventory item for stock tracking. */ quantity: number; /** * Unit abbreviation for quantity measurement display (e.g., "g", "oz", "ml"). */ unitAbbreviation: string | null; /** * Full unit name for quantity measurement (e.g., "grams", "ounces", "milliliters"). */ unit: string | null; /** * Cost per unit for inventory valuation and financial accounting. */ unitCost: number; /** * Tax amount per unit for cannabis tax compliance and reporting. */ unitTax: number; /** * Total cost for the received inventory item including all taxes and fees. */ totalCost: number; /** * Package identifier from state tracking system for compliance documentation. */ packageId: string | null; /** * External package identifier for cross-system tracking and integration. */ externalPackageId: string | null; /** * Batch name for lot tracking and quality control management. */ batchName: string | null; /** * Batch identifier for database references and batch tracking. */ batchId: number | null; /** * Room name for facility location identification and display. */ room: string | null; /** * Room identifier for database references and location tracking. */ roomId: number | null; }; /** * Represents a register cash adjustment transaction record for financial reconciliation and audit trails. * * Register adjustments include manual cash corrections, deposits, withdrawals, close-outs, and other * cash management activities that affect register balances. Each adjustment maintains a complete * audit trail with employee accountability and reason tracking. */ export type RegisterAdjustment = { /** * Unique identifier for the register adjustment transaction. * Primary key for tracking and referencing specific adjustment records. */ adjustmentId: number; /** * Type of register adjustment being performed. * Common values include "Adjustment", "Close Out", "Deposit", "Withdrawal", "Cash Drop". */ adjustmentType: string | null; /** * Dollar amount of the register adjustment (positive or negative). * Positive values indicate cash added to register, negative values indicate cash removed. */ adjustmentAmount: number; /** * Name of the employee who performed the register adjustment. * Used for accountability and audit trail purposes. */ adjustedBy: string | null; /** * Date and time when the register adjustment was performed (optional). * Timestamp for audit trail and reconciliation purposes. */ adjustedOn: string | null; /** * Name of the register/terminal where the adjustment occurred. * Identifies which physical register or point-of-sale terminal was adjusted. */ terminalName: string | null; /** * Unique identifier for the register/terminal where the adjustment occurred. * Numeric identifier for the specific point-of-sale terminal. */ terminalId: number; /** * Employee ID of the staff member who performed the adjustment. * Numeric identifier linking to the employee record for accountability. */ adjustedByEmployeeId: number; /** * Reason code or description for why the adjustment was made. * Provides business justification for the cash adjustment. */ adjustmentReason: string | null; /** * Additional comments or notes about the register adjustment (optional). * Free-text field for additional details or explanations. */ comment: string | null; }; /** * Represents a comprehensive cash flow summary for a specific register terminal. * * This model provides real-time cash reconciliation data including starting balances, * transaction activity, and variance calculations for cash management and balancing * purposes. Used for end-of-shift reconciliation and cash discrepancy identification. */ export type RegisterCashSummary = { /** * Name of the register/terminal for which this cash summary applies. * Identifies the specific point-of-sale terminal or register location. */ terminalName: string | null; /** * Starting cash balance for the register at the beginning of the period. * Base amount of cash in the register before any transactions occurred. */ startingBalance: number; /** * Ending cash balance for the register at the end of the period. * Final amount of cash in the register after all transactions and adjustments. */ endingBalance: number; /** * Total cash sales processed through the register during the period. * Includes all cash payments received for customer transactions. */ sales: number; /** * Total cash refunds and returns processed during the period. * Represents cash paid out to customers for returned merchandise. */ returns: number; /** * Total cash deposits added to the register during the period. * Includes cash added to the register for operational purposes. */ deposits: number; /** * Total register adjustments (positive or negative) made during the period. * Includes manual cash corrections, withdrawals, and balancing entries. */ adjustments: number; /** * Cash variance (over or short) compared to expected register balance. * Positive values indicate cash overage, negative values indicate shortage. */ overShort: number; }; /** * Represents a comprehensive register transaction record including sales, adjustments, and cash management activities. * * This model encompasses all types of register activity including customer sales transactions, cash adjustments, * payment processing, register maintenance, and operational activities. Each transaction maintains complete * audit trails with employee accountability and detailed financial information. */ export type RegisterTransaction = { /** * Unique identifier for the register transaction record. * Primary key for tracking and referencing specific transaction activities. */ registerTransactionId: number; /** * Type of register transaction being recorded. * Examples include "Sale", "Adjustment", "Close Out", "Deposit", "Withdrawal", "Return", "Payment". */ transactionType: string | null; /** * Dollar amount of the register transaction (positive or negative). * Represents the financial impact of the transaction on register balances. */ transactionAmount: number; /** * Name of the employee who processed the register transaction. * Used for accountability and performance tracking. */ transactionBy: string | null; /** * Date and time when the register transaction occurred in UTC (optional). * Timestamp for audit trail and financial reconciliation purposes. */ transactionDateUTC: string | null; /** * Reference to the associated business transaction ID (optional). * Links register activity to customer sales transactions when applicable. */ transactionId: number | null; /** * Name of the register/terminal where the transaction was processed. * Identifies which physical register or point-of-sale terminal handled the transaction. */ terminalName: string | null; /** * Unique identifier for the register/terminal where the transaction occurred. * Numeric identifier for the specific point-of-sale terminal. */ terminalId: number; /** * Employee ID of the staff member who processed the transaction. * Numeric identifier linking to the employee record for accountability tracking. */ transactionByEmployeeId: number; /** * Reason code or description for adjustment transactions (optional). * Provides business justification when the transaction is an adjustment or correction. */ adjustmentReason: string | null; /** * Additional comments or notes about the register transaction (optional). * Free-text field for additional context or explanations. */ comment: string | null; }; /** * Regulatory category model containing state-mandated product classification information for cannabis compliance and reporting. */ export type RegulatoryCategory = { /** * Unique identifier for the regulatory category. */ regulatoryCategoryId: number; /** * Display name of the regulatory category as defined by state cannabis regulations. */ regulatoryCategoryName: string | null; }; /** * Extended discount model with additional reporting and administrative properties for internal operations. */ export type ReportingDiscountDetail = { /** * Indicates if discount is available for online/e-commerce ordering. */ isAvailableOnline: boolean; /** * Method used to apply the discount in the system. */ applicationMethod: string | null; /** * External system identifier for integration mapping. */ externalId: string | null; /** * Indicates if discount application requires manager approval. */ requireManagerApproval: boolean; /** * Indicates if discount has been marked as deleted. */ isDeleted: boolean; /** * Collection of location mappings where this discount applies. */ appliesToLocations: Array | null; /** * Unique identifier for the discount. */ discountId: number; /** * Display name of the discount for customer-facing applications. */ discountName: string | null; /** * Monetary discount amount or percentage value. */ discountAmount: number; /** * Promotional code required to apply the discount (optional). */ discountCode: string | null; /** * Type classification of the discount (e.g., percentage, fixed amount). */ discountType: string | null; /** * Method used to apply the discount (e.g., automatic, code required). */ discountMethod: string | null; /** * Indicates if the discount is currently active and available. */ isActive: boolean; /** * Start date and time when discount becomes valid (UTC converted from Eastern Time). */ validFrom: string | null; /** * End date and time when discount expires (UTC converted from Eastern Time). */ validUntil: string | null; /** * Type of threshold requirement for discount eligibility (optional). */ thresholdType: string | null; /** * Minimum number of qualifying items required for discount application (optional). */ minimumItemsRequired: number | null; /** * Maximum number of items that can receive the discount (optional). */ maximumItemsAllowed: number | null; /** * Maximum number of times this discount can be used (optional). */ maximumUsageCount: number | null; /** * Indicates if discount applies to non-cannabis products. */ includeNonCannabis: boolean; /** * Indicates if discount is restricted to first-time customers only. */ firstTimeCustomerOnly: boolean; /** * Indicates if discount can be combined with other discounts. */ stackOnOtherDiscounts: boolean; weeklyRecurrenceInfo: WeeklyRecurrenceInfo; products: DiscountRestriction; productCategories: DiscountRestriction; brands: DiscountRestriction; vendors: DiscountRestriction; strains: DiscountRestriction; tiers: DiscountRestriction; tags: DiscountRestriction; inventoryTags: DiscountRestriction; customerTypes: DiscountRestriction; /** * Associated discount groups for bundling and organization (loaded conditionally). */ discountGroups: Array | null; }; /** * Extended inventory item model for financial reporting with cost and allocation data. */ export type ReportingInventoryItem = { /** * Unit of measurement for unit weight, always "g" (grams). */ unitWeightUnit: string | null; /** * Unit cost of the inventory item for cost of goods sold calculations (in USD). */ unitCost: number | null; /** * Quantity of inventory allocated to orders or transfers but not yet fulfilled. */ allocatedQuantity: number | null; /** * Unique inventory record identifier for this specific inventory item. */ inventoryId: number; /** * Product identifier linking this inventory to the product catalog. */ productId: number; /** * Stock Keeping Unit (SKU) code for inventory tracking and identification. */ sku: string | null; /** * Display name of the product for customer-facing applications. */ productName: string | null; /** * Detailed product description including effects, characteristics, and usage information. */ description: string | null; /** * Category identifier for product classification (optional). */ categoryId: number | null; /** * Category name for product classification and filtering. */ category: string | null; /** * URL path to product image for display purposes. */ imageUrl: string | null; /** * Current available quantity for sale or transfer. */ quantityAvailable: number; /** * Unit of measurement for the available quantity (e.g., "g", "mg", "ea"). */ quantityUnits: string | null; /** * Weight per unit in grams for dosing and compliance calculations. */ unitWeight: number; /** * Flower equivalent amount in grams for compliance tracking. */ flowerEquivalent: number; /** * Recreational flower equivalent amount in grams (optional). */ recFlowerEquivalent: number | null; /** * Unit of measurement for flower equivalent, always "g" (grams). */ readonly flowerEquivalentUnits: string | null; /** * Batch identifier for lot tracking and quality control. */ batchId: number; /** * Human-readable batch name or lot number for tracking. */ batchName: string | null; /** * Package identifier for compliance tracking and traceability. */ packageId: string | null; /** * Current status of the package (e.g., "Active", "Testing", "Quarantine"). */ packageStatus: string | null; /** * Base unit price for retail sales. */ unitPrice: number; /** * Medical program pricing (optional, different from retail). */ medUnitPrice: number | null; /** * Recreational program pricing (optional, different from medical). */ recUnitPrice: number | null; /** * Strain identifier for cannabis products (optional). */ strainId: number | null; /** * Strain name for cannabis products. */ strain: string | null; /** * Cannabis strain classification (Hybrid, Indica, Sativa, CBD). */ strainType: string | null; /** * Product size designation for packaging and dosing information. */ size: string | null; /** * Collection of laboratory test results for this batch (included when includeLabResults=true). */ labResults: Array | null; /** * Date when laboratory testing was completed (optional). */ testedDate: string | null; /** * Date when sample was collected for laboratory testing (optional). */ sampleDate: string | null; /** * Date when product was packaged for distribution (optional). */ packagedDate: string | null; /** * Date when product was manufactured or produced (optional). */ manufacturingDate: string | null; /** * Last modification timestamp in UTC for data synchronization. */ lastModifiedDateUtc: string | null; /** * Current status of laboratory testing (e.g., "Passed", "Failed", "Pending"). */ labTestStatus: string | null; /** * Vendor identifier for the supplier of this inventory (optional). */ vendorId: number | null; /** * Vendor name for the supplier of this inventory. */ vendor: string | null; /** * Product expiration date for compliance and quality control (optional). */ expirationDate: string | null; /** * Quantity breakdown by storage room/location (included when includeRoomQuantities=true). */ roomQuantities: Array | null; /** * Pricing tier classification for bulk pricing strategies. */ pricingTierName: string | null; /** * Alternative product name for display purposes. */ alternateName: string | null; /** * Collection of compliance tags associated with this inventory package. */ tags: Array | null; /** * Brand identifier for branded products (optional). */ brandId: number | null; /** * Brand name for branded products. */ brandName: string | null; /** * Indicates if product is restricted to medical program only. */ medicalOnly: boolean; /** * External compliance system ID (METRC or BioTrack) for regulatory tracking. */ externalPackageId: string | null; /** * Producer name for cultivation and manufacturing tracking. */ producer: string | null; /** * Producer identifier for cultivation and manufacturing tracking (optional). */ producerId: number | null; /** * Package lineage information for traceability and compliance tracking. */ lineage: Array | null; /** * Potency classification indicator for dosing guidance. */ potencyIndicator: string | null; /** * Master category classification for product grouping. */ masterCategory: string | null; /** * Effective potency in milligrams for dosing calculations (optional). */ effectivePotencyMg: number | null; /** * Indicates if product contains cannabis or is cannabis-related. */ isCannabis: boolean; /** * National Drug Code for pharmaceutical tracking (optional). */ packageNDC: string | null; /** * URL to certificate of analysis or lab testing document. */ labResultUrl: string | null; }; /** * Request model for retagging cannabis plants with new serial numbers for compliance and tracking updates. */ export type RetagPlantRequest = { /** * Plant identifier for the cannabis plant being retagged with a new serial number. */ plantId: number; /** * New serial number for the plant identification tag replacement. */ serialNumber: string | null; }; /** * Detailed specification for retiring immature plants from cultivation batches with compliance documentation. */ export type RetireImmaturePlantsDetails = { /** * Batch identifier for the plant batch containing plants to be retired. */ batchId: number; /** * Number of plants to retire from the specified batch. */ countToRetire: number; /** * Standardized reason code for the plant retirement (e.g., "DISEASE", "PEST", "POOR_HEALTH", "CONTAMINATION"). */ reasonCode: string | null; /** * Date when the plants were retired for cultivation timeline documentation. */ retireDate: string | null; }; /** * Request model for retiring immature cannabis plants due to loss, contamination, or quality issues. */ export type RetireImmaturePlantsRequest = { /** * Collection of plant retirement specifications for batch processing of plant removals. */ plants: Array | null; }; export type RetirePlantRequest = { plantIds: Array | null; reasonId: number | null; reasonCode: string | null; wasteType: string | null; roomId: number; wasteWeight: number | null; comment: string | null; wastePackageId: string | null; wasteDate: string | null; plantWeight: number | null; plantWeightUnitId: number | null; wasteMaterial: string | null; wasteReason: string | null; wasteMethod: string | null; reasonNote: string | null; emptyCloneGroup: boolean; }; /** * Cultivation room model containing facility area configuration information for cannabis operations and facility management. */ export type Room = { /** * Unique identifier for the cultivation room or facility area. * **Required for updates, null/0 for new room creation.** */ roomId: number | null; /** * Human-readable name for room identification and cultivation tracking. * **Required for both create and update operations.** */ roomName: string | null; /** * Indicates if this room is designated for quarantine operations and compliance isolation. */ isQuarantineRoom: boolean; /** * Indicates if this room is designated as a secure vault for valuable inventory storage. */ isVaultRoom: boolean; /** * Indicates if this room is designated as a customer waiting area. */ isWaitingRoom: boolean; /** * Indicates if this room is designated as the main sales floor for customer transactions. */ isSalesFloor: boolean; /** * Indicates if this room is designated for point-of-sale operations and transactions. */ isPOSRoom: boolean; /** * Indicates if this room is designated for inventory storage and management. */ isInventoryRoom: boolean; /** * Indicates if this room is designated for pre-order fulfillment operations. */ isPreOrderRoom: boolean; /** * Indicates if this room is designated for e-commerce order processing and fulfillment. */ isEcommerceRoom: boolean; }; /** * Room-based waste record model for facility waste disposal tracking and compliance documentation. */ export type RoomWaste = { /** * Unique identifier for the waste record. */ wasteId: number | null; /** * Reference number for waste tracking and documentation. */ referenceNo: string | null; /** * Additional comments or notes about the waste disposal. */ comments: string | null; /** * Date when the waste disposal occurred. */ wasteDate: string | null; /** * Type or category of waste material being disposed. */ wasteType: string | null; /** * Identifier for the room or facility area where waste originated. */ roomId: number; /** * Quantity of waste material being disposed. */ wasteAmount: number; /** * Unit of measurement identifier for the waste amount. */ unitId: number; }; /** * Response model for successful inventory receive order creation operations. */ export type SavedReceive = { /** * Unique identifier for the created receive inventory transaction. */ receiveInventoryHistoryId: number; }; /** * Request model for setting a product image through the product image management API. */ export type SetImageRequest = { /** * The unique identifier of the product to associate the image with. */ productId: number; /** * Base64-encoded string representation of the image file data. */ base64Image: string; /** * Original filename of the image including file extension for proper handling. */ fileName: string; /** * Computed property that converts the Base64Image string to byte array for processing. */ readonly image?: string | null; fileType?: UploadFileType; }; /** * Response model for successful product image upload operations. */ export type SetImageResponse = { /** * Unique identifier assigned to the uploaded image for tracking and reference. */ imageId: number; /** * Public URL where the uploaded image can be accessed and displayed. */ imageUrl: string | null; }; export type Severity = 0 | 1 | 2; /** * Represents a product size configuration for cannabis products within an organization. */ export type Size = { /** * Unique identifier for the product size configuration. */ sizeId: number; /** * Display name for the product size. */ sizeName: string | null; /** * Detailed description of the product size and its usage. */ description: string | null; }; export type SplitBatchDetails = { newBatchName: string | null; batchId: number; location: string | null; strain: string | null; quantity: number; splitDate: string | null; }; export type SplitImmaturePlantResult = { batch: Array | null; plant: Array | null; }; export type SplitImmaturePlantResultApiResult = { result: boolean; message: string | null; data: SplitImmaturePlantResult; }; export type SplitImmaturePlantResultDetail = { batchId: number; batchPlantCount: number; newBatchId: number; newBatchPlantCount: number; }; /** * Request model for splitting immature cannabis plant batches and individual plants for cultivation optimization. */ export type SplitImmaturePlantsRequest = { /** * Collection of batch split specifications for dividing immature plant batches into smaller groups. */ batch: Array | null; /** * Collection of individual plant split specifications for precise cultivation management. */ plant: Array | null; }; export type SplitPlantDetails = { batchId: number; location: string | null; strain: string | null; quantity: number; splitDate: string | null; }; export type StandardAllergensDetails = { milk: boolean; eggs: boolean; fish: boolean; peanuts: boolean; treeNuts: boolean; sesame: boolean; shellfish: boolean; soybeans: boolean; wheat: boolean; }; /** * Cannabis strain information with genetic and classification details for product categorization and cultivation tracking. */ export type StrainDetail = { /** * Unique identifier for the strain */ strainId: number; /** * Name of the cannabis strain */ strainName: string | null; /** * Detailed description of the strain's characteristics and effects */ strainDescription: string | null; /** * Short name or code for the strain */ strainAbbreviation: string | null; /** * Classification type of the strain. Valid values: `Indica`, `Sativa`, `Hybrid`, `CBD` */ strainType: string | null; /** * External system identifier for third-party integration */ externalId: string | null; }; export type StringIEnumerableOptional = Array; export type StringOptional = string; export type SuccessResult = { result: boolean; message: string | null; data: { [key: string]: unknown; } | null; }; export type Table = { tableId: number | null; tableName: string | null; }; export type Tag = { tagName: string | null; tagId: number; }; /** * Summary tax information aggregated across transaction items for reporting and receipt generation. */ export type TaxSummaryInfo = { /** * Name of the tax type being summarized (e.g., "State Excise Tax", "Sales Tax"). */ rateName: string | null; /** * Total tax amount for this tax type across all transaction items (in USD). */ amount: number; }; /** * Point-of-sale terminal model containing terminal identification information for retail operations and transaction processing. */ export type Terminal = { /** * Unique identifier for the point-of-sale terminal. */ terminalId: number; /** * Human-readable name for terminal identification and assignment. */ terminalName: string | null; }; /** * Complete cannabis retail transaction model representing all aspects of cannabis sales operations. */ export type Transaction = { transactionId: number; customerId: number; employeeId: number; transactionDate: string; voidDate: string | null; isVoid: boolean; subtotal: number; totalDiscount: number; readonly totalBeforeTax: number; tax: number; tipAmount: number | null; total: number; paid: number; changeDue: number; totalItems: number; terminalName: string | null; checkInDate: string | null; invoiceNumber: string | null; isTaxInclusive: boolean; /** * Will have one of the following values: Retail, Transfer, WholesaleOrder */ transactionType: string | null; /** * Loyalty points earned on this transaction (can be negative if it's a return) */ loyaltyEarned: number | null; /** * Loyalty points spent on this transaction (can be negative if it's a return) */ loyaltySpent: number | null; items: Array | null; readonly discounts: Array | null; lastModifiedDateUTC: string; cashPaid: number | null; debitPaid: number | null; electronicPaid: number | null; electronicPaymentMethod: string | null; checkPaid: number | null; creditPaid: number | null; giftPaid: number | null; mmapPaid: number | null; prePaymentAmount: number | null; revenueFeesAndDonations: number | null; nonRevenueFeesAndDonations: number | null; feesAndDonations: Array | null; readonly taxSummary: Array | null; returnOnTransactionId: number | null; adjustmentForTransactionId: number | null; orderType: string | null; wasPreOrdered: boolean; orderSource: string | null; orderMethod: string | null; invoiceName: string | null; readonly isReturn: boolean; authCode: string | null; customerTypeId: number; isMedical: boolean; orderIds: Array | null; totalCredit: number; completedByUser: string | null; responsibleForSaleUserId: number; transactionDateLocalTime: string; estTimeArrivalLocal: string | null; readonly estDeliveryDateLocal: string | null; referenceId: string | null; manualPayments: Array | null; manualPaid: number | null; integratedPayments: Array | null; integratedPaid: number | null; }; /** * Individual line item within a cannabis retail transaction containing product, pricing, and compliance information. */ export type TransactionItem = { /** * Parent transaction identifier linking this item to the overall transaction. */ transactionId: number; /** * Product identifier for the purchased cannabis product. */ productId: number; /** * Total price for this line item including all taxes and discounts (in USD). */ totalPrice: number; /** * Quantity of the product purchased (units based on product type - grams, pieces, etc.). */ quantity: number; /** * Unit price per individual item before taxes and discounts (in USD). */ unitPrice: number; /** * Cost basis of the product for internal accounting and margin calculations (in USD). */ unitCost: number | null; /** * State tracking system package identifier for regulatory compliance (seed-to-sale tracking). */ packageId: string | null; /** * Original source package identifier for product lineage tracking in state systems. */ sourcePackageId: string | null; /** * Total discount amount applied to this line item (in USD). */ totalDiscount: number; /** * Inventory record identifier for the specific product inventory being sold. */ inventoryId: number; /** * Unit type identifier defining how the product is measured and sold. */ unitId: number; /** * Weight of the product unit in grams (calculated for flower products with UnitId = 1). */ readonly unitWeight: number | null; /** * Unit of measurement for product weight (always "g" for grams). */ readonly unitWeightUnit: string | null; /** * Flower equivalent weight for concentrate products in grams (for regulatory compliance). */ flowerEquivalent: number | null; /** * Unit of measurement for flower equivalent (always "g" for grams). */ readonly flowerEquivalentUnit: string | null; /** * Collection of discounts applied to this transaction item. */ discounts: Array | null; /** * Collection of taxes applied to this transaction item. */ taxes: Array | null; /** * Date when this item was returned (null if not returned). */ returnDate: string | null; /** * Indicates whether this transaction item has been returned. */ readonly isReturned: boolean; /** * Transaction identifier of the return transaction that processed this item's return. */ returnedByTransactionId: number | null; /** * Reason provided for returning this item (e.g., "Defective", "Customer Dissatisfaction"). */ returnReason: string | null; /** * Cultivation batch name for product traceability and regulatory compliance. */ batchName: string | null; /** * Reference identifier to tie child items to parent items within a transaction. * Not guaranteed to be unique outside of a single transaction. */ readonly transactionItemId: number; /** * Vendor or supplier name for the product. */ vendor: string | null; /** * Indicates whether this item represents a coupon or promotional discount rather than a physical product. */ isCoupon: boolean; }; /** * Measurement unit model for cannabis product tracking and inventory management. */ export type Unit = { /** * Unique identifier for the measurement unit. */ unitId: number; /** * Full name of the measurement unit (e.g., "Grams", "Ounces", "Pounds"). */ unitName: string | null; /** * Short abbreviation for the unit (e.g., "g", "oz", "lb"). */ abbreviation: string | null; /** * Unit type classification identifier linking to measurement category. */ unitTypeId: number; }; /** * Unit type classification model for organizing measurement units by category. */ export type UnitType = { /** * Unique identifier for the unit type category. */ unitTypeId: number; /** * Display name of the unit type category (e.g., "Weight", "Volume", "Quantity"). */ unitTypeName: string | null; /** * Short abbreviation for the unit type (e.g., "Wgt", "Vol", "Qty"). */ unitTypeAbbreivation: string | null; }; /** * Request model for updating laboratory test results for a specific batch by batch name. */ export type UpdateBatchLabResultsRequest = { /** * Name of the batch to update with laboratory test results (required). */ batchName: string; /** * Weight of the laboratory sample used for testing (in grams). */ sampleWeight?: number | null; /** * Collection of laboratory test results including cannabinoids and terpenes. */ labResults?: Array | null; }; export type UpdateBatchRequest = { batchName: string | null; roomId: number | null; strainId: number | null; }; /** * Request model for updating delivery route details including vehicle assignments, driver assignments, and delivery status. */ export type UpdateDeliveryRouteDetailRequest = { /** * Delivery transaction identifier to update (required). */ transactionId: number; /** * Primary driver identifier for delivery assignment (optional). */ driverId: number | null; /** * Secondary driver identifier for delivery assignment (optional). */ driverId2: number | null; /** * Vehicle identifier for delivery assignment (optional). */ vehicleId: number | null; /** * Route information or delivery notes (optional). */ route: string | null; /** * Delivery status update (optional). */ status: string | null; }; /** * Request model for updating existing customer journal entries with modified content and details. */ export type UpdateJournalEntryRequest = { /** * The ID of the existing journal entry to update. */ journalEntryId: number; /** * Updated title or summary for the journal entry. */ subject: string; /** * Updated detailed content and notes for the journal entry. */ body: string; /** * Updated date and time when the journal entry should be dated. */ date: string; }; export type UpdatePackageTagsRequest = { packageIds?: StringIEnumerableOptional; inventoryIds?: Int32iEnumerableOptional; /** * Required collection of tags to apply to the specified packages (required). */ tags: Array; }; export type UpdatePlantDetails = { plantId: number; serialNumber: StringOptional; dateCreated: DateTimeNullableOptional; bornDate: DateTimeNullableOptional; isMother: BooleanNullableOptional; strainId: Int32NullableOptional; roomId: Int32NullableOptional; tableId: Int32NullableOptional; batchId: Int32NullableOptional; }; export type UpdatePlantsRequest = { plants: Array | null; }; export type UpdatePreOrderRequest = { orderId: number; items: Array | null; isDelivery: boolean; /** * @deprecated */ orderSource: string | null; deliveryStreet: string | null; deliveryCity: string | null; deliveryState: string | null; deliveryPostalCode: string | null; deliveryScheduleId: DeliveryScheduleType; notes: string | null; redemptions: PreOrderRedemptionIEnumerableOptional; customerId: number; deliveryStreet2: string | null; timeWindowStartDateUtc: string | null; timeWindowEndDateUtc: string | null; }; /** * Request model for creating or updating cannabis strain information. * * **Create vs Update Behavior:** * - **CREATE**: When `StrainId` is null, 0, or omitted, a new strain record will be created * - **UPDATE**: When `StrainId` is provided with a valid strain ID, the existing strain will be updated * * **Sparse Update Behavior:** * - **Provided fields**: Will overwrite existing values with provided data * - **Omitted fields**: Will preserve existing values (no data loss for updates) * - **Special handling**: `StrainDescription` is always required and cannot be null */ export type UpdateStrain = { /** * Unique identifier for strain updates. * - **For CREATE**: Omit this field, set to null, or set to 0 * - **For UPDATE**: Provide the existing strain's ID */ strainId?: number | null; /** * Name of the cannabis strain (required for creation) */ strainName: string; /** * Detailed description of the strain's characteristics and effects. * **REQUIRED** - Cannot be null or empty for both create and update operations. */ strainDescription: string; /** * Short name or code for the strain (optional) */ abbreviation?: string | null; /** * Classification type of the strain (optional). * **Must be one of**: `Indica`, `Sativa`, `Hybrid`, `CBD` * If provided, value will be validated against allowed strain types. */ strainType?: string | null; /** * External system identifier for third-party integration (optional). * Useful for synchronizing with cultivation management systems. */ externalId?: string | null; broadcast?: BooleanOptional; }; export type UploadFileType = 0 | 1 | 2 | 3 | 4 | 5; export type ValidationFailure = { propertyName: string | null; errorMessage: string | null; attemptedValue: { [key: string]: unknown; } | null; customState: { [key: string]: unknown; } | null; severity: Severity; errorCode: string | null; formattedMessagePlaceholderValues: { [key: string]: { [key: string]: unknown; } | null; } | null; }; export type ValidationResult = { readonly isValid: boolean; errors: Array | null; ruleSetsExecuted: Array | null; }; export type VehicleDetail = { vehicleId: number; make: string | null; model: string | null; modelYear: string | null; color: string | null; licensePlate: string | null; vin: string | null; }; /** * Vendor information model for cannabis supply chain and compliance management. */ export type Vendor = { /** * Unique identifier for the vendor in the system (null for new vendor creation). */ vendorId: number | null; /** * Official business name of the vendor as registered with regulatory authorities. */ vendorName: string | null; /** * Street address of the vendor's business location. */ address: string | null; /** * City where the vendor's business is located. */ city: string | null; /** * State or province where the vendor's business is located. */ state: string | null; /** * Postal or ZIP code for the vendor's business address. */ postalCode: string | null; /** * Cannabis business license number issued by state regulatory authorities. */ licenseNumber: string | null; /** * Name of the primary business contact for this vendor. */ contactName: string | null; /** * Email address for business communications with the vendor. */ contactEmail: string | null; /** * Phone number for business communications with the vendor. */ contactPhone: string | null; }; /** * Comprehensive waste summary model containing all waste types for facility waste management and regulatory reporting. */ export type WasteSummary = { /** * Collection of room-based waste disposal records. */ roomWaste: Array | null; /** * Collection of harvest-based waste disposal records. */ harvestWaste: Array | null; /** * Collection of plant-based waste disposal records. */ plantWaste: Array | null; }; /** * Weekly recurring schedule model defining time-based availability patterns for discount application. */ export type WeeklyRecurrenceInfo = { /** * Daily start time when discount becomes available (optional). */ startTime: string | null; /** * Daily end time when discount expires (optional). */ endTime: string | null; /** * Indicates if discount is available on Mondays. */ appliesOnMonday: boolean; /** * Indicates if discount is available on Tuesdays. */ appliesOnTuesday: boolean; /** * Indicates if discount is available on Wednesdays. */ appliesOnWednesday: boolean; /** * Indicates if discount is available on Thursdays. */ appliesOnThursday: boolean; /** * Indicates if discount is available on Fridays. */ appliesOnFriday: boolean; /** * Indicates if discount is available on Saturdays. */ appliesOnSaturday: boolean; /** * Indicates if discount is available on Sundays. */ appliesOnSunday: boolean; }; /** * Anonymous transaction response model containing transaction identifiers for guest checkout operations. */ export type AnonymousTransactionWritable = { /** * Unique identifier for the customer record associated with this anonymous transaction. */ customerId: number; /** * Unique identifier for the transaction record. */ transactionId: number; }; /** * Discount information applied to a specific transaction item in cannabis retail operations. */ export type AppliedDiscountWritable = { /** * Unique identifier for the discount program or campaign applied. */ discountId: number; /** * Display name of the discount for customer receipts and reporting. */ discountName: string | null; /** * Reason or justification for the discount application (e.g., "Loyalty Reward", "Medical Patient"). */ discountReason: string | null; /** * Discount amount applied to the transaction item (in USD, positive value represents savings). */ amount: number; }; export type BroadcastedResponsesWritable = { responses: Array | null; }; /** * Product category sales summary for cannabis retail closing reports and financial analysis. */ export type ClosingReportCategorySummaryWritable = { /** * Product category name (e.g., "Flower", "Edibles", "Concentrates"). */ category: string | null; /** * Gross sales total for the category before discounts (in USD). */ categoryGrossTotal: number; /** * Total discount amount applied to products in this category (in USD). */ categoryDiscountTotal: number; /** * Net sales total for the category after discounts (in USD). */ categoryNetTotal: number; /** * Total cost of goods sold for products in this category (in USD). */ categoryCost: number; }; /** * Customer type sales summary for cannabis retail closing reports and customer segment analysis. */ export type ClosingReportCustomerTypeSummaryWritable = { /** * Customer type classification (e.g., "Recreational", "Medical", "Industry"). */ customerType: string | null; /** * Gross sales total for this customer type before discounts (in USD). */ grossTotal: number; /** * Net sales total for this customer type after discounts (in USD). */ netTotal: number; /** * Total discount amount applied to this customer type (in USD). */ discountTotal: number; /** * Total cost of goods sold for this customer type (in USD). */ customerTypeCost: number; /** * Cannabis product sales total for this customer type (in USD). */ cannabisSales: number; /** * Non-cannabis product sales total for this customer type (accessories, etc.) (in USD). */ nonCannabisSales: number; }; /** * Order source sales summary for cannabis retail closing reports and marketing channel analysis. */ export type ClosingReportOrderSourceSummaryWritable = { /** * Order origination source (e.g., "Website", "Mobile App", "Weedmaps", "Walk-In"). */ orderSource: string | null; /** * Gross sales total for this order source before discounts (in USD). */ grossTotal: number; /** * Net sales total for this order source after discounts (in USD). */ netTotal: number; /** * Total discount amount applied to this order source (in USD). */ discountTotal: number; orderSourceCost: number; }; /** * Order type sales summary for cannabis retail closing reports and fulfillment channel analysis. */ export type ClosingReportOrderTypeSummaryWritable = { /** * Order fulfillment type (e.g., "In-Store", "Pickup", "Delivery", "Curbside"). */ orderType: string | null; /** * Gross sales total for this order type before discounts (in USD). */ grossTotal: number; /** * Net sales total for this order type after discounts (in USD). */ netTotal: number; /** * Total discount amount applied to this order type (in USD). */ discountTotal: number; /** * Total cost of goods sold for this order type (in USD). */ orderTypeCost: number; }; /** * Enhanced closing report model for cannabis dispensary daily financial operations with payment processing integration. */ export type ClosingReportV2Writable = { /** * Tips processed through Pay-by-Bank system for electronic tip distribution. */ payByBankTips: number; /** * Transaction fees charged by Pay-by-Bank system for cost accounting. */ payByBankTransactionFees: number; /** * Batch file summaries for Pay-by-Bank transaction reconciliation. */ payByBankBatchFile: Array | null; /** * Fees and donations collected during the closing period for compliance reporting. */ feesDonations: Array | null; grossSales: number | null; discount: number | null; loyalty: number | null; totalTax: number | null; cost: number | null; coupons: number | null; itemTotal: number | null; transactionCount: number; itemCount: number; customerCount: number; newCustomerCount: number; voidCount: number; voidTotal: number | null; returnTotal: number | null; startingBalance: number | null; endingBalance: number | null; deposits: number | null; adjustments: number | null; totalPayments: number | null; invoiceTotal: number | null; cannabisSales: number | null; nonCannabisSales: number | null; netSales: number | null; revenueFeesDonations: number | null; nonRevenueFeesDonations: number | null; rounding: number | null; totalIncome: number | null; averageCartNetSales: number | null; categorySummary: Array | null; paymentSummary: Array | null; taxSummary: Array | null; customerTypeSummary: Array | null; orderTypeSummary: Array | null; orderSourceSummary: Array | null; }; /** * Represents a customer profile with personal information, contact details, and cannabis compliance data. */ export type CustomerWritable = { /** * Unique internal identifier for the customer record. */ customerId: number; /** * Deprecated name field (use FirstName and LastName instead). * * @deprecated */ name: string | null; /** * Customer's first name. */ firstName: string | null; /** * Customer's last name. */ lastName: string | null; /** * Customer's middle name. */ middleName: string | null; /** * Name suffix (Jr., Sr., III, etc.). */ nameSuffix: string | null; /** * Name prefix (Mr., Mrs., Dr., etc.). */ namePrefix: string | null; /** * Primary street address line. */ address1: string | null; /** * Secondary address line (apartment, suite, etc.). */ address2: string | null; /** * City name. */ city: string | null; /** * State or province. */ state: string | null; /** * Postal or ZIP code. */ postalCode: string | null; /** * Primary phone number. */ phone: string | null; /** * Cell phone number. */ cellPhone: string | null; /** * Email address. */ emailAddress: string | null; /** * Customer account status. */ status: string | null; /** * Medical marijuana identification number. */ mmjidNumber: string | null; /** * Medical marijuana ID expiration date. */ mmjidExpirationDate: string | null; /** * Last modification timestamp in UTC format. */ lastModifiedDateUTC: string | null; /** * Customer record creation date. */ creationDate: string | null; /** * Customer type classification. */ customerType: string | null; /** * Customer's gender. */ gender: string | null; /** * SHA2_256 hash of the Driver License ID */ driversLicenseHash: string | null; /** * Customer's date of birth. */ dateOfBirth: string | null; /** * External system customer identifier. */ externalCustomerId: string | null; /** * Name of the integration system that created this customer. */ createdByIntegrator: string | null; /** * Indicates if this is an anonymous customer record. */ isAnonymous: boolean; /** * How the customer heard about the dispensary. */ referralSource: string | null; /** * Additional details about referral source when "Other" is selected. */ otherReferralSource: string | null; /** * SpringBig loyalty system member identifier. */ springBigMemberId: number; /** * Custom identifier for external system integration. */ customIdentifier: string | null; /** * Location where this customer record was created. */ createdAtLocation: string | null; /** * Additional notes about the customer. */ notes: string | null; /** * Indicates if customer is enrolled in loyalty program. */ isLoyaltyMember: boolean | null; /** * Primary medical condition for medical marijuana patients. */ primaryQualifyingCondition: string | null; /** * Additional medical conditions for medical marijuana patients. */ secondaryQualifyingConditions: Array | null; /** * Customer ID this record was merged into (if applicable). */ mergedIntoCustomerId: number | null; /** * Customer's marketing communication preference. */ optedIntoMarketing: boolean | null; /** * Customer's current loyalty program tier. */ loyaltyTier: string | null; }; /** * Extended customer model that includes search match type information for customer lookup operations. */ export type CustomerSearchResultWritable = { /** * Indicates how the customer record was matched during the search operation. */ matchType: string | null; /** * Unique internal identifier for the customer record. */ customerId: number; /** * Deprecated name field (use FirstName and LastName instead). * * @deprecated */ name: string | null; /** * Customer's first name. */ firstName: string | null; /** * Customer's last name. */ lastName: string | null; /** * Customer's middle name. */ middleName: string | null; /** * Name suffix (Jr., Sr., III, etc.). */ nameSuffix: string | null; /** * Name prefix (Mr., Mrs., Dr., etc.). */ namePrefix: string | null; /** * Primary street address line. */ address1: string | null; /** * Secondary address line (apartment, suite, etc.). */ address2: string | null; /** * City name. */ city: string | null; /** * State or province. */ state: string | null; /** * Postal or ZIP code. */ postalCode: string | null; /** * Primary phone number. */ phone: string | null; /** * Cell phone number. */ cellPhone: string | null; /** * Email address. */ emailAddress: string | null; /** * Customer account status. */ status: string | null; /** * Medical marijuana identification number. */ mmjidNumber: string | null; /** * Medical marijuana ID expiration date. */ mmjidExpirationDate: string | null; /** * Last modification timestamp in UTC format. */ lastModifiedDateUTC: string | null; /** * Customer record creation date. */ creationDate: string | null; /** * Customer type classification. */ customerType: string | null; /** * Customer's gender. */ gender: string | null; /** * SHA2_256 hash of the Driver License ID */ driversLicenseHash: string | null; /** * Customer's date of birth. */ dateOfBirth: string | null; /** * External system customer identifier. */ externalCustomerId: string | null; /** * Name of the integration system that created this customer. */ createdByIntegrator: string | null; /** * Indicates if this is an anonymous customer record. */ isAnonymous: boolean; /** * How the customer heard about the dispensary. */ referralSource: string | null; /** * Additional details about referral source when "Other" is selected. */ otherReferralSource: string | null; /** * SpringBig loyalty system member identifier. */ springBigMemberId: number; /** * Custom identifier for external system integration. */ customIdentifier: string | null; /** * Location where this customer record was created. */ createdAtLocation: string | null; /** * Additional notes about the customer. */ notes: string | null; /** * Indicates if customer is enrolled in loyalty program. */ isLoyaltyMember: boolean | null; /** * Primary medical condition for medical marijuana patients. */ primaryQualifyingCondition: string | null; /** * Additional medical conditions for medical marijuana patients. */ secondaryQualifyingConditions: Array | null; /** * Customer ID this record was merged into (if applicable). */ mergedIntoCustomerId: number | null; /** * Customer's marketing communication preference. */ optedIntoMarketing: boolean | null; /** * Customer's current loyalty program tier. */ loyaltyTier: string | null; }; export type DiscountApiResponseWritable = { id: number | null; externalId: string | null; validDateFrom: string | null; validDateTo: string | null; maxRedemptions: number | null; redemptionLimit: number | null; firstTimeCustomerOnly: DiscountFirstTimeCustomer; discountDescription: string | null; discountCode: string | null; applicationMethodId: DiscountApplicationMethod; canStackAutomatically: boolean; onlineName: string | null; locationRestrictions: Array | null; restrictToGroupIds: Array | null; monday: boolean | null; tuesday: boolean | null; wednesday: boolean | null; thursday: boolean | null; friday: boolean | null; saturday: boolean | null; sunday: boolean | null; isActive: boolean; isBundledDiscount: boolean; constraints: Array | null; reward: DiscountRewardApiResponseWritable; menuDisplay: DiscountMenuDisplayApiResponse; paymentRestrictions: DiscountPaymentRestrictionApiResponse; }; export type DiscountConstraintApiResponseWritable = { discountConstraintId: number | null; discountId: number; thresholdMin: number | null; includeNonCannabis: boolean; thresholdTypeId: DiscountThresholdType; discountItemGroupTypeId: DiscountItemGroupType; restrictions: { [key: string]: IRestrictionApiResponse; } | null; }; export type DiscountRewardApiResponseWritable = { discountRewardId: number | null; discountId: number; calculationMethodId: CalculationMethod; discountValue: number; includeNonCannabis: boolean; highestOrLowest: string | null; thresholdTypeId: DiscountThresholdType; itemGroupTypeId: DiscountItemGroupType; thresholdMin: number | null; thresholdMax: number | null; applyToOnlyOneItem: boolean; restrictions: { [key: string]: IRestrictionApiResponse; } | null; }; export type InventoryDiscrepancyWritable = { inventoryId: number | null; packageId: string | null; quantity: number; roomId: number; unitId: number; externalQuantity: number; externalUnitId: number; equivalentExternalQuantity: number | null; productName: string | null; room: string | null; externalRoom: string | null; batchModeQuantity: number | null; bioTrackCategoryName: string | null; externalBioTrackCategoryName: string | null; sku: string | null; unitErrorMsg: string | null; rooms: Array | null; serialNumber: string | null; }; export type InventoryIntegrationReconResponseWritable = { lastUpdated: string | null; discrepancies: Array | null; }; /** * Inventory item model representing current stock and product details for available inventory. */ export type InventoryItemWritable = { /** * Unit of measurement for unit weight, always "g" (grams). */ unitWeightUnit: string | null; /** * Unique inventory record identifier for this specific inventory item. */ inventoryId: number; /** * Product identifier linking this inventory to the product catalog. */ productId: number; /** * Stock Keeping Unit (SKU) code for inventory tracking and identification. */ sku: string | null; /** * Display name of the product for customer-facing applications. */ productName: string | null; /** * Detailed product description including effects, characteristics, and usage information. */ description: string | null; /** * Category identifier for product classification (optional). */ categoryId: number | null; /** * Category name for product classification and filtering. */ category: string | null; /** * URL path to product image for display purposes. */ imageUrl: string | null; /** * Current available quantity for sale or transfer. */ quantityAvailable: number; /** * Unit of measurement for the available quantity (e.g., "g", "mg", "ea"). */ quantityUnits: string | null; /** * Weight per unit in grams for dosing and compliance calculations. */ unitWeight: number; /** * Flower equivalent amount in grams for compliance tracking. */ flowerEquivalent: number; /** * Recreational flower equivalent amount in grams (optional). */ recFlowerEquivalent: number | null; /** * Batch identifier for lot tracking and quality control. */ batchId: number; /** * Human-readable batch name or lot number for tracking. */ batchName: string | null; /** * Package identifier for compliance tracking and traceability. */ packageId: string | null; /** * Current status of the package (e.g., "Active", "Testing", "Quarantine"). */ packageStatus: string | null; /** * Base unit price for retail sales. */ unitPrice: number; /** * Medical program pricing (optional, different from retail). */ medUnitPrice: number | null; /** * Recreational program pricing (optional, different from medical). */ recUnitPrice: number | null; /** * Strain identifier for cannabis products (optional). */ strainId: number | null; /** * Strain name for cannabis products. */ strain: string | null; /** * Cannabis strain classification (Hybrid, Indica, Sativa, CBD). */ strainType: string | null; /** * Product size designation for packaging and dosing information. */ size: string | null; /** * Collection of laboratory test results for this batch (included when includeLabResults=true). */ labResults: Array | null; /** * Date when laboratory testing was completed (optional). */ testedDate: string | null; /** * Date when sample was collected for laboratory testing (optional). */ sampleDate: string | null; /** * Date when product was packaged for distribution (optional). */ packagedDate: string | null; /** * Date when product was manufactured or produced (optional). */ manufacturingDate: string | null; /** * Last modification timestamp in UTC for data synchronization. */ lastModifiedDateUtc: string | null; /** * Current status of laboratory testing (e.g., "Passed", "Failed", "Pending"). */ labTestStatus: string | null; /** * Vendor identifier for the supplier of this inventory (optional). */ vendorId: number | null; /** * Vendor name for the supplier of this inventory. */ vendor: string | null; /** * Product expiration date for compliance and quality control (optional). */ expirationDate: string | null; /** * Quantity breakdown by storage room/location (included when includeRoomQuantities=true). */ roomQuantities: Array | null; /** * Pricing tier classification for bulk pricing strategies. */ pricingTierName: string | null; /** * Alternative product name for display purposes. */ alternateName: string | null; /** * Collection of compliance tags associated with this inventory package. */ tags: Array | null; /** * Brand identifier for branded products (optional). */ brandId: number | null; /** * Brand name for branded products. */ brandName: string | null; /** * Indicates if product is restricted to medical program only. */ medicalOnly: boolean; /** * External compliance system ID (METRC or BioTrack) for regulatory tracking. */ externalPackageId: string | null; /** * Producer name for cultivation and manufacturing tracking. */ producer: string | null; /** * Producer identifier for cultivation and manufacturing tracking (optional). */ producerId: number | null; /** * Package lineage information for traceability and compliance tracking. */ lineage: Array | null; /** * Potency classification indicator for dosing guidance. */ potencyIndicator: string | null; /** * Master category classification for product grouping. */ masterCategory: string | null; /** * Effective potency in milligrams for dosing calculations (optional). */ effectivePotencyMg: number | null; /** * Indicates if product contains cannabis or is cannabis-related. */ isCannabis: boolean; /** * National Drug Code for pharmaceutical tracking (optional). */ packageNDC: string | null; /** * URL to certificate of analysis or lab testing document. */ labResultUrl: string | null; }; /** * Laboratory testing result model for cannabis and cannabis product analysis. */ export type LabResultWritable = { /** * Name of the laboratory test performed (e.g., "THC", "CBD", "Myrcene", "Total Aerobic Count"). */ labTest: string | null; /** * Numeric test result value (null if not detected or not applicable). */ value: number | null; labResultUnitId: LabResultUnit; }; /** * Tax information applied to individual transaction line items in cannabis retail operations. */ export type LineItemTaxInfoWritable = { /** * Name of the tax rate applied (e.g., "State Excise Tax", "City Cannabis Tax", "Sales Tax"). */ rateName: string | null; /** * Tax rate as a decimal percentage (e.g., 0.0875 for 8.75% tax rate). */ rate: number; /** * Calculated tax amount applied to the line item (in USD). */ amount: number; }; /** * Location identity model containing complete location and parent company information for API key verification and context identification. */ export type LocationIdentityWritable = { /** * Unique identifier for the cannabis dispensary location. */ locationId: number; /** * Unique identifier for the parent company (LSP - Licensed Service Provider). */ lspId: number; /** * Business name of the cannabis dispensary location. */ locationName: string | null; /** * Company name of the parent organization (Licensed Service Provider). */ lspName: string | null; /** * Primary street address of the dispensary location. */ address: string | null; /** * Secondary address line (suite, unit, etc.) if applicable. */ address2: string | null; /** * City where the dispensary is located. */ city: string | null; /** * State or province where the dispensary is licensed to operate. */ state: string | null; /** * Postal code (ZIP code) for the dispensary location. */ postalCode: string | null; /** * State-issued cannabis business license number for regulatory compliance. */ licenseNumber: string | null; /** * "Doing Business As" name if different from the legal business name. */ doingBusinessAs: string | null; /** * Indicates whether customer profiles are shared across locations within the organization. */ shareCustomerProfiles: boolean; /** * Legacy global unique identifier for the location (deprecated). * * @deprecated */ globalId: string | null; /** * Global unique identifier for the location across all systems and integrations. */ locationGlobalId: string | null; /** * Global unique identifier for the parent company (LSP) across all systems. */ lspGlobalId: string | null; /** * Regional identifier for compliance and API routing (internal use only). */ region: string | null; }; export type LocationResponseWritable = { locationName: string | null; locId: number; licenseNumber: string | null; broadcastedTo: string | null; errorDetail: string | null; }; export type PlantWritable = { plantId: number; serialNumber: string | null; growthPhase: string | null; type: string | null; harvestedWeight: number | null; status: string | null; plantCount: number | null; isMother: boolean; motherPlantId: number | null; plantedOn: string | null; addedToHarvestOn: string | null; harvestDate: string | null; destroyedDate: string | null; plantGroupName: string | null; strain: string | null; room: string | null; table: string | null; vegetationStartedOn: string | null; vegetationEndedOn: string | null; floweringStartedOn: string | null; floweringEndedOn: string | null; currentPhaseStartDate: string | null; lastModifiedDate: string | null; daysInCurrentPhase: number | null; floweringRoom: string | null; floweringTable: string | null; vegetationRoom: string | null; vegetationTable: string | null; daysInFlowering: number | null; daysInVegetation: number | null; batchId: number; }; export type ProductDetailWritable = { productId: number; sku: string | null; internalName: string | null; productName: string | null; description: string | null; masterCategory: string | null; categoryId: number | null; category: string | null; imageUrl: string | null; imageUrls: Array | null; strainId: number | null; strain: string | null; strainType: string | null; size: string | null; netWeight: number | null; netWeightUnitId: number | null; brandId: number | null; brandName: string | null; vendorId: number | null; vendorName: string | null; isCannabis: boolean; isActive: boolean; isCoupon: boolean; thcContent: number | null; thcContentUnit: string | null; cbdContent: number | null; cbdContentUnit: string | null; productGrams: number | null; flowerEquivalent: number | null; recFlowerEquivalent: number | null; price: number | null; medPrice: number | null; recPrice: number | null; unitCost: number | null; unitType: string | null; onlineTitle: string | null; onlineDescription: string | null; posProducts: boolean | null; pricingTier: number | null; onlineAvailable: boolean | null; lowInventoryThreshold: number | null; pricingTierName: string | null; pricingTierDescription: string | null; pricingTierData: Array | null; flavor: string | null; alternateName: string | null; lineageName: string | null; distillationName: string | null; maxPurchaseablePerTransaction: number | null; tags: Array | null; effects: Array | null; dosage: string | null; instructions: string | null; allergens: string | null; standardAllergens: StandardAllergensDetails; defaultUnit: string | null; producerId: number | null; producerName: string | null; createdDate: string | null; isMedicalOnly: boolean; lastModifiedDateUTC: string | null; grossWeight: number | null; isTaxable: boolean | null; taxCategories: Array | null; upc: string | null; regulatoryCategory: string | null; ndc: string | null; daysSupply: number | null; externalCategory: string | null; externalId: string | null; syncExternally: boolean; regulatoryName: string | null; broadcastedResponses: BroadcastedResponsesWritable; administrationMethod: string | null; unitCBDContentDose: number | null; unitTHCContentDose: number | null; oilVolume: number | null; ingredientList: string | null; expirationDays: number | null; abbreviation: string | null; isTestProduct: boolean; isFinished: boolean; allowAutomaticDiscounts: boolean; servingSize: string | null; servingSizePerUnit: number | null; isNutrient: boolean; approvalDateUTC: string | null; ecomCategory: string | null; ecomSubcategory: string | null; customMetadata: string | null; }; /** * Extended inventory item model for financial reporting with cost and allocation data. */ export type ReportingInventoryItemWritable = { /** * Unit of measurement for unit weight, always "g" (grams). */ unitWeightUnit: string | null; /** * Unit cost of the inventory item for cost of goods sold calculations (in USD). */ unitCost: number | null; /** * Quantity of inventory allocated to orders or transfers but not yet fulfilled. */ allocatedQuantity: number | null; /** * Unique inventory record identifier for this specific inventory item. */ inventoryId: number; /** * Product identifier linking this inventory to the product catalog. */ productId: number; /** * Stock Keeping Unit (SKU) code for inventory tracking and identification. */ sku: string | null; /** * Display name of the product for customer-facing applications. */ productName: string | null; /** * Detailed product description including effects, characteristics, and usage information. */ description: string | null; /** * Category identifier for product classification (optional). */ categoryId: number | null; /** * Category name for product classification and filtering. */ category: string | null; /** * URL path to product image for display purposes. */ imageUrl: string | null; /** * Current available quantity for sale or transfer. */ quantityAvailable: number; /** * Unit of measurement for the available quantity (e.g., "g", "mg", "ea"). */ quantityUnits: string | null; /** * Weight per unit in grams for dosing and compliance calculations. */ unitWeight: number; /** * Flower equivalent amount in grams for compliance tracking. */ flowerEquivalent: number; /** * Recreational flower equivalent amount in grams (optional). */ recFlowerEquivalent: number | null; /** * Batch identifier for lot tracking and quality control. */ batchId: number; /** * Human-readable batch name or lot number for tracking. */ batchName: string | null; /** * Package identifier for compliance tracking and traceability. */ packageId: string | null; /** * Current status of the package (e.g., "Active", "Testing", "Quarantine"). */ packageStatus: string | null; /** * Base unit price for retail sales. */ unitPrice: number; /** * Medical program pricing (optional, different from retail). */ medUnitPrice: number | null; /** * Recreational program pricing (optional, different from medical). */ recUnitPrice: number | null; /** * Strain identifier for cannabis products (optional). */ strainId: number | null; /** * Strain name for cannabis products. */ strain: string | null; /** * Cannabis strain classification (Hybrid, Indica, Sativa, CBD). */ strainType: string | null; /** * Product size designation for packaging and dosing information. */ size: string | null; /** * Collection of laboratory test results for this batch (included when includeLabResults=true). */ labResults: Array | null; /** * Date when laboratory testing was completed (optional). */ testedDate: string | null; /** * Date when sample was collected for laboratory testing (optional). */ sampleDate: string | null; /** * Date when product was packaged for distribution (optional). */ packagedDate: string | null; /** * Date when product was manufactured or produced (optional). */ manufacturingDate: string | null; /** * Last modification timestamp in UTC for data synchronization. */ lastModifiedDateUtc: string | null; /** * Current status of laboratory testing (e.g., "Passed", "Failed", "Pending"). */ labTestStatus: string | null; /** * Vendor identifier for the supplier of this inventory (optional). */ vendorId: number | null; /** * Vendor name for the supplier of this inventory. */ vendor: string | null; /** * Product expiration date for compliance and quality control (optional). */ expirationDate: string | null; /** * Quantity breakdown by storage room/location (included when includeRoomQuantities=true). */ roomQuantities: Array | null; /** * Pricing tier classification for bulk pricing strategies. */ pricingTierName: string | null; /** * Alternative product name for display purposes. */ alternateName: string | null; /** * Collection of compliance tags associated with this inventory package. */ tags: Array | null; /** * Brand identifier for branded products (optional). */ brandId: number | null; /** * Brand name for branded products. */ brandName: string | null; /** * Indicates if product is restricted to medical program only. */ medicalOnly: boolean; /** * External compliance system ID (METRC or BioTrack) for regulatory tracking. */ externalPackageId: string | null; /** * Producer name for cultivation and manufacturing tracking. */ producer: string | null; /** * Producer identifier for cultivation and manufacturing tracking (optional). */ producerId: number | null; /** * Package lineage information for traceability and compliance tracking. */ lineage: Array | null; /** * Potency classification indicator for dosing guidance. */ potencyIndicator: string | null; /** * Master category classification for product grouping. */ masterCategory: string | null; /** * Effective potency in milligrams for dosing calculations (optional). */ effectivePotencyMg: number | null; /** * Indicates if product contains cannabis or is cannabis-related. */ isCannabis: boolean; /** * National Drug Code for pharmaceutical tracking (optional). */ packageNDC: string | null; /** * URL to certificate of analysis or lab testing document. */ labResultUrl: string | null; }; /** * Request model for setting a product image through the product image management API. */ export type SetImageRequestWritable = { /** * The unique identifier of the product to associate the image with. */ productId: number; /** * Base64-encoded string representation of the image file data. */ base64Image: string; /** * Original filename of the image including file extension for proper handling. */ fileName: string; fileType?: UploadFileType; }; /** * Complete cannabis retail transaction model representing all aspects of cannabis sales operations. */ export type TransactionWritable = { transactionId: number; customerId: number; employeeId: number; transactionDate: string; voidDate: string | null; isVoid: boolean; subtotal: number; totalDiscount: number; tax: number; tipAmount: number | null; total: number; paid: number; changeDue: number; totalItems: number; terminalName: string | null; checkInDate: string | null; invoiceNumber: string | null; isTaxInclusive: boolean; /** * Will have one of the following values: Retail, Transfer, WholesaleOrder */ transactionType: string | null; /** * Loyalty points earned on this transaction (can be negative if it's a return) */ loyaltyEarned: number | null; /** * Loyalty points spent on this transaction (can be negative if it's a return) */ loyaltySpent: number | null; items: Array | null; lastModifiedDateUTC: string; cashPaid: number | null; debitPaid: number | null; electronicPaid: number | null; electronicPaymentMethod: string | null; checkPaid: number | null; creditPaid: number | null; giftPaid: number | null; mmapPaid: number | null; prePaymentAmount: number | null; revenueFeesAndDonations: number | null; nonRevenueFeesAndDonations: number | null; feesAndDonations: Array | null; returnOnTransactionId: number | null; adjustmentForTransactionId: number | null; orderType: string | null; wasPreOrdered: boolean; orderSource: string | null; orderMethod: string | null; invoiceName: string | null; authCode: string | null; customerTypeId: number; isMedical: boolean; orderIds: Array | null; totalCredit: number; completedByUser: string | null; responsibleForSaleUserId: number; transactionDateLocalTime: string; estTimeArrivalLocal: string | null; referenceId: string | null; manualPayments: Array | null; manualPaid: number | null; integratedPayments: Array | null; integratedPaid: number | null; }; /** * Individual line item within a cannabis retail transaction containing product, pricing, and compliance information. */ export type TransactionItemWritable = { /** * Parent transaction identifier linking this item to the overall transaction. */ transactionId: number; /** * Product identifier for the purchased cannabis product. */ productId: number; /** * Total price for this line item including all taxes and discounts (in USD). */ totalPrice: number; /** * Quantity of the product purchased (units based on product type - grams, pieces, etc.). */ quantity: number; /** * Unit price per individual item before taxes and discounts (in USD). */ unitPrice: number; /** * Cost basis of the product for internal accounting and margin calculations (in USD). */ unitCost: number | null; /** * State tracking system package identifier for regulatory compliance (seed-to-sale tracking). */ packageId: string | null; /** * Original source package identifier for product lineage tracking in state systems. */ sourcePackageId: string | null; /** * Total discount amount applied to this line item (in USD). */ totalDiscount: number; /** * Inventory record identifier for the specific product inventory being sold. */ inventoryId: number; /** * Unit type identifier defining how the product is measured and sold. */ unitId: number; /** * Flower equivalent weight for concentrate products in grams (for regulatory compliance). */ flowerEquivalent: number | null; /** * Collection of discounts applied to this transaction item. */ discounts: Array | null; /** * Collection of taxes applied to this transaction item. */ taxes: Array | null; /** * Date when this item was returned (null if not returned). */ returnDate: string | null; /** * Transaction identifier of the return transaction that processed this item's return. */ returnedByTransactionId: number | null; /** * Reason provided for returning this item (e.g., "Defective", "Customer Dissatisfaction"). */ returnReason: string | null; /** * Cultivation batch name for product traceability and regulatory compliance. */ batchName: string | null; /** * Vendor or supplier name for the product. */ vendor: string | null; /** * Indicates whether this item represents a coupon or promotional discount rather than a physical product. */ isCoupon: boolean; }; export type ValidationResultWritable = { errors: Array | null; ruleSetsExecuted: Array | null; }; export type BatchLabResultsPostData = { /** * Batch lab results update request with batch name and lab data - UpdateBatchLabResultsRequest object */ body?: UpdateBatchLabResultsRequest; path?: never; query?: never; url: '/batch/lab-results'; }; export type BatchLabResultsPostErrors = { /** * Bad Request - String error message (parse response body as plain text) OR `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Not Found - Batch with specified name does not exist */ 404: string; /** * Something went wrong. */ 500: unknown; }; export type BatchLabResultsPostError = BatchLabResultsPostErrors[keyof BatchLabResultsPostErrors]; export type BatchLabResultsPostResponses = { /** * Success - Lab results successfully created or updated */ 200: unknown; }; export type BrandGetData = { body?: never; path?: never; query?: never; url: '/brand'; }; export type BrandGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for brand access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type BrandGetResponses = { /** * Success - Returns array of brand objects: `[{ Brand }, ...]` */ 200: Array; }; export type BrandGetResponse = BrandGetResponses[keyof BrandGetResponses]; export type BrandPostData = { /** * Brand information to create or update - BrandEditRequest object with brand details */ body?: BrandEditRequest; path?: never; query?: never; url: '/brand'; }; export type BrandPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Internal server error */ 500: unknown; }; export type BrandPostError = BrandPostErrors[keyof BrandPostErrors]; export type BrandPostResponses = { /** * Success - Returns brand object: `{ Brand }` */ 200: Brand; }; export type BrandPostResponse = BrandPostResponses[keyof BrandPostResponses]; export type CustomerCustomersGetData = { body?: never; path?: never; query?: { /** * Optional date filter to return customers modified after this timestamp - Used for incremental sync */ fromLastModifiedDateUTC?: string; /** * Optional date filter to return customers modified before this timestamp - Used for date range filtering */ toLastModifiedDateUTC?: string; /** * Optional customer ID to return a specific customer by internal ID */ customerID?: number; /** * Include/exclude anonymous customers in results - Default: true */ includeAnonymous?: boolean; /** * Optional unique ID to return a specific customer by unique identifier - Must be valid long integer when provided */ uniqueId?: string; }; url: '/customer/customers'; }; export type CustomerCustomersGetErrors = { /** * Bad Request - Invalid date range or uniqueId format */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for customer data operations */ 403: unknown; /** * Not Found - Customer not found when searching by customerID or uniqueId */ 404: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type CustomerCustomersGetError = CustomerCustomersGetErrors[keyof CustomerCustomersGetErrors]; export type CustomerCustomersGetResponses = { /** * Success - Returns array of customer objects: `[{ Customer }, ...]` */ 200: Array; }; export type CustomerCustomersGetResponse = CustomerCustomersGetResponses[keyof CustomerCustomersGetResponses]; export type CustomerCustomersPaginatedGetData = { body?: never; path?: never; query?: { /** * Optional date filter to return customers modified after this timestamp */ fromLastModifiedDateUTC?: string; /** * Optional date filter to return customers modified before this timestamp */ toLastModifiedDateUTC?: string; /** * Page number for sequential pagination (integer, starts at 0) - Default: 0 */ PageNumber?: number; /** * Number of items per page (integer) - Default: 1000, Maximum: 10000 */ PageSize?: number; /** * Include/exclude anonymous customers in results - Default: true */ includeAnonymous?: boolean; }; url: '/customer/customers-paginated'; }; export type CustomerCustomersPaginatedGetErrors = { /** * Bad Request - PageSize exceeds maximum limit of 10,000 */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type CustomerCustomersPaginatedGetError = CustomerCustomersPaginatedGetErrors[keyof CustomerCustomersPaginatedGetErrors]; export type CustomerCustomersPaginatedGetResponses = { /** * Success */ 200: Array; }; export type CustomerCustomersPaginatedGetResponse = CustomerCustomersPaginatedGetResponses[keyof CustomerCustomersPaginatedGetResponses]; export type CustomerCustomerTypesGetData = { body?: never; path?: never; query?: never; url: '/customer/customer-types'; }; export type CustomerCustomerTypesGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type CustomerCustomerTypesGetResponses = { /** * Success */ 200: Array; }; export type CustomerCustomerTypesGetResponse = CustomerCustomerTypesGetResponses[keyof CustomerCustomerTypesGetResponses]; export type CustomerReferralSourcesGetData = { body?: never; path?: never; query?: never; url: '/customer/referral-sources'; }; export type CustomerReferralSourcesGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type CustomerReferralSourcesGetResponses = { /** * Success */ 200: Array; }; export type CustomerReferralSourcesGetResponse = CustomerReferralSourcesGetResponses[keyof CustomerReferralSourcesGetResponses]; export type CustomerCustomerPostData = { /** * Customer information to create or update - EcomCustomerEdit object with customer details */ body?: EcomCustomerEdit; headers?: { /** * Optional GUID for idempotency checks. When provided with IdempotencyKey in request body, prevents duplicate customer creation */ ConsumerKey?: string; }; path?: never; query?: { /** * Skip duplicate detection and force creation of new customer record - Default: false */ bypassDeduplication?: boolean; }; url: '/customer/customer'; }; export type CustomerCustomerPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for customer management */ 403: unknown; /** * Not Found - Customer ID provided for update but customer does not exist */ 404: string; /** * Internal Server Error - Server error occurred during customer processing */ 500: unknown; }; export type CustomerCustomerPostError = CustomerCustomerPostErrors[keyof CustomerCustomerPostErrors]; export type CustomerCustomerPostResponses = { /** * Success - Returns complete Customer object with assigned ID and loyalty status */ 200: Customer; }; export type CustomerCustomerPostResponse = CustomerCustomerPostResponses[keyof CustomerCustomerPostResponses]; export type CustomerCustomerLookupPostData = { body?: EcomCustomerEdit; path?: never; query?: never; url: '/customer/customerLookup'; }; export type CustomerCustomerLookupPostErrors = { /** * Bad Request */ 400: BadRequestResponse; /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Not Found */ 404: string; /** * Internal Server Error */ 500: unknown; }; export type CustomerCustomerLookupPostError = CustomerCustomerLookupPostErrors[keyof CustomerCustomerLookupPostErrors]; export type CustomerCustomerLookupPostResponses = { /** * OK */ 200: Customer; }; export type CustomerCustomerLookupPostResponse = CustomerCustomerLookupPostResponses[keyof CustomerCustomerLookupPostResponses]; export type CustomerSearchPostData = { /** * Customer search request with search criteria - CustomerSearchRequest object */ body?: CustomerSearchRequest; path?: never; query?: never; url: '/customer/search'; }; export type CustomerSearchPostErrors = { /** * Bad Request - Validation errors or no search criteria provided */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type CustomerSearchPostError = CustomerSearchPostErrors[keyof CustomerSearchPostErrors]; export type CustomerSearchPostResponses = { /** * Success */ 200: Array; }; export type CustomerSearchPostResponse = CustomerSearchPostResponses[keyof CustomerSearchPostResponses]; export type CustomerByExternalIdGetData = { body?: never; path?: never; query?: { externalId?: string; }; url: '/customer/by-external-id'; }; export type CustomerByExternalIdGetErrors = { /** * Bad Request */ 400: BadRequestResponse; /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Not Found */ 404: unknown; /** * Internal Server Error */ 500: unknown; }; export type CustomerByExternalIdGetError = CustomerByExternalIdGetErrors[keyof CustomerByExternalIdGetErrors]; export type CustomerByExternalIdGetResponses = { /** * OK */ 200: Array; }; export type CustomerByExternalIdGetResponse = CustomerByExternalIdGetResponses[keyof CustomerByExternalIdGetResponses]; export type CustomerJournalGetData = { body?: never; path?: never; query?: { /** * Internal customer ID to retrieve journal entries for - Must exist and be accessible to your location */ customerId?: number; }; url: '/customer-journal'; }; export type CustomerJournalGetErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for customer access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type CustomerJournalGetError = CustomerJournalGetErrors[keyof CustomerJournalGetErrors]; export type CustomerJournalGetResponses = { /** * Success - Returns array of journal entry objects: `[{ JournalEntry }, ...]` */ 200: Array; }; export type CustomerJournalGetResponse = CustomerJournalGetResponses[keyof CustomerJournalGetResponses]; export type CustomerJournalUpdatePostData = { /** * Journal entry update request with required fields to update - UpdateJournalEntryRequest object */ body?: UpdateJournalEntryRequest; path?: never; query?: never; url: '/customer-journal/update'; }; export type CustomerJournalUpdatePostErrors = { /** * Bad Request - Validation errors or invalid journal entry ID */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for customer access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type CustomerJournalUpdatePostError = CustomerJournalUpdatePostErrors[keyof CustomerJournalUpdatePostErrors]; export type CustomerJournalUpdatePostResponses = { /** * Success - Returns journal entry object: `{ JournalEntry }` */ 200: JournalEntry; }; export type CustomerJournalUpdatePostResponse = CustomerJournalUpdatePostResponses[keyof CustomerJournalUpdatePostResponses]; export type CustomerJournalCreatePostData = { /** * Journal entry creation request with customer ID and entry details - CreateJournalEntryRequest object */ body?: CreateJournalEntryRequest; path?: never; query?: never; url: '/customer-journal/create'; }; export type CustomerJournalCreatePostErrors = { /** * Bad Request - Validation errors or invalid customer ID */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for customer access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type CustomerJournalCreatePostError = CustomerJournalCreatePostErrors[keyof CustomerJournalCreatePostErrors]; export type CustomerJournalCreatePostResponses = { /** * Success - Returns journal entry object: `{ JournalEntry }` */ 200: JournalEntry; }; export type CustomerJournalCreatePostResponse = CustomerJournalCreatePostResponses[keyof CustomerJournalCreatePostResponses]; export type DeliveriesGetData = { body?: never; path?: never; query?: { /** * Pre-order ID to get delivery status for - Optional, mutually exclusive with other filters */ PreOrderId?: number; /** * Transaction ID to get delivery status for - Optional, mutually exclusive with other filters */ TransactionId?: number; /** * Array of transaction IDs to get delivery status for - Optional, mutually exclusive with other filters */ transactionIds?: Array; /** * Include detailed line item data in response - Default: false */ includeLineItems?: boolean; /** * Filter deliveries by status - Optional, mutually exclusive with other filters */ deliveryStatus?: string; }; url: '/Deliveries'; }; export type DeliveriesGetErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for delivery access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type DeliveriesGetError = DeliveriesGetErrors[keyof DeliveriesGetErrors]; export type DeliveriesGetResponses = { /** * Success - Returns array of delivery objects: `[{ DeliveryOrderStatus }, ...]` */ 200: Array; }; export type DeliveriesGetResponse = DeliveriesGetResponses[keyof DeliveriesGetResponses]; export type DeliveriesSetRouteDetailPostData = { /** * Delivery route detail update request with transaction ID and delivery information - UpdateDeliveryRouteDetailRequest object */ body?: UpdateDeliveryRouteDetailRequest; path?: never; query?: never; url: '/Deliveries/set-route-detail'; }; export type DeliveriesSetRouteDetailPostErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for delivery access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type DeliveriesSetRouteDetailPostError = DeliveriesSetRouteDetailPostErrors[keyof DeliveriesSetRouteDetailPostErrors]; export type DeliveriesSetRouteDetailPostResponses = { /** * Success - Route details successfully updated */ 200: unknown; }; export type DiscountsGetData = { body?: never; path?: never; query?: { /** * Include deleted or inactive discounts in results - Default: false */ includeInactive?: boolean; /** * Include detailed product/category restriction data - Default: false */ includeInclusionExclusionData?: boolean; }; url: '/discounts'; }; export type DiscountsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type DiscountsGetResponses = { /** * Success - Returns array of basic discount information */ 200: Array; }; export type DiscountsGetResponse = DiscountsGetResponses[keyof DiscountsGetResponses]; export type DiscountsV2ListGetData = { body?: never; path?: never; query?: { /** * Include deleted or inactive discounts in results - Default: false */ includeInactive?: boolean; /** * Include detailed product/category restriction data - Default: false */ includeInclusionExclusionData?: boolean; /** * Include credit card and payment method restrictions - Default: false */ includePaymentRestrictions?: boolean; }; url: '/discounts/v2/list'; }; export type DiscountsV2ListGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type DiscountsV2ListGetResponses = { /** * Success - Returns array of comprehensive discount configuration objects */ 200: Array; }; export type DiscountsV2ListGetResponse = DiscountsV2ListGetResponses[keyof DiscountsV2ListGetResponses]; export type DriversGetData = { body?: never; path?: never; query?: never; url: '/drivers'; }; export type DriversGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for driver access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type DriversGetResponses = { /** * Success - Returns array of driver objects: `[{ DriverDetail }, ...]` */ 200: Array; }; export type DriversGetResponse = DriversGetResponses[keyof DriversGetResponses]; export type DriversPostData = { /** * Driver information to create or update - DriverDetail object with driver details */ body?: DriverDetail; path?: never; query?: never; url: '/drivers'; }; export type DriversPostErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for driver access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type DriversPostError = DriversPostErrors[keyof DriversPostErrors]; export type DriversPostResponses = { /** * Success - Driver successfully created or updated */ 200: unknown; }; export type EmployeesGetData = { body?: never; path?: never; query?: never; url: '/employees'; }; export type EmployeesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for employee access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type EmployeesGetResponses = { /** * Success - Returns array of Employee objects: `[{ Employee }, ...]` */ 200: Array; }; export type EmployeesGetResponse = EmployeesGetResponses[keyof EmployeesGetResponses]; export type GuestlistGetData = { body?: never; path?: never; query?: never; url: '/guestlist'; }; export type GuestlistGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for customer access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type GuestlistGetResponses = { /** * Success - Returns array of guest objects: `[{ GuestListEntry }, ...]` */ 200: Array; }; export type GuestlistGetResponse = GuestlistGetResponses[keyof GuestlistGetResponses]; export type HarvestGetData = { body?: never; path?: never; query?: { /** * Filter harvests modified after this date for incremental sync - Optional */ fromLastModifiedDateUTC?: string; /** * Filter harvests modified before this date for date range filtering - Optional */ toLastModifiedDateUTC?: string; /** * Filter by harvest status: true=active, false=completed, null=completed only - Default: null (completed only) */ activeHarvests?: boolean; }; url: '/harvest'; }; export type HarvestGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for cultivation or inventory access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type HarvestGetResponses = { /** * Success - Returns array of harvest objects: `[{ Harvest }, ...]` */ 200: Array; }; export type HarvestGetResponse = HarvestGetResponses[keyof HarvestGetResponses]; export type HarvestPostData = { /** * Harvest information to create or update - CreateOrUpdateHarvest object with harvest details */ body?: CreateOrUpdateHarvest; path?: never; query?: never; url: '/harvest'; }; export type HarvestPostErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for cultivation write access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type HarvestPostResponses = { /** * Success - Returns harvest ID for created or updated harvest: `integer` */ 200: number; }; export type HarvestPostResponse = HarvestPostResponses[keyof HarvestPostResponses]; export type HarvestBulkPostData = { /** * Bulk harvest request with array of harvest operations - BulkCreateOrUpdateHarvest object */ body?: BulkCreateOrUpdateHarvest; path?: never; query?: never; url: '/harvest/bulk'; }; export type HarvestBulkPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for cultivation write access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type HarvestBulkPostError = HarvestBulkPostErrors[keyof HarvestBulkPostErrors]; export type HarvestBulkPostResponses = { /** * Success - Returns bulk harvest response object: `{ BulkCreateOrUpdateHarvestResponse }` */ 200: BulkCreateOrUpdateHarvestResponse; }; export type HarvestBulkPostResponse = HarvestBulkPostResponses[keyof HarvestBulkPostResponses]; export type OkcomputerGetData = { body?: never; path?: never; query?: never; url: '/okcomputer'; }; export type OkcomputerGetErrors = { /** * Internal Server Error - Service is experiencing issues */ 500: unknown; }; export type OkcomputerGetResponses = { /** * Success - Service is healthy and responsive */ 200: SuccessResult; }; export type OkcomputerGetResponse = OkcomputerGetResponses[keyof OkcomputerGetResponses]; export type IntegrationIntegrationReconGetData = { body?: never; path?: never; query?: never; url: '/integration/integration-recon'; }; export type IntegrationIntegrationReconGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type IntegrationIntegrationReconGetResponses = { /** * Success */ 200: InventoryIntegrationReconResponse; }; export type IntegrationIntegrationReconGetResponse = IntegrationIntegrationReconGetResponses[keyof IntegrationIntegrationReconGetResponses]; export type InventoryGetData = { body?: never; path?: never; query?: { /** * Include detailed lab testing data and cannabinoid profiles - Default: false */ includeLabResults?: boolean; /** * Include quantity breakdown by storage room/location - Default: false */ includeRoomQuantities?: boolean; }; url: '/inventory'; }; export type InventoryGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for inventory access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type InventoryGetResponses = { /** * Success - Returns array of inventory items with product and stock details */ 200: Array; }; export type InventoryGetResponse = InventoryGetResponses[keyof InventoryGetResponses]; export type InventoryLabresultsGetData = { body?: never; path?: never; query?: { BatchName?: string; }; url: '/inventory/labresults'; }; export type InventoryLabresultsGetErrors = { /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type InventoryLabresultsGetResponses = { /** * OK */ 200: Array; }; export type InventoryLabresultsGetResponse = InventoryLabresultsGetResponses[keyof InventoryLabresultsGetResponses]; export type InventorySnapshotGetData = { body?: never; path?: never; query?: { fromDate?: string; }; url: '/inventory/snapshot'; }; export type InventorySnapshotGetErrors = { /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type InventorySnapshotGetResponses = { /** * OK */ 200: Array; }; export type InventorySnapshotGetResponse = InventorySnapshotGetResponses[keyof InventorySnapshotGetResponses]; export type InventoryReceivedinventoryGetData = { body?: never; path?: never; query?: { receiveInventoryHistoryId?: number; startDate?: string; endDate?: string; }; url: '/inventory/receivedinventory'; }; export type InventoryReceivedinventoryGetErrors = { /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type InventoryReceivedinventoryGetResponses = { /** * OK */ 200: Array; }; export type InventoryReceivedinventoryGetResponse = InventoryReceivedinventoryGetResponses[keyof InventoryReceivedinventoryGetResponses]; export type InventoryInventorytransactionGetData = { body?: never; path?: never; query?: { startDate?: string; endDate?: string; transactionType?: string; }; url: '/inventory/inventorytransaction'; }; export type InventoryInventorytransactionGetErrors = { /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type InventoryInventorytransactionGetResponses = { /** * OK */ 200: Array; }; export type InventoryInventorytransactionGetResponse = InventoryInventorytransactionGetResponses[keyof InventoryInventorytransactionGetResponses]; export type InventoryReceiveinventoryPostData = { /** * Receive inventory order details including vendor, delivery, and item information */ body?: ReceiveInventorySave; path?: never; query?: never; url: '/inventory/receiveinventory'; }; export type InventoryReceiveinventoryPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) OR String error message (parse response body as plain text) */ 400: string; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for inventory access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type InventoryReceiveinventoryPostError = InventoryReceiveinventoryPostErrors[keyof InventoryReceiveinventoryPostErrors]; export type InventoryReceiveinventoryPostResponses = { /** * Success - Returns SavedReceive object with transaction details */ 200: SavedReceive; }; export type InventoryReceiveinventoryPostResponse = InventoryReceiveinventoryPostResponses[keyof InventoryReceiveinventoryPostResponses]; export type LineagesGetData = { body?: never; path?: never; query?: never; url: '/lineages'; }; export type LineagesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type LineagesGetResponses = { /** * Success - Returns array of lineage objects: `[{ Lineage }, ...]` */ 200: Array; }; export type LineagesGetResponse = LineagesGetResponses[keyof LineagesGetResponses]; export type PackageSetTagsPostData = { /** * Package tag update request with package identifiers and replacement tags - UpdatePackageTagsRequest object */ body?: UpdatePackageTagsRequest; path?: never; query?: never; url: '/package/set-tags'; }; export type PackageSetTagsPostErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PackageSetTagsPostError = PackageSetTagsPostErrors[keyof PackageSetTagsPostErrors]; export type PackageSetTagsPostResponses = { /** * Success - Tags successfully set on specified packages */ 200: unknown; }; export type PackageAddTagsPostData = { /** * Package tag update request with package identifiers and additional tags - UpdatePackageTagsRequest object */ body?: UpdatePackageTagsRequest; path?: never; query?: never; url: '/package/add-tags'; }; export type PackageAddTagsPostErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: unknown; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PackageAddTagsPostResponses = { /** * Success - Tags successfully added to specified packages */ 200: unknown; }; export type PackageRemoveTagsPostData = { /** * Package tag update request with package identifiers and tags to remove - UpdatePackageTagsRequest object */ body?: UpdatePackageTagsRequest; path?: never; query?: never; url: '/package/remove-tags'; }; export type PackageRemoveTagsPostErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: unknown; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PackageRemoveTagsPostResponses = { /** * Success - Tags successfully removed from specified packages */ 200: unknown; }; export type PlantGetData = { body?: never; path?: never; query?: { /** * Dutchie internal plant ID for specific plant lookup - Optional */ plantId?: number; /** * Plant serial number for tracking system integration - Optional */ serialNumber?: string; /** * Plant status filter: Active, Harvesting, Harvested, Retired - Optional */ status?: string; /** * Filter plants modified after this date for incremental sync - Optional */ lastModifiedDateStart?: string; /** * Filter plants modified before this date for date range filtering - Optional */ lastModifiedDateEnd?: string; }; url: '/plant'; }; export type PlantGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantGetResponses = { /** * Success */ 200: Array; }; export type PlantGetResponse = PlantGetResponses[keyof PlantGetResponses]; export type PlantPostData = { /** * Plant creation request with identification and group details - see `CreatePlantRequest` model for complete field documentation */ body?: CreatePlantRequest; path?: never; query?: never; url: '/plant'; }; export type PlantPostErrors = { /** * Bad Request - Validation errors or duplicate serial number */ 400: { [key: string]: unknown; }; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantPostError = PlantPostErrors[keyof PlantPostErrors]; export type PlantPostResponses = { /** * Success - Returns newly created plant ID as integer */ 200: number; }; export type PlantPostResponse = PlantPostResponses[keyof PlantPostResponses]; export type PlantHarvestPostData = { /** * Plant harvest request with plant identifiers and optional weight data - HarvestPlantRequest object */ body?: HarvestPlantRequest; path?: never; query?: never; url: '/plant/harvest'; }; export type PlantHarvestPostErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantHarvestPostResponses = { /** * Success - Plants successfully moved to harvest status */ 200: unknown; }; export type PlantMovePostData = { /** * Plant movement request with plant IDs and target room information - see `MovePlantRequest` model for complete field documentation */ body?: MovePlantRequest; path?: never; query?: never; url: '/plant/move'; }; export type PlantMovePostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: unknown; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantMovePostResponses = { /** * Success - Plants successfully moved to target room */ 200: unknown; }; export type PlantChangePhasePostData = { /** * Growth phase change request with plant IDs and target phase information - see `ChangeGrowthPhaseRequest` model for complete field documentation */ body?: ChangeGrowthPhaseRequest; path?: never; query?: never; url: '/plant/change-phase'; }; export type PlantChangePhasePostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: unknown; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantChangePhasePostResponses = { /** * Success - Plants successfully updated to new growth phase */ 200: unknown; }; export type PlantRetirePostData = { /** * Plant retirement request with plant IDs, reason codes, and waste tracking details - see `RetirePlantRequest` model for complete field documentation */ body?: RetirePlantRequest; path?: never; query?: never; url: '/plant/retire'; }; export type PlantRetirePostErrors = { /** * Bad Request - Invalid reason ID/code or validation errors */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantRetirePostError = PlantRetirePostErrors[keyof PlantRetirePostErrors]; export type PlantRetirePostResponses = { /** * Success - Plants successfully retired from cultivation */ 200: unknown; }; export type PlantGetReasonCodesGetData = { body?: never; path?: never; query?: never; url: '/plant/get-reason-codes'; }; export type PlantGetReasonCodesGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantGetReasonCodesGetResponses = { /** * Success - Returns array of reason code strings: `[string, ...]` */ 200: Array; }; export type PlantGetReasonCodesGetResponse = PlantGetReasonCodesGetResponses[keyof PlantGetReasonCodesGetResponses]; export type PlantAssignPlantsToGroupPostData = { /** * Plant group assignment request with group name and plant serial numbers - see `AssignPlantsToGroupRequest` model for complete field documentation */ body?: AssignPlantsToGroupRequest; path?: never; query?: never; url: '/plant/assign-plants-to-group'; }; export type PlantAssignPlantsToGroupPostErrors = { /** * Bad Request - Validation errors or invalid plant serial numbers */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantAssignPlantsToGroupPostError = PlantAssignPlantsToGroupPostErrors[keyof PlantAssignPlantsToGroupPostErrors]; export type PlantAssignPlantsToGroupPostResponses = { /** * Success - Plants successfully assigned to target group */ 200: unknown; }; export type PlantNonstsUpdatePostData = { /** * Plant update request with PlantId and field updates - UpdatePlantsRequest object */ body?: UpdatePlantsRequest; path?: never; query?: never; url: '/plant/nonsts/update'; }; export type PlantNonstsUpdatePostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantNonstsUpdatePostError = PlantNonstsUpdatePostErrors[keyof PlantNonstsUpdatePostErrors]; export type PlantNonstsUpdatePostResponses = { /** * Success */ 200: SuccessResult; }; export type PlantNonstsUpdatePostResponse = PlantNonstsUpdatePostResponses[keyof PlantNonstsUpdatePostResponses]; export type PlantNonstsBatchImmatureplantsPostData = { /** * Immature plant batch request with plant details - PostImmatureBatchRequest object */ body?: PostImmatureBatchRequest; path?: never; query?: never; url: '/plant/nonsts/batch/immatureplants'; }; export type PlantNonstsBatchImmatureplantsPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantNonstsBatchImmatureplantsPostError = PlantNonstsBatchImmatureplantsPostErrors[keyof PlantNonstsBatchImmatureplantsPostErrors]; export type PlantNonstsBatchImmatureplantsPostResponses = { /** * Success */ 200: CreateImmaturePlantBatchResponseApiResult; }; export type PlantNonstsBatchImmatureplantsPostResponse = PlantNonstsBatchImmatureplantsPostResponses[keyof PlantNonstsBatchImmatureplantsPostResponses]; export type PlantNonstsBatchConvertImmatureplantsPostData = { /** * Immature batch conversion request with conversion details - ConvertImmatureBatchRequest object */ body?: ConvertImmatureBatchRequest; path?: never; query?: never; url: '/plant/nonsts/batch/convert/immatureplants'; }; export type PlantNonstsBatchConvertImmatureplantsPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantNonstsBatchConvertImmatureplantsPostError = PlantNonstsBatchConvertImmatureplantsPostErrors[keyof PlantNonstsBatchConvertImmatureplantsPostErrors]; export type PlantNonstsBatchConvertImmatureplantsPostResponses = { /** * Success */ 200: ConvertImmaturePlantResponseApiResult; }; export type PlantNonstsBatchConvertImmatureplantsPostResponse = PlantNonstsBatchConvertImmatureplantsPostResponses[keyof PlantNonstsBatchConvertImmatureplantsPostResponses]; export type PlantNonstsBatchMatureplantsPostData = { /** * Mature plant batch request with plant details - CreateMatureBatchRequest object */ body?: CreateMatureBatchRequest; path?: never; query?: never; url: '/plant/nonsts/batch/matureplants'; }; export type PlantNonstsBatchMatureplantsPostErrors = { /** * Bad Request - Validation failed or invalid request data */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for mature plant creation or feature flag disabled */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type PlantNonstsBatchMatureplantsPostError = PlantNonstsBatchMatureplantsPostErrors[keyof PlantNonstsBatchMatureplantsPostErrors]; export type PlantNonstsBatchMatureplantsPostResponses = { /** * Success - Returns ApiResult with created plant IDs: `{ "data": { "createdPlants": [plantId1, plantId2, ...] }, "message": "Successfully created mature plants from batches.", "success": true }` */ 200: CreateMaturePlantsResponseApiResult; }; export type PlantNonstsBatchMatureplantsPostResponse = PlantNonstsBatchMatureplantsPostResponses[keyof PlantNonstsBatchMatureplantsPostResponses]; export type PlantNonstsRetagPostData = { /** * Plant retagging request with plant and new tag details - RetagPlantRequest object */ body?: RetagPlantRequest; path?: never; query?: never; url: '/plant/nonsts/retag'; }; export type PlantNonstsRetagPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantNonstsRetagPostError = PlantNonstsRetagPostErrors[keyof PlantNonstsRetagPostErrors]; export type PlantNonstsRetagPostResponses = { /** * Success */ 200: unknown; }; export type PlantNonstsBatchRetirePostData = { /** * Immature plant retirement request with plant details - RetireImmaturePlantsRequest object */ body?: RetireImmaturePlantsRequest; path?: never; query?: never; url: '/plant/nonsts/batch/retire'; }; export type PlantNonstsBatchRetirePostErrors = { /** * Bad Request - Validation failed or invalid plant data */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for plant retirement */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type PlantNonstsBatchRetirePostError = PlantNonstsBatchRetirePostErrors[keyof PlantNonstsBatchRetirePostErrors]; export type PlantNonstsBatchRetirePostResponses = { /** * Success - No response body, operation completed successfully */ 200: unknown; }; export type PlantNonstsBatchFinishHarvestPostData = { /** * Harvest batch finish/unfinish request with batch details - FinishHarvestBatchRequest object */ body?: Array; path?: never; query?: never; url: '/plant/nonsts/batch/finish-harvest'; }; export type PlantNonstsBatchFinishHarvestPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantNonstsBatchFinishHarvestPostError = PlantNonstsBatchFinishHarvestPostErrors[keyof PlantNonstsBatchFinishHarvestPostErrors]; export type PlantNonstsBatchFinishHarvestPostResponses = { /** * Success */ 200: unknown; }; export type PlantNonstsSplitPostData = { /** * Immature plant batch split request with batch and split details - SplitImmaturePlantsRequest object */ body?: SplitImmaturePlantsRequest; path?: never; query?: never; url: '/plant/nonsts/split'; }; export type PlantNonstsSplitPostErrors = { /** * Bad Request - Validation failed or invalid batch data */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for batch splitting */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type PlantNonstsSplitPostError = PlantNonstsSplitPostErrors[keyof PlantNonstsSplitPostErrors]; export type PlantNonstsSplitPostResponses = { /** * Success - Returns ApiResult with split batch details: `{ "data": { "originalBatch": {...}, "newBatch": {...} }, "message": "Successfully split immature batches of plants.", "success": true }` */ 200: SplitImmaturePlantResultApiResult; }; export type PlantNonstsSplitPostResponse = PlantNonstsSplitPostResponses[keyof PlantNonstsSplitPostResponses]; export type PlantNonstsBatchPostData = { /** * Batch update request with batch identification and field updates - UpdateBatchRequest object */ body?: UpdateBatchRequest; path?: never; query?: never; url: '/plant/nonsts/batch'; }; export type PlantNonstsBatchPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PlantNonstsBatchPostError = PlantNonstsBatchPostErrors[keyof PlantNonstsBatchPostErrors]; export type PlantNonstsBatchPostResponses = { /** * Success */ 200: unknown; }; export type PreorderSubmitPostData = { /** * Pre-order details including customer, cart items, and fulfillment information - CreatePreOrderRequest object */ body?: CreatePreOrderRequest; path?: never; query?: never; url: '/preorder/submit'; }; export type PreorderSubmitPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type PreorderSubmitPostError = PreorderSubmitPostErrors[keyof PreorderSubmitPostErrors]; export type PreorderSubmitPostResponses = { /** * Success - Returns orderId and transactionId for the created pre-order */ 200: number; }; export type PreorderSubmitPostResponse = PreorderSubmitPostResponses[keyof PreorderSubmitPostResponses]; export type PreorderUpdatePostData = { /** * Update details including OrderId and fields to be modified */ body?: UpdatePreOrderRequest; path?: never; query?: never; url: '/preorder/update'; }; export type PreorderUpdatePostErrors = { /** * Bad Request - Empty response body (handle via HTTP status code only) */ 400: unknown; /** * Not Found - Order ID does not exist */ 404: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type PreorderUpdatePostResponses = { /** * Success - Order updated successfully */ 200: unknown; }; export type PreorderCancelPostData = { /** * Cancellation request containing the OrderId to cancel */ body?: CancelPreorderRequest; path?: never; query?: never; url: '/preorder/cancel'; }; export type PreorderCancelPostErrors = { /** * Bad Request - Empty response body (handle via HTTP status code only) */ 400: unknown; /** * Not Found - Order ID does not exist */ 404: unknown; /** * Internal Server Error - Server error occurred */ 500: string; }; export type PreorderCancelPostError = PreorderCancelPostErrors[keyof PreorderCancelPostErrors]; export type PreorderCancelPostResponses = { /** * Success - Order cancelled successfully */ 200: number; }; export type PreorderCancelPostResponse = PreorderCancelPostResponses[keyof PreorderCancelPostResponses]; export type PreorderStatusGetData = { body?: never; path?: never; query?: { /** * Specific order ID to retrieve status for (optional - omit for all open orders) */ PreOrderId?: number; /** * Include detailed product line item information (requires PreOrderId) */ includeLineItems?: boolean; }; url: '/preorder/Status'; }; export type PreorderStatusGetErrors = { /** * Bad Request - Empty response body (handle via HTTP status code only) */ 400: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type PreorderStatusGetResponses = { /** * Success - Returns PreOrderStatus object(s) with current order information */ 200: PreOrderStatus; }; export type PreorderStatusGetResponse = PreorderStatusGetResponses[keyof PreorderStatusGetResponses]; export type PreorderPriceCartPostData = { /** * Pricing request containing customer information, cart items, and delivery preferences */ body?: PriceCartRequest; path?: never; query?: never; url: '/preorder/price-cart'; }; export type PreorderPriceCartPostErrors = { /** * Bad Request - String error message (parse response body as plain text) */ 400: string; /** * Internal Server Error - Server error occurred during pricing calculation */ 500: unknown; }; export type PreorderPriceCartPostError = PreorderPriceCartPostErrors[keyof PreorderPriceCartPostErrors]; export type PreorderPriceCartPostResponses = { /** * Success - Returns detailed pricing breakdown for the cart */ 200: CartPrice; }; export type PreorderPriceCartPostResponse = PreorderPriceCartPostResponses[keyof PreorderPriceCartPostResponses]; export type PricingTiersGetData = { body?: never; path?: never; query?: never; url: '/pricing-tiers'; }; export type PricingTiersGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type PricingTiersGetResponses = { /** * Success - Returns array of pricing tier objects: `[{ PricingTier }, ...]` */ 200: Array; }; export type PricingTiersGetResponse = PricingTiersGetResponses[keyof PricingTiersGetResponses]; export type ProducersGetData = { body?: never; path?: never; query?: never; url: '/producers'; }; export type ProducersGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ProducersGetResponses = { /** * Success - Returns array of producer objects: `[{ Producer }, ...]` */ 200: Array; }; export type ProducersGetResponse = ProducersGetResponses[keyof ProducersGetResponses]; export type ProductsLocationOverridesGetData = { body?: never; path?: never; query?: never; url: '/products/location-overrides'; }; export type ProductsLocationOverridesGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ProductsLocationOverridesGetResponses = { /** * Success */ 200: Array; }; export type ProductsLocationOverridesGetResponse = ProductsLocationOverridesGetResponses[keyof ProductsLocationOverridesGetResponses]; export type ProductsLocationOverridesPostData = { /** * Array of location product override requests with ProductId and override values - LocationProductOverrideRequest objects */ body?: Array; path?: never; query?: never; url: '/products/location-overrides'; }; export type ProductsLocationOverridesPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: unknown; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. One or more overrides may have been saved */ 500: unknown; }; export type ProductsLocationOverridesPostResponses = { /** * Success */ 200: unknown; }; export type ProductsGetData = { body?: never; path?: never; query?: { /** * Optional date filter to return only products modified after this timestamp - Used for incremental sync */ fromLastModifiedDateUTC?: string; /** * Optional status filter - true for active products only, false for inactive only, null for all products */ isActive?: boolean; }; url: '/products'; }; export type ProductsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for inventory access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ProductsGetResponses = { /** * Success - Returns array of product objects: `[{ ProductDetail }, ...]` */ 200: Array; }; export type ProductsGetResponse = ProductsGetResponses[keyof ProductsGetResponses]; export type ProductsProductPostData = { /** * Product information to create or update - ProductDetailUpload object with product details */ body?: ProductDetailUpload; path?: never; query?: never; url: '/products/product'; }; export type ProductsProductPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ProductsProductPostError = ProductsProductPostErrors[keyof ProductsProductPostErrors]; export type ProductsProductPostResponses = { /** * Success */ 200: ProductDetail; }; export type ProductsProductPostResponse = ProductsProductPostResponses[keyof ProductsProductPostResponses]; export type ProductsProductsPostData = { /** * Array of product information to create or update - IEnumerable objects */ body?: Array; path?: never; query?: never; url: '/products/products'; }; export type ProductsProductsPostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) OR `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ProductsProductsPostError = ProductsProductsPostErrors[keyof ProductsProductsPostErrors]; export type ProductsProductsPostResponses = { /** * Success - Products processed with individual success/error results */ 200: Array<{ [key: string]: unknown; }>; }; export type ProductsProductsPostResponse = ProductsProductsPostResponses[keyof ProductsProductsPostResponses]; export type ProductsSetImagePostData = { /** * Image upload request with ProductId and base64 image data - SetImageRequest object */ body?: SetImageRequestWritable; path?: never; query?: never; url: '/products/set-image'; }; export type ProductsSetImagePostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ProductsSetImagePostError = ProductsSetImagePostErrors[keyof ProductsSetImagePostErrors]; export type ProductsSetImagePostResponses = { /** * Success */ 200: SetImageResponse; }; export type ProductsSetImagePostResponse = ProductsSetImagePostResponses[keyof ProductsSetImagePostResponses]; export type ProductsRemoveImagePostData = { /** * Image deletion request with ProductId and ImageId - DeleteImageRequest object */ body?: DeleteImageRequest; path?: never; query?: never; url: '/products/remove-image'; }; export type ProductsRemoveImagePostErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ProductsRemoveImagePostError = ProductsRemoveImagePostErrors[keyof ProductsRemoveImagePostErrors]; export type ProductsRemoveImagePostResponses = { /** * Success */ 200: SuccessResult; }; export type ProductsRemoveImagePostResponse = ProductsRemoveImagePostResponses[keyof ProductsRemoveImagePostResponses]; export type ProductsStrainsGetData = { body?: never; path?: never; query?: never; url: '/products/strains'; }; export type ProductsStrainsGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ProductsStrainsGetResponses = { /** * Success */ 200: Array; }; export type ProductsStrainsGetResponse = ProductsStrainsGetResponses[keyof ProductsStrainsGetResponses]; export type ProductsExternalCategoriesGetData = { body?: never; path?: never; query?: { /** * User ID for traceability system access context (highly recommended) - Optional but prevents system failures */ userId?: number; }; url: '/products/external-categories'; }; export type ProductsExternalCategoriesGetErrors = { /** * Bad Request - String error message (parse response body as plain text) */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ProductsExternalCategoriesGetError = ProductsExternalCategoriesGetErrors[keyof ProductsExternalCategoriesGetErrors]; export type ProductsExternalCategoriesGetResponses = { /** * Success */ 200: Array; }; export type ProductsExternalCategoriesGetResponse = ProductsExternalCategoriesGetResponses[keyof ProductsExternalCategoriesGetResponses]; export type ProductCategoryGetData = { body?: never; path?: never; query?: never; url: '/product-category'; }; export type ProductCategoryGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ProductCategoryGetResponses = { /** * Success - Returns array of product category objects: `[{ ProductCategory }, ...]` */ 200: Array; }; export type ProductCategoryGetResponse = ProductCategoryGetResponses[keyof ProductCategoryGetResponses]; export type PurchaseOrderGetData = { body?: never; path?: never; query?: { /** * Start date filter for purchase orders created after this date (optional). */ FromDateCreated?: string; /** * End date filter for purchase orders created before this date (optional). */ ToDateCreated?: string; /** * Specific purchase order identifier for single order retrieval (optional). */ PurchaseOrderId?: number; /** * Whether to include detailed line item information in the response (default: false). */ IncludeItemDetails?: boolean; /** * Page number for pagination control (default: 0). */ PageNumber?: number; /** * Number of results per page for pagination (default: 1000). */ PageSize?: number; }; url: '/purchase-order'; }; export type PurchaseOrderGetErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PurchaseOrderGetError = PurchaseOrderGetErrors[keyof PurchaseOrderGetErrors]; export type PurchaseOrderGetResponses = { /** * Success */ 200: Array; }; export type PurchaseOrderGetResponse = PurchaseOrderGetResponses[keyof PurchaseOrderGetResponses]; export type PurchaseOrderPostData = { /** * Purchase order creation/update request with order details - CreateUpdatePurchaseOrdersRequest object */ body?: CreateUpdatePurchaseOrdersRequest; path?: never; query?: never; url: '/purchase-order'; }; export type PurchaseOrderPostErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: BadRequestResponse; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type PurchaseOrderPostError = PurchaseOrderPostErrors[keyof PurchaseOrderPostErrors]; export type PurchaseOrderPostResponses = { /** * Success */ 200: CreateUpdatePurchaseOrderResponse; }; export type PurchaseOrderPostResponse = PurchaseOrderPostResponses[keyof PurchaseOrderPostResponses]; export type ReferenceUnitsGetData = { body?: never; path?: never; query?: never; url: '/reference/units'; }; export type ReferenceUnitsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReferenceUnitsGetResponses = { /** * Success - Returns array of unit objects: `[{ Unit }, ...]` */ 200: Array; }; export type ReferenceUnitsGetResponse = ReferenceUnitsGetResponses[keyof ReferenceUnitsGetResponses]; export type ReferenceUnitTypesGetData = { body?: never; path?: never; query?: never; url: '/reference/unit-types'; }; export type ReferenceUnitTypesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReferenceUnitTypesGetResponses = { /** * Success - Returns array of unit type objects: `[{ UnitType }, ...]` */ 200: Array; }; export type ReferenceUnitTypesGetResponse = ReferenceUnitTypesGetResponses[keyof ReferenceUnitTypesGetResponses]; export type ReferenceLabResultUnitsGetData = { body?: never; path?: never; query?: never; url: '/reference/lab-result-units'; }; export type ReferenceLabResultUnitsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReferenceLabResultUnitsGetResponses = { /** * Success - Returns array of lab result unit objects: `[{ LabResultUnitData }, ...]` */ 200: Array; }; export type ReferenceLabResultUnitsGetResponse = ReferenceLabResultUnitsGetResponses[keyof ReferenceLabResultUnitsGetResponses]; export type ReferenceLabResultsNamesGetData = { body?: never; path?: never; query?: never; url: '/reference/lab-results-names'; }; export type ReferenceLabResultsNamesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReferenceLabResultsNamesGetResponses = { /** * Success - Returns array of strings with lab result names: `["string", ...]` */ 200: Array; }; export type ReferenceLabResultsNamesGetResponse = ReferenceLabResultsNamesGetResponses[keyof ReferenceLabResultsNamesGetResponses]; export type RegulatoryCategoryGetData = { body?: never; path?: never; query?: never; url: '/regulatory-category'; }; export type RegulatoryCategoryGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type RegulatoryCategoryGetResponses = { /** * Success - Returns array of regulatory category objects: `[{ RegulatoryCategory }, ...]` */ 200: Array; }; export type RegulatoryCategoryGetResponse = RegulatoryCategoryGetResponses[keyof RegulatoryCategoryGetResponses]; export type ReportingInventoryGetData = { body?: never; path?: never; query?: { includeLabResults?: boolean; includeRoomQuantities?: boolean; includeAllocated?: boolean; includeLineage?: boolean; }; url: '/reporting/inventory'; }; export type ReportingInventoryGetErrors = { /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type ReportingInventoryGetResponses = { /** * OK */ 200: Array; }; export type ReportingInventoryGetResponse = ReportingInventoryGetResponses[keyof ReportingInventoryGetResponses]; export type ReportingTransactionsGetData = { body?: never; path?: never; query?: { /** * Specific transaction identifier for single transaction lookup. */ TransactionId?: number; /** * Start date for filtering transactions by last modified date (UTC) for incremental sync. */ FromLastModifiedDateUTC?: string; /** * End date for filtering transactions by last modified date (UTC) for incremental sync. */ ToLastModifiedDateUTC?: string; /** * Start date for filtering transactions by transaction date (UTC) for periodic reports. */ FromDateUTC?: string; /** * End date for filtering transactions by transaction date (UTC) for periodic reports. */ ToDateUTC?: string; /** * Flag to include detailed transaction item information for comprehensive reporting. */ IncludeDetail?: boolean; /** * Flag to include tax information for financial compliance reporting. */ IncludeTaxes?: boolean; /** * Flag to include order identifiers for order fulfillment tracking. */ IncludeOrderIds?: boolean; /** * Flag to include fees and donations for complete financial analysis. */ IncludeFeesAndDonations?: boolean; }; url: '/reporting/transactions'; }; export type ReportingTransactionsGetErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; /** * Temporarily disabled (kill switch). */ 503: unknown; }; export type ReportingTransactionsGetError = ReportingTransactionsGetErrors[keyof ReportingTransactionsGetErrors]; export type ReportingTransactionsGetResponses = { /** * Success */ 200: Array; }; export type ReportingTransactionsGetResponse = ReportingTransactionsGetResponses[keyof ReportingTransactionsGetResponses]; export type ReportingCustomersGetData = { body?: never; path?: never; query?: { /** * Filter customers modified after this UTC date - Used for incremental sync */ fromLastModifiedDateUTC?: string; /** * Filter customers modified before this UTC date - Used for date range filtering */ toLastModifiedDateUTC?: string; /** * Include anonymous customers in results - Default: true */ includeAnonymous?: boolean; }; url: '/reporting/customers'; }; export type ReportingCustomersGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingCustomersGetResponses = { /** * Success - Returns array of customer objects */ 200: Array; }; export type ReportingCustomersGetResponse = ReportingCustomersGetResponses[keyof ReportingCustomersGetResponses]; export type ReportingCustomersPaginatedGetData = { body?: never; path?: never; query?: { /** * Filter customers modified after this UTC date for incremental sync - Optional */ fromLastModifiedDateUTC?: string; /** * Filter customers modified before this UTC date for date range filtering - Optional */ toLastModifiedDateUTC?: string; /** * Page number for sequential pagination (integer, starts at 0) - Default: 0 */ PageNumber?: number; /** * Number of items per page (integer) - Default: 1000, Maximum: 10000 */ PageSize?: number; /** * Include anonymous customers in results - Default: true */ includeAnonymous?: boolean; }; url: '/reporting/customers-paginated'; }; export type ReportingCustomersPaginatedGetErrors = { /** * Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) */ 400: BadRequestResponse; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingCustomersPaginatedGetError = ReportingCustomersPaginatedGetErrors[keyof ReportingCustomersPaginatedGetErrors]; export type ReportingCustomersPaginatedGetResponses = { /** * Success - Returns array of customer objects for the requested page */ 200: Array; }; export type ReportingCustomersPaginatedGetResponse = ReportingCustomersPaginatedGetResponses[keyof ReportingCustomersPaginatedGetResponses]; export type ReportingRegisterAdjustmentsGetData = { body?: never; path?: never; query?: { /** * Filter adjustments modified after this date for incremental sync - Optional */ fromLastModifiedDateUTC?: string; /** * Filter adjustments modified before this date for date range filtering - Optional */ toLastModifiedDateUTC?: string; }; url: '/reporting/register-adjustments'; }; export type ReportingRegisterAdjustmentsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingRegisterAdjustmentsGetResponses = { /** * Success - Returns array of register adjustment objects */ 200: Array; }; export type ReportingRegisterAdjustmentsGetResponse = ReportingRegisterAdjustmentsGetResponses[keyof ReportingRegisterAdjustmentsGetResponses]; export type ReportingRegisterTransactionsGetData = { body?: never; path?: never; query?: { /** * Filter transactions modified after this date for incremental sync - Optional */ fromLastModifiedDateUTC?: string; /** * Filter transactions modified before this date for date range filtering - Optional */ toLastModifiedDateUTC?: string; }; url: '/reporting/register-transactions'; }; export type ReportingRegisterTransactionsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingRegisterTransactionsGetResponses = { /** * Success - Returns array of RegisterTransaction objects with comprehensive transaction data */ 200: Array; }; export type ReportingRegisterTransactionsGetResponse = ReportingRegisterTransactionsGetResponses[keyof ReportingRegisterTransactionsGetResponses]; export type ReportingCashSummaryGetData = { body?: never; path?: never; query?: { /** * Filter activity after this date (must be within last 7 days) - Optional */ fromLastModifiedDateUTC?: string; /** * Filter activity before this date for date range filtering - Optional */ toLastModifiedDateUTC?: string; }; url: '/reporting/cash-summary'; }; export type ReportingCashSummaryGetErrors = { /** * Bad Request - String error message (parse response body as plain text) */ 400: string; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingCashSummaryGetError = ReportingCashSummaryGetErrors[keyof ReportingCashSummaryGetErrors]; export type ReportingCashSummaryGetResponses = { /** * Success - Returns array of register cash summary objects */ 200: Array; }; export type ReportingCashSummaryGetResponse = ReportingCashSummaryGetResponses[keyof ReportingCashSummaryGetResponses]; export type ReportingLoyaltySnapshotGetData = { body?: never; path?: never; query?: never; url: '/reporting/loyalty-snapshot'; }; export type ReportingLoyaltySnapshotGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingLoyaltySnapshotGetResponses = { /** * Success - Returns array of loyalty balance snapshot objects */ 200: Array; }; export type ReportingLoyaltySnapshotGetResponse = ReportingLoyaltySnapshotGetResponses[keyof ReportingLoyaltySnapshotGetResponses]; export type ReportingProductsGetData = { body?: never; path?: never; query?: { /** * Filter products modified after this date for incremental sync - Optional */ fromLastModifiedDateUTC?: string; }; url: '/reporting/products'; }; export type ReportingProductsGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type ReportingProductsGetResponses = { /** * Success */ 200: Array; }; export type ReportingProductsGetResponse = ReportingProductsGetResponses[keyof ReportingProductsGetResponses]; export type ReportingClosingReportGetData = { body?: never; path?: never; query?: { /** * Start date for the report period (required) - Must be UTC datetime */ fromDateUTC?: string; /** * End date for the report period (required) - Must be UTC datetime */ toDateUTC?: string; }; url: '/reporting/closing-report'; }; export type ReportingClosingReportGetErrors = { /** * Bad Request - String error message (parse response body as plain text) */ 400: string; /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingClosingReportGetError = ReportingClosingReportGetErrors[keyof ReportingClosingReportGetErrors]; export type ReportingClosingReportGetResponses = { /** * Success - Returns comprehensive closing report object */ 200: ClosingReportV2; }; export type ReportingClosingReportGetResponse = ReportingClosingReportGetResponses[keyof ReportingClosingReportGetResponses]; export type ReportingDiscountsGetData = { body?: never; path?: never; query?: { /** * Include deleted/archived discounts in results - Default: false */ includeDeleted?: boolean; }; url: '/reporting/discounts'; }; export type ReportingDiscountsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for reporting access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type ReportingDiscountsGetResponses = { /** * Success - Returns array of comprehensive discount configuration objects */ 200: Array; }; export type ReportingDiscountsGetResponse = ReportingDiscountsGetResponses[keyof ReportingDiscountsGetResponses]; export type RoomRoomsGetData = { body?: never; path?: never; query?: { /** * Optional room ID for specific room lookup - integer */ roomId?: number; /** * Optional room name for searching rooms by name - string */ roomName?: string; }; url: '/room/rooms'; }; export type RoomRoomsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for room access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type RoomRoomsGetResponses = { /** * Success - Returns array of room objects: `[{ Room }, ...]` */ 200: Array; }; export type RoomRoomsGetResponse = RoomRoomsGetResponses[keyof RoomRoomsGetResponses]; export type RoomPostData = { /** * Room information to create or update - Room object with RoomId, RoomName, and room type flags */ body?: Room; path?: never; query?: never; url: '/room'; }; export type RoomPostErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for room modification */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type RoomPostResponses = { /** * Success - Returns single room object: `{ Room }` */ 200: Room; }; export type RoomPostResponse = RoomPostResponses[keyof RoomPostResponses]; export type SizesGetData = { body?: never; path?: never; query?: never; url: '/sizes'; }; export type SizesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type SizesGetResponses = { /** * Success - Returns array of size objects: `[{ Size }, ...]` */ 200: Array; }; export type SizesGetResponse = SizesGetResponses[keyof SizesGetResponses]; export type StrainsGetData = { body?: never; path?: never; query?: never; url: '/strains'; }; export type StrainsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for inventory access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type StrainsGetResponses = { /** * Success - Returns array of strain objects: `[{ StrainDetail }, ...]` */ 200: Array; }; export type StrainsGetResponse = StrainsGetResponses[keyof StrainsGetResponses]; export type StrainsPostData = { body?: UpdateStrain; path?: never; query?: never; url: '/strains'; }; export type StrainsPostErrors = { /** * Bad Request */ 400: string; /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type StrainsPostError = StrainsPostErrors[keyof StrainsPostErrors]; export type StrainsPostResponses = { /** * OK */ 200: StrainDetail; }; export type StrainsPostResponse = StrainsPostResponses[keyof StrainsPostResponses]; export type StrainsTypesGetData = { body?: never; path?: never; query?: never; url: '/strains/types'; }; export type StrainsTypesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for inventory access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type StrainsTypesGetResponses = { /** * Success - Returns array of strings with strain type names: `["Indica", "Sativa", "Hybrid", "CBD"]` */ 200: Array; }; export type StrainsTypesGetResponse = StrainsTypesGetResponses[keyof StrainsTypesGetResponses]; export type TableTablesGetData = { body?: never; path?: never; query?: { /** * Optional table ID for specific table lookup - integer */ tableId?: number; /** * Optional table name for searching tables by name - string */ tableName?: string; }; url: '/table/tables'; }; export type TableTablesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for table access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type TableTablesGetResponses = { /** * Success - Returns array of table objects: `[{ Table }, ...]` */ 200: Array; }; export type TableTablesGetResponse = TableTablesGetResponses[keyof TableTablesGetResponses]; export type TablePostData = { /** * Table information to create or update - Table object with TableId and TableName fields */ body?: Table; path?: never; query?: never; url: '/table'; }; export type TablePostErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for table modification */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type TablePostResponses = { /** * Success - Returns single table object: `{ Table }` */ 200: Table; }; export type TablePostResponse = TablePostResponses[keyof TablePostResponses]; export type TagGetData = { body?: never; path?: never; query?: never; url: '/tag'; }; export type TagGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for inventory access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type TagGetResponses = { /** * Success - Returns array of tag objects: `[{ Tag }, ...]` */ 200: Array; }; export type TagGetResponse = TagGetResponses[keyof TagGetResponses]; export type TerminalsGetData = { body?: never; path?: never; query?: never; url: '/terminals'; }; export type TerminalsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type TerminalsGetResponses = { /** * Success - Returns array of terminal objects: `[{ Terminal }, ...]` */ 200: Array; }; export type TerminalsGetResponse = TerminalsGetResponses[keyof TerminalsGetResponses]; export type TransactionCreateAnonymousPostData = { /** * Anonymous transaction request with optional transaction reference - CreateAnonymousTransactionRequest object */ body?: CreateAnonymousTransactionRequest; path?: never; query?: never; url: '/transaction/create-anonymous'; }; export type TransactionCreateAnonymousPostErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for transaction creation */ 403: unknown; /** * Internal Server Error - Server error occurred during transaction creation */ 500: unknown; }; export type TransactionCreateAnonymousPostResponses = { /** * Success - Returns anonymous transaction object: `{ AnonymousTransaction }` */ 200: AnonymousTransaction; }; export type TransactionCreateAnonymousPostResponse = TransactionCreateAnonymousPostResponses[keyof TransactionCreateAnonymousPostResponses]; export type UtilAuthorizationHeaderByApiKeyGetData = { body?: never; path: { /** * API key to convert into authorization header format - string */ apiKey: string; }; query?: never; url: '/util/AuthorizationHeader/{apiKey}'; }; export type UtilAuthorizationHeaderByApiKeyGetResponses = { /** * Success - Returns formatted authorization header string: "Basic {base64-encoded-key}" */ 200: string; }; export type UtilAuthorizationHeaderByApiKeyGetResponse = UtilAuthorizationHeaderByApiKeyGetResponses[keyof UtilAuthorizationHeaderByApiKeyGetResponses]; export type VehiclesGetData = { body?: never; path?: never; query?: never; url: '/vehicles'; }; export type VehiclesGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for vehicle access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type VehiclesGetResponses = { /** * Success - Returns array of vehicle objects: `[{ VehicleDetail }, ...]` */ 200: Array; }; export type VehiclesGetResponse = VehiclesGetResponses[keyof VehiclesGetResponses]; export type VehiclesPostData = { /** * Vehicle information to create or update - VehicleDetail object with fleet details */ body?: VehicleDetail; path?: never; query?: never; url: '/vehicles'; }; export type VehiclesPostErrors = { /** * Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array */ 400: ValidationResult; /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type VehiclesPostError = VehiclesPostErrors[keyof VehiclesPostErrors]; export type VehiclesPostResponses = { /** * Success */ 200: unknown; }; export type VendorVendorsGetData = { body?: never; path?: never; query?: { /** * Optional vendor ID to filter by specific vendor - Returns exact match */ vendorId?: number; /** * Optional vendor name to filter by - Supports partial matching for flexible search */ vendorName?: string; }; url: '/vendor/vendors'; }; export type VendorVendorsGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for vendor access */ 403: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type VendorVendorsGetResponses = { /** * Success - Returns array of vendor objects: `[{ Vendor }, ...]` */ 200: Array; }; export type VendorVendorsGetResponse = VendorVendorsGetResponses[keyof VendorVendorsGetResponses]; export type VendorPostData = { /** * Vendor information to create or update - Vendor object with supplier details */ body?: Vendor; path?: never; query?: never; url: '/vendor'; }; export type VendorPostErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - Account not authorized for vendor management */ 403: unknown; /** * Internal Server Error - Server error occurred during vendor operation */ 500: unknown; }; export type VendorPostResponses = { /** * Success - Returns vendor object: `{ Vendor }` */ 200: Vendor; }; export type VendorPostResponse = VendorPostResponses[keyof VendorPostResponses]; export type WasteGetData = { body?: never; path?: never; query?: never; url: '/waste'; }; export type WasteGetErrors = { /** * Invalid API Key */ 401: unknown; /** * Account not authorized */ 403: unknown; /** * Something went wrong. */ 500: unknown; }; export type WasteGetResponses = { /** * Success */ 200: WasteSummary; }; export type WasteGetResponse = WasteGetResponses[keyof WasteGetResponses]; export type WasteHarvestWastePostData = { body?: HarvestWasteDetailWaste; path?: never; query?: never; url: '/waste/HarvestWaste'; }; export type WasteHarvestWastePostErrors = { /** * Bad Request */ 400: string; /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type WasteHarvestWastePostError = WasteHarvestWastePostErrors[keyof WasteHarvestWastePostErrors]; export type WasteHarvestWastePostResponses = { /** * OK */ 200: { [key: string]: unknown; }; }; export type WasteHarvestWastePostResponse = WasteHarvestWastePostResponses[keyof WasteHarvestWastePostResponses]; export type WastePlantWastePostData = { body?: PlantWasteDetailWaste; path?: never; query?: never; url: '/waste/PlantWaste'; }; export type WastePlantWastePostErrors = { /** * Bad Request */ 400: string; /** * Unauthorized */ 401: unknown; /** * Forbidden */ 403: unknown; /** * Internal Server Error */ 500: unknown; }; export type WastePlantWastePostError = WastePlantWastePostErrors[keyof WastePlantWastePostErrors]; export type WastePlantWastePostResponses = { /** * OK */ 200: { [key: string]: unknown; }; }; export type WastePlantWastePostResponse = WastePlantWastePostResponses[keyof WastePlantWastePostResponses]; export type WhoamiGetData = { body?: never; path?: never; query?: never; url: '/whoami'; }; export type WhoamiGetErrors = { /** * Unauthorized - Invalid or missing API key */ 401: unknown; /** * Forbidden - API key doesn't have access to this location */ 403: unknown; /** * Not Found - Location not found for the authenticated API key */ 404: unknown; /** * Internal Server Error - Server error occurred */ 500: unknown; }; export type WhoamiGetResponses = { /** * Success - Returns location identity object: `{ LocationIdentity }` */ 200: LocationIdentity; }; export type WhoamiGetResponse = WhoamiGetResponses[keyof WhoamiGetResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BarRead, BarReadWritable, BarWrite, BarWriteWritable, Baz, ClientOptions, Corge, CorgeWritable, FooRead, FooReadWritable, FooReadWrite, FooReadWriteWritable, FooWrite, FooWriteWritable, PostFooReadData, PostFooReadResponse, PostFooReadResponses, PostFooReadWriteData, PostFooReadWriteResponse, PostFooReadWriteResponses, PostFooWriteData, PostFooWriteResponse, PostFooWriteResponses, Quux, QuuxWritable, QuxAllRead } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-read-write/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type FooReadWrite = BarRead; export type FooRead = BarRead & { readonly foo?: string; }; export type FooWrite = BarWrite; export type BarRead = Baz | { readonly bar?: string; }; export type BarWrite = Baz; export type Baz = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type Quux = { baz?: Array; qux?: QuxAllRead; }; export type Corge = { bar?: { readonly baz?: boolean; }; }; export type FooReadWriteWritable = BarReadWritable & { foo?: string; }; export type FooReadWritable = BarReadWritable; export type FooWriteWritable = BarWriteWritable & { foo?: string; }; export type BarReadWritable = Baz; export type BarWriteWritable = Baz | { bar?: string; }; export type QuuxWritable = { baz?: Array; }; export type CorgeWritable = { foo?: { baz?: boolean; }; }; export type PostFooReadWriteData = { body: FooReadWriteWritable; path?: never; query?: never; url: '/foo-read-write'; }; export type PostFooReadWriteResponses = { /** * OK */ 200: FooReadWrite; }; export type PostFooReadWriteResponse = PostFooReadWriteResponses[keyof PostFooReadWriteResponses]; export type PostFooReadData = { body: FooReadWritable; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: FooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; export type PostFooWriteData = { body: FooWriteWritable; path?: never; query?: never; url: '/foo-write'; }; export type PostFooWriteResponses = { /** * OK */ 200: FooWrite; }; export type PostFooWriteResponse = PostFooWriteResponses[keyof PostFooWriteResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-schemas-name/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Comment, GetUsersData, GetUsersResponse, GetUsersResponses, Post, PostPostsData, PostPostsResponse, PostPostsResponses, User, UserProfile } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-schemas-name/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type User = { id?: string; name?: string; profile?: UserProfile; }; export type UserProfile = { bio?: string; avatar?: string; }; export type Post = { id?: string; title?: string; author?: User; comments?: Array; }; export type Comment = { id?: string; text?: string; author?: User; }; export type GetUsersData = { body?: never; path?: never; query?: never; url: '/users'; }; export type GetUsersResponses = { /** * Success */ 200: User; }; export type GetUsersResponse = GetUsersResponses[keyof GetUsersResponses]; export type PostPostsData = { body?: Post; path?: never; query?: never; url: '/posts'; }; export type PostPostsResponses = { /** * Created */ 201: Post; }; export type PostPostsResponse = PostPostsResponses[keyof PostPostsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-schemas-name-collision/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetTestData, GetTestResponse, GetTestResponses, User, UserV1User, UserV2User } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/transforms-schemas-name-collision/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type UserV1User = { id?: string; version?: 'v1'; }; export type User = { name?: string; }; export type UserV2User = { email?: string; version?: 'v2'; }; export type GetTestData = { body?: never; path?: never; query?: never; url: '/test'; }; export type GetTestResponses = { /** * Success */ 200: { user1?: UserV1User; user2?: User; user3?: UserV2User; }; }; export type GetTestResponse = GetTestResponses[keyof GetTestResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/type-invalid/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/type-invalid/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = unknown; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: string; }; export type Bar = Foo & {}; export type Baz = Foo & { bar: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-true/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-true/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: string; [key: string]: unknown; }; export type Bar = Foo & { [key: string]: unknown; }; export type Baz = Foo & { bar: string; [key: string]: unknown; }; export type Qux = { [key: string]: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-true-any/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-true-any/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: string; [key: string]: any; }; export type Bar = Foo & { [key: string]: any; }; export type Baz = Foo & { bar: string; [key: string]: any; }; export type Qux = { [key: string]: any; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-undefined/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/additional-properties-undefined/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: { [key: string]: unknown; }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/array-items-one-of-length-1/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/array-items-one-of-length-1/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: Array; }; export type Bar = string; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/array-nested-one-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/array-nested-one-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = Array<{ foo?: string; bar?: string; } | { baz?: string; qux?: string; }> | Array<{ foo?: string; bar?: string; }>; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { ClientOptions, PostFooData, PostFooResponse, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options: Options) => (options.client ?? client).post({ bodySerializer: null, url: '/foo', ...options, headers: { 'Content-Type': 'text/plain', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/body-response-text-plain/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PostFooData = { body: string; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: string; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, ClientOptions, Foo, FooBar, FooBar2, FooBar3, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type Foo = { /** * original name: fooBar */ fooBar: FooBar; /** * original name: BarBaz */ BarBaz: Foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: FooBar2; /** * original name: BarBaz */ BarBaz: FooBar3; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type FooBar = boolean; /** * original name: fooBar */ export type FooBar2 = number; /** * original name: FooBar */ export type FooBar3 = string; export type GetFooData = { body: Foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Foo; /** * OK */ 201: _201; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, clientOptions, foo, fooBar, fooBar2, fooBar3, getFooData, getFooResponse, getFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type clientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type foo = { /** * original name: fooBar */ fooBar: fooBar; /** * original name: BarBaz */ BarBaz: foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: fooBar2; /** * original name: BarBaz */ BarBaz: fooBar3; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type fooBar = boolean; /** * original name: fooBar */ export type fooBar2 = number; /** * original name: FooBar */ export type fooBar3 = string; export type getFooData = { body: foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type getFooResponses = { /** * OK */ 200: foo; /** * OK */ 201: _201; }; export type getFooResponse = getFooResponses[keyof getFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, ClientOptions, Foo, foo_bar, fooBar, FooBar, getFooData, getFooResponse, getFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type Foo = { /** * original name: fooBar */ fooBar: foo_bar; /** * original name: BarBaz */ BarBaz: Foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: fooBar; /** * original name: BarBaz */ BarBaz: FooBar; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type foo_bar = boolean; /** * original name: fooBar */ export type fooBar = number; /** * original name: FooBar */ export type FooBar = string; export type getFooData = { body: Foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type getFooResponses = { /** * OK */ 200: Foo; /** * OK */ 201: _201; }; export type getFooResponse = getFooResponses[keyof getFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _201, client_options, foo, foo_bar, foo_bar2, foo_bar3, get_foo_data, get_foo_response, get_foo_responses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/case-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type client_options = { baseUrl: `${string}://${string}` | (string & {}); }; /** * original name: 201 */ export type _201 = number; /** * original name: Foo */ export type foo = { /** * original name: fooBar */ fooBar: foo_bar; /** * original name: BarBaz */ BarBaz: foo; /** * original name: qux_quux */ qux_quux: { /** * original name: fooBar */ fooBar: foo_bar2; /** * original name: BarBaz */ BarBaz: foo_bar3; /** * original name: qux_quux */ qux_quux: boolean; }; }; /** * original name: foo_bar */ export type foo_bar = boolean; /** * original name: fooBar */ export type foo_bar2 = number; /** * original name: FooBar */ export type foo_bar3 = string; export type get_foo_data = { body: foo; path?: never; query: { /** * original name: fooBar */ fooBar: string; /** * original name: BarBaz */ BarBaz: string; /** * original name: qux_quux */ qux_quux: string; }; url: '/foo'; }; export type get_foo_responses = { /** * OK */ 200: foo; /** * OK */ 201: _201; }; export type get_foo_response = get_foo_responses[keyof get_foo_responses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/clean-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen.ts'; import type { HttpMethod } from '../core/types.gen.ts'; import { getValidRequestBody } from '../core/utils.gen.ts'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen.ts'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.ts'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.ts'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts'; export { buildClientParams } from '../core/params.gen.ts'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts'; export { createClient } from './client.gen.ts'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.ts'; export { createConfig, mergeHeaders } from './utils.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen.ts'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.ts'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.ts'; import type { Middleware } from './utils.gen.ts'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen.ts'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen.ts'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.ts'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.ts'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.ts'; import type { ClientOptions as ClientOptions2 } from './types.gen.ts'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.ts'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.ts'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.ts'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.ts'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.ts'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.ts'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.ts'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.ts'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.ts'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.ts'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/import-file-extension-ts/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen.js'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-node16-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen.js'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-angular/tsconfig-nodenext-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/clean-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen.ts'; import type { HttpMethod } from '../core/types.gen.ts'; import { getValidRequestBody } from '../core/utils.gen.ts'; import type { Client, Config, RequestOptions } from './types.gen.ts'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen.ts'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.ts'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts'; export { buildClientParams } from '../core/params.gen.ts'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts'; export { createClient } from './client.gen.ts'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.ts'; export { createConfig } from './utils.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen.ts'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.ts'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.ts'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.ts'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.ts'; import { getUrl } from '../core/utils.gen.ts'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.ts'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.ts'; import type { ClientOptions as ClientOptions2 } from './types.gen.ts'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.ts'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.ts'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.ts'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.ts'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.ts'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.ts'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.ts'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.ts'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.ts'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.ts'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/import-file-extension-ts/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions } from './types.gen.js'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen.js'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.js'; export { createConfig } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-node16-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions } from './types.gen.js'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen.js'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.js'; export { createConfig } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-axios/tsconfig-nodenext-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/clean-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen.ts'; import type { HttpMethod } from '../core/types.gen.ts'; import { getValidRequestBody } from '../core/utils.gen.ts'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.ts'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.ts'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.ts'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts'; export { buildClientParams } from '../core/params.gen.ts'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts'; export { createClient } from './client.gen.ts'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.ts'; export { createConfig, mergeHeaders } from './utils.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen.ts'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.ts'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.ts'; import type { Middleware } from './utils.gen.ts'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.ts'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; import { jsonBodySerializer } from '../core/bodySerializer.gen.ts'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.ts'; import { getUrl } from '../core/utils.gen.ts'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.ts'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.ts'; import type { ClientOptions as ClientOptions2 } from './types.gen.ts'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.ts'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.ts'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.ts'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.ts'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.ts'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.ts'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.ts'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.ts'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.ts'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.ts'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/import-file-extension-ts/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-node16-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-fetch/tsconfig-nodenext-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/clean-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen.ts'; import type { HttpMethod } from '../core/types.gen.ts'; import { getValidRequestBody } from '../core/utils.gen.ts'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen.ts'; import type { Middleware } from './utils.gen.ts'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.ts'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.ts'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts'; export { buildClientParams } from '../core/params.gen.ts'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts'; export { createClient } from './client.gen.ts'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen.ts'; export { createConfig, mergeHeaders } from './utils.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen.ts'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.ts'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.ts'; import type { Middleware } from './utils.gen.ts'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.ts'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; import { jsonBodySerializer } from '../core/bodySerializer.gen.ts'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.ts'; import { getUrl } from '../core/utils.gen.ts'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.ts'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.ts'; import type { ClientOptions as ClientOptions2 } from './types.gen.ts'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.ts'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.ts'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.ts'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.ts'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.ts'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.ts'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.ts'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.ts'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.ts'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.ts'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/import-file-extension-ts/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen'; import type { Middleware } from './utils.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen.js'; import type { Middleware } from './utils.gen.js'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-node16-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HTTPError, Options as KyOptions } from 'ky'; import ky from 'ky'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, RetryOptions } from './types.gen.js'; import type { Middleware } from './utils.gen.js'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), ky: options.ky ?? _config.ky ?? ky, serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const parseErrorResponse = async ( response: Response, request: Request, opts: ResolvedRequestOptions, interceptorsMiddleware: Middleware, ) => { const result = { request, response, }; const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { jsonError = undefined; } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptorsMiddleware.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const kyInstance = opts.ky!; const validBody = getValidRequestBody(opts); const kyOptions: KyOptions = { body: validBody as BodyInit, cache: opts.cache, credentials: opts.credentials, headers: opts.headers, integrity: opts.integrity, keepalive: opts.keepalive, method: opts.method as KyOptions['method'], mode: opts.mode, redirect: 'follow', referrer: opts.referrer, referrerPolicy: opts.referrerPolicy, signal: opts.signal, throwHttpErrors: opts.throwOnError ?? false, timeout: opts.timeout, ...opts.kyOptions, }; if (opts.retry && typeof opts.retry === 'object') { const retryOpts = opts.retry as RetryOptions; kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; } let request = new Request(url, { body: kyOptions.body as BodyInit, headers: kyOptions.headers as HeadersInit, method: kyOptions.method, }); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } let response: Response; try { response = await kyInstance(request, kyOptions); } catch (error) { if (error && typeof error === 'object' && 'response' in error) { const httpError = error as HTTPError; response = httpError.response; for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } return parseErrorResponse(response, request, opts, interceptors); } throw error; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } return parseErrorResponse(response, request, opts, interceptors); }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, fetch: globalThis.fetch, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, RetryOptions, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface RetryOptions { /** * Maximum number of retry attempts * * @default 2 */ limit?: number; /** * HTTP methods to retry * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * * @default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; } export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Ky instance to use. You can use this option to provide a custom * ky instance. */ ky?: typeof ky; /** * Additional ky-specific options that will be passed directly to ky. * This allows you to use any ky option not explicitly exposed in the config. */ kyOptions?: Omit; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Retry configuration */ retry?: RetryOptions; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Request timeout in milliseconds * * @default 10000 */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, throwOnError: false, timeout: 10000, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ky/tsconfig-nodenext-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/clean-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen.ts'; import type { HttpMethod } from '../core/types.gen.ts'; import { getValidRequestBody } from '../core/utils.gen.ts'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.ts'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.ts'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.ts'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts'; export { buildClientParams } from '../core/params.gen.ts'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts'; export { createClient } from './client.gen.ts'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.ts'; export { createConfig } from './utils.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen.ts'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.ts'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.ts'; import type { Middleware } from './utils.gen.ts'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.ts'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen.ts'; import { jsonBodySerializer } from '../core/bodySerializer.gen.ts'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.ts'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.ts'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.ts'; import type { ClientOptions as ClientOptions2 } from './types.gen.ts'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.ts'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.ts'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.ts'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.ts'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.ts'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.ts'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.ts'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.ts'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.ts'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.ts'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/import-file-extension-ts/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.js'; export { createConfig } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-node16-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.js'; export { createConfig } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-next/tsconfig-nodenext-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, type Composable, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/clean-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, type Composable, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen.ts'; import type { HttpMethod } from '../core/types.gen.ts'; import { getValidRequestBody } from '../core/utils.gen.ts'; import type { Client, Config, RequestOptions } from './types.gen.ts'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen.ts'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.ts'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts'; export { buildClientParams } from '../core/params.gen.ts'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts'; export { createClient } from './client.gen.ts'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.ts'; export { createConfig } from './utils.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen.ts'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.ts'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.ts'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen.ts'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; import { jsonBodySerializer } from '../core/bodySerializer.gen.ts'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.ts'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen.ts'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.ts'; import type { ClientOptions as ClientOptions2 } from './types.gen.ts'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.ts'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.ts'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.ts'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.ts'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.ts'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.ts'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.ts'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.ts'; import { type Client, type Composable, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.ts'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen.ts'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/import-file-extension-ts/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, type Composable, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, type Composable, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions } from './types.gen.js'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen.js'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.js'; export { createConfig } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen.js'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, type Composable, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-node16-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions } from './types.gen.js'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen.js'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen.js'; export { createConfig } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen.js'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, type Composable, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => (options.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-nuxt/tsconfig-nodenext-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/clean-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen.ts'; import type { HttpMethod } from '../core/types.gen.ts'; import { getValidRequestBody } from '../core/utils.gen.ts'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.ts'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen.ts'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.ts'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts'; export { buildClientParams } from '../core/params.gen.ts'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts'; export { createClient } from './client.gen.ts'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.ts'; export { createConfig, mergeHeaders } from './utils.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen.ts'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.ts'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.ts'; import type { Middleware } from './utils.gen.ts'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen.ts'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts'; import { jsonBodySerializer } from '../core/bodySerializer.gen.ts'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.ts'; import { getUrl } from '../core/utils.gen.ts'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen.ts'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.ts'; import type { ClientOptions as ClientOptions2 } from './types.gen.ts'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.ts'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.ts'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.ts'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.ts'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.ts'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.ts'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.ts'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.ts'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.ts'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.ts'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.ts'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/import-file-extension-ts/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen.js'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-node16-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen.js'; import type { HttpMethod } from '../core/types.gen.js'; import { getValidRequestBody } from '../core/utils.gen.js'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen.js'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen.js'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js'; export { buildClientParams } from '../core/params.gen.js'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js'; export { createClient } from './client.gen.js'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.js'; export { createConfig, mergeHeaders } from './utils.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen.js'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen.js'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js'; import type { Middleware } from './utils.gen.js'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen.js'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js'; import { jsonBodySerializer } from '../core/bodySerializer.gen.js'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen.js'; import { getUrl } from '../core/utils.gen.js'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen.js'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js'; import type { ClientOptions as ClientOptions2 } from './types.gen.js'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen.js'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen.js'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen.js'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen.js'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { client } from './client.gen.js'; import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client/index.js'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen.js'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/@hey-api/client-ofetch/tsconfig-nodenext-sdk/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-false/custom-client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from '@hey-api/custom-client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-number/custom-client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from '@hey-api/custom-client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-strict/custom-client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from '@hey-api/custom-client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-string/custom-client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from '@hey-api/custom-client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/default/custom-client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from '@hey-api/custom-client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from '@hey-api/custom-client'; import { client } from './custom-client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-optional/custom-client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from '@hey-api/custom-client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from '@hey-api/custom-client'; import { client } from './custom-client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-required/custom-client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from '@hey-api/custom-client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from '@hey-api/custom-client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/client-custom/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-number/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-strict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base'; }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/base-url-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './custom.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/bundle/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './custom.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './custom.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-optional/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/custom.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options: Options) => options.client.get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options: Options) => options.client.patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => options.client.post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options: Options) => options.client.put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options: Options) => options.client.delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options: Options) => options.client.head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options: Options) => options.client.options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options: Options) => options.client.patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options: Options) => options.client.post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options: Options) => options.client.put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => options.client.delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options: Options) => options.client.post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => options.client.get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => options.client.post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options: Options) => options.client.post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionFormData = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const callWithDefaultParameters = (options: Options) => options.client.get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options: Options) => options.client.post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options: Options) => options.client.delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options: Options) => options.client.get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options: Options) => options.client.post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options: Options) => options.client.put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options: Options) => options.client.get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options: Options) => options.client.post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options: Options) => options.client.put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => options.client.get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => options.client.get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => options.client.post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => options.client.get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options: Options) => options.client.get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options: Options) => options.client.post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options.headers } }); export const complexParams = (options: Options) => options.client.put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options: Options) => options.client.post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => options.client.post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => options.client.post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => options.client.put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/clients/my-client/sdk-client-required/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/components-request-bodies/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/components-request-bodies/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * Foo */ export type Foo = { page?: number; }; export type PostFooData = { /** * Foo */ body: Foo; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/const/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/const/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: 'First line.\n\nSecond line.\n\nPS: I love you.'; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-binary/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetBarData, GetBarResponse, GetBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-binary/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type GetBarData = { body?: never; path?: never; query?: never; url: '/bar'; }; export type GetBarResponses = { 200: Blob | File; }; export type GetBarResponse = GetBarResponses[keyof GetBarResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-media-type/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, FileUploadRequest, FileUploadRequestTyped, UploadFileData, UploadFileResponses, UploadFileTypedData, UploadFileTypedResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-media-type/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type FileUploadRequest = { /** * Binary file content */ file: Blob | File; }; export type FileUploadRequestTyped = { /** * Binary file content with explicit string type */ file: Blob | File; }; export type UploadFileData = { body?: FileUploadRequest; path?: never; query?: never; url: '/upload'; }; export type UploadFileResponses = { /** * OK */ 200: unknown; }; export type UploadFileTypedData = { body?: FileUploadRequestTyped; path?: never; query?: never; url: '/upload-typed'; }; export type UploadFileTypedResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/content-types/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-all-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, BarMapped, BarUnion, Baz, BazMapped, BazUnion, ClientOptions, Foo, FooMapped, FooUnion, Qux, QuxExtend, QuxMapped } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-all-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { id: string; }; export type Bar = Omit & { bar?: string; id: 'Bar'; }; export type Baz = Omit & { baz?: string; id: 'Baz'; }; export type Qux = Omit & { qux?: boolean; id: 'Qux'; }; export type FooMapped = { id: string; }; export type BarMapped = Omit & { bar?: string; id: 'bar'; }; export type BazMapped = Omit & { baz?: string; id: 'baz'; }; export type QuxMapped = Omit & { qux?: boolean; id: 'QuxMapped'; }; export type FooUnion = ({ id: 'bar'; } & BarUnion) | ({ id: 'baz'; } & BazUnion); export type BarUnion = { id?: string; bar?: string; }; export type BazUnion = { id?: string; baz?: string; }; export type QuxExtend = FooUnion; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-allof-inline/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, GetFoosData, GetFoosResponse, GetFoosResponses, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-allof-inline/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { $type: string; foo?: string; }; export type Bar = Omit & { $type: 'FooBar'; bar?: string; }; export type Baz = Omit & { baz?: string; $type: 'FooBaz'; }; export type Qux = Omit & { qux?: string; $type: 'BarQux'; }; export type GetFoosData = { body?: never; path?: never; query?: never; url: '/foos'; }; export type GetFoosResponses = { /** * OK */ 200: Bar | Baz | Qux; }; export type GetFoosResponse = GetFoosResponses[keyof GetFoosResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-allof-nested/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { CarDto, ClientOptions, GetCarsData, GetCarsResponse, GetCarsResponses, VehicleDto, VolvoDto } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-allof-nested/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type VehicleDto = { $type: string; id: number; }; export type CarDto = Omit & { modelName: string; $type: 'Car'; }; export type VolvoDto = Omit & { seatbeltCount: number; $type: 'Volvo'; }; export type GetCarsData = { body?: never; path?: never; query?: never; url: '/cars'; }; export type GetCarsResponses = { /** * List of cars */ 200: Array; }; export type GetCarsResponse = GetCarsResponses[keyof GetCarsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-any-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Quux, Quuz, Qux, Spæcial } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-any-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ type?: 'Bar'; } & Bar) | ({ type?: 'Baz'; } & Baz); export type Baz = Qux; export type Bar = Qux; export type Spæcial = Qux; export type Qux = { id: string; type: Quux; }; export type Quux = 'Bar' | 'Baz'; export type Quuz = ({ type?: 'bar'; } & Bar) | ({ type?: 'baz'; } & Baz) | ({ type?: 'non-ascii'; } & Spæcial); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-mapped-many/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Spæcial } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-mapped-many/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ foo: 'one' | 'two'; } & Bar) | ({ foo: 'three'; } & Baz) | ({ foo: 'four'; } & Spæcial); export type Bar = { foo?: 'one' | 'two'; }; export type Baz = { foo?: 'three'; }; export type Spæcial = { foo?: 'four'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-non-string/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { AutoConfig, BooleanAnyOf, BooleanOneOf, ClientOptions, CustomConfig, IntegerAllOfBase, IntegerAllOfChildA, IntegerAllOfChildB, IntegerOneOf, NullableIntegerOneOf, NullableVariantX, NullableVariantY, NumberOneOf, TypeOne, TypeTwo, VersionAlpha, VersionBeta } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-non-string/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type BooleanOneOf = ({ use_custom: false; } & AutoConfig) | ({ use_custom: true; } & CustomConfig); export type AutoConfig = { use_custom: false; auto_setting: string; }; export type CustomConfig = { use_custom: true; custom_value: number; }; export type BooleanAnyOf = ({ use_custom?: false; } & AutoConfig) | ({ use_custom?: true; } & CustomConfig); export type IntegerOneOf = ({ type_id: 1; } & TypeOne) | ({ type_id: 2; } & TypeTwo); export type TypeOne = { type_id: 1; one_data: string; }; export type TypeTwo = { type_id: 2; two_data: string; }; export type NumberOneOf = ({ version: 1; } & VersionAlpha) | ({ version: 2.5; } & VersionBeta); export type VersionAlpha = { version: 1; alpha_field: string; }; export type VersionBeta = { version: 2.5; beta_field: string; }; export type IntegerAllOfBase = { kind: number; }; export type IntegerAllOfChildA = Omit & { child_a_field: string; kind: 1; }; export type IntegerAllOfChildB = Omit & { child_b_field: string; kind: 2; }; export type NullableIntegerOneOf = ({ tag: 10; } & NullableVariantX) | ({ tag: 20; } & NullableVariantY); export type NullableVariantX = { tag: 10 | null; x_data: string; }; export type NullableVariantY = { tag: 20 | null; y_data: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-object-self-mapped/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BlogPostDto, BlogPostWithImageDto, ClientOptions, GetBlogPostsData, GetBlogPostsResponse, GetBlogPostsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-object-self-mapped/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type BlogPostDto = { $type: 'BlogPost'; id: number; title: string; }; export type BlogPostWithImageDto = Omit & { imageUrl: string; $type: 'BlogPostWithImage'; }; export type GetBlogPostsData = { body?: never; path?: never; query?: never; url: '/blog-posts'; }; export type GetBlogPostsResponses = { /** * List of blog posts */ 200: Array; }; export type GetBlogPostsResponse = GetBlogPostsResponses[keyof GetBlogPostsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-one-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, Quux, Quuz, Qux, Spæcial } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-one-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ type: 'Bar'; } & Bar) | ({ type: 'Baz'; } & Baz); export type Baz = Qux; export type Bar = Qux; export type Spæcial = Qux; export type Qux = { id: string; type: Quux; }; export type Quux = 'Bar' | 'Baz'; export type Quuz = ({ type: 'bar'; } & Bar) | ({ type: 'baz'; } & Baz) | ({ type: 'non-ascii'; } & Spæcial); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-one-of-read-write/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { AnimalPayload, AnimalPayloadWritable, CatPayload, CatPayloadWritable, ClientOptions, CreatePetRequest, CreatePetRequestWritable, CreatePetResponse, CreatePetResponseWritable, DogPayload, DogPayloadWritable, PostPetsData, PostPetsResponse, PostPetsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/discriminator-one-of-read-write/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type AnimalPayload = { typeDiscriminator: string; }; export type DogPayload = Omit & { breed: string; canFetch: boolean; readonly displayBreed: string; typeDiscriminator: 'dog'; }; export type CatPayload = Omit & { breed: string; livesRemaining: number; readonly displayBreed: string; typeDiscriminator: 'cat'; }; export type CreatePetRequest = { name: string; animal: ({ typeDiscriminator: 'dog'; } & DogPayload) | ({ typeDiscriminator: 'cat'; } & CatPayload); }; export type CreatePetResponse = { id: string; name: string; animal: ({ typeDiscriminator: 'dog'; } & DogPayload) | ({ typeDiscriminator: 'cat'; } & CatPayload); }; export type DogPayloadWritable = Omit & { breed: string; canFetch: boolean; typeDiscriminator: 'dog'; }; export type CatPayloadWritable = Omit & { breed: string; livesRemaining: number; typeDiscriminator: 'cat'; }; export type CreatePetRequestWritable = { name: string; animal: ({ typeDiscriminator: 'dog'; } & DogPayloadWritable) | ({ typeDiscriminator: 'cat'; } & CatPayloadWritable); }; export type CreatePetResponseWritable = { id: string; name: string; animal: ({ typeDiscriminator: 'dog'; } & DogPayloadWritable) | ({ typeDiscriminator: 'cat'; } & CatPayloadWritable); }; export type AnimalPayloadWritable = { typeDiscriminator: string; }; export type PostPetsData = { body: CreatePetRequestWritable; path?: never; query?: never; url: '/pets'; }; export type PostPetsResponses = { /** * OK */ 200: CreatePetResponse; }; export type PostPetsResponse = PostPetsResponses[keyof PostPetsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/duplicate-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, WeirdEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/duplicate-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * should not produce duplicate null */ export type WeirdEnum = '' | string | null; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-escape/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-escape/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: 'foo\'bar' | 'foo"bar'; }; export type Bar = 'foo\'bar' | 'foo"bar'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, FooEnum, FooEnum2, GetFooData, GetFooResponse, GetFooResponses, PostFooData, PostFooResponse, PostFooResponses, PutFooData, PutFooResponse, PutFooResponses, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export type Bar = { type?: Baz; }; export type Baz = 'qux' | 'quux'; export type FooEnum = 'foo' | 'bar' | 'FooBar' | 'fooBar' | 'foo bar'; export type FooEnum2 = 'baz'; export type TypeEnum = 'foo' | 'bar'; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: { foo?: FooEnum; }; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: { foo?: FooEnum2; }; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; export type PutFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PutFooResponses = { /** * OK */ 200: Baz; }; export type PutFooResponse = PutFooResponses[keyof PutFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-javascript/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Bar, Baz, type ClientOptions, type Foo, FooEnum, FooEnum2, type GetFooData, type GetFooResponse, type GetFooResponses, type PostFooData, type PostFooResponse, type PostFooResponses, type PutFooData, type PutFooResponse, type PutFooResponses, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-javascript/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export type Bar = { type?: Baz; }; export const Baz = { QUX: 'qux', QUUX: 'quux' } as const; export type Baz = typeof Baz[keyof typeof Baz]; export const FooEnum = { FOO: 'foo', BAR: 'bar', FOO_BAR: 'FooBar', FOO_BAR2: 'fooBar', FOO_BAR3: 'foo bar' } as const; export type FooEnum = typeof FooEnum[keyof typeof FooEnum]; export const FooEnum2 = { BAZ: 'baz' } as const; export type FooEnum2 = typeof FooEnum2[keyof typeof FooEnum2]; export const TypeEnum = { FOO: 'foo', BAR: 'bar' } as const; export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: { foo?: FooEnum; }; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: { foo?: FooEnum2; }; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; export type PutFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PutFooResponses = { /** * OK */ 200: Baz; }; export type PutFooResponse = PutFooResponses[keyof PutFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-name-resolver/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Bar, Baz, type ClientOptions, type Foo, FooEnum, FooEnum2, type GetFooData, type GetFooResponse, type GetFooResponses, type PostFooData, type PostFooResponse, type PostFooResponses, type PutFooData, type PutFooResponse, type PutFooResponses, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-name-resolver/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export type Bar = { type?: Baz; }; export const Baz = { QUX: 'qux', QUUX: 'quux' } as const; export type Baz = typeof Baz[keyof typeof Baz]; export const FooEnum = { FOO: 'foo', BAR: 'bar', FOO_BAR: 'FooBar', FOO_BAR_N2: 'fooBar', FOO_BAR_N3: 'foo bar' } as const; export type FooEnum = typeof FooEnum[keyof typeof FooEnum]; export const FooEnum2 = { BAZ: 'baz' } as const; export type FooEnum2 = typeof FooEnum2[keyof typeof FooEnum2]; export const TypeEnum = { FOO: 'foo', BAR: 'bar' } as const; export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: { foo?: FooEnum; }; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: { foo?: FooEnum2; }; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; export type PutFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PutFooResponses = { /** * OK */ 200: Baz; }; export type PutFooResponse = PutFooResponses[keyof PutFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-name-resolver-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Bar, Baz, type ClientOptions, type Foo, FooEnum, FooEnum2, type GetFooData, type GetFooResponse, type GetFooResponses, type PostFooData, type PostFooResponse, type PostFooResponses, type PutFooData, type PutFooResponse, type PutFooResponses, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-name-resolver-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export type Bar = { type?: Baz; }; export const Baz = { QUX: 'qux', QUUX: 'quux' } as const; export type Baz = typeof Baz[keyof typeof Baz]; export const FooEnum = { FOO: 'foo', BAR: 'bar', FOO_BAR: 'FooBar', FOO_BAR2: 'fooBar', FOO_BAR3: 'foo bar' } as const; export type FooEnum = typeof FooEnum[keyof typeof FooEnum]; export const FooEnum2 = { BAZ: 'baz' } as const; export type FooEnum2 = typeof FooEnum2[keyof typeof FooEnum2]; export const TypeEnum = { FOO: 'foo', BAR: 'bar' } as const; export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: { foo?: FooEnum; }; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: { foo?: FooEnum2; }; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; export type PutFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PutFooResponses = { /** * OK */ 200: Baz; }; export type PutFooResponse = PutFooResponses[keyof PutFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-typescript/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Bar, Baz, type ClientOptions, type Foo, FooEnum, FooEnum2, type GetFooData, type GetFooResponse, type GetFooResponses, type PostFooData, type PostFooResponse, type PostFooResponses, type PutFooData, type PutFooResponse, type PutFooResponses, TypeEnum } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-inline-typescript/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { type?: TypeEnum; }; export type Bar = { type?: Baz; }; export enum Baz { QUX = 'qux', QUUX = 'quux' } export enum FooEnum { FOO = 'foo', BAR = 'bar', FOO_BAR = 'FooBar', FOO_BAR2 = 'fooBar', FOO_BAR3 = 'foo bar' } export enum FooEnum2 { BAZ = 'baz' } export enum TypeEnum { FOO = 'foo', BAR = 'bar' } export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: { foo?: FooEnum; }; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: { foo?: FooEnum2; }; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; export type PutFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PutFooResponses = { /** * OK */ 200: Baz; }; export type PutFooResponse = PutFooResponses[keyof PutFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _110, Arrays, ClientOptions, Foo, MyFoo, MyFoo2, MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type _110 = '1-10' | '11-20'; export type MyFoo = 'myFoo' | 'myBar'; export type MyFoo2 = 'MyFoo' | 'MyBar'; export type Foo = 'foo' | 'bar' | null | '' | true | false; export type Numbers = 100 | 200 | 300 | -100 | -200 | -300; export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { 110: '1-10', 1120: '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { MyFoo: 'myFoo', MyBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { Foo: 'foo', Bar: 'bar', Null: null, '': '', True: true, False: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-SCREAMING_SNAKE_CASE/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-SCREAMING_SNAKE_CASE/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1_10': '1-10', '11_20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { MY_FOO: 'myFoo', MY_BAR: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MY_FOO: 'MyFoo', MY_BAR: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { FOO: 'foo', BAR: 'bar', NULL: null, '': '', TRUE: true, FALSE: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { 110: '1-10', 1120: '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { myFoo: 'MyFoo', myBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', null: null, '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-ignore-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-ignore-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1-10': '1-10', '11-20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1-10': '1-10', '11-20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { myFoo: 'myFoo', myBar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { MyFoo: 'MyFoo', MyBar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', null: null, '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, Arrays, type ClientOptions, Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-javascript-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const _110 = { '1_10': '1-10', '11_20': '11-20' } as const; export type _110 = typeof _110[keyof typeof _110]; export const MyFoo = { my_foo: 'myFoo', my_bar: 'myBar' } as const; export type MyFoo = typeof MyFoo[keyof typeof MyFoo]; export const MyFoo2 = { my_foo: 'MyFoo', my_bar: 'MyBar' } as const; export type MyFoo2 = typeof MyFoo2[keyof typeof MyFoo2]; export const Foo = { foo: 'foo', bar: 'bar', null: null, '': '', true: true, false: false } as const; export type Foo = typeof Foo[keyof typeof Foo]; export const Numbers = { 100: 100, 200: 200, 300: 300, '-100': -100, '-200': -200, '-300': -300 } as const; export type Numbers = typeof Numbers[keyof typeof Numbers]; export const Arrays = { 0: ['foo'], 1: ['bar'], 2: ['baz'] } as const; export type Arrays = typeof Arrays[keyof typeof Arrays]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-PascalCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-PascalCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { _110 = '1-10', _1120 = '11-20' } export enum MyFoo { MyFoo = 'myFoo', MyBar = 'myBar' } export enum MyFoo2 { MyFoo = 'MyFoo', MyBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-SCREAMING_SNAKE_CASE/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-SCREAMING_SNAKE_CASE/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { '1_10' = '1-10', '11_20' = '11-20' } export enum MyFoo { MY_FOO = 'myFoo', MY_BAR = 'myBar' } export enum MyFoo2 { MY_FOO = 'MyFoo', MY_BAR = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-camelCase/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-camelCase/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { _110 = '1-10', _1120 = '11-20' } export enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export enum MyFoo2 { myFoo = 'MyFoo', myBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-const/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-const/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export const enum _110 { _110 = '1-10', _1120 = '11-20' } export const enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export const enum MyFoo2 { myFoo = 'MyFoo', myBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export const enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-preserve/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-preserve/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { '1-10' = '1-10', '11-20' = '11-20' } export enum MyFoo { myFoo = 'myFoo', myBar = 'myBar' } export enum MyFoo2 { MyFoo = 'MyFoo', MyBar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-snake_case/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { _110, type Arrays, type ClientOptions, type Foo, MyFoo, MyFoo2, type MyFooRef, Numbers } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-names-values-typescript-snake_case/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export enum _110 { '1_10' = '1-10', '11_20' = '11-20' } export enum MyFoo { my_foo = 'myFoo', my_bar = 'myBar' } export enum MyFoo2 { my_foo = 'MyFoo', my_bar = 'MyBar' } export type Foo = 'foo' | 'bar' | null | '' | true | false; export enum Numbers { _100 = 100, _200 = 200, _300 = 300, '_-100' = -100, '_-200' = -200, '_-300' = -300 } export type Arrays = [ 'foo' ] | [ 'bar' ] | [ 'baz' ]; export type MyFooRef = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/enum-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = 'foo' | 'bar' | null; export type Bar = 'foo' | 'bar'; export type Baz = 'foo' | 'bar'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/exclude-deprecated/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/exclude-deprecated/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = string; export type PostFooData = { body: Foo; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/external/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _1, ClientOptions, Deep, ExternalAllOfSchema, ExternalAnyOfSchema, ExternalArraySchema, ExternalDeepParam, ExternalDoubleNestedNumeric, ExternalDoubleNestedProp, ExternalIdParam, ExternalMixedBody, ExternalMixedProperties, ExternalModelBody, ExternalNested, ExternalNestedBody, ExternalNestedNumeric, ExternalNestedNumericObjectA, ExternalNestedNumericObjectB, ExternalNestedObjectA, ExternalNestedObjectB, ExternalNumericParam, ExternalSchemaA, ExternalSchemaB, ExternalSchemaC, ExternalSchemaExternalProp, ExternalSchemaExternalPropAlias, ExternalSchemaPathA, ExternalSchemaPathB, ExternalSchemaPropertyA, ExternalSchemaPropertyB, ExternalSchemaPropertyC, ExternalSchemaPropertyD, ExternalSharedModel, ExternalSharedModelWithUuid, ExternalUnionSchema, ExternalUuidBody, ExternalUuidParam, GetExternalArrayData, GetExternalArrayResponse, GetExternalArrayResponses, GetExternalMixedData, GetExternalMixedResponse, GetExternalMixedResponses, GetExternalModelData, GetExternalModelError, GetExternalModelErrors, GetExternalModelResponse, GetExternalModelResponses, GetExternalNestedData, GetExternalNestedResponse, GetExternalNestedResponses, GetExternalPropertiesByIdData, GetExternalPropertiesByIdResponse, GetExternalPropertiesByIdResponses, GetExternalUnionData, GetExternalUnionResponse, GetExternalUnionResponses, GetExternalUuidData, GetExternalUuidResponse, GetExternalUuidResponses, Id, Name, PostExternalArrayData, PostExternalArrayResponse, PostExternalArrayResponses, PostExternalMixedData, PostExternalMixedResponse, PostExternalMixedResponses, PostExternalModelData, PostExternalModelError, PostExternalModelErrors, PostExternalModelResponse, PostExternalModelResponses, PostExternalNestedData, PostExternalNestedResponse, PostExternalNestedResponses, PostExternalUnionData, PostExternalUnionResponse, PostExternalUnionResponses, PutExternalUuidData, PutExternalUuidResponse, PutExternalUuidResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/external/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type _1 = string; /** * External schema (A) */ export type ExternalSchemaA = ExternalSharedModel; /** * External schema (B) - second use of ExternalSharedModel */ export type ExternalSchemaB = ExternalSharedModel; /** * External schema (C) - third use of ExternalSharedModel */ export type ExternalSchemaC = ExternalSharedModel; /** * External schema via path reference (A) */ export type ExternalSchemaPathA = ExternalSharedModel; /** * External schema via path reference (B) - second use */ export type ExternalSchemaPathB = ExternalSharedModel; /** * External schema property (A) */ export type ExternalSchemaPropertyA = { uuid1?: ExternalSharedModelWithUuid; }; /** * External schema property (B) - second use of UUID */ export type ExternalSchemaPropertyB = { uuid2?: ExternalSharedModelWithUuid; }; /** * External schema property (C) - third use of UUID */ export type ExternalSchemaPropertyC = { uuid3?: ExternalSharedModelWithUuid; }; /** * External schema property with duplicate refs (D) */ export type ExternalSchemaPropertyD = { uuid4?: ExternalSharedModelWithUuid; uuid5?: ExternalSharedModelWithUuid; }; /** * External schema property via external property ref (id) */ export type ExternalSchemaExternalProp = { id3?: Id; id4?: Id; }; /** * Alias to external property via component property ref */ export type ExternalSchemaExternalPropAlias = { id5?: Id; id6?: Id; }; /** * External double nested prop via property ref */ export type ExternalDoubleNestedProp = { deep1?: Deep; deep2?: Deep; }; /** * External double nested numeric properties */ export type ExternalDoubleNestedNumeric = { numeric1?: _1; numeric2?: _1; }; /** * External nested object reference (A) */ export type ExternalNestedObjectA = ExternalNested; /** * External nested object reference (B) - second use */ export type ExternalNestedObjectB = ExternalNested; /** * External numeric nested object reference (A) */ export type ExternalNestedNumericObjectA = ExternalNestedNumeric; /** * External numeric nested object reference (B) - second use */ export type ExternalNestedNumericObjectB = ExternalNestedNumeric; /** * Mixed external property references */ export type ExternalMixedProperties = { id7?: Id; name1?: Name; uuid6?: ExternalSharedModelWithUuid; deep3?: Deep; numeric3?: _1; }; /** * Array containing external references */ export type ExternalArraySchema = { items?: Array; uuidItems?: Array; }; /** * Union type with external references */ export type ExternalUnionSchema = ExternalSharedModel | ExternalSharedModelWithUuid; /** * AllOf with external references */ export type ExternalAllOfSchema = ExternalSharedModel & { additional?: ExternalSharedModelWithUuid; }; /** * AnyOf with external references */ export type ExternalAnyOfSchema = ExternalNested | ExternalNestedNumeric; export type ExternalNested = { inner?: { deep?: string; }; }; export type Deep = string; export type ExternalNestedNumeric = { 0?: { 1?: string; }; }; export type ExternalSharedModel = { id: string; name?: string; }; export type Id = string; export type Name = string; export type ExternalSharedModelWithUuid = string; export type ExternalIdParam = Id; export type ExternalUuidParam = ExternalSharedModelWithUuid; export type ExternalDeepParam = Deep; export type ExternalNumericParam = _1; /** * Request body using external model */ export type ExternalModelBody = ExternalSharedModel; /** * Request body using external UUID */ export type ExternalUuidBody = ExternalSharedModelWithUuid; /** * Request body using external nested object */ export type ExternalNestedBody = ExternalNested; /** * Request body with mixed external properties */ export type ExternalMixedBody = { id?: Id; name?: Name; uuid?: ExternalSharedModelWithUuid; deep?: Deep; }; export type GetExternalModelData = { body?: never; path: { id: Id; }; query?: { uuid?: ExternalSharedModelWithUuid; }; url: '/external-model'; }; export type GetExternalModelErrors = { /** * Response using external UUID */ 400: ExternalSharedModelWithUuid; }; export type GetExternalModelError = GetExternalModelErrors[keyof GetExternalModelErrors]; export type GetExternalModelResponses = { /** * Response using external model */ 200: ExternalSharedModel; }; export type GetExternalModelResponse = GetExternalModelResponses[keyof GetExternalModelResponses]; export type PostExternalModelData = { /** * Request body using external model */ body: ExternalModelBody; path?: never; query?: never; url: '/external-model'; }; export type PostExternalModelErrors = { /** * Response with union of external types */ 422: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; }; export type PostExternalModelError = PostExternalModelErrors[keyof PostExternalModelErrors]; export type PostExternalModelResponses = { /** * Response using external model */ 201: ExternalSharedModel; }; export type PostExternalModelResponse = PostExternalModelResponses[keyof PostExternalModelResponses]; export type GetExternalUuidData = { body?: never; path?: never; query?: { uuid?: ExternalSharedModelWithUuid; }; url: '/external-uuid'; }; export type GetExternalUuidResponses = { /** * Response using external UUID */ 200: ExternalSharedModelWithUuid; }; export type GetExternalUuidResponse = GetExternalUuidResponses[keyof GetExternalUuidResponses]; export type PutExternalUuidData = { /** * Request body using external UUID */ body?: ExternalUuidBody; path?: never; query?: never; url: '/external-uuid'; }; export type PutExternalUuidResponses = { /** * Response using external UUID */ 200: ExternalSharedModelWithUuid; }; export type PutExternalUuidResponse = PutExternalUuidResponses[keyof PutExternalUuidResponses]; export type GetExternalNestedData = { body?: never; headers?: { deep?: Deep; }; path?: never; query?: never; url: '/external-nested'; }; export type GetExternalNestedResponses = { /** * Response using external nested object */ 200: ExternalNested; }; export type GetExternalNestedResponse = GetExternalNestedResponses[keyof GetExternalNestedResponses]; export type PostExternalNestedData = { /** * Request body using external nested object */ body?: ExternalNestedBody; path?: never; query?: never; url: '/external-nested'; }; export type PostExternalNestedResponses = { /** * Response using external nested object */ 201: ExternalNested; }; export type PostExternalNestedResponse = PostExternalNestedResponses[keyof PostExternalNestedResponses]; export type GetExternalMixedData = { body?: never; headers?: { deep?: Deep; }; path: { id: Id; }; query?: { uuid?: ExternalSharedModelWithUuid; numeric?: _1; }; url: '/external-mixed'; }; export type GetExternalMixedResponses = { /** * Response with array of external models */ 200: Array; }; export type GetExternalMixedResponse = GetExternalMixedResponses[keyof GetExternalMixedResponses]; export type PostExternalMixedData = { /** * Request body with mixed external properties */ body?: ExternalMixedBody; path?: never; query?: never; url: '/external-mixed'; }; export type PostExternalMixedResponses = { /** * Response using external model */ 201: ExternalSharedModel; }; export type PostExternalMixedResponse = PostExternalMixedResponses[keyof PostExternalMixedResponses]; export type GetExternalArrayData = { body?: never; path?: never; query?: never; url: '/external-array'; }; export type GetExternalArrayResponses = { /** * Response with array of external models */ 200: Array; }; export type GetExternalArrayResponse = GetExternalArrayResponses[keyof GetExternalArrayResponses]; export type PostExternalArrayData = { body: Array; path?: never; query?: never; url: '/external-array'; }; export type PostExternalArrayResponses = { /** * Response with array of external models */ 201: Array; }; export type PostExternalArrayResponse = PostExternalArrayResponses[keyof PostExternalArrayResponses]; export type GetExternalUnionData = { body?: never; path?: never; query?: never; url: '/external-union'; }; export type GetExternalUnionResponses = { /** * Response with union of external types */ 200: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; }; export type GetExternalUnionResponse = GetExternalUnionResponses[keyof GetExternalUnionResponses]; export type PostExternalUnionData = { body: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; path?: never; query?: never; url: '/external-union'; }; export type PostExternalUnionResponses = { /** * Response with union of external types */ 201: ExternalSharedModel | ExternalSharedModelWithUuid | ExternalNested; }; export type PostExternalUnionResponse = PostExternalUnionResponses[keyof PostExternalUnionResponses]; export type GetExternalPropertiesByIdData = { body?: never; headers?: { deep?: Deep; }; path: { id: Id; }; query?: { uuid?: ExternalSharedModelWithUuid; }; url: '/external-properties/{id}'; }; export type GetExternalPropertiesByIdResponses = { 200: { id?: Id; name?: Name; uuid?: ExternalSharedModelWithUuid; deep?: Deep; numeric?: _1; }; }; export type GetExternalPropertiesByIdResponse = GetExternalPropertiesByIdResponses[keyof GetExternalPropertiesByIdResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options, patchFoo, postFoo, putFoo } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses, PatchFooData, PatchFooResponse, PatchFooResponses, PostFooData, PostFooResponse, PostFooResponses, PutFooData, PutFooResponse, PutFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses, PatchFooData, PatchFooResponses, PostFooData, PostFooResponses, PutFooData, PutFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options: Options) => (options.client ?? client).get({ url: '/foo', ...options }); export const patchFoo = (options?: Options) => (options?.client ?? client).patch({ url: '/foo', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postFoo = (options: Options) => (options.client ?? client).post({ url: '/foo', ...options, headers: { 'content-type': 'application/json', ...options.headers } }); export const putFoo = (options: Options) => (options.client ?? client).put({ url: '/foo', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/headers/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body: string; headers: { 'Content-Type': string; }; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PatchFooData = { body?: string; headers?: { 'Content-Type'?: string; }; path?: never; query?: never; url: '/foo'; }; export type PatchFooResponses = { /** * OK */ 200: string; }; export type PatchFooResponse = PatchFooResponses[keyof PatchFooResponses]; export type PostFooData = { body: string; headers?: { 'content-type'?: string; }; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: string; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; export type PutFooData = { body: string; path?: never; query?: never; url: '/foo'; }; export type PutFooResponses = { /** * OK */ 200: string; }; export type PutFooResponse = PutFooResponses[keyof PutFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { create, create2, create3, type Options } from '../sdk.gen'; import type { Create2Data, Create3Data, CreateData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const createQueryKey2 = (options?: Options) => createQueryKey('create', options); export const createOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await create({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: createQueryKey2(options) }); export const create2Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await create2({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const create3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await create3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { create, create2, create3, type Options } from './sdk.gen'; export type { ClientOptions, Create2Data, Create2Responses, Create3Data, Create3Responses, CreateData, CreateResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { Create2Data, Create2Responses, Create3Data, Create3Responses, CreateData, CreateResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const create = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const create2 = (options?: Options) => (options?.client ?? client).patch({ url: '/foo', ...options }); export const create3 = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type CreateData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type CreateResponses = { /** * OK */ 200: unknown; }; export type Create2Data = { body?: never; path?: never; query?: never; url: '/foo'; }; export type Create2Responses = { /** * OK */ 200: unknown; }; export type Create3Data = { body?: never; path?: never; query?: never; url: '/foo'; }; export type Create3Responses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/negative-property-names/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, ReactionRollup } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/negative-property-names/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; /** * Reaction Rollup */ export type ReactionRollup = { url: string; total_count: number; '+1': number; '-1': number; laugh: number; confused: number; heart: number; hooray: number; eyes: number; rocket: number; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-properties-all-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-properties-all-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { bar: string; } & { baz: string; } & { foo: string; bar?: string; baz?: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-properties-any-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-properties-any-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ bar: string; } | { baz: string; }) & { foo: string; bar?: string; baz?: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-properties-one-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-properties-one-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = ({ bar: string; } | { baz: string; }) & { foo: string; bar?: string; baz?: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-property-names/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/object-property-names/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = 'foo' | 'bar'; export type Bar = { [key in Foo]?: string; }; export type Baz = { [key in Foo]?: number; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/operation-204/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, PostFooData, PostFooResponse, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/operation-204/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: string; /** * Created */ 204: void; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { getFoo, type Options, postFoo } from '../sdk.gen'; import type { GetFooData, GetFooResponse, PostFooData } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getFooInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getFoo', options, true); export const getFooInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | null | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { 'foo.page': pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getFoo({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getFooInfiniteQueryKey(options) }); export const postFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses, PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options: Options) => (options.client ?? client).get({ url: '/foo', ...options }); export const postFoo = (options: Options) => (options.client ?? client).post({ url: '/foo', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { page?: number | null; }; export type Bar = { page: number | null; size: number | null; sort: Array | null; }; export type GetFooData = { body?: never; path?: never; query: { foo: Bar; }; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: number; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body: Foo; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { ClientOptions, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ querySerializer: { parameters: { foo: { array: { explode: false } } } }, url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PostFooData = { body?: never; path?: never; query?: { foo?: Array; }; url: '/foo'; }; export type PostFooResponses = { /** * OK */ default: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { ClientOptions, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ querySerializer: { parameters: { foo: { array: { explode: false } } } }, url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-explode-false-axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: `${string}://${string}` | (string & {}); }; export type PostFooData = { body?: never; path?: never; query?: { foo?: Array; }; url: '/foo'; }; export type PostFooResponses = { /** * OK */ default: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-tuple/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, PostFooData, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/parameter-tuple/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PostFooData = { body?: never; path?: never; query?: { tuple?: [ number, number, number, number ]; }; url: '/foo'; }; export type PostFooResponses = { /** * OK */ default: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pattern-properties/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, MetadataObject, NestedPatternObject, PatternPropertiesResponse, PatternPropertiesTest, PostPatternTestData, PostPatternTestResponse, PostPatternTestResponses, UnionPatternObject } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pattern-properties/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PatternPropertiesTest = { id?: string; metadata?: MetadataObject; }; export type MetadataObject = { name?: string; description?: string; [key: string]: Array | string | { value?: string; enabled?: boolean; } | undefined; }; export type NestedPatternObject = { base?: string; [key: string]: { [key: string]: string; } | string | undefined; }; export type UnionPatternObject = { type?: 'user' | 'admin' | 'guest'; [key: string]: ({ [key: string]: unknown; } & { level?: number; }) | string | number | 'user' | 'admin' | 'guest' | undefined; }; export type PatternPropertiesResponse = { success?: boolean; data?: MetadataObject; }; export type PostPatternTestData = { body: PatternPropertiesTest; path?: never; query?: never; url: '/pattern-test'; }; export type PostPatternTestResponses = { /** * Success */ 200: PatternPropertiesResponse; }; export type PostPatternTestResponse = PostPatternTestResponses[keyof PostPatternTestResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/@angular/common.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type HttpRequest, httpResource } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { client } from '../client.gen'; import type { Options } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; @Injectable({ providedIn: 'root' }) export class DefaultServiceRequests { public export(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/no+tag', ...options }); } public patchApiVbyApiVersionNoTag(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PATCH', url: '/api/v{api-version}/no+tag', ...options }); } public import(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/no+tag', ...options }); } public fooWow(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/no+tag', ...options }); } public getApiVbyApiVersionSimpleOperation(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/simple:operation', ...options }); } } export class ODataControllerService { public count(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/simple/$count', ...options }); } } export class VVersionService { private _oDataControllerService?: ODataControllerService; get oDataControllerService(): ODataControllerService { return this._oDataControllerService ??= new ODataControllerService(); } } export class ApiService { private _vVersionService?: VVersionService; get vVersionService(): VVersionService { return this._vVersionService ??= new VVersionService(); } } @Injectable({ providedIn: 'root' }) export class SimpleServiceRequests { public deleteCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/simple', ...options }); } public getCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/simple', ...options }); } public headCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'HEAD', url: '/api/v{api-version}/simple', ...options }); } public optionsCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'OPTIONS', url: '/api/v{api-version}/simple', ...options }); } public patchCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PATCH', url: '/api/v{api-version}/simple', ...options }); } public postCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/simple', ...options }); } public putCallWithoutParametersAndResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/simple', ...options }); } private _apiService?: ApiService; get apiService(): ApiService { return this._apiService ??= new ApiService(); } } @Injectable({ providedIn: 'root' }) export class ParametersServiceRequests { public deleteFoo(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); } public callWithParameters(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); } public callWithWeirdParameterNames(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options }); } public getCallWithOptionalParam(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/parameters', ...options }); } public postCallWithOptionalParam(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters', ...options }); } } @Injectable({ providedIn: 'root' }) export class DescriptionsServiceRequests { public callWithDescriptions(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/descriptions', ...options }); } } @Injectable({ providedIn: 'root' }) export class DeprecatedServiceRequests { /** * @deprecated */ public deprecatedCall(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/parameters/deprecated', ...options }); } } @Injectable({ providedIn: 'root' }) export class RequestBodyServiceRequests { public postApiVbyApiVersionRequestBody(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/requestBody', ...options }); } } @Injectable({ providedIn: 'root' }) export class FormDataServiceRequests { public postApiVbyApiVersionFormData(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/formData', ...options }); } } @Injectable({ providedIn: 'root' }) export class DefaultsServiceRequests { public callWithDefaultParameters(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/defaults', ...options }); } public callWithDefaultOptionalParameters(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/defaults', ...options }); } public callToTestOrderOfParams(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/defaults', ...options }); } } @Injectable({ providedIn: 'root' }) export class DuplicateServiceRequests { public duplicateName(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName2(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'DELETE', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName22(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName3(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/duplicate', ...options }); } public duplicateName4(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/duplicate', ...options }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceRequests { public callWithNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/no-content', ...options }); } } @Injectable({ providedIn: 'root' }) export class ResponseServiceRequests { public callWithResponseAndNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); } public callWithResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/response', ...options }); } public callWithDuplicateResponses(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/response', ...options }); } public callWithResponses(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/response', ...options }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceRequests2 { public callWithResponseAndNoContentResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags1ServiceRequests { public dummyA(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/a', ...options }); } public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags2ServiceRequests { public dummyA(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/a', ...options }); } public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags3ServiceRequests { public dummyB(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multiple-tags/b', ...options }); } } @Injectable({ providedIn: 'root' }) export class CollectionFormatServiceRequests { public collectionFormat(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/collectionFormat', ...options }); } } @Injectable({ providedIn: 'root' }) export class TypesServiceRequests { public types(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/types', ...options }); } } @Injectable({ providedIn: 'root' }) export class UploadServiceRequests { public uploadFile(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/upload', ...options }); } } @Injectable({ providedIn: 'root' }) export class FileResponseServiceRequests { public fileResponse(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/file/{id}', ...options }); } } @Injectable({ providedIn: 'root' }) export class ComplexServiceRequests { public complexTypes(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/complex', ...options }); } public complexParams(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/complex/{id}', ...options }); } } @Injectable({ providedIn: 'root' }) export class MultipartServiceRequests { public multipartResponse(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'GET', url: '/api/v{api-version}/multipart', ...options }); } public multipartRequest(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/multipart', ...options }); } } @Injectable({ providedIn: 'root' }) export class HeaderServiceRequests { public callWithResultFromHeader(options?: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/header', ...options }); } } @Injectable({ providedIn: 'root' }) export class ErrorServiceRequests { public testErrorCode(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/error', ...options }); } } @Injectable({ providedIn: 'root' }) export class NonAsciiÆøåÆøÅöôêÊServiceRequests { public nonAsciiæøåÆøÅöôêÊ字符串(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'POST', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); } /** * Login User */ public putWithFormUrlEncoded(options: Options): HttpRequest { return (options?.client ?? client).requestOptions({ responseStyle: 'data', method: 'PUT', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); } } @Injectable({ providedIn: 'root' }) export class DefaultServiceResources { public export(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).export(opts) : undefined; }); } public patchApiVbyApiVersionNoTag(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).patchApiVbyApiVersionNoTag(opts) : undefined; }); } public import(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).import(opts) : undefined; }); } public fooWow(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).fooWow(opts) : undefined; }); } public getApiVbyApiVersionSimpleOperation(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultServiceRequests).getApiVbyApiVersionSimpleOperation(opts) : undefined; }); } } export class ODataControllerService2 { public count(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).apiService.vVersionService.oDataControllerService.count(opts) : undefined; }); } } export class VVersionService2 { private _oDataControllerService?: ODataControllerService2; get oDataControllerService(): ODataControllerService2 { return this._oDataControllerService ??= new ODataControllerService2(); } } export class ApiService2 { private _vVersionService?: VVersionService2; get vVersionService(): VVersionService2 { return this._vVersionService ??= new VVersionService2(); } } @Injectable({ providedIn: 'root' }) export class SimpleServiceResources { public deleteCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).deleteCallWithoutParametersAndResponse(opts) : undefined; }); } public getCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).getCallWithoutParametersAndResponse(opts) : undefined; }); } public headCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).headCallWithoutParametersAndResponse(opts) : undefined; }); } public optionsCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).optionsCallWithoutParametersAndResponse(opts) : undefined; }); } public patchCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).patchCallWithoutParametersAndResponse(opts) : undefined; }); } public postCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).postCallWithoutParametersAndResponse(opts) : undefined; }); } public putCallWithoutParametersAndResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(SimpleServiceRequests).putCallWithoutParametersAndResponse(opts) : undefined; }); } private _apiService?: ApiService2; get apiService(): ApiService2 { return this._apiService ??= new ApiService2(); } } @Injectable({ providedIn: 'root' }) export class ParametersServiceResources { public deleteFoo(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).deleteFoo(opts) : undefined; }); } public callWithParameters(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).callWithParameters(opts) : undefined; }); } public callWithWeirdParameterNames(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).callWithWeirdParameterNames(opts) : undefined; }); } public getCallWithOptionalParam(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).getCallWithOptionalParam(opts) : undefined; }); } public postCallWithOptionalParam(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ParametersServiceRequests).postCallWithOptionalParam(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DescriptionsServiceResources { public callWithDescriptions(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DescriptionsServiceRequests).callWithDescriptions(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DeprecatedServiceResources { /** * @deprecated */ public deprecatedCall(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DeprecatedServiceRequests).deprecatedCall(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class RequestBodyServiceResources { public postApiVbyApiVersionRequestBody(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(RequestBodyServiceRequests).postApiVbyApiVersionRequestBody(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class FormDataServiceResources { public postApiVbyApiVersionFormData(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(FormDataServiceRequests).postApiVbyApiVersionFormData(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DefaultsServiceResources { public callWithDefaultParameters(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callWithDefaultParameters(opts) : undefined; }); } public callWithDefaultOptionalParameters(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callWithDefaultOptionalParameters(opts) : undefined; }); } public callToTestOrderOfParams(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DefaultsServiceRequests).callToTestOrderOfParams(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class DuplicateServiceResources { public duplicateName(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName(opts) : undefined; }); } public duplicateName2(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName(opts) : undefined; }); } public duplicateName22(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName22(opts) : undefined; }); } public duplicateName3(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName3(opts) : undefined; }); } public duplicateName4(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(DuplicateServiceRequests).duplicateName4(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceResources { public callWithNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NoContentServiceRequests).callWithNoContentResponse(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ResponseServiceResources { public callWithResponseAndNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponseAndNoContentResponse(opts) : undefined; }); } public callWithResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponse(opts) : undefined; }); } public callWithDuplicateResponses(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithDuplicateResponses(opts) : undefined; }); } public callWithResponses(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponses(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class NoContentServiceResources2 { public callWithResponseAndNoContentResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ResponseServiceRequests).callWithResponseAndNoContentResponse(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags1ServiceResources { public dummyA(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyA(opts) : undefined; }); } public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags2ServiceResources { public dummyA(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyA(opts) : undefined; }); } public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipleTags3ServiceResources { public dummyB(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipleTags1ServiceRequests).dummyB(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class CollectionFormatServiceResources { public collectionFormat(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(CollectionFormatServiceRequests).collectionFormat(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class TypesServiceResources { public types(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(TypesServiceRequests).types(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class UploadServiceResources { public uploadFile(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(UploadServiceRequests).uploadFile(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class FileResponseServiceResources { public fileResponse(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(FileResponseServiceRequests).fileResponse(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ComplexServiceResources { public complexTypes(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ComplexServiceRequests).complexTypes(opts) : undefined; }); } public complexParams(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ComplexServiceRequests).complexParams(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class MultipartServiceResources { public multipartResponse(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipartServiceRequests).multipartResponse(opts) : undefined; }); } public multipartRequest(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(MultipartServiceRequests).multipartRequest(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class HeaderServiceResources { public callWithResultFromHeader(options?: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(HeaderServiceRequests).callWithResultFromHeader(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class ErrorServiceResources { public testErrorCode(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(ErrorServiceRequests).testErrorCode(opts) : undefined; }); } } @Injectable({ providedIn: 'root' }) export class NonAsciiÆøåÆøÅöôêÊServiceResources { public nonAsciiæøåÆøÅöôêÊ字符串(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NonAsciiÆøåÆøÅöôêÊServiceRequests).nonAsciiæøåÆøÅöôêÊ字符串(opts) : undefined; }); } /** * Login User */ public putWithFormUrlEncoded(options: () => Options | undefined) { return httpResource(() => { const opts = options ? options() : undefined; return opts ? inject(NonAsciiÆøåÆøÅöôêÊServiceRequests).putWithFormUrlEncoded(opts) : undefined; }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@angular/common/default-class/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Business, Business2, Business3, Business4, Business5, Domains, Domains2, Domains3, Domains4, Locations, type Options, Providers, Providers2, Providers3, Providers4 } from './sdk.gen'; export type { BusinessGetData, BusinessGetResponse, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponse, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponse, BusinessProvidersDomainsPostResponses, ClientOptions, GetData, GetResponse, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponse, PutBusinessProvidersDomainsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { BusinessGetData, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponses, GetData, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class Domains { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers { static domains = Domains; } export class Business { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations/businesses', ...options }); } static providers = Providers; } export class Business2 { static business = Business; } export class Domains2 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers2 { static domains = Domains2; } export class Business3 { static providers = Providers2; } export class Providers3 { static business = Business3; } export class Domains3 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/business/providers/domains', ...options }); } public static post(options?: Options) { return (options?.client ?? client).post({ url: '/business/providers/domains', ...options }); } } export class Providers4 { static domains = Domains3; } export class Business4 { static providers = Providers4; } export class Domains4 { public static putBusinessProvidersDomains(options?: Options) { return (options?.client ?? client).put({ url: '/business/providers/domains', ...options }); } static business = Business4; } export class Business5 { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations/businesses', ...options }); } } export class Locations { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/locations', ...options }); } static business = Business5; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type BusinessProvidersDomainsGetData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsGetResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsGetResponse = BusinessProvidersDomainsGetResponses[keyof BusinessProvidersDomainsGetResponses]; export type BusinessProvidersDomainsPostData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsPostResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsPostResponse = BusinessProvidersDomainsPostResponses[keyof BusinessProvidersDomainsPostResponses]; export type PutBusinessProvidersDomainsData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type PutBusinessProvidersDomainsResponses = { /** * OK */ 200: string; }; export type PutBusinessProvidersDomainsResponse = PutBusinessProvidersDomainsResponses[keyof PutBusinessProvidersDomainsResponses]; export type BusinessGetData = { body?: never; path?: never; query?: never; url: '/locations/businesses'; }; export type BusinessGetResponses = { /** * OK */ 200: string; }; export type BusinessGetResponse = BusinessGetResponses[keyof BusinessGetResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/locations'; }; export type GetResponses = { /** * OK */ 200: string; }; export type GetResponse = GetResponses[keyof GetResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Business, Domains, NestedSdkWithInstance, type Options, Providers } from './sdk.gen'; export type { BusinessGetData, BusinessGetResponse, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponse, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponse, BusinessProvidersDomainsPostResponses, ClientOptions, GetData, GetResponse, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponse, PutBusinessProvidersDomainsResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { BusinessGetData, BusinessGetResponses, BusinessProvidersDomainsGetData, BusinessProvidersDomainsGetResponses, BusinessProvidersDomainsPostData, BusinessProvidersDomainsPostResponses, GetData, GetResponses, PutBusinessProvidersDomainsData, PutBusinessProvidersDomainsResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new NestedSdkWithInstance()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class Domains extends HeyApiClient { public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/business/providers/domains', ...options }); } public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/business/providers/domains', ...options }); } } export class Providers extends HeyApiClient { private _domains?: Domains; get domains(): Domains { return this._domains ??= new Domains({ client: this.client }); } } export class Business extends HeyApiClient { public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/locations/businesses', ...options }); } private _providers?: Providers; get providers(): Providers { return this._providers ??= new Providers({ client: this.client }); } } export class NestedSdkWithInstance extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); NestedSdkWithInstance.__registry.set(this, args?.key); } public putBusinessProvidersDomains(options?: Options) { return (options?.client ?? this.client).put({ url: '/business/providers/domains', ...options }); } public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/locations', ...options }); } private _business?: Business; get business(): Business { return this._business ??= new Business({ client: this.client }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/client-fetch/sdk-nested-classes-instance/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type BusinessProvidersDomainsGetData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsGetResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsGetResponse = BusinessProvidersDomainsGetResponses[keyof BusinessProvidersDomainsGetResponses]; export type BusinessProvidersDomainsPostData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type BusinessProvidersDomainsPostResponses = { /** * OK */ 200: string; }; export type BusinessProvidersDomainsPostResponse = BusinessProvidersDomainsPostResponses[keyof BusinessProvidersDomainsPostResponses]; export type PutBusinessProvidersDomainsData = { body?: never; path?: never; query?: never; url: '/business/providers/domains'; }; export type PutBusinessProvidersDomainsResponses = { /** * OK */ 200: string; }; export type PutBusinessProvidersDomainsResponse = PutBusinessProvidersDomainsResponses[keyof PutBusinessProvidersDomainsResponses]; export type BusinessGetData = { body?: never; path?: never; query?: never; url: '/locations/businesses'; }; export type BusinessGetResponses = { /** * OK */ 200: string; }; export type BusinessGetResponse = BusinessGetResponses[keyof BusinessGetResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/locations'; }; export type GetResponses = { /** * OK */ 200: string; }; export type GetResponse = GetResponses[keyof GetResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/schemas/default/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const _400Schema = { description: 'Model with number-only name', type: 'string' } as const; export const ExternalRefASchema = { description: 'External ref to shared model (A)', $ref: '#/components/schemas/ExternalSharedModel' } as const; export const ExternalRefBSchema = { description: 'External ref to shared model (B)', $ref: '#/components/schemas/ExternalSharedModel' } as const; export const camelCaseCommentWithBreaksSchema = { description: 'Testing multiline comments in string: First line\nSecond line\n\nFourth line', type: 'integer' } as const; export const CommentWithBreaksSchema = { description: 'Testing multiline comments in string: First line\nSecond line\n\nFourth line', type: 'integer' } as const; export const CommentWithBackticksSchema = { description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work', type: 'integer' } as const; export const CommentWithBackticksAndQuotesSchema = { description: 'Testing backticks and quotes in string: `backticks`, \'quotes\', "double quotes" and ```multiple backticks``` should work', type: 'integer' } as const; export const CommentWithSlashesSchema = { description: 'Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work', type: 'integer' } as const; export const CommentWithExpressionPlaceholdersSchema = { description: 'Testing expression placeholders in string: ${expression} should work', type: 'integer' } as const; export const CommentWithQuotesSchema = { description: 'Testing quotes in string: \'single quote\'\'\' and "double quotes""" should work', type: 'integer' } as const; export const CommentWithReservedCharactersSchema = { description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work', type: 'integer' } as const; export const SimpleIntegerSchema = { description: 'This is a simple number', type: 'integer' } as const; export const SimpleBooleanSchema = { description: 'This is a simple boolean', type: 'boolean' } as const; export const SimpleStringSchema = { description: 'This is a simple string', type: 'string' } as const; export const NonAsciiStringæøåÆØÅöôêÊ字符串Schema = { description: 'A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串)', type: 'string' } as const; export const SimpleFileSchema = { description: 'This is a simple file', format: 'binary', type: 'string' } as const; export const SimpleReferenceSchema = { description: 'This is a simple reference', $ref: '#/components/schemas/ModelWithString' } as const; export const SimpleStringWithPatternSchema = { description: 'This is a simple string', maxLength: 64, pattern: '^[a-zA-Z0-9_]*$', type: [ 'string', 'null' ] } as const; export const EnumWithStringsSchema = { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ] } as const; export const EnumWithReplacedCharactersSchema = { enum: [ '\'Single Quote\'', '"Double Quotes"', 'øæåôöØÆÅÔÖ字符串', 3.1, '' ], type: 'string' } as const; export const EnumWithNumbersSchema = { description: 'This is a simple enum with numbers', enum: [ 1, 2, 3, 1.1, 1.2, 1.3, 100, 200, 300, -100, -200, -300, -1.1, -1.2, -1.3 ], default: 200 } as const; export const EnumFromDescriptionSchema = { description: 'Success=1,Warning=2,Error=3', type: 'number' } as const; export const EnumWithExtensionsSchema = { description: 'This is a simple enum with numbers', enum: [ 200, 400, 500 ], 'x-enum-varnames': [ 'CUSTOM_SUCCESS', 'CUSTOM_WARNING', 'CUSTOM_ERROR' ], 'x-enum-descriptions': [ 'Used when the status of something is successful', 'Used when the status of something has a warning', 'Used when the status of something has an error' ] } as const; export const EnumWithXEnumNamesSchema = { enum: [ 0, 1, 2 ], 'x-enumNames': [ 'zero', 'one', 'two' ] } as const; export const ArrayWithNumbersSchema = { description: 'This is a simple array with numbers', type: 'array', items: { type: 'integer' } } as const; export const ArrayWithBooleansSchema = { description: 'This is a simple array with booleans', type: 'array', items: { type: 'boolean' } } as const; export const ArrayWithStringsSchema = { description: 'This is a simple array with strings', type: 'array', items: { type: 'string' }, default: [ 'test' ] } as const; export const ArrayWithReferencesSchema = { description: 'This is a simple array with references', type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } } as const; export const ArrayWithArraySchema = { description: 'This is a simple array containing an array', type: 'array', items: { type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const ArrayWithPropertiesSchema = { description: 'This is a simple array with properties', type: 'array', items: { type: 'object', properties: { '16x16': { $ref: '#/components/schemas/camelCaseCommentWithBreaks' }, bar: { type: 'string' } } } } as const; export const ArrayWithAnyOfPropertiesSchema = { description: 'This is a simple array with any of properties', type: 'array', items: { anyOf: [ { type: 'object', properties: { foo: { type: 'string', default: 'test' } } }, { type: 'object', properties: { bar: { type: 'string' } } } ] } } as const; export const AnyOfAnyAndNullSchema = { type: 'object', properties: { data: { anyOf: [ {}, { type: 'null' } ] } } } as const; export const AnyOfArraysSchema = { description: 'This is a simple array with any of properties', type: 'object', properties: { results: { items: { anyOf: [ { type: 'object', properties: { foo: { type: 'string' } } }, { type: 'object', properties: { bar: { type: 'string' } } } ] }, type: 'array' } } } as const; export const DictionaryWithStringSchema = { description: 'This is a string dictionary', type: 'object', additionalProperties: { type: 'string' } } as const; export const DictionaryWithPropertiesAndAdditionalPropertiesSchema = { type: 'object', properties: { foo: { type: 'number' }, bar: { type: 'boolean' } }, additionalProperties: { type: 'string' } } as const; export const DictionaryWithReferenceSchema = { description: 'This is a string reference', type: 'object', additionalProperties: { $ref: '#/components/schemas/ModelWithString' } } as const; export const DictionaryWithArraySchema = { description: 'This is a complex dictionary', type: 'object', additionalProperties: { type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const DictionaryWithDictionarySchema = { description: 'This is a string dictionary', type: 'object', additionalProperties: { type: 'object', additionalProperties: { type: 'string' } } } as const; export const DictionaryWithPropertiesSchema = { description: 'This is a complex dictionary', type: 'object', additionalProperties: { type: 'object', properties: { foo: { type: 'string' }, bar: { type: 'string' } } } } as const; export const ModelWithIntegerSchema = { description: 'This is a model with one number property', type: 'object', properties: { prop: { description: 'This is a simple number property', type: 'integer' } } } as const; export const ModelWithBooleanSchema = { description: 'This is a model with one boolean property', type: 'object', properties: { prop: { description: 'This is a simple boolean property', type: 'boolean' } } } as const; export const ModelWithStringSchema = { description: 'This is a model with one string property', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } } } as const; export const ModelWithStringErrorSchema = { description: 'This is a model with one string property', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } } } as const; export const Model_From_ZendeskSchema = { description: '`Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets)', type: 'string' } as const; export const ModelWithNullableStringSchema = { description: 'This is a model with one string property', type: 'object', required: [ 'nullableRequiredProp1', 'nullableRequiredProp2' ], properties: { nullableProp1: { description: 'This is a simple string property', type: [ 'string', 'null' ] }, nullableRequiredProp1: { description: 'This is a simple string property', type: [ 'string', 'null' ] }, nullableProp2: { description: 'This is a simple string property', type: [ 'string', 'null' ] }, nullableRequiredProp2: { description: 'This is a simple string property', type: [ 'string', 'null' ] }, 'foo_bar-enum': { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ] } } } as const; export const ModelWithEnumSchema = { description: 'This is a model with one enum', type: 'object', properties: { 'foo_bar-enum': { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ] }, statusCode: { description: 'These are the HTTP error code enums', enum: [ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ] }, bool: { description: 'Simple boolean enum', type: 'boolean', enum: [ true ] } } } as const; export const ModelWithEnumWithHyphenSchema = { description: 'This is a model with one enum with escaped name', type: 'object', properties: { 'foo-bar-baz-qux': { type: 'string', enum: [ '3.0' ], title: 'Foo-Bar-Baz-Qux', default: '3.0' } } } as const; export const ModelWithEnumFromDescriptionSchema = { description: 'This is a model with one enum', type: 'object', properties: { test: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } } } as const; export const ModelWithNestedEnumsSchema = { description: 'This is a model with nested enums', type: 'object', properties: { dictionaryWithEnum: { type: 'object', additionalProperties: { enum: [ 'Success', 'Warning', 'Error' ] } }, dictionaryWithEnumFromDescription: { type: 'object', additionalProperties: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } }, arrayWithEnum: { type: 'array', items: { enum: [ 'Success', 'Warning', 'Error' ] } }, arrayWithDescription: { type: 'array', items: { type: 'integer', description: 'Success=1,Warning=2,Error=3' } }, 'foo_bar-enum': { description: 'This is a simple enum with strings', enum: [ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ] } } } as const; export const ModelWithReferenceSchema = { description: 'This is a model with one property containing a reference', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithProperties' } } } as const; export const ModelWithArrayReadOnlyAndWriteOnlySchema = { description: 'This is a model with one property containing an array', type: 'object', properties: { prop: { type: 'array', items: { $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' } }, propWithFile: { type: 'array', items: { format: 'binary', type: 'string' } }, propWithNumber: { type: 'array', items: { type: 'number' } } } } as const; export const ModelWithArraySchema = { description: 'This is a model with one property containing an array', type: 'object', properties: { prop: { type: 'array', items: { $ref: '#/components/schemas/ModelWithString' } }, propWithFile: { type: 'array', items: { format: 'binary', type: 'string' } }, propWithNumber: { type: 'array', items: { type: 'number' } } } } as const; export const ModelWithDictionarySchema = { description: 'This is a model with one property containing a dictionary', type: 'object', properties: { prop: { type: 'object', additionalProperties: { type: 'string' } } } } as const; export const DeprecatedModelSchema = { deprecated: true, description: 'This is a deprecated model with a deprecated property', type: 'object', properties: { prop: { deprecated: true, description: 'This is a deprecated property', type: 'string' } } } as const; export const ModelWithCircularReferenceSchema = { description: 'This is a model with one property containing a circular reference', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithCircularReference' } } } as const; export const CompositionWithOneOfSchema = { description: 'This is a model with one property with a \'one of\' relationship', type: 'object', properties: { propA: { type: 'object', oneOf: [ { $ref: '#/components/schemas/ModelWithString' }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithOneOfAnonymousSchema = { description: 'This is a model with one property with a \'one of\' relationship where the options are not $ref', type: 'object', properties: { propA: { type: 'object', oneOf: [ { description: 'Anonymous object type', type: 'object', properties: { propA: { type: 'string' } } }, { description: 'Anonymous string type', type: 'string' }, { description: 'Anonymous integer type', type: 'integer' } ] } } } as const; export const ModelCircleSchema = { description: 'Circle', type: 'object', required: [ 'kind' ], properties: { kind: { type: 'string' }, radius: { type: 'number' } } } as const; export const ModelSquareSchema = { description: 'Square', type: 'object', required: [ 'kind' ], properties: { kind: { type: 'string' }, sideLength: { type: 'number' } } } as const; export const CompositionWithOneOfDiscriminatorSchema = { description: 'This is a model with one property with a \'one of\' relationship where the options are not $ref', type: 'object', oneOf: [ { $ref: '#/components/schemas/ModelCircle' }, { $ref: '#/components/schemas/ModelSquare' } ], discriminator: { propertyName: 'kind', mapping: { circle: '#/components/schemas/ModelCircle', square: '#/components/schemas/ModelSquare' } } } as const; export const CompositionWithAnyOfSchema = { description: 'This is a model with one property with a \'any of\' relationship', type: 'object', properties: { propA: { type: 'object', anyOf: [ { $ref: '#/components/schemas/ModelWithString' }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithAnyOfAnonymousSchema = { description: 'This is a model with one property with a \'any of\' relationship where the options are not $ref', type: 'object', properties: { propA: { type: 'object', anyOf: [ { description: 'Anonymous object type', type: 'object', properties: { propA: { type: 'string' } } }, { description: 'Anonymous string type', type: 'string' }, { description: 'Anonymous integer type', type: 'integer' } ] } } } as const; export const CompositionWithNestedAnyAndTypeNullSchema = { description: 'This is a model with nested \'any of\' property with a type null', type: 'object', properties: { propA: { type: 'object', anyOf: [ { items: { anyOf: [ { $ref: '#/components/schemas/ModelWithDictionary' }, { type: 'null' } ] }, type: 'array' }, { items: { anyOf: [ { $ref: '#/components/schemas/ModelWithArray' }, { type: 'null' } ] }, type: 'array' } ] } } } as const; export const _3e_num_1ПериодSchema = { enum: [ 'Bird', 'Dog' ], type: 'string' } as const; export const ConstValueSchema = { type: 'string', const: 'ConstValue' } as const; export const CompositionWithNestedAnyOfAndNullSchema = { description: 'This is a model with one property with a \'any of\' relationship where the options are not $ref', type: 'object', properties: { propA: { anyOf: [ { items: { anyOf: [ { $ref: '#/components/schemas/3e-num_1Период' }, { $ref: '#/components/schemas/ConstValue' } ] }, type: 'array' }, { type: 'null' } ], title: 'Scopes' } } } as const; export const CompositionWithOneOfAndNullableSchema = { description: 'This is a model with one property with a \'one of\' relationship', type: 'object', properties: { propA: { type: [ 'object', 'null' ], oneOf: [ { type: 'object', properties: { boolean: { type: 'boolean' } } }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithOneOfAndSimpleDictionarySchema = { description: 'This is a model that contains a simple dictionary within composition', type: 'object', properties: { propA: { oneOf: [ { type: 'boolean' }, { type: 'object', additionalProperties: { type: 'number' } } ] } } } as const; export const CompositionWithOneOfAndSimpleArrayDictionarySchema = { description: 'This is a model that contains a dictionary of simple arrays within composition', type: 'object', properties: { propA: { oneOf: [ { type: 'boolean' }, { type: 'object', additionalProperties: { type: 'array', items: { type: 'boolean' } } } ] } } } as const; export const CompositionWithOneOfAndComplexArrayDictionarySchema = { description: 'This is a model that contains a dictionary of complex arrays (composited) within composition', type: 'object', properties: { propA: { oneOf: [ { type: 'boolean' }, { type: 'object', additionalProperties: { type: 'array', items: { oneOf: [ { type: 'number' }, { type: 'string' } ] } } } ] } } } as const; export const CompositionWithAllOfAndNullableSchema = { description: 'This is a model with one property with a \'all of\' relationship', type: 'object', properties: { propA: { type: [ 'object', 'null' ], allOf: [ { type: 'object', properties: { boolean: { type: 'boolean' } } }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionWithAnyOfAndNullableSchema = { description: 'This is a model with one property with a \'any of\' relationship', type: 'object', properties: { propA: { type: [ 'object', 'null' ], anyOf: [ { type: 'object', properties: { boolean: { type: 'boolean' } } }, { $ref: '#/components/schemas/ModelWithEnum' }, { $ref: '#/components/schemas/ModelWithArray' }, { $ref: '#/components/schemas/ModelWithDictionary' } ] } } } as const; export const CompositionBaseModelSchema = { description: 'This is a base model with two simple optional properties', type: 'object', properties: { firstName: { type: 'string' }, lastname: { type: 'string' } } } as const; export const CompositionExtendedModelSchema = { description: 'This is a model that extends the base model', type: 'object', allOf: [ { $ref: '#/components/schemas/CompositionBaseModel' } ], properties: { age: { type: 'number' } }, required: [ 'firstName', 'lastname', 'age' ] } as const; export const ModelWithPropertiesSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'required', 'requiredAndReadOnly', 'requiredAndNullable' ], properties: { required: { type: 'string' }, requiredAndReadOnly: { type: 'string', readOnly: true }, requiredAndNullable: { type: [ 'string', 'null' ] }, string: { type: 'string' }, number: { type: 'number' }, boolean: { type: 'boolean' }, reference: { $ref: '#/components/schemas/ModelWithString' }, 'property with space': { type: 'string' }, default: { type: 'string' }, try: { type: 'string' }, '@namespace.string': { type: 'string', readOnly: true }, '@namespace.integer': { type: 'integer', readOnly: true } } } as const; export const ModelWithNestedPropertiesSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'first' ], properties: { first: { type: [ 'object', 'null' ], required: [ 'second' ], readOnly: true, properties: { second: { type: [ 'object', 'null' ], required: [ 'third' ], readOnly: true, properties: { third: { type: [ 'string', 'null' ], required: true, readOnly: true } } } } } } } as const; export const ModelWithDuplicatePropertiesSchema = { description: 'This is a model with duplicated properties', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const ModelWithOrderedPropertiesSchema = { description: 'This is a model with ordered properties', type: 'object', properties: { zebra: { type: 'string' }, apple: { type: 'string' }, hawaii: { type: 'string' } } } as const; export const ModelWithDuplicateImportsSchema = { description: 'This is a model with duplicated imports', type: 'object', properties: { propA: { $ref: '#/components/schemas/ModelWithString' }, propB: { $ref: '#/components/schemas/ModelWithString' }, propC: { $ref: '#/components/schemas/ModelWithString' } } } as const; export const ModelThatExtendsSchema = { description: 'This is a model that extends another model', type: 'object', allOf: [ { $ref: '#/components/schemas/ModelWithString' }, { type: 'object', properties: { propExtendsA: { type: 'string' }, propExtendsB: { $ref: '#/components/schemas/ModelWithString' } } } ] } as const; export const ModelThatExtendsExtendsSchema = { description: 'This is a model that extends another model', type: 'object', allOf: [ { $ref: '#/components/schemas/ModelWithString' }, { $ref: '#/components/schemas/ModelThatExtends' }, { type: 'object', properties: { propExtendsC: { type: 'string' }, propExtendsD: { $ref: '#/components/schemas/ModelWithString' } } } ] } as const; export const ModelWithPatternSchema = { description: 'This is a model that contains a some patterns', type: 'object', required: [ 'key', 'name' ], properties: { key: { maxLength: 64, pattern: '^[a-zA-Z0-9_]*$', type: 'string' }, name: { maxLength: 255, type: 'string' }, enabled: { type: 'boolean', readOnly: true }, modified: { type: 'string', format: 'date-time', readOnly: true }, id: { type: 'string', pattern: '^\\d{2}-\\d{3}-\\d{4}$' }, text: { type: 'string', pattern: '^\\w+$' }, patternWithSingleQuotes: { type: 'string', pattern: '^[a-zA-Z0-9\']*$' }, patternWithNewline: { type: 'string', pattern: 'aaa\\nbbb' }, patternWithBacktick: { type: 'string', pattern: 'aaa`bbb' }, patternWithUnicode: { type: 'string', pattern: '^\\p{L}+$' } } } as const; export const FileSchema = { required: [ 'mime' ], type: 'object', properties: { id: { title: 'Id', type: 'string', readOnly: true, minLength: 1 }, updated_at: { title: 'Updated at', type: 'string', format: 'date-time', readOnly: true }, created_at: { title: 'Created at', type: 'string', format: 'date-time', readOnly: true }, mime: { title: 'Mime', type: 'string', maxLength: 24, minLength: 1 }, file: { title: 'File', type: 'string', readOnly: true, format: 'uri' } } } as const; export const defaultSchema = { type: 'object', properties: { name: { type: 'string' } } } as const; export const PageableSchema = { type: 'object', properties: { page: { minimum: 0, type: 'integer', format: 'int32', default: 0 }, size: { minimum: 1, type: 'integer', format: 'int32' }, sort: { type: 'array', items: { type: 'string' } } } } as const; export const FreeFormObjectWithoutAdditionalPropertiesSchema = { description: 'This is a free-form object without additionalProperties.', type: 'object' } as const; export const FreeFormObjectWithAdditionalPropertiesEqTrueSchema = { description: 'This is a free-form object with additionalProperties: true.', type: 'object', additionalProperties: true } as const; export const FreeFormObjectWithAdditionalPropertiesEqEmptyObjectSchema = { description: 'This is a free-form object with additionalProperties: {}.', type: 'object', additionalProperties: {} } as const; export const ModelWithConstSchema = { type: 'object', properties: { String: { const: 'String' }, number: { const: 0 }, null: { const: null }, withType: { type: 'string', const: 'Some string' } } } as const; export const ModelWithAdditionalPropertiesEqTrueSchema = { description: 'This is a model with one property and additionalProperties: true', type: 'object', properties: { prop: { description: 'This is a simple string property', type: 'string' } }, additionalProperties: true } as const; export const NestedAnyOfArraysNullableSchema = { properties: { nullableArray: { anyOf: [ { items: { anyOf: [ { type: 'string' }, { type: 'boolean' } ] }, type: 'array' }, { type: 'null' } ] } }, type: 'object' } as const; export const CompositionWithOneOfAndPropertiesSchema = { type: 'object', oneOf: [ { type: 'object', required: [ 'foo' ], properties: { foo: { $ref: '#/components/parameters/SimpleParameter' } }, additionalProperties: false }, { type: 'object', required: [ 'bar' ], properties: { bar: { $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' } }, additionalProperties: false } ], required: [ 'baz', 'qux' ], properties: { baz: { type: [ 'integer', 'null' ], format: 'uint16', minimum: 0 }, qux: { type: 'integer', format: 'uint8', minimum: 0 } } } as const; export const NullableObjectSchema = { type: [ 'object', 'null' ], description: 'An object that can be null', properties: { foo: { type: 'string' } }, default: null } as const; export const CharactersInDescriptionSchema = { type: 'string', description: 'Some % character' } as const; export const ModelWithNullableObjectSchema = { type: 'object', properties: { data: { $ref: '#/components/schemas/NullableObject' } } } as const; export const ModelWithAdditionalPropertiesRefSchema = { type: 'object', description: 'An object with additional properties that can be null (anyOf ref + null)', additionalProperties: { anyOf: [ { $ref: '#/components/schemas/NullableObject' }, { type: 'null' } ] } } as const; export const ModelWithOneOfEnumSchema = { oneOf: [ { type: 'object', required: [ 'foo' ], properties: { foo: { type: 'string', enum: [ 'Bar' ] } } }, { type: 'object', required: [ 'foo' ], properties: { foo: { type: 'string', enum: [ 'Baz' ] } } }, { type: 'object', required: [ 'foo' ], properties: { foo: { type: 'string', enum: [ 'Qux' ] } } }, { type: 'object', required: [ 'content', 'foo' ], properties: { content: { type: 'string', format: 'date-time' }, foo: { type: 'string', enum: [ 'Quux' ] } } }, { type: 'object', required: [ 'content', 'foo' ], properties: { content: { type: 'array', prefixItems: [ { type: 'string', format: 'date-time' }, { type: 'string' } ], maxItems: 2, minItems: 2 }, foo: { type: 'string', enum: [ 'Corge' ] } } } ] } as const; export const ModelWithNestedArrayEnumsDataFooSchema = { enum: [ 'foo', 'bar' ], type: 'string' } as const; export const ModelWithNestedArrayEnumsDataBarSchema = { enum: [ 'baz', 'qux' ], type: 'string' } as const; export const ModelWithNestedArrayEnumsDataSchema = { type: 'object', properties: { foo: { type: 'array', items: { $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' } }, bar: { type: 'array', items: { $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataBar' } } } } as const; export const ModelWithNestedArrayEnumsSchema = { type: 'object', properties: { array_strings: { type: 'array', items: { type: 'string' } }, data: { allOf: [ { $ref: '#/components/schemas/ModelWithNestedArrayEnumsData' } ] } } } as const; export const ModelWithNestedCompositionEnumsSchema = { type: 'object', properties: { foo: { allOf: [ { $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' } ] } } } as const; export const ModelWithReadOnlyAndWriteOnlySchema = { type: 'object', required: [ 'foo', 'bar' ], properties: { foo: { type: 'string' }, bar: { readOnly: true, type: 'string' } } } as const; export const ModelWithConstantSizeArraySchema = { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 } as const; export const ModelWithAnyOfConstantSizeArraySchema = { type: 'array', items: { oneOf: [ { type: 'number' }, { type: 'string' } ] }, minItems: 3, maxItems: 3 } as const; export const ModelWithPrefixItemsConstantSizeArraySchema = { type: 'array', prefixItems: [ { $ref: '#/components/schemas/ModelWithInteger' }, { oneOf: [ { type: 'number' }, { type: 'string' } ] }, { type: 'string' } ] } as const; export const ModelWithAnyOfConstantSizeArrayNullableSchema = { type: [ 'array' ], items: { oneOf: [ { type: [ 'number', 'null' ] }, { type: 'string' } ] }, minItems: 3, maxItems: 3 } as const; export const ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsSchema = { type: 'array', items: { oneOf: [ { type: 'number' }, { $ref: '#/components/schemas/import' } ] }, minItems: 2, maxItems: 2 } as const; export const ModelWithAnyOfConstantSizeArrayAndIntersectSchema = { type: 'array', items: { allOf: [ { type: 'number' }, { type: 'string' } ] }, minItems: 2, maxItems: 2 } as const; export const ModelWithNumericEnumUnionSchema = { type: 'object', properties: { value: { type: 'number', description: 'Период', enum: [ -10, -1, 0, 1, 3, 6, 12 ] } } } as const; export const ModelWithBackticksInDescriptionSchema = { description: 'Some description with `back ticks`', type: 'object', properties: { template: { type: 'string', description: 'The template `that` should be used for parsing and importing the contents of the CSV file.\n\n

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    \n
    \n[\n  {\n    "resourceType": "Asset",\n    "identifier": {\n      "name": "${1}",\n      "domain": {\n        "name": "${2}",\n        "community": {\n          "name": "Some Community"\n        }\n      }\n    },\n    "attributes" : {\n      "00000000-0000-0000-0000-000000003115" : [ {\n        "value" : "${3}"\n      } ],\n      "00000000-0000-0000-0000-000000000222" : [ {\n        "value" : "${4}"\n      } ]\n    }\n  }\n]\n
    ' } } } as const; export const ModelWithOneOfAndPropertiesSchema = { type: 'object', oneOf: [ { $ref: '#/components/parameters/SimpleParameter' }, { $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' } ], required: [ 'baz', 'qux' ], properties: { baz: { type: [ 'integer', 'null' ], format: 'uint16', minimum: 0 }, qux: { type: 'integer', format: 'uint8', minimum: 0 } } } as const; export const ParameterSimpleParameterUnusedSchema = { description: 'Model used to test deduplication strategy (unused)', type: 'string' } as const; export const PostServiceWithEmptyTagResponseSchema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const PostServiceWithEmptyTagResponse2Schema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const DeleteFooDataSchema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const DeleteFooData2Schema = { description: 'Model used to test deduplication strategy', type: 'string' } as const; export const importSchema = { description: 'Model with restricted keyword name', type: 'string' } as const; export const SchemaWithFormRestrictedKeysSchema = { type: 'object', properties: { description: { type: 'string' }, 'x-enum-descriptions': { type: 'string' }, 'x-enum-varnames': { type: 'string' }, 'x-enumNames': { type: 'string' }, title: { type: 'string' }, object: { type: 'object', properties: { description: { type: 'string' }, 'x-enum-descriptions': { type: 'string' }, 'x-enum-varnames': { type: 'string' }, 'x-enumNames': { type: 'string' }, title: { type: 'string' } } }, array: { type: 'array', items: { type: 'object', properties: { description: { type: 'string' }, 'x-enum-descriptions': { type: 'string' }, 'x-enum-varnames': { type: 'string' }, 'x-enumNames': { type: 'string' }, title: { type: 'string' } } } } } } as const; export const io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptionsSchema = { description: 'This schema was giving PascalCase transformations a hard time', properties: { preconditions: { allOf: [ { $ref: '#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions' } ], description: 'Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.' } }, type: 'object' } as const; export const io_k8s_apimachinery_pkg_apis_meta_v1_PreconditionsSchema = { description: 'This schema was giving PascalCase transformations a hard time', properties: { resourceVersion: { description: 'Specifies the target ResourceVersion', type: 'string' }, uid: { description: 'Specifies the target UID.', type: 'string' } }, type: 'object' } as const; export const AdditionalPropertiesUnknownIssueSchema = { type: 'object', additionalProperties: { anyOf: [ { type: 'string' }, { type: 'number' } ] } } as const; export const AdditionalPropertiesUnknownIssue2Schema = { type: 'object', additionalProperties: { anyOf: [ { type: 'string' }, { type: 'number' } ] } } as const; export const AdditionalPropertiesUnknownIssue3Schema = { type: 'object', allOf: [ { type: 'string' }, { type: 'object', required: [ 'entries' ], properties: { entries: { type: 'object', additionalProperties: { $ref: '#/components/schemas/AdditionalPropertiesUnknownIssue' } } } } ] } as const; export const AdditionalPropertiesIntegerIssueSchema = { type: 'object', required: [ 'value' ], properties: { value: { type: 'integer' } }, additionalProperties: { type: 'integer' } } as const; export const OneOfAllOfIssueSchema = { oneOf: [ { allOf: [ { oneOf: [ { $ref: '#/components/schemas/ConstValue' }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' } ] }, { $ref: '#/components/schemas/3e-num_1Период' } ] }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' } ] } as const; export const Generic_Schema_Duplicate_Issue_1_System_Boolean_Schema = { type: 'object', properties: { item: { type: 'boolean' }, error: { type: [ 'string', 'null' ] }, hasError: { type: 'boolean', readOnly: true }, data: { type: 'object', additionalProperties: false } }, additionalProperties: false } as const; export const Generic_Schema_Duplicate_Issue_1_System_String_Schema = { type: 'object', properties: { item: { type: [ 'string', 'null' ] }, error: { type: [ 'string', 'null' ] }, hasError: { type: 'boolean', readOnly: true } }, additionalProperties: false } as const; export const ExternalSharedModelSchema = { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: [ 'id' ] } as const; export const ModelWithReferenceWritableSchema = { description: 'This is a model with one property containing a reference', type: 'object', properties: { prop: { $ref: '#/components/schemas/ModelWithPropertiesWritable' } } } as const; export const ModelWithArrayReadOnlyAndWriteOnlyWritableSchema = { description: 'This is a model with one property containing an array', type: 'object', properties: { prop: { type: 'array', items: { $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnlyWritable' } }, propWithFile: { type: 'array', items: { format: 'binary', type: 'string' } }, propWithNumber: { type: 'array', items: { type: 'number' } } } } as const; export const ModelWithPropertiesWritableSchema = { description: 'This is a model with one nested property', type: 'object', required: [ 'required', 'requiredAndNullable' ], properties: { required: { type: 'string' }, requiredAndNullable: { type: [ 'string', 'null' ] }, string: { type: 'string' }, number: { type: 'number' }, boolean: { type: 'boolean' }, reference: { $ref: '#/components/schemas/ModelWithString' }, 'property with space': { type: 'string' }, default: { type: 'string' }, try: { type: 'string' } } } as const; export const ModelWithPatternWritableSchema = { description: 'This is a model that contains a some patterns', type: 'object', required: [ 'key', 'name' ], properties: { key: { maxLength: 64, pattern: '^[a-zA-Z0-9_]*$', type: 'string' }, name: { maxLength: 255, type: 'string' }, id: { type: 'string', pattern: '^\\d{2}-\\d{3}-\\d{4}$' }, text: { type: 'string', pattern: '^\\w+$' }, patternWithSingleQuotes: { type: 'string', pattern: '^[a-zA-Z0-9\']*$' }, patternWithNewline: { type: 'string', pattern: 'aaa\\nbbb' }, patternWithBacktick: { type: 'string', pattern: 'aaa`bbb' }, patternWithUnicode: { type: 'string', pattern: '^\\p{L}+$' } } } as const; export const FileWritableSchema = { required: [ 'mime' ], type: 'object', properties: { mime: { title: 'Mime', type: 'string', maxLength: 24, minLength: 1 } } } as const; export const ModelWithReadOnlyAndWriteOnlyWritableSchema = { type: 'object', required: [ 'foo', 'baz' ], properties: { foo: { type: 'string' }, baz: { type: 'string', writeOnly: true } } } as const; export const ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritableSchema = { type: 'array', items: { oneOf: [ { type: 'number' }, { $ref: '#/components/schemas/import' } ] }, minItems: 2, maxItems: 2 } as const; export const AdditionalPropertiesUnknownIssueWritableSchema = { type: 'object', additionalProperties: { anyOf: [ { type: 'string' }, { type: 'number' } ] } } as const; export const OneOfAllOfIssueWritableSchema = { oneOf: [ { allOf: [ { oneOf: [ { $ref: '#/components/schemas/ConstValue' }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' } ] }, { $ref: '#/components/schemas/3e-num_1Период' } ] }, { $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' } ] } as const; export const Generic_Schema_Duplicate_Issue_1_System_Boolean_WritableSchema = { type: 'object', properties: { item: { type: 'boolean' }, error: { type: [ 'string', 'null' ] }, data: { type: 'object', additionalProperties: false } }, additionalProperties: false } as const; export const Generic_Schema_Duplicate_Issue_1_System_String_WritableSchema = { type: 'object', properties: { item: { type: [ 'string', 'null' ] }, error: { type: [ 'string', 'null' ] } }, additionalProperties: false } as const; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { Bar, Foo, type Options, Sdk } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new Sdk()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class Bar extends HeyApiClient { public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/foo/bar', ...options }); } public put(options?: Options) { return (options?.client ?? this.client).put({ url: '/foo/bar', ...options }); } } export class Foo extends HeyApiClient { public post(options?: Options) { return (options?.client ?? this.client).post({ url: '/foo', ...options }); } public put(options?: Options) { return (options?.client ?? this.client).put({ url: '/foo', ...options }); } private _bar?: Bar; get bar(): Bar { return this._bar ??= new Bar({ client: this.client }); } } export class Sdk extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); Sdk.__registry.set(this, args?.key); } public getFoo(options?: Options) { return (options?.client ?? this.client).get({ url: '/foo', ...options }); } public getFooBar(options?: Options) { return (options?.client ?? this.client).get({ url: '/foo/bar', ...options }); } private _foo?: Foo; get foo(): Foo { return this._foo ??= new Foo({ client: this.client }); } } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/instance/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base', throwOnError: true })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/sdk/throwOnError/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Baz, ClientOptions, Foo, Foo2, PostFooReadData, PostFooReadResponse, PostFooReadResponses, PostFooReadWriteData, PostFooReadWriteResponse, PostFooReadWriteResponses, PostFooWriteData, PostFooWriteResponse, PostFooWriteResponses, PutFooWriteData, PutFooWriteResponse, PutFooWriteResponses, QuxAllRead, QuxAllWrite, ReadableBarRead, ReadableBarWrite, ReadableCorge, ReadableFooRead, ReadableFooReadWrite, ReadableFooReadWriteRef, ReadableFooReadWriteRef2, ReadableFooWrite, ReadableQuux, WritableBarRead, WritableBarWrite, WritableCorge, WritableFooRead, WritableFooReadWrite, WritableFooReadWriteRef, WritableFooReadWriteRef2, WritableFooWrite, WritableQuux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-custom-name/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Baz = { baz?: string; }; export type QuxAllWrite = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type ReadableFooReadWrite = ReadableBarRead; export type WritableFooReadWrite = WritableBarRead & { foo?: string; }; export type ReadableFooRead = ReadableBarRead & { readonly foo?: string; }; export type WritableFooRead = WritableBarRead; export type ReadableFooWrite = ReadableBarWrite; export type WritableFooWrite = WritableBarWrite & { foo?: string; }; export type ReadableBarRead = Baz | QuxAllRead | { readonly bar?: string; }; export type WritableBarRead = Baz | QuxAllWrite; export type ReadableBarWrite = Baz | QuxAllRead; export type WritableBarWrite = Baz | QuxAllWrite | { bar?: string; }; export type ReadableQuux = { baz?: Array; qux?: QuxAllRead; }; export type WritableQuux = { baz?: Array; }; export type ReadableCorge = { bar?: { readonly baz?: boolean; }; }; export type WritableCorge = { foo?: { baz?: boolean; }; }; export type ReadableFooReadWriteRef = { foo?: ReadableFooReadWrite; bar?: ReadableFooReadWriteRef; }; export type WritableFooReadWriteRef = { foo?: WritableFooReadWrite; bar?: WritableFooReadWriteRef; }; export type ReadableFooReadWriteRef2 = ReadableFooReadWrite; export type WritableFooReadWriteRef2 = WritableFooReadWrite; /** * Query parameter */ export type Foo = string; /** * PUT /foo-write payload */ export type Foo2 = { foo?: WritableBarRead; }; export type PostFooReadWriteData = { body: WritableFooReadWrite; path?: never; query?: never; url: '/foo-read-write'; }; export type PostFooReadWriteResponses = { /** * OK */ 200: ReadableFooReadWrite; }; export type PostFooReadWriteResponse = PostFooReadWriteResponses[keyof PostFooReadWriteResponses]; export type PostFooReadData = { body: WritableFooRead; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: ReadableFooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; export type PostFooWriteData = { body: WritableFooWrite; path?: never; query?: never; url: '/foo-write'; }; export type PostFooWriteResponses = { /** * OK */ 200: ReadableFooWrite; }; export type PostFooWriteResponse = PostFooWriteResponses[keyof PostFooWriteResponses]; export type PutFooWriteData = { /** * PUT /foo-write payload */ body: Foo2; path?: never; query?: { /** * Query parameter */ foo?: string; }; url: '/foo-write'; }; export type PutFooWriteResponses = { /** * OK */ 200: ReadableFooWrite; }; export type PutFooWriteResponse = PutFooWriteResponses[keyof PutFooWriteResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BarRead, BarWrite, Baz, ClientOptions, Corge, Foo, Foo2, FooRead, FooReadWrite, FooReadWriteRef, FooReadWriteRef2, FooWrite, PostFooReadData, PostFooReadResponse, PostFooReadResponses, PostFooReadWriteData, PostFooReadWriteResponse, PostFooReadWriteResponses, PostFooWriteData, PostFooWriteResponse, PostFooWriteResponses, PutFooWriteData, PutFooWriteResponse, PutFooWriteResponses, Quux, QuxAllRead, QuxAllWrite } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@hey-api/typescript/transforms-read-write-ignore/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type FooReadWrite = BarRead & { foo?: string; }; export type FooRead = BarRead & { readonly foo?: string; }; export type FooWrite = BarWrite & { foo?: string; }; export type BarRead = Baz | QuxAllWrite | QuxAllRead | { readonly bar?: string; }; export type BarWrite = Baz | QuxAllWrite | QuxAllRead | { bar?: string; }; export type Baz = { baz?: string; }; export type QuxAllWrite = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type Quux = { baz?: Array; qux?: QuxAllRead; }; export type Corge = { foo?: { baz?: boolean; }; bar?: { readonly baz?: boolean; }; }; export type FooReadWriteRef = { foo?: FooReadWrite; bar?: FooReadWriteRef; }; export type FooReadWriteRef2 = FooReadWrite; /** * Query parameter */ export type Foo = string; /** * PUT /foo-write payload */ export type Foo2 = { foo?: BarRead; }; export type PostFooReadWriteData = { body: FooReadWrite; path?: never; query?: never; url: '/foo-read-write'; }; export type PostFooReadWriteResponses = { /** * OK */ 200: FooReadWrite; }; export type PostFooReadWriteResponse = PostFooReadWriteResponses[keyof PostFooReadWriteResponses]; export type PostFooReadData = { body: FooRead; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: FooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; export type PostFooWriteData = { body: FooWrite; path?: never; query?: never; url: '/foo-write'; }; export type PostFooWriteResponses = { /** * OK */ 200: FooWrite; }; export type PostFooWriteResponse = PostFooWriteResponses[keyof PostFooWriteResponses]; export type PutFooWriteData = { /** * PUT /foo-write payload */ body: Foo2; path?: never; query?: { /** * Query parameter */ foo?: string; }; url: '/foo-write'; }; export type PutFooWriteResponses = { /** * OK */ 200: FooWrite; }; export type PutFooWriteResponse = PutFooWriteResponses[keyof PutFooWriteResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/@pinia/colada.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'; import { serializeQueryKeyValue } from '../client'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; baseUrl?: _JSONValue; body?: _JSONValue; query?: _JSONValue; tags?: _JSONValue; } ]; const createQueryKey = (id: string, options?: TOptions, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (tags) { params.tags = tags as unknown as _JSONValue; } if (options?.body !== undefined) { const normalizedBody = serializeQueryKeyValue(options.body); if (normalizedBody !== undefined) { params.body = normalizedBody; } } if (options?.path) { params.path = options.path; } if (options?.query !== undefined) { const normalizedQuery = serializeQueryKeyValue(options.query); if (normalizedQuery !== undefined) { params.query = normalizedQuery; } } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooQuery = defineQueryOptions, GetFooResponse, Error>((options?: Options) => ({ key: getFooQueryKey(options), query: async (context) => { const { data } = await FooBazService.getFoo({ ...options, ...context, throwOnError: true }); return data; } })); export const fooPostMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await FooService.post({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooPutMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await FooService.put({ ...options, ...vars, throwOnError: true }); return data; } }); export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarQuery = defineQueryOptions, GetFooBarResponse, Error>((options?: Options) => ({ key: getFooBarQueryKey(options), query: async (context) => { const { data } = await BarBazService.getFooBar({ ...options, ...context, throwOnError: true }); return data; } })); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await BarService.post({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooBarPutMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await BarService.put({ ...options, ...vars, throwOnError: true }); return data; } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/@pinia/colada.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'; import { serializeQueryKeyValue } from '../client'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; baseUrl?: _JSONValue; body?: _JSONValue; query?: _JSONValue; tags?: _JSONValue; } ]; const createQueryKey = (id: string, options?: TOptions, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (tags) { params.tags = tags as unknown as _JSONValue; } if (options?.body !== undefined) { const normalizedBody = serializeQueryKeyValue(options.body); if (normalizedBody !== undefined) { params.body = normalizedBody; } } if (options?.path) { params.path = options.path; } if (options?.query !== undefined) { const normalizedQuery = serializeQueryKeyValue(options.query); if (normalizedQuery !== undefined) { params.query = normalizedQuery; } } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: exportQueryKey(options), query: async (context) => { const { data } = await export_({ ...options, ...context, throwOnError: true }); return data; } })); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...vars, throwOnError: true }); return data; } }); export const importMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await import_({ ...options, ...vars, throwOnError: true }); return data; } }); export const fooWowMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await fooWow({ ...options, ...vars, throwOnError: true }); return data; } }); export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountQuery = defineQueryOptions, ApiVVersionODataControllerCountResponse, Error>((options?: Options) => ({ key: apiVVersionODataControllerCountQueryKey(options), query: async (context) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...context, throwOnError: true }); return data; } })); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationQuery = defineQueryOptions, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationError>((options: Options) => ({ key: getApiVbyApiVersionSimpleOperationQueryKey(options), query: async (context) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...context, throwOnError: true }); return data; } })); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: getCallWithoutParametersAndResponseQueryKey(options), query: async (context) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...vars, throwOnError: true }); return data; } }); export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deleteFoo({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithDescriptions({ ...options, ...vars, throwOnError: true }); return data; } }); /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await deprecatedCall({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithParameters({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithWeirdParameterNames({ ...options, ...vars, throwOnError: true }); return data; } }); export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamQuery = defineQueryOptions, unknown, Error>((options: Options) => ({ key: getCallWithOptionalParamQueryKey(options), query: async (context) => { const { data } = await getCallWithOptionalParam({ ...options, ...context, throwOnError: true }); return data; } })); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postCallWithOptionalParam({ ...options, ...vars, throwOnError: true }); return data; } }); export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...vars, throwOnError: true }); return data; } }); export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersQuery = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: callWithDefaultParametersQueryKey(options), query: async (context) => { const { data } = await callWithDefaultParameters({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...vars, throwOnError: true }); return data; } }); export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callToTestOrderOfParams({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Query = defineQueryOptions, unknown, Error>((options?: Options) => ({ key: duplicateName2QueryKey(options), query: async (context) => { const { data } = await duplicateName2({ ...options, ...context, throwOnError: true }); return data; } })); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName3({ ...options, ...vars, throwOnError: true }); return data; } }); export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await duplicateName4({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseQuery = defineQueryOptions, CallWithNoContentResponseResponse, Error>((options?: Options) => ({ key: callWithNoContentResponseQueryKey(options), query: async (context) => { const { data } = await callWithNoContentResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseQuery = defineQueryOptions, CallWithResponseAndNoContentResponseResponse, Error>((options?: Options) => ({ key: callWithResponseAndNoContentResponseQueryKey(options), query: async (context) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAQuery = defineQueryOptions, DummyAResponse, Error>((options?: Options) => ({ key: dummyAQueryKey(options), query: async (context) => { const { data } = await dummyA({ ...options, ...context, throwOnError: true }); return data; } })); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBQuery = defineQueryOptions, DummyBResponse, Error>((options?: Options) => ({ key: dummyBQueryKey(options), query: async (context) => { const { data } = await dummyB({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseQuery = defineQueryOptions, CallWithResponseResponse, Error>((options?: Options) => ({ key: callWithResponseQueryKey(options), query: async (context) => { const { data } = await callWithResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, CallWithDuplicateResponsesError> => ({ mutation: async (vars) => { const { data } = await callWithDuplicateResponses({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, CallWithResponsesError> => ({ mutation: async (vars) => { const { data } = await callWithResponses({ ...options, ...vars, throwOnError: true }); return data; } }); export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatQuery = defineQueryOptions, unknown, Error>((options: Options) => ({ key: collectionFormatQueryKey(options), query: async (context) => { const { data } = await collectionFormat({ ...options, ...context, throwOnError: true }); return data; } })); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesQuery = defineQueryOptions, TypesResponse, Error>((options: Options) => ({ key: typesQueryKey(options), query: async (context) => { const { data } = await types({ ...options, ...context, throwOnError: true }); return data; } })); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await uploadFile({ ...options, ...vars, throwOnError: true }); return data; } }); export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseQuery = defineQueryOptions, FileResponseResponse, Error>((options: Options) => ({ key: fileResponseQueryKey(options), query: async (context) => { const { data } = await fileResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesQuery = defineQueryOptions, ComplexTypesResponse, Error>((options: Options) => ({ key: complexTypesQueryKey(options), query: async (context) => { const { data } = await complexTypes({ ...options, ...context, throwOnError: true }); return data; } })); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseQuery = defineQueryOptions, MultipartResponseResponse, Error>((options?: Options) => ({ key: multipartResponseQueryKey(options), query: async (context) => { const { data } = await multipartResponse({ ...options, ...context, throwOnError: true }); return data; } })); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await multipartRequest({ ...options, ...vars, throwOnError: true }); return data; } }); export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await complexParams({ ...options, ...vars, throwOnError: true }); return data; } }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await callWithResultFromHeader({ ...options, ...vars, throwOnError: true }); return data; } }); export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await testErrorCode({ ...options, ...vars, throwOnError: true }); return data; } }); export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...vars, throwOnError: true }); return data; } }); /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Error> => ({ mutation: async (vars) => { const { data } = await putWithFormUrlEncoded({ ...options, ...vars, throwOnError: true }); return data; } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@pinia/colada/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, useMutation, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePatchApiVbyApiVersionNoTagMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...patchApiVbyApiVersionNoTagMutation(), ...mutationOptions }); export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useImportMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...importMutation(), ...mutationOptions }); export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useFooWowMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...fooWowMutation(), ...mutationOptions }); export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDeleteCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...deleteCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePatchCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...patchCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePutCallWithoutParametersAndResponseMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...putCallWithoutParametersAndResponseMutation(), ...mutationOptions }); export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDeleteFooMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...deleteFooMutation(), ...mutationOptions }); export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDescriptionsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDescriptionsMutation(), ...mutationOptions }); /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const useDeprecatedCallMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...deprecatedCallMutation(), ...mutationOptions }); export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithParametersMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithParametersMutation(), ...mutationOptions }); export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithWeirdParameterNamesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithWeirdParameterNamesMutation(), ...mutationOptions }); export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostCallWithOptionalParamMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postCallWithOptionalParamMutation(), ...mutationOptions }); export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostApiVbyApiVersionRequestBodyMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postApiVbyApiVersionRequestBodyMutation(), ...mutationOptions }); export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const usePostApiVbyApiVersionFormDataMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...postApiVbyApiVersionFormDataMutation(), ...mutationOptions }); export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDefaultOptionalParametersMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDefaultOptionalParametersMutation(), ...mutationOptions }); export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallToTestOrderOfParamsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callToTestOrderOfParamsMutation(), ...mutationOptions }); export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateNameMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateNameMutation(), ...mutationOptions }); export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateName3Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateName3Mutation(), ...mutationOptions }); export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useDuplicateName4Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...duplicateName4Mutation(), ...mutationOptions }); export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithDuplicateResponsesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithDuplicateResponsesMutation(), ...mutationOptions }); export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithResponsesMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithResponsesMutation(), ...mutationOptions }); export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useUploadFileMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...uploadFileMutation(), ...mutationOptions }); export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useMultipartRequestMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...multipartRequestMutation(), ...mutationOptions }); export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useComplexParamsMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...complexParamsMutation(), ...mutationOptions }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useCallWithResultFromHeaderMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...callWithResultFromHeaderMutation(), ...mutationOptions }); export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useTestErrorCodeMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...testErrorCodeMutation(), ...mutationOptions }); export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const useNonAsciiæøåÆøÅöôêÊ字符串Mutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...nonAsciiæøåÆøÅöôêÊ字符串Mutation(), ...mutationOptions }); /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const usePutWithFormUrlEncodedMutation = (mutationOptions?: Partial>, 'mutationFn'>>) => useMutation({ ...putWithFormUrlEncodedMutation(), ...mutationOptions }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions, Options> => { const mutationOptions: MutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): MutationOptions> => { const mutationOptions: MutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); export const getFooOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooQueryKey(options) }); export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await FooService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarQueryKey(options) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.post({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await BarService.put({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { BarBazService, BarService, BarService2, FooBazService, FooService, FooService2, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class BarService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo', ...options }); } static barService = BarService; } export class FooBazService { public static getFoo(options?: Options) { return (options?.client ?? client).get({ url: '/foo', ...options }); } static fooService = FooService; } export class BarService2 { public static post(options?: Options) { return (options?.client ?? client).post({ url: '/foo/bar', ...options }); } public static put(options?: Options) { return (options?.client ?? client).put({ url: '/foo/bar', ...options }); } } export class FooService2 { static barService = BarService2; } export class BarBazService { public static getFooBar(options?: Options) { return (options?.client ?? client).get({ url: '/foo/bar', ...options }); } static fooService = FooService2; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseURL: options?.baseURL || (options?.client ?? client).getConfig().baseURL } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseURL: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ responseType: 'json', url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, responseType: 'json', url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ responseType: 'blob', url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, responseType: 'json', url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ responseType: 'json', url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ responseType: 'json', url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const exportQueryKey = (options?: Options) => createQueryKey('export', options); export const exportOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: exportQueryKey(options) }); export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchApiVbyApiVersionNoTag({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const importMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await import_({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooWow({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: apiVVersionODataControllerCountQueryKey(options) }); export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getApiVbyApiVersionSimpleOperationQueryKey(options) }); export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithoutParametersAndResponseQueryKey(options) }); export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await patchCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putCallWithoutParametersAndResponse({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deleteFoo({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDescriptions({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * @deprecated */ export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await deprecatedCall({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithWeirdParameterNames({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamQueryKey(options) }); const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { const params = { ...queryKey[0] }; if (page.body) { params.body = { ...queryKey[0].body as any, ...page.body as any }; } if (page.headers) { params.headers = { ...queryKey[0].headers, ...page.headers }; } if (page.path) { params.path = { ...queryKey[0].path as any, ...page.path as any }; } if (page.query) { params.query = { ...queryKey[0].query as any, ...page.query as any }; } return params as unknown as typeof page; }; export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { page: pageParam } }; const params = createInfiniteParams(queryKey, page); const { data } = await getCallWithOptionalParam({ ...options, ...params, signal, throwOnError: true }); return data; }, queryKey: getCallWithOptionalParamInfiniteQueryKey(options) }); export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postCallWithOptionalParam({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionRequestBody({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await postApiVbyApiVersionFormData({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithDefaultParametersQueryKey(options) }); export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDefaultOptionalParameters({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callToTestOrderOfParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); export const duplicateName2Options = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: duplicateName2QueryKey(options) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName3({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await duplicateName4({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithNoContentResponseQueryKey(options) }); export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseAndNoContentResponseQueryKey(options) }); export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); export const dummyAOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyAQueryKey(options) }); export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); export const dummyBOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: dummyBQueryKey(options) }); export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); export const callWithResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: callWithResponseQueryKey(options) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithDuplicateResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResponses({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); export const collectionFormatOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: collectionFormatQueryKey(options) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); export const typesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: typesQueryKey(options) }); export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await uploadFile({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); export const fileResponseOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: fileResponseQueryKey(options) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); export const complexTypesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: complexTypesQueryKey(options) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); export const multipartResponseOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: multipartResponseQueryKey(options) }); export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await multipartRequest({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await complexParams({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await callWithResultFromHeader({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await testErrorCode({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; /** * Login User */ export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await putWithFormUrlEncoded({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; import { client } from './client.gen'; import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); export const import_ = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/no+tag', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); /** * @deprecated */ export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/requestBody', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/formData', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); export const uploadFile = (options: Options) => (options.client ?? client).post({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/upload', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); export const complexTypes = (options: Options) => (options.client ?? client).get({ querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, url: '/api/v{api-version}/complex', ...options }); export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v{api-version}/multipart', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const complexParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/complex/{id}', ...options, headers: { 'Content-Type': 'application/json-patch+json', ...options.headers } }); export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); /** * Login User */ export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ ...urlSearchParamsBodySerializer, url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options, headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; import type { FooBarPostData, FooBarPostResponse, FooBarPutData, FooBarPutResponse, FooPostData, FooPostResponse, FooPutData, FooPutResponse, GetFooBarData, GetFooBarResponse, GetFooData, GetFooResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const getFooD = (options?: Options) => createQueryKey('getFoo', options); export const getFooE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooD(options) }); export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); export const getFooBarE = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: getFooBarD(options) }); export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPost({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; export const fooBarPutC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { const { data } = await fooBarPut({ ...options, ...fnOptions, throwOnError: true }); return data; } }; return mutationOptions; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from './sdk.gen'; export type { ClientOptions, FooBarPostData, FooBarPostResponse, FooBarPostResponses, FooBarPutData, FooBarPutResponse, FooBarPutResponses, FooPostData, FooPostResponse, FooPostResponses, FooPutData, FooPutResponse, FooPutResponses, GetFooBarData, GetFooBarResponse, GetFooBarResponses, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { FooBarPostData, FooBarPostResponses, FooBarPutData, FooBarPutResponses, FooPostData, FooPostResponses, FooPutData, FooPutResponses, GetFooBarData, GetFooBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); export const fooPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo', ...options }); export const fooPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo', ...options }); export const getFooBar = (options?: Options) => (options?.client ?? client).get({ url: '/foo/bar', ...options }); export const fooBarPost = (options?: Options) => (options?.client ?? client).post({ url: '/foo/bar', ...options }); export const fooBarPut = (options?: Options) => (options?.client ?? client).put({ url: '/foo/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type FooPostData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPostResponses = { /** * OK */ 200: string; }; export type FooPostResponse = FooPostResponses[keyof FooPostResponses]; export type FooPutData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type FooPutResponses = { /** * OK */ 200: string; }; export type FooPutResponse = FooPutResponses[keyof FooPutResponses]; export type GetFooBarData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type GetFooBarResponses = { /** * OK */ 200: string; }; export type GetFooBarResponse = GetFooBarResponses[keyof GetFooBarResponses]; export type FooBarPostData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPostResponses = { /** * OK */ 200: string; }; export type FooBarPostResponse = FooBarPostResponses[keyof FooBarPostResponses]; export type FooBarPutData = { body?: never; path?: never; query?: never; url: '/foo/bar'; }; export type FooBarPutResponses = { /** * OK */ 200: string; }; export type FooBarPutResponse = FooBarPutResponses[keyof FooBarPutResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/fastify/default/fastify.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { RouteHandler } from 'fastify'; import type { ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseResponses, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteFooData3, DeprecatedCallData, DummyAResponses, DummyBResponses, FileResponseData, FileResponseResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; export type RouteHandlers = { import: RouteHandler<{ Body: ImportData['body']; Reply: Omit; }>; apiVVersionODataControllerCount: RouteHandler<{ Reply: ApiVVersionODataControllerCountResponses; }>; getApiVbyApiVersionSimpleOperation: RouteHandler<{ Params: GetApiVbyApiVersionSimpleOperationData['path']; Reply: GetApiVbyApiVersionSimpleOperationResponses; }>; deleteFoo: RouteHandler<{ Headers: DeleteFooData3['headers']; Params: DeleteFooData3['path']; }>; callWithDescriptions: RouteHandler<{ Querystring?: CallWithDescriptionsData['query']; }>; deprecatedCall: RouteHandler<{ Headers: DeprecatedCallData['headers']; }>; callWithParameters: RouteHandler<{ Body: CallWithParametersData['body']; Headers: CallWithParametersData['headers']; Params: CallWithParametersData['path']; Querystring: CallWithParametersData['query']; }>; callWithWeirdParameterNames: RouteHandler<{ Body: CallWithWeirdParameterNamesData['body']; Headers: CallWithWeirdParameterNamesData['headers']; Params: CallWithWeirdParameterNamesData['path']; Querystring: CallWithWeirdParameterNamesData['query']; }>; getCallWithOptionalParam: RouteHandler<{ Body: GetCallWithOptionalParamData['body']; Querystring?: GetCallWithOptionalParamData['query']; }>; postCallWithOptionalParam: RouteHandler<{ Body?: PostCallWithOptionalParamData['body']; Querystring: PostCallWithOptionalParamData['query']; Reply: PostCallWithOptionalParamResponses; }>; postApiVbyApiVersionRequestBody: RouteHandler<{ Body?: PostApiVbyApiVersionRequestBodyData['body']; Querystring?: PostApiVbyApiVersionRequestBodyData['query']; }>; postApiVbyApiVersionFormData: RouteHandler<{ Body?: PostApiVbyApiVersionFormDataData['body']; Querystring?: PostApiVbyApiVersionFormDataData['query']; }>; callWithDefaultParameters: RouteHandler<{ Querystring?: CallWithDefaultParametersData['query']; }>; callWithDefaultOptionalParameters: RouteHandler<{ Querystring?: CallWithDefaultOptionalParametersData['query']; }>; callToTestOrderOfParams: RouteHandler<{ Querystring: CallToTestOrderOfParamsData['query']; }>; callWithNoContentResponse: RouteHandler<{ Reply: CallWithNoContentResponseResponses; }>; callWithResponseAndNoContentResponse: RouteHandler<{ Reply: CallWithResponseAndNoContentResponseResponses; }>; dummyA: RouteHandler<{ Reply: DummyAResponses; }>; dummyB: RouteHandler<{ Reply: DummyBResponses; }>; callWithDuplicateResponses: RouteHandler<{ Reply: Omit & CallWithDuplicateResponsesResponses; }>; callWithResponses: RouteHandler<{ Reply: Omit & CallWithResponsesResponses; }>; collectionFormat: RouteHandler<{ Querystring: CollectionFormatData['query']; }>; types: RouteHandler<{ Params?: TypesData['path']; Querystring: TypesData['query']; Reply: TypesResponses; }>; uploadFile: RouteHandler<{ Body: UploadFileData['body']; Params: UploadFileData['path']; Reply: UploadFileResponses; }>; fileResponse: RouteHandler<{ Params: FileResponseData['path']; Reply: FileResponseResponses; }>; complexTypes: RouteHandler<{ Querystring: ComplexTypesData['query']; Reply: ComplexTypesErrors & ComplexTypesResponses; }>; multipartResponse: RouteHandler<{ Reply: MultipartResponseResponses; }>; multipartRequest: RouteHandler<{ Body?: MultipartRequestData['body']; }>; complexParams: RouteHandler<{ Body?: ComplexParamsData['body']; Params: ComplexParamsData['path']; Reply: ComplexParamsResponses; }>; callWithResultFromHeader: RouteHandler<{ Reply: CallWithResultFromHeaderErrors & CallWithResultFromHeaderResponses; }>; testErrorCode: RouteHandler<{ Querystring: TestErrorCodeData['query']; Reply: TestErrorCodeErrors & TestErrorCodeResponses; }>; nonAsciiæøåÆøÅöôêÊ字符串: RouteHandler<{ Querystring: NonAsciiæøåÆøÅöôêÊ字符串Data['query']; Reply: NonAsciiæøåÆøÅöôêÊ字符串Responses; }>; putWithFormUrlEncoded: RouteHandler<{ Body: PutWithFormUrlEncodedData['body']; }>; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/fastify/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/fastify/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/ref-deep/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses, PostFooData, PostFooResponse, PostFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/ref-deep/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: Array<{ baz?: string; }>; bar?: Array<{ baz?: string; }>; }; export type Bar = { foo?: Array<{ baz?: string; }>; bar?: Array<{ baz?: string; }>; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Array<{ foo?: number; bar?: string; }>; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: { foo?: { foo?: number; bar?: string; }; bar?: string; }; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/ref-type/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/ref-type/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: Array<{ baz: Bar | null; }>; }; export type Bar = { bar: number; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Foo | null; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/required-all-of-ref/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/required-all-of-ref/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: string; baz?: string; }; export type Bar = Foo & { bar: number; foo: string; baz: string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/required-any-of-ref/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/required-any-of-ref/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: string; baz?: string; }; export type Bar = Foo & { bar: number; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/required-one-of-ref/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/required-one-of-ref/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: string; baz?: string; }; export type Bar = Foo & { bar: number; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/schema-const/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/schema-const/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: 'foo'; bar?: 3.2; baz?: -1; qux?: true; quux?: [ 1, 2, 3, 'foo', true ]; corge?: { [key: string]: unknown; }; garply?: '10n'; numberInt8?: 100; numberInt16?: 1000; numberInt32?: 100000; numberInt64?: 1000000000000; numberUint8?: 200; numberUint16?: 50000; numberUint32?: 3000000000; numberUint64?: 18000000000000000000; integerInt8?: -100; integerInt16?: -1000; integerInt32?: -100000; integerInt64?: -1000000000000; integerUint8?: 255; integerUint16?: 65535; integerUint32?: 4294967295; integerUint64?: '18446744073709551615n'; stringInt64?: '-9223372036854775808'; stringUint64?: '18446744073709551615'; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getBar, getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetBarData, GetBarResponses, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetBarData, GetBarResponses, GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ in: 'query', name: 'foo', type: 'apiKey' }], url: '/foo', ...options }); export const getBar = (options?: Options) => (options?.client ?? client).get({ security: [{ in: 'cookie', name: 'bar', type: 'apiKey' }], url: '/bar', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-api-key/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; export type GetBarData = { body?: never; path?: never; query?: never; url: '/bar'; }; export type GetBarResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-false/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-http-bearer/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-oauth2/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { getFoo, type Options } from './sdk.gen'; export type { ClientOptions, GetFooData, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { GetFooData, GetFooResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const getFoo = (options?: Options) => (options?.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/security-open-id-connect/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig({ baseUrl: 'https://foo.com/v1' })); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/servers/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'https://foo.com/v1' | `${string}://${string}/v1` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: string; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, provideAppInitializer, runInInjectionContext, } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; import { buildUrl, createConfig, createInterceptors, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; export function provideHeyApiClient(client: Client) { return provideAppInitializer(() => { const httpClient = inject(HttpClient); client.setConfig({ httpClient }); }); } export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >(); const requestOptions = < TData = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), httpClient: options.httpClient ?? _config.httpClient, serializedBody: undefined as string | undefined, }; if (!opts.httpClient) { if (opts.injector) { opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); } } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts as any); const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { redirect: 'follow', ...opts, }); return { opts, req, url }; }; const beforeRequest = async (options: RequestOptions) => { const { opts, req, url } = requestOptions(options); if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } return { opts, req, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, req: initialReq } = await beforeRequest(options); let req = initialReq; for (const fn of interceptors.request.fns) { if (fn) { req = await fn(req, opts as any); } } const result: { request: HttpRequest; response: any; } = { request: req, response: null, }; try { result.response = (await firstValueFrom( opts .httpClient!.request(req) .pipe(filter((event) => event.type === HttpEventType.Response)), )) as HttpResponse; for (const fn of interceptors.response.fns) { if (fn) { result.response = await fn(result.response, req, opts as any); } } let bodyResponse = result.response.body; if (opts.responseValidator) { await opts.responseValidator(bodyResponse); } if (opts.responseTransformer) { bodyResponse = await opts.responseTransformer(bodyResponse); } return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; } let finalError = error instanceof HttpErrorResponse ? error.error : error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } if (opts.throwOnError) { throw finalError; } return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, requestOptions: (options) => { if (options.security) { throw new Error('Security is not supported in requestOptions'); } if (options.requestValidator) { throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; }, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse, } from '@angular/common/http'; import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, Omit { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * An object containing any HTTP headers that you want to pre-populate your * `HttpHeaders` object with. * * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more} */ headers?: | HttpHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. */ httpClient?: HttpClient; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; /** * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one. */ injector?: Injector; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = Promise< ThrowOnError extends true ? TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; } | { data: undefined; error: TError[keyof TError]; request: HttpRequest; response: HttpErrorResponse & { error: TError[keyof TError] | null; }; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < T, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: RequestOptions, ) => HttpRequest; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, unknown, ResolvedRequestOptions >; requestOptions: RequestOptionsFn; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = ( contentType: string | null, ): 'blob' | 'formData' | 'json' | 'stream' | 'text' | undefined => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ( options: Pick, 'security'> & Pick & { headers: HttpHeaders; }, ) => { for (const auth of options.security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers = options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers = options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): HttpHeaders => { let mergedHeaders = new HttpHeaders(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } if (header instanceof HttpHeaders) { // Merge HttpHeaders instance header.keys().forEach((key) => { const values = header.getAll(key); if (values) { values.forEach((value) => { mergedHeaders = mergedHeaders.append(key, value); }); } }); } else { // Merge plain object headers for (const [key, value] of Object.entries(header)) { if (value === null) { mergedHeaders = mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders = mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { eventSubscribe, type Options } from './sdk.gen'; export type { AgentPart, ApiError, AssistantMessage, ClientOptions, CompactionPart, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, FileDiff, FilePart, FilePartSource, FilePartSourceText, FileSource, Message, MessageAbortedError, MessageOutputLengthError, Part, PatchPart, PermissionAction, PermissionRequest, PermissionRule, PermissionRuleset, Project, ProviderAuthError, Pty, Range, ReasoningPart, RetryPart, Session, SessionStatus, SnapshotPart, StepFinishPart, StepStartPart, SymbolSource, TextPart, Todo, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, UnknownError, UserMessage } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { EventSubscribeData, EventSubscribeResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (options?: Options) => (options?.client ?? client).sse.get({ url: '/event', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-angular/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type FilePartSource = FileSource | SymbolSource; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios'; import axios from 'axios'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); let instance: AxiosInstance; if (_config.axios && !('Axios' in _config.axios)) { instance = _config.axios; } else { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...configWithoutAuth } = _config; instance = axios.create(configWithoutAuth); } const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); instance.defaults = { ...instance.defaults, ..._config, // @ts-expect-error headers: mergeHeaders(instance.defaults.headers, _config.headers), }; return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, axios: options.axios ?? _config.axios ?? instance, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); try { // assign Axios here for consistency with fetch const _axios = opts.axios!; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { auth, ...optsWithoutAuth } = opts; const response = await _axios({ ...optsWithoutAuth, baseURL: '', // the baseURL is already included in `url` data: getValidRequestBody(opts), headers: opts.headers as RawAxiosRequestHeaders, // let `paramsSerializer()` handle query params if it exists params: opts.paramsSerializer ? opts.query : undefined, url, }); let { data } = response; if (opts.responseType === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { ...response, data: data ?? {}, }; } catch (error) { const e = error as AxiosError; if (opts.throwOnError) { throw e; } // @ts-expect-error e.error = e.response?.data ?? {}; return e; } }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as Record, method, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, // @ts-expect-error signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ axios: instance, ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), instance, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosStatic, CreateAxiosDefaults, } from 'axios'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. * * @default axios */ axios?: AxiosStatic | AxiosInstance; /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | AxiosRequestHeaders | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ClientOptions { baseURL?: string; throwOnError?: boolean; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise ? TData[keyof TData] : TData>> : Promise< | (AxiosResponse ? TData[keyof TData] : TData> & { error: undefined; }) | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; }) >; type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { instance: AxiosInstance; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Record; }, name?: string, ): boolean => { if (!name) { return false; } if (name in options.headers || options.query?.[name]) { return true; } if ( 'Cookie' in options.headers && options.headers['Cookie'] && typeof options.headers['Cookie'] === 'string' ) { return options.headers['Cookie'].includes(`${name}=`); } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Record; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': { const value = `${name}=${token}`; if ('Cookie' in options.headers && options.headers['Cookie']) { options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`; } else { options.headers['Cookie'] = value; } break; } case 'header': default: options.headers[name] = token; break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, path: options.path, // let `paramsSerializer()` handle query params if it exists query: !options.paramsSerializer ? options.query : undefined, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; config.headers = mergeHeaders(a.headers, b.headers); return config; }; /** * Special Axios headers keywords allowing to set headers by request method. */ export const axiosHeadersKeywords = [ 'common', 'delete', 'get', 'head', 'patch', 'post', 'put', ] as const; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Record => { const mergedHeaders: Record = {}; for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = Object.entries(header); for (const [key, value] of iterator) { if ( axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { ...(mergedHeaders[key] as Record), ...value, }; } else if (value === null) { delete mergedHeaders[key]; } else if (Array.isArray(value)) { for (const v of value) { // @ts-expect-error mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string]; } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } return mergedHeaders; }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { eventSubscribe, type Options } from './sdk.gen'; export type { AgentPart, ApiError, AssistantMessage, ClientOptions, CompactionPart, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, FileDiff, FilePart, FilePartSource, FilePartSourceText, FileSource, Message, MessageAbortedError, MessageOutputLengthError, Part, PatchPart, PermissionAction, PermissionRequest, PermissionRule, PermissionRuleset, Project, ProviderAuthError, Pty, Range, ReasoningPart, RetryPart, Session, SessionStatus, SnapshotPart, StepFinishPart, StepStartPart, SymbolSource, TextPart, Todo, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, UnknownError, UserMessage } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { EventSubscribeData, EventSubscribeResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (options?: Options) => (options?.client ?? client).sse.get({ responseType: 'text', url: '/event', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-axios/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: `${string}://${string}` | (string & {}); }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type FilePartSource = FileSource | SymbolSource; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { eventSubscribe, type Options } from './sdk.gen'; export type { AgentPart, ApiError, AssistantMessage, ClientOptions, CompactionPart, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, FileDiff, FilePart, FilePartSource, FilePartSourceText, FileSource, Message, MessageAbortedError, MessageOutputLengthError, Part, PatchPart, PermissionAction, PermissionRequest, PermissionRule, PermissionRuleset, Project, ProviderAuthError, Pty, Range, ReasoningPart, RetryPart, Session, SessionStatus, SnapshotPart, StepFinishPart, StepStartPart, SymbolSource, TextPart, Todo, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, UnknownError, UserMessage } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { EventSubscribeData, EventSubscribeResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (options?: Options) => (options?.client ?? client).sse.get({ url: '/event', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-fetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type FilePartSource = FileSource | SymbolSource; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; // @ts-expect-error const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); for (const fn of interceptors.request.fns) { if (fn) { await fn(opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; const requestInit: ReqInit = { ...opts, body: getValidRequestBody(opts), }; let response = await _fetch(url, requestInit); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, opts); } } const result = { response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); const requestInit = { ...init, method: init.method as Config['method'], url, }; for (const fn of interceptors.request.fns) { if (fn) { await fn(requestInit); request = new Request(requestInit.url, requestInit); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData extends Record ? TData[keyof TData] : TData; response: Response; }> : Promise< ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type SseFn = ( options: Omit, 'method'>, ) => Promise>; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializer, QuerySerializerOptions, } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, options: Options, ) => Err | Promise; type ReqInterceptor = (options: Options) => void | Promise; type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { eventSubscribe, type Options } from './sdk.gen'; export type { AgentPart, ApiError, AssistantMessage, ClientOptions, CompactionPart, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, FileDiff, FilePart, FilePartSource, FilePartSourceText, FileSource, Message, MessageAbortedError, MessageOutputLengthError, Part, PatchPart, PermissionAction, PermissionRequest, PermissionRule, PermissionRuleset, Project, ProviderAuthError, Pty, Range, ReasoningPart, RetryPart, Session, SessionStatus, SnapshotPart, StepFinishPart, StepStartPart, SymbolSource, TextPart, Todo, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, UnknownError, UserMessage } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { EventSubscribeData, EventSubscribeResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (options?: Options) => (options?.client ?? client).sse.get({ url: '/event', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-next/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type FilePartSource = FileSource | SymbolSource; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { useAsyncData, useFetch, useLazyAsyncData, useLazyFetch } from 'nuxt/app'; import { reactive, ref, toValue, watch } from 'vue'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; import { buildUrl, createConfig, executeFetchFn, mergeConfigs, mergeHeaders, mergeInterceptors, serializeBody, setAuthParams, unwrapRefs, } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = ({ asyncDataOptions, composable = '$fetch', ...options }) => { const key = options.key; const opts = { ..._config, ...options, $fetch: options.$fetch ?? _config.$fetch ?? $fetch, headers: mergeHeaders(_config.headers, options.headers), onRequest: mergeInterceptors(_config.onRequest, options.onRequest), onResponse: mergeInterceptors(_config.onResponse, options.onResponse), }; const { requestValidator, responseTransformer, responseValidator, security } = opts; if (requestValidator || security) { // auth must happen in interceptors otherwise we'd need to require // asyncContext enabled // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext opts.onRequest = [ async ({ options }) => { if (security) { await setAuthParams({ auth: opts.auth, headers: options.headers, query: options.query, security, }); } if (requestValidator) { await requestValidator({ ...options, // @ts-expect-error body: options.rawBody, }); } }, ...opts.onRequest, ]; } if (responseTransformer || responseValidator) { opts.onResponse = [ ...opts.onResponse, async ({ options, response }) => { if (options.responseType && options.responseType !== 'json') { return; } if (!response.ok) { return; } if (responseValidator) { await responseValidator(response._data); } if (responseTransformer) { response._data = await responseTransformer(response._data); } }, ]; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const fetchFn = opts.$fetch; if (composable === '$fetch') { return executeFetchFn( // @ts-expect-error opts, fetchFn, ); } if (composable === 'useFetch' || composable === 'useLazyFetch') { opts.rawBody = opts.body; const bodyParams = reactive({ body: opts.body, bodySerializer: opts.bodySerializer, }); const body = ref(serializeBody({ ...opts, body: toValue(opts.body) })); opts.body = body; watch(bodyParams, (changed) => { body.value = serializeBody(changed); }); return composable === 'useLazyFetch' ? useLazyFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }) : useFetch(() => buildUrl(opts), { ...opts, ...asyncDataOptions }); } const handler: any = () => executeFetchFn( // @ts-expect-error opts, fetchFn, ); if (composable === 'useAsyncData') { return key ? useAsyncData(key, handler, asyncDataOptions) : useAsyncData(handler, asyncDataOptions); } if (composable === 'useLazyAsyncData') { return key ? useLazyAsyncData(key, handler, asyncDataOptions) : useLazyAsyncData(handler, asyncDataOptions); } return undefined as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...unwrapRefs(opts), body: opts.body as BodyInit | null | undefined, method, onRequest: undefined, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, signal: unwrapRefs(opts.signal) as AbortSignal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options } as typeof options); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Composable, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types.gen'; export { createConfig } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { AsyncDataOptions, useAsyncData, useFetch, UseFetchOptions, useLazyAsyncData, useLazyFetch, } from 'nuxt/app'; import type { Ref } from 'vue'; import type { Auth } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; type ObjectStyle = 'form' | 'deepObject'; export type QuerySerializer = (query: Parameters[0]['query']) => string; type WithRefs = { [K in keyof TData]: NonNullable extends object ? WithRefs> | Ref> | Extract : NonNullable | Ref> | Extract; }; // copied from Nuxt export type KeysOf = Array; export interface Config extends Omit, 'baseURL' | 'body' | 'headers' | 'method' | 'query'>, WithRefs, 'query'>>, Omit { /** * Base URL for all requests made by this client. */ baseURL?: T['baseURL']; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; } export interface RequestOptions< TComposable extends Composable = '$fetch', ResT = unknown, DefaultT = undefined, Url extends string = string, > extends Config, WithRefs<{ path?: FetchOptions['query']; query?: FetchOptions['query']; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { asyncDataOptions?: AsyncDataOptions, DefaultT>; /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: NonNullable | Ref> | null; composable?: TComposable; key?: string; rawBody?: NonNullable | Ref> | null; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TComposable extends Composable, ResT, TError, > = TComposable extends '$fetch' ? ReturnType> : TComposable extends 'useAsyncData' ? ReturnType> : TComposable extends 'useFetch' ? ReturnType> : TComposable extends 'useLazyAsyncData' ? ReturnType> : TComposable extends 'useLazyFetch' ? ReturnType> : never; export interface ClientOptions { baseURL?: string; } type MethodFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'>, ) => Promise>>; type RequestFn = < TComposable extends Composable = '$fetch', ResT = unknown, TError = unknown, DefaultT = undefined, >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: FetchOptions['query']; query?: FetchOptions['query']; url: string; } export type BuildUrlOptions< TData extends Omit = Omit, > = Pick, 'path' | 'query'> & Pick & Pick, 'baseURL' | 'querySerializer'>; type BuildUrlFn = >( options: BuildUrlOptions, ) => string; export type Client = CoreClient; type OmitKeys = Pick>; export type Options< TComposable extends Composable = '$fetch', TData extends TDataShape = TDataShape, ResT = unknown, DefaultT = undefined, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : WithRefs>); type FetchOptions = Omit, keyof AsyncDataOptions>; export type Composable = | '$fetch' | 'useAsyncData' | 'useFetch' | 'useLazyAsyncData' | 'useLazyFetch'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ComputedRef, Ref } from 'vue'; import { isRef, toValue, unref } from 'vue'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import type { ArraySeparatorStyle, BuildUrlOptions, Client, ClientOptions, Config, QuerySerializer, RequestOptions, } from './types.gen'; type PathSerializer = Pick, 'path' | 'url'>; const PATH_PARAM_RE = /\{[^{}]+\}/g; type MaybeArray = T | T[]; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = toValue((toValue(path) as Record | undefined)?.[name]); if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; const qParams = toValue(queryParams); if (qParams && typeof qParams === 'object') { for (const name in qParams) { const value = toValue(qParams[name]); if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || (toValue(options.query) as Record | undefined)?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': { if (!options.query) { options.query = {}; } const queryValue = toValue(options.query) as Record | undefined; if (queryValue) { queryValue[name] = token; } break; } case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseURL as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: Pick & { baseUrl?: string; querySerializer: QuerySerializer; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseURL?.endsWith('/')) { config.baseURL = config.baseURL.substring(0, config.baseURL.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } let h: unknown = header; if (isRef(h)) { h = unref(h); } const iterator = h instanceof Headers ? headersEntries(h) : Object.entries(h as Record); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, unwrapRefs(v) as string); } } else if (value !== undefined) { const v = unwrapRefs(value); // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set(key, typeof v === 'object' ? JSON.stringify(v) : (v as string)); } } } return mergedHeaders; }; export const mergeInterceptors = (...args: Array>): Array => args.reduce>((acc, item) => { if (typeof item === 'function') { acc.push(item); } else if (Array.isArray(item)) { return acc.concat(item); } return acc; }, []); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, querySerializer: defaultQuerySerializer, ...override, }); type UnwrapRefs = T extends Ref ? V : T extends ComputedRef ? V : T extends Record // this doesn't handle functions well ? { [K in keyof T]: UnwrapRefs } : T; export const unwrapRefs = (value: T): UnwrapRefs => { if (value === null || typeof value !== 'object' || value instanceof Headers) { return (isRef(value) ? unref(value) : value) as UnwrapRefs; } if ( value instanceof Blob || value instanceof FormData || value instanceof ReadableStream || value instanceof AbortSignal ) { return value as UnwrapRefs; } if (Array.isArray(value)) { return value.map((item) => unwrapRefs(item)) as UnwrapRefs; } if (isRef(value)) { return unwrapRefs(unref(value) as T); } // unwrap into new object to avoid modifying the source const result: Record = {}; for (const key in value) { result[key] = unwrapRefs(value[key] as T); } return result as UnwrapRefs; }; export const serializeBody = ( opts: Pick[0], 'body' | 'bodySerializer'>, ) => { if (opts.body && opts.bodySerializer) { return opts.bodySerializer(opts.body); } return opts.body; }; export const executeFetchFn = ( opts: Omit[0], 'composable'>, fetchFn: Required['$fetch'], ) => { const unwrappedOpts = unwrapRefs(opts); unwrappedOpts.rawBody = unwrappedOpts.body; unwrappedOpts.body = serializeBody(unwrappedOpts); return fetchFn( buildUrl(opts), // @ts-expect-error unwrappedOpts, ); }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { eventSubscribe, type Options } from './sdk.gen'; export type { AgentPart, ApiError, AssistantMessage, ClientOptions, CompactionPart, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, FileDiff, FilePart, FilePartSource, FilePartSourceText, FileSource, Message, MessageAbortedError, MessageOutputLengthError, Part, PatchPart, PermissionAction, PermissionRequest, PermissionRule, PermissionRuleset, Project, ProviderAuthError, Pty, Range, ReasoningPart, RetryPart, Session, SessionStatus, SnapshotPart, StepFinishPart, StepStartPart, SymbolSource, TextPart, Todo, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, UnknownError, UserMessage } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Composable, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { EventSubscribeData, EventSubscribeResponse } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (options: Options) => (options.client ?? client).sse.get({ url: '/event', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-nuxt/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseURL: `${string}://${string}` | (string & {}); }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type FilePartSource = FileSource | SymbolSource; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { ofetch, type ResponseType as OfetchResponseType } from 'ofetch'; import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildOfetchOptions, buildUrl, createConfig, createInterceptors, isRepeatableBody, mapParseAsToResponseType, mergeConfigs, mergeHeaders, parseError, parseSuccess, setAuthParams, wrapDataReturn, wrapErrorReturn, } from './utils.gen'; type ReqInit = Omit & { body?: BodyInit | null | undefined; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // precompute serialized / network body const resolveOptions = async (options: RequestOptions) => { const opts = { ..._config, ...options, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type if body is empty to avoid invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } // if a raw body is provided (no serializer), adjust Content-Type only when it // equals the default JSON value to better match the concrete body type if ( opts.body !== undefined && opts.bodySerializer === null && (opts.headers.get('Content-Type') || '').toLowerCase() === 'application/json' ) { const b: unknown = opts.body; if (typeof FormData !== 'undefined' && b instanceof FormData) { // let the runtime set the multipart boundary opts.headers.delete('Content-Type'); } else if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) { // standard urlencoded content type (+ charset) opts.headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } else if (typeof Blob !== 'undefined' && b instanceof Blob) { const t = b.type?.trim(); if (t) { opts.headers.set('Content-Type', t); } else { // unknown blob type: avoid sending a misleading JSON header opts.headers.delete('Content-Type'); } } } // precompute network body (stability for retries and interceptors) const networkBody = getValidRequestBody(opts) as RequestInit['body'] | null | undefined; const url = buildUrl(opts); return { networkBody, opts, url }; }; // apply request interceptors and mirror header/method/signal back to opts const applyRequestInterceptors = async ( request: Request, opts: ResolvedRequestOptions, body: BodyInit | null | undefined, ) => { for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // reflect interceptor changes into opts used by the network layer opts.headers = request.headers; opts.method = request.method as Uppercase; // ignore request.body changes to avoid turning serialized bodies into streams // body comes only from getValidRequestBody(options) // reflect signal if present opts.signal = (request as any).signal as AbortSignal | undefined; // When body is FormData, remove Content-Type header to avoid boundary mismatch. // Note: We already delete Content-Type in resolveOptions for FormData, but the // Request constructor (line 175) re-adds it with an auto-generated boundary. // Since we pass the original FormData (not the Request's body) to ofetch, and // ofetch will generate its own boundary, we must remove the Request's Content-Type // to let ofetch set the correct one. Otherwise the boundary in the header won't // match the boundary in the actual multipart body sent by ofetch. if (typeof FormData !== 'undefined' && body instanceof FormData) { opts.headers.delete('Content-Type'); } return request; }; // build ofetch options with stable retry logic based on body repeatability const buildNetworkOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, ) => { const effectiveRetry = isRepeatableBody(body) ? (opts.retry as any) : (0 as any); return buildOfetchOptions(opts, body, responseType, effectiveRetry); }; const request: Client['request'] = async (options) => { const { networkBody: initialNetworkBody, opts, url } = await resolveOptions(options as any); // map parseAs -> ofetch responseType once per request const ofetchResponseType: OfetchResponseType | undefined = mapParseAsToResponseType( opts.parseAs, opts.responseType, ); const $ofetch = opts.ofetch ?? ofetch; // create Request before network to run middleware consistently const networkBody = initialNetworkBody; const requestInit: ReqInit = { body: networkBody, headers: opts.headers as Headers, method: opts.method, redirect: 'follow', signal: opts.signal, }; let request = new Request(url, requestInit); request = await applyRequestInterceptors(request, opts, networkBody); const finalUrl = request.url; // build ofetch options and perform the request (.raw keeps the Response) const responseOptions = buildNetworkOptions( opts as ResolvedRequestOptions, networkBody, ofetchResponseType, ); let response = await $ofetch.raw(finalUrl, responseOptions); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response }; if (response.ok) { const data = await parseSuccess(response, opts, ofetchResponseType); return wrapDataReturn(data, result, opts.responseStyle); } let finalError = await parseError(response); for (const fn of interceptors.error.fns) { if (fn) { finalError = await fn(finalError, response, request, opts); } } // ensure error is never undefined after interceptors finalError = (finalError as any) || ({} as string); if (opts.throwOnError) { throw finalError; } return wrapErrorReturn(finalError, result, opts.responseStyle) as any; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method } as any); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { networkBody, opts, url } = await resolveOptions(options); const optsForSse: any = { ...opts }; delete optsForSse.body; // body is provided via serializedBody below return createSseClient({ ...optsForSse, fetch: opts.fetch, headers: opts.headers as Headers, method, onRequest: async (url, init) => { let request = new Request(url, init); request = await applyRequestInterceptors(request, opts, networkBody); return request; }, serializedBody: networkBody as BodyInit | null | undefined, signal: opts.signal, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import type { ofetch } from 'ofetch'; import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * HTTP(S) agent configuration (Node.js only). Passed through to ofetch. */ agent?: OfetchOptions['agent']; /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Node-only proxy/agent options. */ dispatcher?: OfetchOptions['dispatcher']; /** * Fetch API implementation. Used for SSE streaming. You can use this option * to provide a custom fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Controls the native ofetch behaviour that throws `FetchError` when * `response.ok === false`. We default to suppressing it to match the fetch * client semantics and let `throwOnError` drive the outcome. */ ignoreResponseError?: OfetchOptions['ignoreResponseError']; // No custom fetch option: provide custom instance via `ofetch` instead /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Custom ofetch instance created via `ofetch.create()`. If provided, it will * be used for requests instead of the default `ofetch` export. */ ofetch?: typeof ofetch; /** * ofetch hook called before a request is sent. */ onRequest?: OfetchOptions['onRequest']; /** * ofetch hook called when a request fails before receiving a response * (e.g., network errors or aborted requests). */ onRequestError?: OfetchOptions['onRequestError']; /** * ofetch hook called after a successful response is received and parsed. */ onResponse?: OfetchOptions['onResponse']; /** * ofetch hook called when the response indicates an error (non-ok status) * or when response parsing fails. */ onResponseError?: OfetchOptions['onResponseError']; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** Custom response parser (ofetch). */ parseResponse?: OfetchOptions['parseResponse']; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * ofetch responseType override. If provided, it will be passed directly to * ofetch and take precedence over `parseAs`. */ responseType?: OfetchResponseType; /** * Automatically retry failed requests. */ retry?: OfetchOptions['retry']; /** * Delay (in ms) between retry attempts. */ retryDelay?: OfetchOptions['retryDelay']; /** * HTTP status codes that should trigger a retry. */ retryStatusCodes?: OfetchOptions['retryStatusCodes']; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; /** * Abort the request after the given milliseconds. */ timeout?: number; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { FetchOptions as OfetchOptions, ResponseType as OfetchResponseType } from 'ofetch'; import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions, ResolvedRequestOptions, ResponseStyle, } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; /** * Map our parseAs value to ofetch responseType when not explicitly provided. */ export const mapParseAsToResponseType = ( parseAs: Config['parseAs'] | undefined, explicit?: OfetchResponseType, ): OfetchResponseType | undefined => { if (explicit) return explicit; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'json': case 'text': case 'stream': return parseAs; case 'formData': case 'auto': default: return undefined; // let ofetch auto-detect } }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; /** * Heuristic to detect whether a request body can be safely retried. */ export const isRepeatableBody = (body: unknown): boolean => { if (body == null) return true; // undefined/null treated as no-body if (typeof body === 'string') return true; if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return true; if (typeof Uint8Array !== 'undefined' && body instanceof Uint8Array) return true; if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) return true; if (typeof Blob !== 'undefined' && body instanceof Blob) return true; if (typeof FormData !== 'undefined' && body instanceof FormData) return true; // Streams are not repeatable if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false; // Default: assume non-repeatable for unknown structured bodies return false; }; /** * Small helper to unify data vs fields return style. */ export const wrapDataReturn = ( data: T, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): T | ((T extends Record ? { data: T } : { data: T }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? (data as any) : ({ data, ...result } as any); /** * Small helper to unify error vs fields return style. */ export const wrapErrorReturn = ( error: E, result: { request: Request; response: Response }, responseStyle: ResponseStyle | undefined, ): | undefined | ((E extends Record ? { error: E } : { error: E }) & typeof result) => (responseStyle ?? 'fields') === 'data' ? undefined : ({ error, ...result } as any); /** * Build options for $ofetch.raw from our resolved opts and body. */ export const buildOfetchOptions = ( opts: ResolvedRequestOptions, body: BodyInit | null | undefined, responseType: OfetchResponseType | undefined, retryOverride?: OfetchOptions['retry'], ): OfetchOptions => ({ agent: opts.agent as OfetchOptions['agent'], body, credentials: opts.credentials as OfetchOptions['credentials'], dispatcher: opts.dispatcher as OfetchOptions['dispatcher'], headers: opts.headers as Headers, ignoreResponseError: (opts.ignoreResponseError as OfetchOptions['ignoreResponseError']) ?? true, method: opts.method, onRequest: opts.onRequest as OfetchOptions['onRequest'], onRequestError: opts.onRequestError as OfetchOptions['onRequestError'], onResponse: opts.onResponse as OfetchOptions['onResponse'], onResponseError: opts.onResponseError as OfetchOptions['onResponseError'], parseResponse: opts.parseResponse as OfetchOptions['parseResponse'], // URL already includes query query: undefined, responseType, retry: retryOverride ?? (opts.retry as OfetchOptions['retry']), retryDelay: opts.retryDelay as OfetchOptions['retryDelay'], retryStatusCodes: opts.retryStatusCodes as OfetchOptions['retryStatusCodes'], signal: opts.signal, timeout: opts.timeout as number | undefined, }) as OfetchOptions; /** * Parse a successful response, handling empty bodies and stream cases. */ export const parseSuccess = async ( response: Response, opts: ResolvedRequestOptions, ofetchResponseType?: OfetchResponseType, ): Promise => { // Stream requested: return stream body if (ofetchResponseType === 'stream') { return response.body; } const inferredParseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; // Handle empty responses if (response.status === 204 || response.headers.get('Content-Length') === '0') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'text': return await (response as any)[inferredParseAs](); case 'formData': return new FormData(); case 'stream': return response.body; default: return {}; } } // Prefer ofetch-populated data unless we explicitly need raw `formData` let data: unknown = (response as any)._data; if (inferredParseAs === 'formData' || typeof data === 'undefined') { switch (inferredParseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await (response as any)[inferredParseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; detect empty via clone().text() first. const txt = await response.clone().text(); if (!txt) { data = {}; } else { data = await (response as any).json(); } break; } case 'stream': return response.body; } } if (inferredParseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return data; }; /** * Parse an error response payload. */ export const parseError = async (response: Response): Promise => { let error: unknown = (response as any)._data; if (typeof error === 'undefined') { const textError = await response.text(); try { error = JSON.parse(textError); } catch { error = textError; } } return error ?? ({} as string); }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, ignoreResponseError: true, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { eventSubscribe, type Options } from './sdk.gen'; export type { AgentPart, ApiError, AssistantMessage, ClientOptions, CompactionPart, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, FileDiff, FilePart, FilePartSource, FilePartSourceText, FileSource, Message, MessageAbortedError, MessageOutputLengthError, Part, PatchPart, PermissionAction, PermissionRequest, PermissionRule, PermissionRuleset, Project, ProviderAuthError, Pty, Range, ReasoningPart, RetryPart, Session, SessionStatus, SnapshotPart, StepFinishPart, StepStartPart, SymbolSource, TextPart, Todo, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, UnknownError, UserMessage } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { EventSubscribeData, EventSubscribeResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (options?: Options) => (options?.client ?? client).sse.get({ url: '/event', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-ofetch/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type FilePartSource = FileSource | SymbolSource; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/@tanstack/react-query.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type DefaultError, queryOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; import { listEvents, type Options } from '../sdk.gen'; import type { ListEventsData, ListEventsResponse } from '../types.gen'; export type QueryKey = [ Pick & { _id: string; _infinite?: boolean; tags?: ReadonlyArray; } ]; const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ QueryKey[0] ] => { const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; if (infinite) { params._infinite = infinite; } if (tags) { params.tags = tags; } if (options?.body) { params.body = options.body; } if (options?.headers) { params.headers = options.headers; } if (options?.path) { params.path = options.path; } if (options?.query) { params.query = options.query; } return [params]; }; export const listEventsQueryKey = (options?: Options) => createQueryKey('listEvents', options); /** * List events */ export const listEventsOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { const { data } = await listEvents({ ...options, ...queryKey[0], signal, throwOnError: true }); return data; }, queryKey: listEventsQueryKey(options) }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { listEvents, type Options, subscribeToEventStream } from './sdk.gen'; export type { ClientOptions, ListEventsData, ListEventsResponse, ListEventsResponses, SubscribeToEventStreamData, SubscribeToEventStreamResponse, SubscribeToEventStreamResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { ListEventsData, ListEventsResponses, SubscribeToEventStreamData, SubscribeToEventStreamResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Subscribe to event stream */ export const subscribeToEventStream = (options?: Options) => (options?.client ?? client).sse.post({ url: '/events/subscribe', ...options }); /** * List events */ export const listEvents = (options?: Options) => (options?.client ?? client).get({ url: '/events/list', ...options }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type SubscribeToEventStreamData = { body?: never; path?: never; query?: never; url: '/events/subscribe'; }; export type SubscribeToEventStreamResponses = { /** * Event stream */ 200: { [key: string]: unknown; }; }; export type SubscribeToEventStreamResponse = SubscribeToEventStreamResponses[keyof SubscribeToEventStreamResponses]; export type ListEventsData = { body?: never; path?: never; query?: never; url: '/events/list'; }; export type ListEventsResponses = { /** * OK */ 200: Array; }; export type ListEventsResponse = ListEventsResponses[keyof ListEventsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/string-with-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/string-with-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo?: Array; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Bar, Baz, ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses, Qux } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetFooResponse } from './types.gen'; const quxSchemaResponseTransformer = (data: any) => { if (data.baz) { data.baz = new Date(data.baz); } return data; }; const bazSchemaResponseTransformer = (data: any) => { data = quxSchemaResponseTransformer(data); data.bar = new Date(data.bar); return data; }; const barSchemaResponseTransformer = (data: any) => { data.foo = data.foo.map((item: any) => bazSchemaResponseTransformer(item)); return data; }; const fooSchemaResponseTransformer = (data: any) => { data.foo = data.foo.map((item: any) => barSchemaResponseTransformer(item)); return data; }; export const getFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-all-of/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { foo: Array; }; export type Bar = { foo: Array; bar: 'foo' | 'bar' | 'baz'; }; export type Baz = Omit & { foo: number; bar: Date; baz: 'foo' | 'bar' | 'baz'; qux: number; id: 'Baz'; }; export type Qux = { foo: number; bar: number; baz?: Date; id: string; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Foo; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, CreateSecretData, CreateSecretResponse, CreateSecretResponses, ListSecretsData, ListSecretsResponse, ListSecretsResponses, PaginatedResponse, RepositorySecret } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { CreateSecretResponse, ListSecretsResponse } from './types.gen'; const repositorySecretSchemaResponseTransformer = (data: any) => { data.createdAt = new Date(data.createdAt); data.updatedAt = new Date(data.updatedAt); return data; }; export const listSecretsResponseTransformer = async (data: any): Promise => { if (data.data) { data.data = data.data.map((item: any) => repositorySecretSchemaResponseTransformer(item)); } return data; }; export const createSecretResponseTransformer = async (data: any): Promise => { data = repositorySecretSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-allof-response-wrapper/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: '{protocol}://specs' | (string & {}); }; export type PaginatedResponse = { meta?: { page?: number; limit?: number; total?: number; totalPages?: number; }; }; export type RepositorySecret = { id: number; name: string; createdAt: Date; updatedAt: Date; }; export type ListSecretsData = { body?: never; path?: never; query?: never; url: '/secrets'; }; export type ListSecretsResponses = { /** * PaginatedResponseRepositorySecret * * OK */ 200: PaginatedResponse & { data?: Array; }; }; export type ListSecretsResponse = ListSecretsResponses[keyof ListSecretsResponses]; export type CreateSecretData = { body?: never; path?: never; query?: never; url: '/secrets/{id}'; }; export type CreateSecretResponses = { /** * Created */ 201: RepositorySecret; }; export type CreateSecretResponse = CreateSecretResponses[keyof CreateSecretResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo, GetFooData, GetFooResponse, GetFooResponses, GetNullablePollData, GetNullablePollResponse, GetNullablePollResponses, GetPollData, GetPollResponse, GetPollResponses, NestedDateObject, NestedDateObjectData, NestedDateObjectResponse, NestedDateObjectResponses, Poll } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetFooResponse, GetNullablePollResponse, GetPollResponse, NestedDateObjectResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { if (data.foo) { data.foo = new Date(data.foo); } if (data.bar) { data.bar = new Date(data.bar); } if (data.baz) { data.baz = new Date(data.baz); } if (data.requiredQux) { data.requiredQux = new Date(data.requiredQux); } return data; }; export const getFooResponseTransformer = async (data: any): Promise => { data = data.map((item: any) => fooSchemaResponseTransformer(item)); return data; }; const pollSchemaResponseTransformer = (data: any) => { data.createdAt = new Date(data.createdAt); return data; }; export const getPollResponseTransformer = async (data: any): Promise => { data = pollSchemaResponseTransformer(data); return data; }; export const getNullablePollResponseTransformer = async (data: any): Promise => { if (data) { data = pollSchemaResponseTransformer(data); } return data; }; const nestedDateObjectSchemaResponseTransformer = (data: any) => { if (data.foo) { if (data.foo.bar) { data.foo.bar = new Date(data.foo.bar); } } return data; }; export const nestedDateObjectResponseTransformer = async (data: any): Promise => { data = nestedDateObjectSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-any-of-null/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Poll = { id: number; createdAt: Date; }; /** * Object with a nested date structure */ export type NestedDateObject = { foo?: { bar?: Date; }; }; export type Foo = { foo?: Date; bar?: Date | null; baz?: Date | null; requiredQux: Date | null; }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: Array; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; export type GetPollData = { body?: never; path?: never; query?: never; url: '/polls'; }; export type GetPollResponses = { /** * OK */ 200: Poll; }; export type GetPollResponse = GetPollResponses[keyof GetPollResponses]; export type GetNullablePollData = { body?: never; path?: never; query?: never; url: '/polls/nullable'; }; export type GetNullablePollResponses = { /** * OK */ 200: Poll | null; }; export type GetNullablePollResponse = GetNullablePollResponses[keyof GetNullablePollResponses]; export type NestedDateObjectData = { body?: never; path?: never; query?: never; url: '/api/nested-date-object'; }; export type NestedDateObjectResponses = { /** * Object with nested date */ 200: NestedDateObject; }; export type NestedDateObjectResponse = NestedDateObjectResponses[keyof NestedDateObjectResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetFooData, GetFooResponse, GetFooResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetFooResponse } from './types.gen'; export const getFooResponseTransformer = async (data: any): Promise => { data.foo = data.foo.map((item: any) => { item.baz = new Date(item.baz); return item; }); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-array/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type GetFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type GetFooResponses = { /** * OK */ 200: { foo: Array<{ baz: Date; }>; }; }; export type GetFooResponse = GetFooResponses[keyof GetFooResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { CategoryAction, ClientOptions, DirectAction, ListRulesData, ListRulesResponse, ListRulesResponses, RoundRobinAction, Rule, StatusAction, Then } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ListRulesResponse } from './types.gen'; const ruleSchemaResponseTransformer = (data: any) => { if (data.createdAt) { data.createdAt = new Date(data.createdAt); } return data; }; export const listRulesResponseTransformer = async (data: any): Promise => { data.rules = data.rules.map((item: any) => ruleSchemaResponseTransformer(item)); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-one-of-discriminated/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Rule = { id: string; createdAt?: Date; then: Then; }; /** * Action to take when rule conditions are met */ export type Then = ({ type: 'direct'; } & DirectAction) | ({ type: 'round-robin'; } & RoundRobinAction) | ({ type: 'category'; } & CategoryAction) | ({ type: 'status'; } & StatusAction); export type DirectAction = { type: 'direct'; assignee: string; }; export type RoundRobinAction = { type: 'round-robin'; id: string; items: Array; }; export type CategoryAction = { type: 'category'; category: string; }; export type StatusAction = { type: 'status'; status: string; }; export type ListRulesData = { body?: never; path?: never; query?: never; url: '/rules'; }; export type ListRulesResponses = { /** * Rules response */ 200: { rules: Array; }; }; export type ListRulesResponse = ListRulesResponses[keyof ListRulesResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, GetTreeData, GetTreeResponse, GetTreeResponses, TreeNode } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { GetTreeResponse } from './types.gen'; const treeNodeSchemaResponseTransformer = (data: any) => { if (data.createdAt) { data.createdAt = new Date(data.createdAt); } if (data.children) { data.children = data.children.map((item: any) => treeNodeSchemaResponseTransformer(item)); } return data; }; export const getTreeResponseTransformer = async (data: any): Promise => { data = data.map((item: any) => treeNodeSchemaResponseTransformer(item)); return data; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transformers-recursive/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TreeNode = { id?: string; name?: string; createdAt?: Date; children?: Array; }; export type GetTreeData = { body?: never; path?: never; query?: never; url: '/tree'; }; export type GetTreeResponses = { /** * Success */ 200: Array; }; export type GetTreeResponse = GetTreeResponses[keyof GetTreeResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { BarRead, BarReadWritable, BarWrite, BarWriteWritable, Baz, ClientOptions, Corge, CorgeWritable, Foo, Foo2, FooRead, FooReadWritable, FooReadWrite, FooReadWriteRef, FooReadWriteRef2, FooReadWriteRef2Writable, FooReadWriteRefWritable, FooReadWriteWritable, FooWrite, FooWriteWritable, PostFooReadData, PostFooReadResponse, PostFooReadResponses, PostFooReadWriteData, PostFooReadWriteResponse, PostFooReadWriteResponses, PostFooWriteData, PostFooWriteResponse, PostFooWriteResponses, PutFooWriteData, PutFooWriteResponse, PutFooWriteResponses, Quux, QuuxWritable, QuxAllRead, QuxAllWrite } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type FooReadWrite = BarRead; export type FooRead = BarRead & { readonly foo?: string; }; export type FooWrite = BarWrite; export type BarRead = Baz | QuxAllRead | { readonly bar?: string; }; export type BarWrite = Baz | QuxAllRead; export type Baz = { baz?: string; }; export type QuxAllWrite = { baz?: string; }; export type QuxAllRead = { readonly baz?: string; }; export type Quux = { baz?: Array; qux?: QuxAllRead; }; export type Corge = { bar?: { readonly baz?: boolean; }; }; export type FooReadWriteRef = { foo?: FooReadWrite; bar?: FooReadWriteRef; }; export type FooReadWriteRef2 = FooReadWrite; export type FooReadWriteWritable = BarReadWritable & { foo?: string; }; export type FooReadWritable = BarReadWritable; export type FooWriteWritable = BarWriteWritable & { foo?: string; }; export type BarReadWritable = Baz | QuxAllWrite; export type BarWriteWritable = Baz | QuxAllWrite | { bar?: string; }; export type QuuxWritable = { baz?: Array; }; export type CorgeWritable = { foo?: { baz?: boolean; }; }; export type FooReadWriteRefWritable = { foo?: FooReadWriteWritable; bar?: FooReadWriteRefWritable; }; export type FooReadWriteRef2Writable = FooReadWriteWritable; /** * Query parameter */ export type Foo = string; /** * PUT /foo-write payload */ export type Foo2 = { foo?: BarReadWritable; }; export type PostFooReadWriteData = { body: FooReadWriteWritable; path?: never; query?: never; url: '/foo-read-write'; }; export type PostFooReadWriteResponses = { /** * OK */ 200: FooReadWrite; }; export type PostFooReadWriteResponse = PostFooReadWriteResponses[keyof PostFooReadWriteResponses]; export type PostFooReadData = { body: FooReadWritable; path?: never; query?: never; url: '/foo-read'; }; export type PostFooReadResponses = { /** * OK */ 200: FooRead; }; export type PostFooReadResponse = PostFooReadResponses[keyof PostFooReadResponses]; export type PostFooWriteData = { body: FooWriteWritable; path?: never; query?: never; url: '/foo-write'; }; export type PostFooWriteResponses = { /** * OK */ 200: FooWrite; }; export type PostFooWriteResponse = PostFooWriteResponses[keyof PostFooWriteResponses]; export type PutFooWriteData = { /** * PUT /foo-write payload */ body: Foo2; path?: never; query?: { /** * Query parameter */ foo?: string; }; url: '/foo-write'; }; export type PutFooWriteResponses = { /** * OK */ 200: FooWrite; }; export type PutFooWriteResponse = PutFooWriteResponses[keyof PutFooWriteResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write-nested/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, CreateItemRequest, CreateItemRequestWritable, ItemCreateData, ItemCreateResponses, Payload, PayloadWritable } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write-nested/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type CreateItemRequest = { payload: Payload; }; export type Payload = { kind: 'jpeg'; }; export type CreateItemRequestWritable = { payload: PayloadWritable; }; export type PayloadWritable = { kind: 'jpeg'; /** * Data required on write */ encoded: string; }; export type ItemCreateData = { body: CreateItemRequestWritable; path?: never; query?: never; url: '/items'; }; export type ItemCreateResponses = { /** * Created */ 201: unknown; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write-response/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Item, ItemListData, ItemListResponse, ItemListResponse2, ItemListResponses, ItemListResponseWritable, ItemWritable } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write-response/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type ItemListResponse = { items: Array; }; export type Item = { /** * Server-generated ID */ readonly id: string; name: string; /** * Server-generated timestamp */ readonly created_at?: string; }; export type ItemListResponseWritable = { items: Array; }; export type ItemWritable = { name: string; }; export type ItemListData = { body?: never; path?: never; query?: never; url: '/items'; }; export type ItemListResponses = { /** * Success */ 200: ItemListResponse; }; export type ItemListResponse2 = ItemListResponses[keyof ItemListResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write-unevaluated/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, CreateXData, CreateXResponse, CreateXResponses, DisposableEmail, DisposableEmailWritable, GetXData, GetXResponse, GetXResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-read-write-unevaluated/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type DisposableEmail = { domain: string; readonly disposable: boolean; metadata: { [key: string]: unknown; }; }; export type DisposableEmailWritable = { domain: string; metadata: { [key: string]: unknown; }; }; export type GetXData = { body?: never; path?: never; query?: never; url: '/x'; }; export type GetXResponses = { /** * ok */ 200: DisposableEmail; }; export type GetXResponse = GetXResponses[keyof GetXResponses]; export type CreateXData = { body: DisposableEmailWritable; path?: never; query?: never; url: '/x'; }; export type CreateXResponses = { /** * ok */ 200: DisposableEmail; }; export type CreateXResponse = CreateXResponses[keyof CreateXResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-schemas-name/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Comment, GetUsersData, GetUsersResponse, GetUsersResponses, Post, PostPostsData, PostPostsResponse, PostPostsResponses, User, UserProfile } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/transforms-schemas-name/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type User = { id?: string; name?: string; profile?: UserProfile; }; export type UserProfile = { bio?: string; avatar?: string; }; export type Post = { id?: string; title?: string; author?: User; comments?: Array; }; export type Comment = { id?: string; text?: string; author?: User; }; export type GetUsersData = { body?: never; path?: never; query?: never; url: '/users'; }; export type GetUsersResponses = { /** * Success */ 200: User; }; export type GetUsersResponse = GetUsersResponses[keyof GetUsersResponses]; export type PostPostsData = { body?: Post; path?: never; query?: never; url: '/posts'; }; export type PostPostsResponses = { /** * Created */ 201: Post; }; export type PostPostsResponse = PostPostsResponses[keyof PostPostsResponses]; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/type-invalid/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/type-invalid/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = unknown; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/union-types/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, Foo } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/union-types/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Foo = { bar?: number | boolean | string; }; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/webhooks/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ClientOptions, SessionAlertWebhookPayload, SessionAlertWebhookRequest, SessionEndedWebhookPayload, SessionEndedWebhookRequest, SessionLiveStreamingStartedWebhookPayload, SessionLiveStreamingStartedWebhookRequest, SessionLiveStreamingStoppedWebhookPayload, SessionLiveStreamingStoppedWebhookRequest, SessionRecordingCompletedWebhookPayload, SessionRecordingCompletedWebhookRequest, SessionRecordingDeletedWebhookPayload, SessionRecordingDeletedWebhookRequest, SessionRecordingPausedWebhookPayload, SessionRecordingPausedWebhookRequest, SessionRecordingRecoveredWebhookPayload, SessionRecordingRecoveredWebhookRequest, SessionRecordingResumedWebhookPayload, SessionRecordingResumedWebhookRequest, SessionRecordingStartedWebhookPayload, SessionRecordingStartedWebhookRequest, SessionRecordingStoppedWebhookPayload, SessionRecordingStoppedWebhookRequest, SessionRecordingTranscriptCompletedWebhookPayload, SessionRecordingTranscriptCompletedWebhookRequest, SessionRecordingTranscriptFailedWebhookPayload, SessionRecordingTranscriptFailedWebhookRequest, SessionRecordingTrashedWebhookPayload, SessionRecordingTrashedWebhookRequest, SessionSharingEndedWebhookPayload, SessionSharingEndedWebhookRequest, SessionSharingStartedWebhookPayload, SessionSharingStartedWebhookRequest, SessionStartedWebhookPayload, SessionStartedWebhookRequest, SessionStreamIngestionConnectedWebhookPayload, SessionStreamIngestionConnectedWebhookRequest, SessionStreamIngestionDisconnectedWebhookPayload, SessionStreamIngestionDisconnectedWebhookRequest, SessionStreamIngestionStartedWebhookPayload, SessionStreamIngestionStartedWebhookRequest, SessionStreamIngestionStoppedWebhookPayload, SessionStreamIngestionStoppedWebhookRequest, SessionStreamIngestionUnbindWebhookPayload, SessionStreamIngestionUnbindWebhookRequest, SessionUserJoinedWebhookPayload, SessionUserJoinedWebhookRequest, SessionUserLeftWebhookPayload, SessionUserLeftWebhookRequest, SessionUserPhoneCalloutAcceptedWebhookPayload, SessionUserPhoneCalloutAcceptedWebhookRequest, SessionUserPhoneCalloutCanceledWebhookPayload, SessionUserPhoneCalloutCanceledWebhookRequest, SessionUserPhoneCalloutMissedWebhookPayload, SessionUserPhoneCalloutMissedWebhookRequest, SessionUserPhoneCalloutRejectedWebhookPayload, SessionUserPhoneCalloutRejectedWebhookRequest, SessionUserPhoneCalloutRingingWebhookPayload, SessionUserPhoneCalloutRingingWebhookRequest, SessionUserRoomSystemCalloutAcceptedWebhookPayload, SessionUserRoomSystemCalloutAcceptedWebhookRequest, SessionUserRoomSystemCalloutFailedWebhookPayload, SessionUserRoomSystemCalloutFailedWebhookRequest, SessionUserRoomSystemCalloutMissedWebhookPayload, SessionUserRoomSystemCalloutMissedWebhookRequest, SessionUserRoomSystemCalloutRejectedWebhookPayload, SessionUserRoomSystemCalloutRejectedWebhookRequest, SessionUserRoomSystemCalloutRingingWebhookPayload, SessionUserRoomSystemCalloutRingingWebhookRequest, Webhooks } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/webhooks/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type Webhooks = SessionUserPhoneCalloutRingingWebhookRequest | SessionUserRoomSystemCalloutRingingWebhookRequest | SessionRecordingStartedWebhookRequest | SessionRecordingResumedWebhookRequest | SessionLiveStreamingStoppedWebhookRequest | SessionStreamIngestionStoppedWebhookRequest | SessionUserRoomSystemCalloutRejectedWebhookRequest | SessionAlertWebhookRequest | SessionSharingEndedWebhookRequest | SessionRecordingPausedWebhookRequest | SessionEndedWebhookRequest | SessionStartedWebhookRequest | SessionStreamIngestionUnbindWebhookRequest | SessionLiveStreamingStartedWebhookRequest | SessionUserRoomSystemCalloutMissedWebhookRequest | SessionUserPhoneCalloutAcceptedWebhookRequest | SessionUserLeftWebhookRequest | SessionSharingStartedWebhookRequest | SessionUserPhoneCalloutCanceledWebhookRequest | SessionRecordingTranscriptCompletedWebhookRequest | SessionRecordingDeletedWebhookRequest | SessionUserRoomSystemCalloutFailedWebhookRequest | SessionRecordingCompletedWebhookRequest | SessionRecordingTranscriptFailedWebhookRequest | SessionRecordingTrashedWebhookRequest | SessionUserJoinedWebhookRequest | SessionStreamIngestionStartedWebhookRequest | SessionStreamIngestionConnectedWebhookRequest | SessionStreamIngestionDisconnectedWebhookRequest | SessionRecordingRecoveredWebhookRequest | SessionUserPhoneCalloutMissedWebhookRequest | SessionUserPhoneCalloutRejectedWebhookRequest | SessionUserRoomSystemCalloutAcceptedWebhookRequest | SessionRecordingStoppedWebhookRequest; /** * # session.user_phone_callout_ringing * * The **Invited party's phone (call out) ringing** event is triggered every time a user's phone is ringing when they were invited to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party's phone (call out) ringing** subscription enabled under the **Session** event. * * * * * **Event type**: `session.user_phone_callout_ringing` * */ export type SessionUserPhoneCalloutRingingWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * Another identifier for the inviter. Can be a number or characters. */ user_key: string; /** * The user ID of the session host. */ host_id: string; /** * Information about the invited user. */ participant: { /** * The user's name to display in the session. */ invitee_name: string; /** * The user's phone number. */ phone_number: number; /** * The number used to call out to the invited user. */ from_number: number; }; }; }; }; export type SessionUserPhoneCalloutRingingWebhookRequest = { body: SessionUserPhoneCalloutRingingWebhookPayload; key: 'session.user_phone_callout_ringing'; path?: never; query?: never; }; /** * # session.user_room_system_callout_ringing * * The **Invited party's phone (call out) ringing in Zoom room** event is triggered every time a user's phone is ringing when they were invited to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party's phone (call out) ringing in Zoom room** subscription enabled under the **Session** event. * * * * **Event type**: `session.user_room_system_callout_ringing` * */ export type SessionUserRoomSystemCalloutRingingWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The user ID of the session host. */ host_id: string; /** * The request unique identifier (UUID). */ message_id: string; /** * The user name of the event's trigger. */ inviter_name: string; /** * Information about the invited participant. */ participant: { /** * The type of call out. Use a value of h323 or sip. */ call_type: string; /** * The user's device IP address. */ device_ip: string; [key: string]: unknown; }; }; }; }; export type SessionUserRoomSystemCalloutRingingWebhookRequest = { body: SessionUserRoomSystemCalloutRingingWebhookPayload; key: 'session.user_room_system_callout_ringing'; path?: never; query?: never; }; /** * # session.recording_started * --- * * Event: `session.recording_started` * * ## Event description * * The **Session recording started** event is triggered every time a recording is started by one of your app users or account users. * * Only a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * **Session recording started** subscription enabled under the **Recording** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_started` event notification: * * * * **Event type**: `session.recording_started` * */ export type SessionRecordingStartedWebhookPayload = { /** * The event's name. */ event: 'session.recording_started'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; recording_file: { /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; }; }; }; }; export type SessionRecordingStartedWebhookRequest = { body: SessionRecordingStartedWebhookPayload; key: 'session.recording_started'; path?: never; query?: never; }; /** * # session.recording_resumed * --- * * Event: `session.recording_resumed` * * ## Event description * * The **Session recording resumed** event is triggered every time a previously paused recording of a session is resumed. * * Only a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * **Session recording resumed** subscription enabled under the **Recording** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_resumed` event notification: * * * * **Event type**: `session.recording_resumed` * */ export type SessionRecordingResumedWebhookPayload = { /** * The event's name. */ event: 'session.recording_resumed'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; recording_file: { /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; }; }; }; }; export type SessionRecordingResumedWebhookRequest = { body: SessionRecordingResumedWebhookPayload; key: 'session.recording_resumed'; path?: never; query?: never; }; /** * # session.live_streaming_stopped * --- * * * The Session Live Streaming Stopped event is triggered every time a user stops a live stream. * * ## Prerequisites * Event Subscriptions must be enabled for your app with the following configurations: * * * A valid Event Notification Endpoint URL. * * **Session Live Streaming Stopped** subscription enabled under the **Video SDK** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.live_streaming_stopped` event notification: * * * * **Event type**: `session.live_streaming_stopped` * */ export type SessionLiveStreamingStoppedWebhookPayload = { /** * The name of the event. */ event: 'session.live_streaming_stopped'; /** * Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * The session's start time. */ start_time: string; /** * Information about the participant. */ live_streaming: { /** * The name of the Live Streaming service. */ service: 'Facebook' | 'Workplace_by_Facebook' | 'YouTube' | 'Custom_Live_Streaming_Service'; /** * The live stream settings. */ custom_live_streaming_settings: { /** * The stream's URL. */ stream_url: string; /** * The stream's Key. */ stream_key: string; /** * The live stream's page URL. */ page_url: string; /** * The number of pixels in each dimension that the video camera can display. */ resolution?: string; }; /** * The live stream's stop time. */ date_time: string; }; }; }; }; export type SessionLiveStreamingStoppedWebhookRequest = { body: SessionLiveStreamingStoppedWebhookPayload; key: 'session.live_streaming_stopped'; path?: never; query?: never; }; /** * # session.stream_ingestion_stopped * Zoom triggers the **Session stream ingestion stopped** event every time a user stops sending live incoming streams. * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Session stream ingestion stopped** subscription enabled under the **Video SDK** event. * * * **Event type**: `session.stream_ingestion_stopped` * */ export type SessionStreamIngestionStoppedWebhookPayload = { /** * Event name. */ event: 'session.stream_ingestion_stopped'; /** * Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the stream ingestion. */ stream_ingestion: { /** * The stream ingestion ID. */ stream_id: string; /** * The stream ingestion name. */ stream_name: string; /** * The stream ingestion description. */ stream_description?: string; /** * The stream ingestion key. */ stream_key: string; /** * The stream URL. */ stream_url: string; /** * The backup stream URL. */ backup_stream_url: string; }; }; }; }; export type SessionStreamIngestionStoppedWebhookRequest = { body: SessionStreamIngestionStoppedWebhookPayload; key: 'session.stream_ingestion_stopped'; path?: never; query?: never; }; /** * # session.user_room_system_callout_rejected * * The **Invited party rejected a session invitation through phone (call out) via Zoom room** event is triggered every time a user rejects an invitation to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party rejected a session invitation through phone (call out) via Zoom room** subscription enabled under the **Session** event. * * * * **Event type**: `session.user_room_system_callout_rejected` * */ export type SessionUserRoomSystemCalloutRejectedWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The user ID of the session host. */ host_id: string; /** * The request unique identifier (UUID). */ message_id: string; /** * The user name of the event's trigger. */ inviter_name: string; /** * Information about the invited participant. */ participant: { /** * The type of call out. Use a value of h323 or sip. */ call_type: string; /** * The user's device IP address. */ device_ip: string; [key: string]: unknown; }; }; }; }; export type SessionUserRoomSystemCalloutRejectedWebhookRequest = { body: SessionUserRoomSystemCalloutRejectedWebhookPayload; key: 'session.user_room_system_callout_rejected'; path?: never; query?: never; }; /** * # session.alert * --- * * * The Session Alert event is triggered every time a service issue is encountered during a session in your account. * * The following quality metrics can trigger an alert: * * * Unstable audio quality * * Unstable video quality * * Unstable screen share quality * * High CPU occupation * * Call Reconnection * * ## Prerequisites * Event Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations: * * * A valid Event Notification Endpoint URL. * * Session Alert subscription enabled under the Video SDK event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.alert` event notification: * * * **Event type**: `session.alert` * */ export type SessionAlertWebhookPayload = { /** * The event's name. */ event: 'session.alert'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * The session ID. */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Issues that occurred during the session. */ issues: Array<'Unstable audio quality' | 'Unstable video quality' | 'Unstable screen share quality' | 'High CPU occupation' | 'Call Reconnection'>; }; }; }; export type SessionAlertWebhookRequest = { body: SessionAlertWebhookPayload; key: 'session.alert'; path?: never; query?: never; }; /** * # session.sharing_ended * --- * * * The Session Sharing Ended event is triggered every time a user stops sharing the screen during a session. * * ## Prerequisites * Event Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations: * * * A valid Event Notification Endpoint URL. * * **Session Sharing Ended** subscription enabled under the **Video SDK** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.sharing_ended` event notification: * * * * **Event type**: `session.sharing_ended` * */ export type SessionSharingEndedWebhookPayload = { /** * The event's name. */ event: 'session.sharing_ended'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * The session ID. * * @deprecated */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the user. */ user: { /** * The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session. */ id: string; /** * The user's username. */ name: string; /** * Another identifier for the user. Can be a number or characters. */ user_key?: string; /** * Information about the session's screen sharing. */ sharing_details: { /** * The type of shared content: * * application — An application. For example, a web browser. * * whiteboard — The Zoom [whiteboard](https://support.zoom.us/hc/en-us/articles/205677665-Sharing-a-whiteboard). * * desktop — A user's desktop. * * unknown — An unrecognized application, such as a third party app. */ content: 'application' | 'whiteboard' | 'desktop' | 'unknown'; /** * The session's screen sharing date and time. */ date_time: string; }; }; }; }; }; export type SessionSharingEndedWebhookRequest = { body: SessionSharingEndedWebhookPayload; key: 'session.sharing_ended'; path?: never; query?: never; }; /** * # session.recording_paused * --- * * Event: `session.recording_paused` * * ## Event description * * The **Session recording paused** event is triggered every time a recording is paused by one of your app or account users. * * Only a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * "**Session recording paused**" subscription enabled under the **Recording** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_paused` event notification: * * * * **Event type**: `session.recording_paused` * */ export type SessionRecordingPausedWebhookPayload = { /** * The event's name. */ event: 'session.recording_paused'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; recording_file: { /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; }; }; }; }; export type SessionRecordingPausedWebhookRequest = { body: SessionRecordingPausedWebhookPayload; key: 'session.recording_paused'; path?: never; query?: never; }; /** * # session.ended * --- * * * The Session Ended event is triggered when the host ends the session, or when all users have left the session. * * ## Prerequisites * Event Subscriptions must be enabled for your app with the following configurations: * * * A valid Event Notification Endpoint URL. * * **Session Ended** subscription enabled under the **Video SDK** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.ended` event notification: * * * * **Event type**: `session.ended` * */ export type SessionEndedWebhookPayload = { /** * The name of the event. */ event: 'session.ended'; /** * Timestamp at which the event occurred, in milliseconds since epoch. The value of this field is returned in long(int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * The session's start time. */ start_time: string; /** * The session's end time. */ end_time: string; }; }; }; export type SessionEndedWebhookRequest = { body: SessionEndedWebhookPayload; key: 'session.ended'; path?: never; query?: never; }; /** * # session.started * --- * * * The Session Start event is triggered when the first user (including host and co-host) joins. * * ## Prerequisites * Event Subscriptions must be enabled for your app with the following configurations: * * * A valid Event Notification Endpoint URL. * * **Session Started** subscription enabled under the **Video SDK** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.started` event notification: * * * * **Event type**: `session.started` * */ export type SessionStartedWebhookPayload = { /** * The name of the event. */ event: 'session.started'; /** * Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * The session's ID. * * @deprecated */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * The session's start time. */ start_time: string; }; }; }; export type SessionStartedWebhookRequest = { body: SessionStartedWebhookPayload; key: 'session.started'; path?: never; query?: never; }; /** * # session.stream_ingestion_unbind * Zoom triggers the **Session stream ingestion unbind** event every time a session unbinds a stream key. * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Session stream ingestion unbind** subscription enabled under the **Video SDK** event. * * * **Event type**: `session.stream_ingestion_unbind` * */ export type SessionStreamIngestionUnbindWebhookPayload = { /** * Event name. */ event: 'session.stream_ingestion_unbind'; /** * Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long (int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the stream ingestion. */ stream_ingestion: { /** * The stream ingestion ID. */ stream_id: string; /** * The stream ingestion name. */ stream_name: string; /** * The stream ingestion description. */ stream_description?: string; /** * The stream ingestion key. */ stream_key: string; /** * The stream URL. */ stream_url: string; /** * The backup stream URL. */ backup_stream_url: string; }; }; }; }; export type SessionStreamIngestionUnbindWebhookRequest = { body: SessionStreamIngestionUnbindWebhookPayload; key: 'session.stream_ingestion_unbind'; path?: never; query?: never; }; /** * # session.live_streaming_started * --- * * * The Session Live Streaming Started event is triggered every time a user starts a live stream. * * ## Prerequisites * Event Subscriptions must be enabled for your app with the following configurations: * * * A valid Event Notification Endpoint URL. * * **Session Live Streaming Started** subscription enabled under the **Video SDK** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.live_streaming_started` event notification: * * * * **Event type**: `session.live_streaming_started` * */ export type SessionLiveStreamingStartedWebhookPayload = { /** * Name of the event. */ event: 'session.live_streaming_started'; /** * Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * The session's start time. */ start_time: string; /** * Information about the participant. */ live_streaming: { /** * The name of the Live Streaming service. */ service: 'Facebook' | 'Workplace_by_Facebook' | 'YouTube' | 'Custom_Live_Streaming_Service'; /** * The live stream settings. */ custom_live_streaming_settings: { /** * The stream's URL. */ stream_url: string; /** * The stream's key. */ stream_key: string; /** * The live stream's page URL. */ page_url: string; /** * The number of pixels in each dimension that the video camera can display. */ resolution?: string; }; /** * The live stream's start time. */ date_time: string; }; }; }; }; export type SessionLiveStreamingStartedWebhookRequest = { body: SessionLiveStreamingStartedWebhookPayload; key: 'session.live_streaming_started'; path?: never; query?: never; }; /** * # session.user_room_system_callout_missed * * The **Invited party missed a session invitation through phone (call out) via Zoom room** event is triggered every time an invitation to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035) times out. * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party missed a session invitation through phone (call out) via Zoom room** subscription enabled under the **Session** event. * * * * **Event type**: `session.user_room_system_callout_missed` * */ export type SessionUserRoomSystemCalloutMissedWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The user ID of the session host. */ host_id: string; /** * The request unique identifier (UUID). */ message_id: string; /** * The user name of the event's trigger. */ inviter_name: string; /** * Information about the invited participant. */ participant: { /** * The type of call out. Use a value of h323 or sip. */ call_type: string; /** * The user's device IP address. */ device_ip: string; [key: string]: unknown; }; }; }; }; export type SessionUserRoomSystemCalloutMissedWebhookRequest = { body: SessionUserRoomSystemCalloutMissedWebhookPayload; key: 'session.user_room_system_callout_missed'; path?: never; query?: never; }; /** * # session.user_phone_callout_accepted * * The **Invited party answered a session invitation through phone (call out)** event is triggered every time a user accepts an invitation to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party answered a session invitation through phone (call out)** subscription enabled under the **Session** event. * * * * **Event type**: `session.user_phone_callout_accepted` * */ export type SessionUserPhoneCalloutAcceptedWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * Another identifier for the inviter. Can be a number or characters. */ user_key: string; /** * The user ID of the session host. */ host_id: string; /** * Information about the invited participant. */ participant: { /** * The user's name to display in the session. */ invitee_name: string; /** * The user's phone number. */ phone_number: number; /** * The number used to call out to the invited user. */ from_number: number; }; }; }; }; export type SessionUserPhoneCalloutAcceptedWebhookRequest = { body: SessionUserPhoneCalloutAcceptedWebhookPayload; key: 'session.user_phone_callout_accepted'; path?: never; query?: never; }; /** * # session.user_left * * * The Session User Left event is triggered every time a user (including host and co-host) leaves a session. * * ## Prerequisites * Event Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations: * * * A valid Event Notification Endpoint URL. * * Session User Left subscription enabled under the Video SDK event. * * * * **Event type**: `session.user_left` * */ export type SessionUserLeftWebhookPayload = { /** * The event's name. */ event: 'session.user_left'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * The session ID. */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the user. */ user: { /** * The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session. */ id: string; /** * The user's username. */ name: string; /** * The time at which the user left the session. */ leave_time: string; /** * The reason why the user left the session, where $name is the participant's username: * * $name left the session. * * $name got disconnected from the session. * * Host ended the session. * * Host closed the session. * * Host started a new session. * * Network connection error. * * Host did not join. * * Exceeded free session minutes limit. * * Removed by host. * * Unknown reason. * * Leave waiting room. * * Removed by host from waiting room. */ leave_reason?: string; /** * Another identifier for the user. Can be a number or characters. */ user_key?: string; /** * Phone number of participant joined via PSTN. */ phone_number?: string; /** * The participant's UUID. This value is assigned to a participant upon joining a session and is only valid for the session's duration. */ participant_uuid: string; }; }; }; }; export type SessionUserLeftWebhookRequest = { body: SessionUserLeftWebhookPayload; key: 'session.user_left'; path?: never; query?: never; }; /** * # session.sharing_started * * * The Session Sharing Started event is triggered every time a user starts sharing the screen during a session. * * ## Prerequisites * Event Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations: * * * A valid Event Notification Endpoint URL. * * **Session Sharing Started** subscription enabled under the **Video SDK** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.sharing_started` event notification: * * * * **Event type**: `session.sharing_started` * */ export type SessionSharingStartedWebhookPayload = { /** * The event's name. */ event: 'session.sharing_started'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * The session ID. */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the user. */ user: { /** * The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session. */ id: string; /** * The user's username. */ name: string; /** * Another identifier for the user. Can be a number or characters. */ user_key?: string; /** * Information about the session's screen sharing. */ sharing_details: { /** * The type of shared content: * * application — An application. For example, a web browser. * * whiteboard — The Zoom [whiteboard](https://support.zoom.us/hc/en-us/articles/205677665-Sharing-a-whiteboard). * * desktop — A user's desktop. * * unknown — An unrecognized application, such as a third party app. */ content: 'application' | 'whiteboard' | 'desktop' | 'unknown'; /** * The session's screen sharing date and time. */ date_time: string; }; }; }; }; }; export type SessionSharingStartedWebhookRequest = { body: SessionSharingStartedWebhookPayload; key: 'session.sharing_started'; path?: never; query?: never; }; /** * # session.user_phone_callout_canceled * The **Invited party's phone (call out) canceled** event is triggered every time the inviter cancels the call out when they were invited to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party's phone (call out) canceled** subscription enabled under the **Session** event. * * * **Event type**: `session.user_phone_callout_canceled` * */ export type SessionUserPhoneCalloutCanceledWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * Another identifier for the inviter. Can be a number or characters. */ user_key: string; /** * Information about the invited participant. */ participant: { /** * The user's name to display in the session. */ invitee_name: string; /** * The user's phone number. */ phone_number: number; /** * The number used to call out to the invited user. */ from_number: number; }; }; }; }; export type SessionUserPhoneCalloutCanceledWebhookRequest = { body: SessionUserPhoneCalloutCanceledWebhookPayload; key: 'session.user_phone_callout_canceled'; path?: never; query?: never; }; /** * # session.recording_transcript_completed * --- * * Event: `session.recording_transcript_completed` * * ## Event description * * The **Session recording transcript completed** event is triggered every time the transcript of the recording of a session becomes available to view or download. * * Only a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * Session recording transcript completed subscription enabled under the Recording event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_transcript_completed` event notification: * * * * **Event type**: `session.recording_transcript_completed` * */ export type SessionRecordingTranscriptCompletedWebhookPayload = { /** * The event's name. */ event: 'session.recording_transcript_completed'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; /** * A generated token used to download the recording. The download token only lasts for 24 hours after its creation and you can only download the file within 24 hours of receiving the event notification. You can either pass the download_token as a Bearer token in the Authorization header of your HTTP request (recommended) or include it as a query parameter. See the following for examples. * * **Using an Authorization header (Recommended)** * * * curl --request GET \ * --url {download_url} \ * --header 'authorization: Bearer {download_token} \ * --header 'content-type: application/json' * * * **Using a query parameter** * * * {download_url}/?access_token={download_token} * * * For example: https://zoom.us/recording/download/123456?access_token=abcdefgh */ download_token: string; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; /** * Recording file List * * List of recording file. */ recording_files: Array<{ /** * The recording file ID. Included in the response of general query. */ id?: string; /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; /** * Name of the file. */ file_name?: string; /** * The file path to the On-Premise account recording. * * **Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field. */ file_path?: string; /** * The recording file type. The value of this field could be one of the following:
    * MP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the "Add a timestamp to the recording" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile. *
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format. * *
    * * A recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    * id, status, file_size, recording_type. */ file_type?: 'MP4' | 'M4A' | 'CHAT' | 'TRANSCRIPT' | 'CSV' | 'CC' | 'TB' | 'CHAT_MESSAGE' | 'TIMELINE'; /** * The recording file size. */ file_size?: number; /** * The archived file's file extension. */ file_extension?: 'MP4' | 'M4A' | 'TXT' | 'VTT' | 'CSV' | 'JSON' | 'JPG'; /** * The URL at which to download the the recording. * * To access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). You can either pass the generated JWT as a Bearer token in the Authorization header of your HTTP request (recommended) or include it as a query parameter at the end of the URL. See the following for examples. * * **Using an Authorization header (Recommended)** * * * curl --request GET \ * --url {download_url} \ * --header 'authorization: Bearer {JWT} \ * --header 'content-type: application/json' * * * **Using a query parameter** * * * {download_url}/?access_token={download_token} * * * For example: https://{base-domain}/recording/download/{path-to-file-download}?access_token={JWT}. */ download_url?: string; /** * The recording status. */ status?: 'completed'; /** * The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption */ recording_type?: 'shared_screen_with_speaker_view(CC)' | 'shared_screen_with_speaker_view' | 'shared_screen_with_gallery_view' | 'gallery_view' | 'shared_screen' | 'audio_only' | 'audio_transcript' | 'chat_file' | 'active_speaker' | 'host_video' | 'audio_only_each_participant' | 'cc_transcript' | 'closed_caption' | 'poll' | 'timeline' | 'thumbnail' | 'chat_message'; }>; }; }; }; export type SessionRecordingTranscriptCompletedWebhookRequest = { body: SessionRecordingTranscriptCompletedWebhookPayload; key: 'session.recording_transcript_completed'; path?: never; query?: never; }; /** * # session.recording_deleted * --- * * Event: `session.recording_deleted` * * ## Event description * * The **Session recording permanently deleted** event is triggered every time one of your app users or account users permanently deletes a cloud recording. * * When a user initially deletes a recording, it is sent to the trash. At this stage, the recording can still be recovered for up to 30 days after deletion. To permanently delete a recording, users must delete it from the trash. Users can permanently delete a recording using: * * * The [Delete session's recording API](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingDelete) **with the delete query parameter** or * * The Zoom web portal. See [Video SDK account](https://developers.zoom.us/docs/video-sdk/account/) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * "**Session recording permanently deleted**" subscription enabled under the **Recording** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_deleted` event notification: * * * * **Event type**: `session.recording_deleted` * */ export type SessionRecordingDeletedWebhookPayload = { /** * The event's name. */ event: 'session.recording_deleted'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * The email address of the user who deleted the recording. */ operator: string; /** * The user ID of the user who deleted the recording. */ operator_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; }; }; }; export type SessionRecordingDeletedWebhookRequest = { body: SessionRecordingDeletedWebhookPayload; key: 'session.recording_deleted'; path?: never; query?: never; }; /** * # session.user_room_system_callout_failed * * The **Session invitation through phone (call out) via Zoom room failed** event is triggered every time an invitation to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035) fails. * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Session invitation through phone (call out) via Zoom room failed** subscription enabled under the **Session** event. * * * * **Event type**: `session.user_room_system_callout_failed` * */ export type SessionUserRoomSystemCalloutFailedWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The user ID of the session host. */ host_id: string; /** * The request unique identifier (UUID). */ message_id: string; /** * The user name of the event's trigger. */ inviter_name: string; /** * reason type for failure: * * 1 — Encryption_Fail. * * 2 — Disconnected_By_Remote. * * 3 — Retry. * * 4 — Bad_Seq. * * 5 — Call_Limit. * * 6 — Not_Registered. * * 7 — Timeout. * * 8 — Bad_Addr. * * 9 — Unreachable * * 10 — Disconnect_By_Local * * 11 — Server_Internal_Error * * 12 — Exceed_Free_Port * * 13 — Connect_Error * * 14 — Proxy_Connect_Error * * 0 — Other_Failed_Reason. */ reason_type: 0 | 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14; /** * Information about the invited participant. */ participant: { /** * The type of call out. Use a value of h323 or sip. */ call_type: string; /** * The user's device IP address. */ device_ip: string; [key: string]: unknown; }; }; }; }; export type SessionUserRoomSystemCalloutFailedWebhookRequest = { body: SessionUserRoomSystemCalloutFailedWebhookPayload; key: 'session.user_room_system_callout_failed'; path?: never; query?: never; }; /** * # session.recording_completed * --- * * Event: `session.recording_completed` * * ## Event description * * The **Session recording completed** event is triggered every time a recording of a session becomes available to view and/or download. * * Only a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * Session recording completed subscription enabled under the Recording event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_completed` event notification: * * * * **Event type**: `session.recording_completed` * */ export type SessionRecordingCompletedWebhookPayload = { /** * The event's name. */ event: 'session.recording_completed'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; /** * A generated token used to download the recording. The download token only lasts for 24 hours after its creation and you can only download the file within 24 hours of receiving the event notification. Pass the download_token as a Bearer token in the Authorization header of your HTTP request. For example: * * * curl --request GET \ * --url {download_url} \ * --header 'authorization: Bearer {download_token} \ * --header 'content-type: application/json' * */ download_token: string; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; /** * Recording file List * * List of recording file. */ recording_files: Array<{ /** * The recording file ID. Included in the response of general query. */ id?: string; /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; /** * Name of the file. */ file_name?: string; /** * The file path to the On-Premise account recording. * * **Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field. */ file_path?: string; /** * The recording file type. The value of this field could be one of the following:
    * MP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the "Add a timestamp to the recording" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile. *
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format. * *
    * * A recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    * id, status, file_size, recording_type. */ file_type?: 'MP4' | 'M4A' | 'CHAT' | 'TRANSCRIPT' | 'CSV' | 'CC' | 'TB' | 'CHAT_MESSAGE'; /** * The recording file size. */ file_size?: number; /** * The archived file's file extension. */ file_extension?: 'MP4' | 'M4A' | 'TXT' | 'VTT' | 'CSV' | 'JSON' | 'JPG'; /** * The URL at which to download the the recording. * * To access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: * * * curl --request GET \ * --url {download_url} \ * --header 'authorization: Bearer {JWT} \ * --header 'content-type: application/json' * */ download_url?: string; /** * The recording status. */ status?: 'completed'; /** * The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption */ recording_type?: 'shared_screen_with_speaker_view(CC)' | 'shared_screen_with_speaker_view' | 'shared_screen_with_gallery_view' | 'gallery_view' | 'shared_screen' | 'audio_only' | 'audio_transcript' | 'chat_file' | 'active_speaker' | 'host_video' | 'audio_only_each_participant' | 'cc_transcript' | 'closed_caption' | 'poll' | 'timeline' | 'thumbnail' | 'chat_message'; }>; /** * Recording file List * * List of recording file. */ participant_audio_files?: Array<{ /** * The recording file ID. Included in the response of general query. */ id?: string; /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; /** * Name of the file. */ file_name?: string; /** * The file path to the On-Premise account recording. * * **Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field. */ file_path?: string; /** * The recording file type. The value of this field could be one of the following:
    * MP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the "Add a timestamp to the recording" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile. *
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format. * *
    * * A recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    * id, status, file_size, recording_type. */ file_type?: 'MP4' | 'M4A' | 'CHAT' | 'TRANSCRIPT' | 'CSV' | 'CC' | 'TB' | 'CHAT_MESSAGE'; /** * The recording file size. */ file_size?: number; /** * The archived file's file extension. */ file_extension?: 'MP4' | 'M4A' | 'TXT' | 'VTT' | 'CSV' | 'JSON' | 'JPG'; /** * The URL at which to download the the recording. * * To access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: * * * curl --request GET \ * --url {download_url} \ * --header 'authorization: Bearer {JWT} \ * --header 'content-type: application/json' * */ download_url?: string; /** * The recording status. */ status?: 'completed'; /** * The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption */ recording_type?: 'shared_screen_with_speaker_view(CC)' | 'shared_screen_with_speaker_view' | 'shared_screen_with_gallery_view' | 'gallery_view' | 'shared_screen' | 'audio_only' | 'audio_transcript' | 'chat_file' | 'active_speaker' | 'host_video' | 'audio_only_each_participant' | 'cc_transcript' | 'closed_caption' | 'poll' | 'timeline' | 'thumbnail' | 'chat_message'; /** * The participant's session user ID. This value is assigned to a participant upon joining a session and is only valid for the duration of the session. */ user_id?: string; /** * The participant's SDK identifier. Set with the user_identity key in the Video SDK JWT payload. This value can be alphanumeric, up to a maximum length of 35 characters. */ user_key?: string; }>; /** * Recording file List * * List of recording file. */ participant_video_files?: Array<{ /** * The recording file ID. Included in the response of general query. */ id?: string; /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; /** * Name of the file. */ file_name?: string; /** * The file path to the On-Premise account recording. * * **Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field. */ file_path?: string; /** * The recording file type. The value of this field could be one of the following:
    * MP4: Video file of the recording. */ file_type?: 'MP4'; /** * The recording file size. */ file_size?: number; /** * The archived file's file extension. */ file_extension?: 'MP4'; /** * The URL at which to download the the recording. * * To access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: * * * curl --request GET \ * --url {download_url} \ * --header 'authorization: Bearer {JWT} \ * --header 'content-type: application/json' * */ download_url?: string; /** * The recording status. */ status?: 'completed'; /** * The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption */ recording_type?: 'individual_user' | 'individual_shared_screen'; /** * The participant's session user ID. This value is assigned to a participant upon joining a session and is only valid for the duration of the session. */ user_id?: string; /** * The participant's SDK identifier. Set with the user_identity key in the Video SDK JWT payload. This value can be alphanumeric, up to a maximum length of 35 characters. */ user_key?: string; }>; }; }; }; export type SessionRecordingCompletedWebhookRequest = { body: SessionRecordingCompletedWebhookPayload; key: 'session.recording_completed'; path?: never; query?: never; }; /** * # session.recording_transcript_failed * --- * * Event: `session.recording_transcript_failed` * * ## Event description * * The **Session recording transcript failed** event is triggered every time the transcript of the recording of a session generated failed. * * Only a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details. * * ## Prerequisites * * * Enable Cloud Recording on the Video SDK account. * * Enable Event Subscriptions for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * Enable session recording transcript completed subscription under the Recording event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_transcript_completed` event notification: * * * * **Event type**: `session.recording_transcript_failed` * */ export type SessionRecordingTranscriptFailedWebhookPayload = { /** * The event's name. */ event: 'session.recording_transcript_failed'; /** * A timestamp, in milliseconds since epoch, when the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time when the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; }; }; }; export type SessionRecordingTranscriptFailedWebhookRequest = { body: SessionRecordingTranscriptFailedWebhookPayload; key: 'session.recording_transcript_failed'; path?: never; query?: never; }; /** * # session.recording_trashed * --- * * Event: `session.recording_trashed` * * ## Event description * * The **Session recording deleted to trash** event is triggered every time one of your app users or account users temporarily delete a cloud recording. * * When a user initially deletes a recording, it is deleted to the trash. Recordings deleted to the trash can be recovered up to 30 days after deletion. Users can move a recording to the trash using: * * * The [Delete session's recording](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingDelete) API **with the trash query parameter** or * * The Zoom web portal. See [Video SDK account](https://developers.zoom.us/docs/video-sdk/account/) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * **Session recording deleted to trash** subscription enabled under the **Recording** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_trashed` event notification: * * * * **Event type**: `session.recording_trashed` * */ export type SessionRecordingTrashedWebhookPayload = { /** * The event's name. */ event: 'session.recording_trashed'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * The email address of the user who deleted the recording. */ operator: string; /** * The user ID of the user who deleted the recording. */ operator_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; }; }; }; export type SessionRecordingTrashedWebhookRequest = { body: SessionRecordingTrashedWebhookPayload; key: 'session.recording_trashed'; path?: never; query?: never; }; /** * # session.user_joined * --- * * * The Session User Joined event is triggered every time a user (including host and co-host) joins a session. * * ## Prerequisites * Event Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations: * * * A valid Event Notification Endpoint URL. * * Session User Joined subscription enabled under the Video SDK event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.user_joined` event notification: * * * * **Event type**: `session.user_joined` * */ export type SessionUserJoinedWebhookPayload = { /** * The event's name. */ event: 'session.user_joined'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * The session ID. */ id: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the user. */ user: { /** * The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session. */ id: string; /** * The user's username. */ name: string; /** * The time at which the user joined the session. */ join_time: string; /** * Another identifier for the user. Can be a number or characters. */ user_key?: string; /** * Phone number of participant joined via PSTN. */ phone_number?: string; /** * The participant's UUID. This value is assigned to a participant upon joining a session and is only valid for the session's duration. */ participant_uuid: string; }; }; }; }; export type SessionUserJoinedWebhookRequest = { body: SessionUserJoinedWebhookPayload; key: 'session.user_joined'; path?: never; query?: never; }; /** * # session.stream_ingestion_started * Zoom triggers the **Session stream ingestion started** event every time a host starts sending an incoming live stream to a session. The session user can subscribe to it to see what's being streamed live into this session. * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Session stream ingestion started** subscription enabled under the **Video SDK** event. * * * **Event type**: `session.stream_ingestion_started` * */ export type SessionStreamIngestionStartedWebhookPayload = { /** * Event name. */ event: 'session.stream_ingestion_started'; /** * Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the stream ingestion. */ stream_ingestion: { /** * The stream ingestion ID. */ stream_id: string; /** * The stream ingestion name. */ stream_name: string; /** * The stream ingestion description. */ stream_description?: string; /** * The stream ingestion key. */ stream_key: string; /** * The stream URL. */ stream_url: string; /** * The backup stream URL. */ backup_stream_url: string; }; }; }; }; export type SessionStreamIngestionStartedWebhookRequest = { body: SessionStreamIngestionStartedWebhookPayload; key: 'session.stream_ingestion_started'; path?: never; query?: never; }; /** * # session.stream_ingestion_connected * Zoom triggers the **Session stream ingestion connected** event every time live streaming software connects to the Zoom Video SDK session. This indicates that the Zoom streaming platform is receiving data from the streaming software, but the received Real-Time Messaging Protocol (RTMP) data is not sent to the session yet. * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Session stream ingestion connected** subscription enabled under the **Video SDK** event. * * * **Event type**: `session.stream_ingestion_connected` * */ export type SessionStreamIngestionConnectedWebhookPayload = { /** * Name of the event. */ event: 'session.stream_ingestion_connected'; /** * Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the stream ingestion. */ stream_ingestion: { /** * The stream ingestion ID. */ stream_id: string; /** * The stream ingestion name. */ stream_name: string; /** * The stream ingestion description. */ stream_description?: string; /** * The stream ingestion key. */ stream_key: string; /** * The stream URL. */ stream_url: string; /** * The backup stream URL. */ backup_stream_url: string; }; }; }; }; export type SessionStreamIngestionConnectedWebhookRequest = { body: SessionStreamIngestionConnectedWebhookPayload; key: 'session.stream_ingestion_connected'; path?: never; query?: never; }; /** * # session.stream_ingestion_disconnected * Zoom triggers the **Session stream ingestion disconnected** event every time a Real-Time Messaging Protocol (RTMP) software program disconnects. * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Session stream ingestion disconnected** subscription enabled under the **Video SDK** event. * * * **Event type**: `session.stream_ingestion_disconnected` * */ export type SessionStreamIngestionDisconnectedWebhookPayload = { /** * Name of the event. */ event: 'session.stream_ingestion_disconnected'; /** * Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key?: string; /** * Information about the stream ingestion. */ stream_ingestion: { /** * The stream ingestion ID. */ stream_id: string; /** * The stream ingestion name. */ stream_name: string; /** * The stream ingestion description. */ stream_description?: string; /** * The stream ingestion key. */ stream_key: string; /** * The stream URL. */ stream_url: string; /** * The backup stream URL. */ backup_stream_url: string; }; }; }; }; export type SessionStreamIngestionDisconnectedWebhookRequest = { body: SessionStreamIngestionDisconnectedWebhookPayload; key: 'session.stream_ingestion_disconnected'; path?: never; query?: never; }; /** * # session.recording_recovered * --- * * Event: `session.recording_recovered` * * ## Event description * * The **Session recording recovered** event is triggered every time one of your app users or account users recover a recording from the trash. * * Zoom allows users to recover their cloud recordings from trash within 30 days of deletion. You can recover a deleted cloud recording with: * * * The tab in the Zoom web client. See [Video SDK recordings and reports](https://developers.zoom.us/docs/video-sdk/reports/) for details. * * The [Recover a single recording](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingStatusUpdateOne) or [Recover session's recordings](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingStatusUpdate) API. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * "**Session recording recovered**" subscription enabled under the **Recording** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_recovered` event notification: * * * * **Event type**: `session.recording_recovered` * */ export type SessionRecordingRecoveredWebhookPayload = { /** * The event's name. */ event: 'session.recording_recovered'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * The email address of the user who deleted the recording. */ operator: string; /** * The user ID of the user who deleted the recording. */ operator_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; }; }; }; export type SessionRecordingRecoveredWebhookRequest = { body: SessionRecordingRecoveredWebhookPayload; key: 'session.recording_recovered'; path?: never; query?: never; }; /** * # session.user_phone_callout_missed * * The **Invited party missed a session invitation through phone (call out)** event is triggered every time an invitation to join a session through phone (call out) times out. Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party missed a session invitation through phone (call out)** subscription enabled under the **Session** event. * * * * * **Event type**: `session.user_phone_callout_missed` * */ export type SessionUserPhoneCalloutMissedWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * Another identifier for the inviter. Can be a number or characters. */ user_key: string; /** * The user ID of the session host. */ host_id: string; /** * Information about the invited user. */ participant: { /** * The user's name to display in the session. */ invitee_name: string; /** * The user's phone number. */ phone_number: number; /** * The number used to call out to the invited user. */ from_number: number; }; }; }; }; export type SessionUserPhoneCalloutMissedWebhookRequest = { body: SessionUserPhoneCalloutMissedWebhookPayload; key: 'session.user_phone_callout_missed'; path?: never; query?: never; }; /** * # session.user_phone_callout_rejected * * The **Invited party rejected a session invitation through phone (call out)** event is triggered every time a user rejects an invitation to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party rejected a session invitation through phone (call out)** subscription enabled under the **Session** event. * * * * * **Event type**: `session.user_phone_callout_rejected` * */ export type SessionUserPhoneCalloutRejectedWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * Another identifier for the inviter. Can be a number or characters. */ user_key: string; /** * The user ID of the session host. */ host_id: string; /** * Information about the invited user. */ participant: { /** * The user's name to display in the session. */ invitee_name: string; /** * The user's phone number. */ phone_number: number; /** * The number used to call out to the invited user. */ from_number: number; }; }; }; }; export type SessionUserPhoneCalloutRejectedWebhookRequest = { body: SessionUserPhoneCalloutRejectedWebhookPayload; key: 'session.user_phone_callout_rejected'; path?: never; query?: never; }; /** * # session.user_room_system_callout_accepted * * The **Invited party answered a session invitation through phone (call out) via Zoom room** event is triggered every time a user [joins a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035). * * ## Prerequisites * * * **Event Subscriptions** must be enabled for your app with the following configurations: * * A valid **Event Notification Endpoint URL**. * * The **Invited party answered a session invitation through phone (call out) via Zoom room** subscription enabled under the **Session** event. * * * * **Event type**: `session.user_room_system_callout_accepted` * */ export type SessionUserRoomSystemCalloutAcceptedWebhookPayload = { /** * The name of the event. */ event: string; /** * A timestamp at which the event occurred. */ event_ts: number; payload: { /** * The account ID of the session host. */ account_id: string; /** * Information about the session. */ object: { /** * The session ID. * * @deprecated */ id?: number; /** * The session's universally unique identifier (UUID). Each session instance generates a session UUID. * * @deprecated */ uuid?: string; /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The user ID of the session host. */ host_id: string; /** * The request unique identifier (UUID). */ message_id: string; /** * The user name of the event's trigger. */ inviter_name: string; /** * Information about the invited participant. */ participant: { /** * The type of call out. Use a value of h323 or sip. */ call_type: string; /** * The user's device IP address. */ device_ip: string; [key: string]: unknown; }; }; }; }; export type SessionUserRoomSystemCalloutAcceptedWebhookRequest = { body: SessionUserRoomSystemCalloutAcceptedWebhookPayload; key: 'session.user_room_system_callout_accepted'; path?: never; query?: never; }; /** * # session.recording_stopped * --- * * Event: `session.recording_stopped` * * ## Event description * * The **Session recording stopped** event is triggered every time a previously paused recording of a session is resumed. * * Only a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details. * * ## Prerequisites * * * Cloud Recording must be enabled on the Video SDK account. * * Event Subscriptions must be enabled for your app with the following configurations: * * A valid Event Notification Endpoint URL. * * **Session recording stopped** subscription enabled under the **Recording** event. * * The tabs below display the complete schema, payload with data types, and an example of the `session.recording_stopped` event notification: * * * * **Event type**: `session.recording_stopped` * */ export type SessionRecordingStoppedWebhookPayload = { /** * The event's name. */ event: 'session.recording_stopped'; /** * A timestamp, in milliseconds since epoch, at which the event occurred. */ event_ts: number; payload: { /** * The Video SDK account ID. */ account_id: string; /** * Information about the session. This object only returns updated properties. */ object: { /** * Unique session identifier. Each instance of the session will have its own session_id. */ session_id: string; /** * Session name. */ session_name: string; /** * The Video SDK custom session ID. */ session_key: string; /** * The time at which the session started. */ start_time: string; /** * The user's timezone. */ timezone: string; recording_file: { /** * The recording start time. */ recording_start?: string; /** * The recording end time. Response in general query. */ recording_end?: string; }; }; }; }; export type SessionRecordingStoppedWebhookRequest = { body: SessionRecordingStoppedWebhookPayload; key: 'session.recording_stopped'; path?: never; query?: never; }; ================================================ FILE: packages/openapi-ts-tests/main/test/cli.test.ts ================================================ import path from 'node:path'; import { sync } from 'cross-spawn'; import { getSpecsPath } from '../../utils'; const specs = getSpecsPath(); describe('bin', () => { it('openapi-ts works', () => { const result = sync('openapi-ts', [ '--input', path.resolve(specs, '3.1.x', 'full.yaml'), '--output', path.resolve(__dirname, '.gen'), '--dry-run', ]); expect(result.error).toBeFalsy(); expect(result.status).toBe(0); }); }); ================================================ FILE: packages/openapi-ts-tests/main/test/clients.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { customClientPlugin } from '@hey-api/custom-client/plugin'; import { createClient, type UserConfig } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; import { myClientPlugin } from './custom/client/plugin'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const clients = [ '@hey-api/client-angular', '@hey-api/client-axios', '@hey-api/client-fetch', '@hey-api/client-ky', '@hey-api/client-next', '@hey-api/client-nuxt', '@hey-api/client-ofetch', ] satisfies UserConfig['plugins']; for (const client of clients) { const namespace = 'clients'; const outputDir = path.join(__dirname, 'generated', '3.1.x', namespace, client); describe(client, () => { const createConfig = ( userConfig: Omit & Pick, 'input'>, ) => { const output = userConfig.output instanceof Array ? userConfig.output[0] : userConfig.output; return { ...userConfig, input: path.join(getSpecsPath(), '3.1.x', 'full.yaml'), logs: { level: 'silent', }, output: typeof output === 'string' ? path.join(outputDir, output) : { ...output, path: path.join(outputDir, output?.path ?? ''), }, } as const satisfies UserConfig; }; const scenarios = [ { config: createConfig({ output: 'default', plugins: [client], }), description: 'default output', }, { config: createConfig({ output: 'sdk-client-optional', plugins: [ client, { client: true, name: '@hey-api/sdk', }, ], }), description: 'SDK with optional client option', }, { config: createConfig({ output: 'sdk-client-required', plugins: [ client, { client: false, name: '@hey-api/sdk', }, ], }), description: 'SDK with required client option', }, { config: createConfig({ output: 'base-url-false', plugins: [ { baseUrl: false, name: client, }, '@hey-api/typescript', ], }), description: 'client without base URL', }, { config: createConfig({ output: 'base-url-number', plugins: [ { baseUrl: 0, name: client, }, '@hey-api/typescript', ], }), description: 'client with numeric base URL', }, { config: createConfig({ output: 'base-url-string', plugins: [ { baseUrl: 'https://foo.com', name: client, }, '@hey-api/typescript', ], }), description: 'client with custom string base URL', }, { config: createConfig({ output: 'base-url-strict', plugins: [ { name: client, strictBaseUrl: true, }, '@hey-api/typescript', ], }), description: 'client with strict base URL', }, { config: createConfig({ output: { path: 'tsconfig-nodenext-sdk', tsConfigPath: path.join(__dirname, 'tsconfig', 'tsconfig.nodenext.json'), }, plugins: [client, '@hey-api/sdk'], }), description: 'SDK with NodeNext tsconfig', }, { config: createConfig({ output: { path: 'tsconfig-node16-sdk', tsConfigPath: path.join(__dirname, 'tsconfig', 'tsconfig.node16.json'), }, plugins: [client, '@hey-api/sdk'], }), description: 'SDK with Node16 tsconfig', }, { config: createConfig({ output: { importFileExtension: '.ts', path: 'import-file-extension-ts', }, plugins: [client, '@hey-api/sdk'], }), description: 'SDK with .ts import file extensions', }, { config: createConfig({ output: { clean: false, path: 'clean-false', }, plugins: [client, '@hey-api/sdk'], }), description: 'avoid appending extension multiple times | twice', }, ]; it.each(scenarios)('$description', async ({ config, description }) => { await createClient(config); if (description.endsWith('twice')) { await createClient(config); } const outputPath = typeof config.output === 'string' ? config.output : config.output.path; const filePaths = getFilePaths(outputPath); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); // flaky test reordering client imports, skip if ( client === '@hey-api/client-nuxt' && typeof config.output === 'string' && config.output.includes('bundle') ) { expect(1).toBe(1); return; } await expect(fileContent).toMatchFileSnapshot( path.join( __dirname, '__snapshots__', '3.1.x', namespace, client, filePath.slice(outputDir.length + 1), ), ); }), ); }); }); } describe('custom-client', () => { const namespace = 'clients'; const outputDir = path.join(__dirname, 'generated', '3.1.x', namespace, 'client-custom'); const createConfig = ( userConfig: Omit & Pick, 'input'>, ) => ({ ...userConfig, input: path.join(getSpecsPath(), '3.1.x', 'full.yaml'), logs: { level: 'silent', }, output: path.join(outputDir, typeof userConfig.output === 'string' ? userConfig.output : ''), }) as const satisfies UserConfig; const scenarios = [ { config: createConfig({ output: 'default', plugins: [customClientPlugin()], }), description: 'default output', }, // TODO: enable custom client bundle, it's currently producing CJS output which fails typecheck // { // config: createConfig({ // output: 'bundle', // plugins: [ // customClientPlugin({ // bundle: true, // }), // ], // }), // description: 'default output with bundled client', // }, { config: createConfig({ output: 'sdk-client-optional', plugins: [ customClientPlugin(), { client: true, name: '@hey-api/sdk', }, ], }), description: 'SDK with optional client option', }, { config: createConfig({ output: 'sdk-client-required', plugins: [ customClientPlugin(), { client: false, name: '@hey-api/sdk', }, ], }), description: 'SDK with required client option', }, { config: createConfig({ output: 'base-url-false', plugins: [ customClientPlugin({ baseUrl: false, }), '@hey-api/typescript', ], }), description: 'client without base URL', }, { config: createConfig({ output: 'base-url-number', plugins: [ customClientPlugin({ baseUrl: 0, }), '@hey-api/typescript', ], }), description: 'client with numeric base URL', }, { config: createConfig({ output: 'base-url-string', plugins: [ customClientPlugin({ baseUrl: 'https://foo.com', }), '@hey-api/typescript', ], }), description: 'client with custom string base URL', }, { config: createConfig({ output: 'base-url-strict', plugins: [ customClientPlugin({ strictBaseUrl: true, }), '@hey-api/typescript', ], }), description: 'client with strict base URL', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join( __dirname, '__snapshots__', '3.1.x', namespace, 'client-custom', filePath.slice(outputDir.length + 1), ), ); }), ); }); }); describe('my-client', () => { const namespace = 'clients'; const outputDir = path.join(__dirname, 'generated', '3.1.x', namespace, 'my-client'); const createConfig = ( userConfig: Omit & Pick, 'input'>, ) => ({ ...userConfig, input: path.join(getSpecsPath(), '3.1.x', 'full.yaml'), logs: { level: 'silent', }, output: path.join(outputDir, typeof userConfig.output === 'string' ? userConfig.output : ''), }) as const satisfies UserConfig; const scenarios = [ { config: createConfig({ output: 'default', plugins: [myClientPlugin()], }), description: 'default output', }, { config: createConfig({ output: 'bundle', plugins: [ myClientPlugin({ bundle: true, }), ], }), description: 'default output with bundled client', }, { config: createConfig({ output: 'sdk-client-optional', plugins: [ myClientPlugin(), { client: true, name: '@hey-api/sdk', }, ], }), description: 'SDK with optional client option', }, { config: createConfig({ output: 'sdk-client-required', plugins: [ myClientPlugin(), { client: false, name: '@hey-api/sdk', }, ], }), description: 'SDK with required client option', }, { config: createConfig({ output: 'base-url-false', plugins: [ myClientPlugin({ baseUrl: false, }), '@hey-api/typescript', ], }), description: 'client without base URL', }, { config: createConfig({ output: 'base-url-number', plugins: [ myClientPlugin({ baseUrl: 0, }), '@hey-api/typescript', ], }), description: 'client with numeric base URL', }, { config: createConfig({ output: 'base-url-string', plugins: [ myClientPlugin({ baseUrl: 'https://foo.com', }), '@hey-api/typescript', ], }), description: 'client with custom string base URL', }, { config: createConfig({ output: 'base-url-strict', plugins: [ myClientPlugin({ strictBaseUrl: true, }), '@hey-api/typescript', ], }), description: 'client with strict base URL', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join( __dirname, '__snapshots__', '3.1.x', namespace, 'my-client', filePath.slice(outputDir.length + 1), ), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/client.ts ================================================ import type { Client, Config, RequestOptions } from './types'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); // @ts-expect-error const request: Client['request'] = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.body && opts.bodySerializer) { opts.body = opts.bodySerializer(opts.body); } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.body === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); const requestInit: ReqInit = { redirect: 'follow', ...opts, }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response = await _fetch(request); for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { if (response.status === 204 || response.headers.get('Content-Length') === '0') { return { data: {}, ...result, }; } const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (parseAs === 'stream') { return { data: response.body, ...result, }; } let data = await response[parseAs](); if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return { data, ...result, }; } let error = await response.text(); try { error = JSON.parse(error); } catch { // noop } let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } return { error: finalError, ...result, }; }; return { buildUrl, connect: (options) => request({ ...options, method: 'CONNECT' }), delete: (options) => request({ ...options, method: 'DELETE' }), get: (options) => request({ ...options, method: 'GET' }), getConfig, head: (options) => request({ ...options, method: 'HEAD' }), interceptors, options: (options) => request({ ...options, method: 'OPTIONS' }), patch: (options) => request({ ...options, method: 'PATCH' }), post: (options) => request({ ...options, method: 'POST' }), put: (options) => request({ ...options, method: 'PUT' }), request, setConfig, trace: (options) => request({ ...options, method: 'TRACE' }), }; }; ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/core/auth.ts ================================================ export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/core/bodySerializer.ts ================================================ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown) => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown) => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown) => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown) => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown) => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/core/params.ts ================================================ type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; key: string; map?: string; } | { in: Extract; key?: string; map?: string; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, { in: Slot; map?: string; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else { for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/core/pathSerializer.ts ================================================ interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/core/types.ts ================================================ import type { Auth, AuthToken } from './auth'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer'; export interface Client { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; connect: MethodFn; delete: MethodFn; get: MethodFn; getConfig: () => Config; head: MethodFn; options: MethodFn; patch: MethodFn; post: MethodFn; put: MethodFn; request: RequestFn; setConfig: (config: Config) => Config; trace: MethodFn; } export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/index.ts ================================================ export { createClient } from './client'; export type { Auth } from './core/auth'; export type { QuerySerializerOptions } from './core/bodySerializer'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from './core/bodySerializer'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, TDataShape, } from './types'; export { createConfig } from './utils'; ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/plugin.ts ================================================ import { type Client, clientDefaultConfig, clientDefaultMeta, clientPluginHandler, type DefinePlugin, definePluginConfig, } from '@hey-api/openapi-ts'; export type Config = Client.Config & { /** * Plugin name. Must be unique. */ name: string; }; export type MyClientPlugin = DefinePlugin; export const defaultConfig: MyClientPlugin['Config'] = { ...clientDefaultMeta, config: clientDefaultConfig, handler: clientPluginHandler as MyClientPlugin['Handler'], name: __filename, }; /** * Type helper for `my-client` plugin, returns {@link Plugin.Config} object */ export const myClientPlugin = definePluginConfig(defaultConfig); ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/types.ts ================================================ import type { Auth } from './core/auth'; import type { Client as CoreClient, Config as CoreConfig } from './core/types'; import type { Middleware } from './utils'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: (request: Request) => ReturnType; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ throwOnError: ThrowOnError; }> { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true ? Promise<{ data: TData; request: Request; response: Response; }> : Promise< ({ data: TData; error: undefined } | { data: undefined; error: TError }) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; throwOnError?: boolean; } type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, > = OmitKeys, 'body' | 'path' | 'query' | 'url'> & Omit; ================================================ FILE: packages/openapi-ts-tests/main/test/custom/client/utils.ts ================================================ import { getAuthToken } from './core/auth'; import type { QuerySerializer, QuerySerializerOptions } from './core/bodySerializer'; import { jsonBodySerializer } from './core/bodySerializer'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './core/pathSerializer'; import type { Client, ClientOptions, Config, RequestOptions } from './types'; interface PathSerializer { path: Record; url: string; } const PATH_PARAM_RE = /\{[^{}]+\}/g; type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; type MatrixStyle = 'label' | 'matrix' | 'simple'; type ArraySeparatorStyle = ArrayStyle | MatrixStyle; const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const createQuerySerializer = ({ allowReserved, array, object, }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { let search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { search = [ ...search, serializeArrayParam({ allowReserved, explode: true, name, style: 'form', value, ...array, }), ]; continue; } if (typeof value === 'object') { search = [ ...search, serializeObjectParam({ allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...object, }), ]; continue; } search = [ ...search, serializePrimitiveParam({ allowReserved, name, value: value as string, }), ]; } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } return; } }; export const buildUrl: Client['buildUrl'] = (options) => { const url = getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== 'object') { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/main/test/custom/request.ts ================================================ import type { ApiRequestOptions } from './ApiRequestOptions'; import { CancelablePromise } from './CancelablePromise'; import type { OpenAPIConfig } from './OpenAPI'; export const request = ( config: OpenAPIConfig, options: ApiRequestOptions, ): CancelablePromise => new CancelablePromise((resolve, reject, onCancel) => { const url = `${config.BASE}${options.path}`.replace('{api-version}', config.VERSION); try { // Do your request... const timeout = setTimeout(() => { resolve({ body: { ...options, }, ok: true, status: 200, statusText: 'dummy', url, }); }, 500); // Cancel your request... onCancel(() => { clearTimeout(timeout); }); } catch (error) { reject(error); } }); ================================================ FILE: packages/openapi-ts-tests/main/test/meta-function.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createClient, type UserConfig } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const version = '3.1.x'; const namespace = 'plugins'; const outputDir = path.join(__dirname, 'generated', version, namespace); // TODO: further clean up describe('TanStack Query Meta Function Customization', () => { const createConfig = ( userConfig: Omit & Pick, 'input'>, ): UserConfig => ({ input: path.join(getSpecsPath(), version, 'security-api-key.yaml'), logs: { level: 'silent', }, ...userConfig, }); // Framework configurations const frameworks = [ { description: 'React Query', name: '@tanstack/react-query', output: 'react-query', }, { description: 'Vue Query', name: '@tanstack/vue-query', output: 'vue-query', }, { description: 'Svelte Query', name: '@tanstack/svelte-query', output: 'svelte-query', }, { description: 'Solid Query', name: '@tanstack/solid-query', output: 'solid-query', }, { description: 'Angular Query', name: '@tanstack/angular-query-experimental', output: 'angular-query-experimental', }, { description: 'Preact Query', name: '@tanstack/preact-query', output: 'preact-query', }, ] as const; // Generate scenarios for each framework const scenarios = frameworks.map((framework) => ({ config: createConfig({ output: path.join(outputDir, '@tanstack', framework.output, 'meta-function'), plugins: [ { infiniteQueryOptions: { meta: (operation) => ({ id: operation.id, method: operation.method, path: operation.path, }), }, mutationOptions: { meta: (operation) => ({ id: operation.id, method: operation.method, path: operation.path, }), }, name: framework.name, queryOptions: { meta: (operation) => ({ id: operation.id, method: operation.method, path: operation.path, }), }, }, '@hey-api/client-fetch', ], }), description: `generates ${framework.description} options with custom meta function`, })); it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const outputPath = config.output as string; const filePaths = getFilePaths(outputPath); // Create snapshots for all generated files await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); const relativePath = filePath.slice(outputPath.length + 1); const fileName = path.basename(relativePath); const frameworkDir = path.dirname(relativePath).split(path.sep).pop()!; await expect(fileContent).toMatchFileSnapshot( path.join( __dirname, '..', '..', '__snapshots__', 'plugins', '@tanstack', 'meta', frameworkDir, fileName, ), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/main/test/plugins.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createClient, type DefinePlugin, type UserConfig } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const versions = ['2.0.x', '3.0.x', '3.1.x']; for (const version of versions) { const namespace = 'plugins'; const outputDir = path.join(__dirname, 'generated', version, namespace); describe(`OpenAPI ${version} ${namespace}`, () => { const createConfig = ( userConfig: Omit & Pick, 'plugins'> & Pick, 'input'>, ) => ({ ...userConfig, input: path.join( getSpecsPath(), version, typeof userConfig.input === 'string' ? userConfig.input : 'full.yaml', ), logs: { level: 'silent', }, output: path.join( outputDir, typeof userConfig.plugins[0] === 'string' ? userConfig.plugins[0] : userConfig.plugins[0]!.name, typeof userConfig.output === 'string' ? userConfig.output : '', ), plugins: userConfig.plugins ?? ['@hey-api/client-fetch'], }) as const satisfies UserConfig; const scenarios = [ { config: createConfig({ output: 'fetch', plugins: ['@tanstack/angular-query-experimental', '@hey-api/client-fetch'], }), description: 'generate Fetch API client with TanStack Angular Query Experimental plugin', }, { config: createConfig({ output: 'fetch', plugins: ['@tanstack/preact-query', '@hey-api/client-fetch'], }), description: 'generate Fetch API client with TanStack Preact Query plugin', }, { config: createConfig({ output: 'fetch', plugins: ['@tanstack/react-query', '@hey-api/client-fetch'], }), description: 'generate Fetch API client with TanStack React Query plugin', }, { config: createConfig({ output: 'fetch', plugins: ['@tanstack/solid-query', '@hey-api/client-fetch'], }), description: 'generate Fetch API client with TanStack Solid Query plugin', }, { config: createConfig({ output: 'fetch', plugins: ['@tanstack/svelte-query', '@hey-api/client-fetch'], }), description: 'generate Fetch API client with TanStack Svelte Query plugin', }, { config: createConfig({ output: 'fetch', plugins: ['@tanstack/vue-query', '@hey-api/client-fetch'], }), description: 'generate Fetch API client with TanStack Vue Query plugin', }, { config: createConfig({ output: 'axios', plugins: ['@tanstack/angular-query-experimental', '@hey-api/client-axios'], }), description: 'generate Axios client with TanStack Angular Query Experimental plugin', }, { config: createConfig({ output: 'axios', plugins: ['@tanstack/preact-query', '@hey-api/client-axios'], }), description: 'generate Axios client with TanStack Preact Query plugin', }, { config: createConfig({ output: 'axios', plugins: ['@tanstack/react-query', '@hey-api/client-axios'], }), description: 'generate Axios client with TanStack React Query plugin', }, { config: createConfig({ output: 'axios', plugins: ['@tanstack/solid-query', '@hey-api/client-axios'], }), description: 'generate Axios client with TanStack Solid Query plugin', }, { config: createConfig({ output: 'axios', plugins: ['@tanstack/svelte-query', '@hey-api/client-axios'], }), description: 'generate Axios client with TanStack Svelte Query plugin', }, { config: createConfig({ output: 'axios', plugins: ['@tanstack/vue-query', '@hey-api/client-axios'], }), description: 'generate Axios client with TanStack Vue Query plugin', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'asClass', plugins: [ '@tanstack/angular-query-experimental', '@hey-api/client-fetch', { asClass: true, classNameBuilder: '{{name}}Service', name: '@hey-api/sdk', }, ], }), description: 'generate Fetch API client with TanStack Angular Query Experimental plugin using class-based SDKs', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'asClass', plugins: [ '@tanstack/preact-query', '@hey-api/client-fetch', { asClass: true, classNameBuilder: '{{name}}Service', name: '@hey-api/sdk', }, ], }), description: 'generate Fetch API client with TanStack Preact Query plugin using class-based SDKs', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'asClass', plugins: [ '@tanstack/react-query', '@hey-api/client-fetch', { asClass: true, classNameBuilder: '{{name}}Service', name: '@hey-api/sdk', }, ], }), description: 'generate Fetch API client with TanStack React Query plugin using class-based SDKs', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'asClass', plugins: [ '@tanstack/solid-query', '@hey-api/client-fetch', { asClass: true, classNameBuilder: '{{name}}Service', name: '@hey-api/sdk', }, ], }), description: 'generate Fetch API client with TanStack Solid Query plugin using class-based SDKs', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'asClass', plugins: [ '@tanstack/svelte-query', '@hey-api/client-fetch', { asClass: true, classNameBuilder: '{{name}}Service', name: '@hey-api/sdk', }, ], }), description: 'generate Fetch API client with TanStack Svelte Query plugin using class-based SDKs', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'asClass', plugins: [ '@tanstack/vue-query', '@hey-api/client-fetch', { asClass: true, classNameBuilder: '{{name}}Service', name: '@hey-api/sdk', }, ], }), description: 'generate Fetch API client with TanStack Vue Query plugin using class-based SDKs', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'name-builder', plugins: [ { infiniteQueryKeys: { name: '{{name}}A', }, infiniteQueryOptions: { name: '{{name}}B', }, mutationOptions: { name: '{{name}}C', }, name: '@tanstack/angular-query-experimental', queryKeys: { name: '{{name}}D', }, queryOptions: { name: '{{name}}E', }, }, '@hey-api/client-fetch', '@hey-api/sdk', ], }), description: 'generate Fetch API client with TanStack Angular Query Experimental plugin with custom names', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'name-builder', plugins: [ { infiniteQueryKeys: { name: '{{name}}A', }, infiniteQueryOptions: { name: '{{name}}B', }, mutationOptions: { name: '{{name}}C', }, name: '@tanstack/preact-query', queryKeys: { name: '{{name}}D', }, queryOptions: { name: '{{name}}E', }, }, '@hey-api/client-fetch', '@hey-api/sdk', ], }), description: 'generate Fetch API client with TanStack Preact Query plugin with custom names', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'name-builder', plugins: [ { infiniteQueryKeys: { name: '{{name}}A', }, infiniteQueryOptions: { name: '{{name}}B', }, mutationOptions: { name: '{{name}}C', }, name: '@tanstack/react-query', queryKeys: { name: '{{name}}D', }, queryOptions: { name: '{{name}}E', }, }, '@hey-api/client-fetch', '@hey-api/sdk', ], }), description: 'generate Fetch API client with TanStack React Query plugin with custom names', }, { config: createConfig({ output: 'useMutation', plugins: [ { name: '@tanstack/react-query', useMutation: true, }, '@hey-api/client-fetch', ], }), description: 'generate Fetch API client with TanStack React Query plugin with useMutation hooks', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'name-builder', plugins: [ { infiniteQueryKeys: { name: '{{name}}A', }, infiniteQueryOptions: { name: '{{name}}B', }, mutationOptions: { name: '{{name}}C', }, name: '@tanstack/solid-query', queryKeys: { name: '{{name}}D', }, queryOptions: { name: '{{name}}E', }, }, '@hey-api/client-fetch', '@hey-api/sdk', ], }), description: 'generate Fetch API client with TanStack Solid Query plugin with custom names', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'name-builder', plugins: [ { infiniteQueryKeys: { name: '{{name}}A', }, infiniteQueryOptions: { name: '{{name}}B', }, mutationOptions: { name: '{{name}}C', }, name: '@tanstack/svelte-query', queryKeys: { name: '{{name}}D', }, queryOptions: { name: '{{name}}E', }, }, '@hey-api/client-fetch', '@hey-api/sdk', ], }), description: 'generate Fetch API client with TanStack Svelte Query plugin with custom names', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'name-builder', plugins: [ { infiniteQueryKeys: { name: '{{name}}A', }, infiniteQueryOptions: { name: '{{name}}B', }, mutationOptions: { name: '{{name}}C', }, name: '@tanstack/vue-query', queryKeys: { name: '{{name}}D', }, queryOptions: { name: '{{name}}E', }, }, '@hey-api/client-fetch', '@hey-api/sdk', ], }), description: 'generate Fetch API client with TanStack Vue Query plugin with custom names', }, { config: createConfig({ output: 'default', plugins: ['@hey-api/schemas'], }), description: 'generate schemas', }, { config: createConfig({ output: 'default', plugins: ['@hey-api/sdk', '@hey-api/client-fetch'], }), description: 'generate SDK', }, { config: createConfig({ output: 'throwOnError', plugins: [ '@hey-api/sdk', { name: '@hey-api/client-fetch', throwOnError: true, }, ], }), description: 'generate SDK that throws on error', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'instance', plugins: [ { instance: true, name: '@hey-api/sdk', }, '@hey-api/client-fetch', ], }), description: 'generate SDK instance', }, { config: createConfig({ output: 'default', plugins: ['fastify'], }), description: 'generate Fastify types with Fastify plugin', }, { config: createConfig({ input: 'transforms-read-write.yaml', output: 'transforms-read-write-ignore', parser: { transforms: { readWrite: false, }, }, plugins: ['@hey-api/typescript', '@hey-api/client-fetch'], }), description: 'ignores read-only and write-only handling', }, { config: createConfig({ input: 'transforms-read-write.yaml', output: 'transforms-read-write-custom-name', parser: { transforms: { readWrite: { requests: 'Writable{{name}}', responses: 'Readable{{name}}', }, }, }, plugins: ['@hey-api/typescript', '@hey-api/client-fetch'], }), description: 'custom read-only and write-only naming', }, { config: createConfig({ input: 'sdk-nested-classes.yaml', output: 'sdk-nested-classes', plugins: [ '@hey-api/client-fetch', { asClass: true, classStructure: 'auto', name: '@hey-api/sdk', }, ], }), description: 'generate nested classes with auto class structure', }, { config: createConfig({ input: 'sdk-nested-classes.yaml', output: 'sdk-nested-classes-instance', plugins: [ '@hey-api/client-fetch', { asClass: true, classStructure: 'auto', instance: 'NestedSdkWithInstance', name: '@hey-api/sdk', }, ], }), description: 'generate nested classes with auto class structure', }, { config: createConfig({ output: 'fetch', plugins: ['@pinia/colada', '@hey-api/client-fetch'], }), description: 'generate Fetch API client with Pinia Colada plugin', }, { config: createConfig({ input: 'sdk-instance.yaml', output: 'asClass', plugins: [ '@pinia/colada', '@hey-api/client-fetch', { asClass: true, classNameBuilder: '{{name}}Service', name: '@hey-api/sdk', }, ], }), description: 'generate Fetch API client with Pinia Colada plugin using class-based SDKs', }, { config: createConfig({ output: 'default', plugins: ['@angular/common', '@hey-api/client-angular'], }), description: 'generate Angular requests and resources', }, { config: createConfig({ output: 'default-class', plugins: [ { httpRequests: { containerName: '{{name}}ServiceRequests', segmentName: '{{name}}Service', strategy: 'byTags', }, httpResources: { containerName: '{{name}}ServiceResources', segmentName: '{{name}}Service', strategy: 'byTags', }, name: '@angular/common', }, '@hey-api/client-angular', ], }), description: 'generate Angular requests and resources (class)', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join( __dirname, '__snapshots__', version, namespace, filePath.slice(outputDir.length + 1), ), ); }), ); }); }); describe('custom plugin', () => { it('handles a custom plugin', async () => { const myPlugin: DefinePlugin<{ customOption: boolean; name: any; }>['Config'] = { api: undefined, config: { customOption: true, }, dependencies: ['@hey-api/typescript'], handler: vi.fn(), name: 'my-plugin', }; await createClient({ input: path.join(getSpecsPath(), '3.1.x', 'full.yaml'), logs: { level: 'silent', }, output: path.join(outputDir, myPlugin.name, 'default'), plugins: [myPlugin, '@hey-api/client-fetch'], }); expect(myPlugin.handler).toHaveBeenCalled(); }); // TODO: fix test it.skip('throws on invalid dependency', async () => { const myPlugin: DefinePlugin<{ name: any; }>['Config'] = { api: undefined, config: {}, dependencies: ['@hey-api/oops'], handler: vi.fn(), name: 'my-plugin', }; await expect(() => createClient({ input: path.join(getSpecsPath(), '3.1.x', 'full.yaml'), logs: { level: 'silent', }, output: path.join(outputDir, myPlugin.name, 'default'), plugins: [myPlugin, '@hey-api/client-fetch'], }), ).rejects.toThrowError(/Found 1 configuration error./g); expect(myPlugin.handler).not.toHaveBeenCalled(); }); }); } ================================================ FILE: packages/openapi-ts-tests/main/test/tsconfig/tsconfig.node16.json ================================================ { "extends": "../../../tsconfig.base.json", "compilerOptions": { "declaration": false, "moduleResolution": "node16", "resolveJsonModule": true, "skipLibCheck": true } } ================================================ FILE: packages/openapi-ts-tests/main/test/tsconfig/tsconfig.nodenext.json ================================================ { "extends": "../../../tsconfig.base.json", "compilerOptions": { "declaration": false, "moduleResolution": "nodenext", "resolveJsonModule": true, "skipLibCheck": true } } ================================================ FILE: packages/openapi-ts-tests/main/tsconfig.json ================================================ { "extends": "../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true, "resolveJsonModule": true }, "exclude": ["test/custom/request.ts", "test/generated/**"], "references": [{ "path": "../../openapi-ts" }] } ================================================ FILE: packages/openapi-ts-tests/main/turbo.json ================================================ { "$schema": "../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts-tests/main/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/2.0.x/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/2.0.x/default/nestjs.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesResponse, CallWithParametersData, CallWithResponseAndNoContentResponseResponse, CallWithResponseResponse, CallWithResponsesResponse, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyResponse, TestErrorCodeData, TypesData, TypesResponse } from './types.gen'; export type DefaultControllerMethods = { serviceWithEmptyTag: () => Promise; patchApiVbyApiVersionNoTag: () => Promise; fooWow: () => Promise; postApiVbyApiVersionBody: (body: PostApiVbyApiVersionBodyData['body']) => Promise; }; export type SimpleControllerMethods = { deleteCallWithoutParametersAndResponse: () => Promise; getCallWithoutParametersAndResponse: () => Promise; headCallWithoutParametersAndResponse: () => Promise; optionsCallWithoutParametersAndResponse: () => Promise; patchCallWithoutParametersAndResponse: () => Promise; postCallWithoutParametersAndResponse: () => Promise; putCallWithoutParametersAndResponse: () => Promise; }; export type DescriptionsControllerMethods = { callWithDescriptions: (query?: CallWithDescriptionsData['query']) => Promise; }; export type ParametersControllerMethods = { callWithParameters: (path: CallWithParametersData['path'], query: CallWithParametersData['query'], headers: CallWithParametersData['headers']) => Promise; callWithWeirdParameterNames: (path: CallWithWeirdParameterNamesData['path'], query: CallWithWeirdParameterNamesData['query'], body: CallWithWeirdParameterNamesData['body'], headers: CallWithWeirdParameterNamesData['headers']) => Promise; }; export type DefaultsControllerMethods = { callWithDefaultParameters: (query: CallWithDefaultParametersData['query']) => Promise; callWithDefaultOptionalParameters: (query?: CallWithDefaultOptionalParametersData['query']) => Promise; callToTestOrderOfParams: (query: CallToTestOrderOfParamsData['query']) => Promise; }; export type DuplicateControllerMethods = { duplicateName: () => Promise; duplicateName2: () => Promise; duplicateName3: () => Promise; duplicateName4: () => Promise; }; export type NoContentControllerMethods = { callWithNoContentResponse: () => Promise; }; export type ResponseControllerMethods = { callWithResponseAndNoContentResponse: () => Promise; callWithResponse: () => Promise; callWithDuplicateResponses: () => Promise; callWithResponses: () => Promise; }; export type MultipleTags1ControllerMethods = { dummyA: () => Promise; dummyB: () => Promise; }; export type CollectionFormatControllerMethods = { collectionFormat: (query: CollectionFormatData['query']) => Promise; }; export type TypesControllerMethods = { types: (query: TypesData['query'], path?: TypesData['path']) => Promise; }; export type ComplexControllerMethods = { complexTypes: (query: ComplexTypesData['query']) => Promise; }; export type HeaderControllerMethods = { callWithResultFromHeader: () => Promise; }; export type ErrorControllerMethods = { testErrorCode: (query: TestErrorCodeData['query']) => Promise; }; export type NonAsciiÆøåÆøÅöôêÊControllerMethods = { nonAsciiæøåÆøÅöôêÊ字符串: (query: NonAsciiæøåÆøÅöôêÊ字符串Data['query']) => Promise; }; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/2.0.x/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ foo?: string; bar?: string; }>; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a type-only model that defines Date as a string */ export type Date = string; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp?: string | null; /** * This is a simple string property */ nullableRequiredProp: string | null; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string; }; }; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; export type Default = { name?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ParameterActivityParams = { description?: string; graduate_id?: number; organization_id?: number; parent_activity?: number; post_id?: number; }; export type ResponsePostActivityResponse = { description?: string; graduate_id?: number; organization_id?: number; parent_activity_id?: number; post_id?: number; }; export type FailureFailure = { error?: string; message?: string; reference_code?: string; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type ServiceWithEmptyTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions/'; }; export type CallWithParametersData = { body?: never; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter that goes into the query params */ parameterQuery: string; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that is sent as request body */ body: string; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query: { /** * This is a simple string with default value */ parameterString: string; /** * This is a simple number with default value */ parameterNumber: number; /** * This is a simple boolean with default value */ parameterBoolean: boolean; /** * This is a simple enum with default value */ parameterEnum: 'Success' | 'Warning' | 'Error'; /** * This is a model with one string property */ parameterModel: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: unknown; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { /** * Success */ 204: unknown; }; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: unknown; }; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { /** * Message for default response */ default: ModelWithString; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithString; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string; /** * This is a boolean parameter */ parameterBoolean: boolean; /** * This is an array parameter */ parameterArray: Array; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; }; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * This is a model with one string property */ parameterReference: { /** * This is a simple string property */ prop?: string; }; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: string; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: NonAsciiStringæøåÆøÅöôêÊ字符串; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PostApiVbyApiVersionBodyData = { /** * Body should not be unknown */ body: ParameterActivityParams; path?: never; query?: never; url: '/api/v{api-version}/body'; }; export type PostApiVbyApiVersionBodyErrors = { /** * Bad Request */ 400: FailureFailure; /** * Internal Server Error */ 500: FailureFailure; }; export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; export type PostApiVbyApiVersionBodyResponses = { /** * OK */ 200: ResponsePostActivityResponse; }; export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/3.0.x/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/3.0.x/default/nestjs.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesResponse, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseResponse, CallWithResponseResponse, CallWithResponsesResponse, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteFooData3, DeprecatedCallData, DummyAResponse, DummyBResponse, FileResponseData, FileResponseResponse, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; export type DefaultControllerMethods = { export: () => Promise; patchApiVbyApiVersionNoTag: () => Promise; import: (body: ImportData['body']) => Promise; fooWow: () => Promise; getApiVbyApiVersionSimpleOperation: (path: GetApiVbyApiVersionSimpleOperationData['path']) => Promise; }; export type SimpleControllerMethods = { apiVVersionODataControllerCount: () => Promise; deleteCallWithoutParametersAndResponse: () => Promise; getCallWithoutParametersAndResponse: () => Promise; headCallWithoutParametersAndResponse: () => Promise; optionsCallWithoutParametersAndResponse: () => Promise; patchCallWithoutParametersAndResponse: () => Promise; postCallWithoutParametersAndResponse: () => Promise; putCallWithoutParametersAndResponse: () => Promise; }; export type ParametersControllerMethods = { deleteFoo: (path: DeleteFooData3['path'], headers: DeleteFooData3['headers']) => Promise; callWithParameters: (path: CallWithParametersData['path'], query: CallWithParametersData['query'], body: CallWithParametersData['body'], headers: CallWithParametersData['headers']) => Promise; callWithWeirdParameterNames: (path: CallWithWeirdParameterNamesData['path'], query: CallWithWeirdParameterNamesData['query'], body: CallWithWeirdParameterNamesData['body'], headers: CallWithWeirdParameterNamesData['headers']) => Promise; getCallWithOptionalParam: (body: GetCallWithOptionalParamData['body'], query?: GetCallWithOptionalParamData['query']) => Promise; postCallWithOptionalParam: (query: PostCallWithOptionalParamData['query'], body?: PostCallWithOptionalParamData['body']) => Promise; }; export type DescriptionsControllerMethods = { callWithDescriptions: (query?: CallWithDescriptionsData['query']) => Promise; }; export type DeprecatedControllerMethods = { deprecatedCall: (headers: DeprecatedCallData['headers']) => Promise; }; export type RequestBodyControllerMethods = { postApiVbyApiVersionRequestBody: (query?: PostApiVbyApiVersionRequestBodyData['query'], body?: PostApiVbyApiVersionRequestBodyData['body']) => Promise; }; export type FormDataControllerMethods = { postApiVbyApiVersionFormData: (query?: PostApiVbyApiVersionFormDataData['query'], body?: PostApiVbyApiVersionFormDataData['body']) => Promise; }; export type DefaultsControllerMethods = { callWithDefaultParameters: (query?: CallWithDefaultParametersData['query']) => Promise; callWithDefaultOptionalParameters: (query?: CallWithDefaultOptionalParametersData['query']) => Promise; callToTestOrderOfParams: (query: CallToTestOrderOfParamsData['query']) => Promise; }; export type DuplicateControllerMethods = { duplicateName: () => Promise; duplicateName2: () => Promise; duplicateName3: () => Promise; duplicateName4: () => Promise; }; export type NoContentControllerMethods = { callWithNoContentResponse: () => Promise; }; export type ResponseControllerMethods = { callWithResponseAndNoContentResponse: () => Promise; callWithResponse: () => Promise; callWithDuplicateResponses: () => Promise; callWithResponses: () => Promise; }; export type MultipleTags1ControllerMethods = { dummyA: () => Promise; dummyB: () => Promise; }; export type CollectionFormatControllerMethods = { collectionFormat: (query: CollectionFormatData['query']) => Promise; }; export type TypesControllerMethods = { types: (query: TypesData['query'], path?: TypesData['path']) => Promise; }; export type UploadControllerMethods = { uploadFile: (path: UploadFileData['path'], body: UploadFileData['body']) => Promise; }; export type FileResponseControllerMethods = { fileResponse: (path: FileResponseData['path']) => Promise; }; export type ComplexControllerMethods = { complexTypes: (query: ComplexTypesData['query']) => Promise; complexParams: (path: ComplexParamsData['path'], body?: ComplexParamsData['body']) => Promise; }; export type MultipartControllerMethods = { multipartResponse: () => Promise; multipartRequest: (body?: MultipartRequestData['body']) => Promise; }; export type HeaderControllerMethods = { callWithResultFromHeader: () => Promise; }; export type ErrorControllerMethods = { testErrorCode: (query: TestErrorCodeData['query']) => Promise; }; export type NonAsciiÆøåÆøÅöôêÊControllerMethods = { nonAsciiæøåÆøÅöôêÊ字符串: (query: NonAsciiæøåÆøÅöôêÊ字符串Data['query']) => Promise; putWithFormUrlEncoded: (body: PutWithFormUrlEncodedData['body']) => Promise; }; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/3.0.x/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; export type ExternalRefA = ExternalSharedModel; export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: unknown; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = Array; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; export type SimpleRequestBody = ModelWithString; export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error'; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/3.1.x/default/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/3.1.x/default/nestjs.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesResponse, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseResponse, CallWithResponseResponse, CallWithResponsesResponse, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteFooData3, DeprecatedCallData, DummyAResponse, DummyBResponse, FileResponseData, FileResponseResponse, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; export type DefaultControllerMethods = { export: () => Promise; patchApiVbyApiVersionNoTag: () => Promise; import: (body: ImportData['body']) => Promise; fooWow: () => Promise; getApiVbyApiVersionSimpleOperation: (path: GetApiVbyApiVersionSimpleOperationData['path']) => Promise; }; export type SimpleControllerMethods = { apiVVersionODataControllerCount: () => Promise; deleteCallWithoutParametersAndResponse: () => Promise; getCallWithoutParametersAndResponse: () => Promise; headCallWithoutParametersAndResponse: () => Promise; optionsCallWithoutParametersAndResponse: () => Promise; patchCallWithoutParametersAndResponse: () => Promise; postCallWithoutParametersAndResponse: () => Promise; putCallWithoutParametersAndResponse: () => Promise; }; export type ParametersControllerMethods = { deleteFoo: (path: DeleteFooData3['path'], headers: DeleteFooData3['headers']) => Promise; callWithParameters: (path: CallWithParametersData['path'], query: CallWithParametersData['query'], body: CallWithParametersData['body'], headers: CallWithParametersData['headers']) => Promise; callWithWeirdParameterNames: (path: CallWithWeirdParameterNamesData['path'], query: CallWithWeirdParameterNamesData['query'], body: CallWithWeirdParameterNamesData['body'], headers: CallWithWeirdParameterNamesData['headers']) => Promise; getCallWithOptionalParam: (body: GetCallWithOptionalParamData['body'], query?: GetCallWithOptionalParamData['query']) => Promise; postCallWithOptionalParam: (query: PostCallWithOptionalParamData['query'], body?: PostCallWithOptionalParamData['body']) => Promise; }; export type DescriptionsControllerMethods = { callWithDescriptions: (query?: CallWithDescriptionsData['query']) => Promise; }; export type DeprecatedControllerMethods = { deprecatedCall: (headers: DeprecatedCallData['headers']) => Promise; }; export type RequestBodyControllerMethods = { postApiVbyApiVersionRequestBody: (query?: PostApiVbyApiVersionRequestBodyData['query'], body?: PostApiVbyApiVersionRequestBodyData['body']) => Promise; }; export type FormDataControllerMethods = { postApiVbyApiVersionFormData: (query?: PostApiVbyApiVersionFormDataData['query'], body?: PostApiVbyApiVersionFormDataData['body']) => Promise; }; export type DefaultsControllerMethods = { callWithDefaultParameters: (query?: CallWithDefaultParametersData['query']) => Promise; callWithDefaultOptionalParameters: (query?: CallWithDefaultOptionalParametersData['query']) => Promise; callToTestOrderOfParams: (query: CallToTestOrderOfParamsData['query']) => Promise; }; export type DuplicateControllerMethods = { duplicateName: () => Promise; duplicateName2: () => Promise; duplicateName3: () => Promise; duplicateName4: () => Promise; }; export type NoContentControllerMethods = { callWithNoContentResponse: () => Promise; }; export type ResponseControllerMethods = { callWithResponseAndNoContentResponse: () => Promise; callWithResponse: () => Promise; callWithDuplicateResponses: () => Promise; callWithResponses: () => Promise; }; export type MultipleTags1ControllerMethods = { dummyA: () => Promise; dummyB: () => Promise; }; export type CollectionFormatControllerMethods = { collectionFormat: (query: CollectionFormatData['query']) => Promise; }; export type TypesControllerMethods = { types: (query: TypesData['query'], path?: TypesData['path']) => Promise; }; export type UploadControllerMethods = { uploadFile: (path: UploadFileData['path'], body: UploadFileData['body']) => Promise; }; export type FileResponseControllerMethods = { fileResponse: (path: FileResponseData['path']) => Promise; }; export type ComplexControllerMethods = { complexTypes: (query: ComplexTypesData['query']) => Promise; complexParams: (path: ComplexParamsData['path'], body?: ComplexParamsData['body']) => Promise; }; export type MultipartControllerMethods = { multipartResponse: () => Promise; multipartRequest: (body?: MultipartRequestData['body']) => Promise; }; export type HeaderControllerMethods = { callWithResultFromHeader: () => Promise; }; export type ErrorControllerMethods = { testErrorCode: (query: TestErrorCodeData['query']) => Promise; }; export type NonAsciiÆøåÆøÅöôêÊControllerMethods = { nonAsciiæøåÆøÅöôêÊ字符串: (query: NonAsciiæøåÆøÅöôêÊ字符串Data['query']) => Promise; putWithFormUrlEncoded: (body: PutWithFormUrlEncodedData['body']) => Promise; }; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/__snapshots__/3.1.x/default/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: 'http://localhost:3000/base' | (string & {}); }; /** * Model with number-only name */ export type _400 = string; /** * External ref to shared model (A) */ export type ExternalRefA = ExternalSharedModel; /** * External ref to shared model (B) */ export type ExternalRefB = ExternalSharedModel; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CamelCaseCommentWithBreaks = number; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export type CommentWithBreaks = number; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export type CommentWithBackticks = number; /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export type CommentWithBackticksAndQuotes = number; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export type CommentWithSlashes = number; /** * Testing expression placeholders in string: ${expression} should work */ export type CommentWithExpressionPlaceholders = number; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export type CommentWithQuotes = number; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export type CommentWithReservedCharacters = number; /** * This is a simple number */ export type SimpleInteger = number; /** * This is a simple boolean */ export type SimpleBoolean = boolean; /** * This is a simple string */ export type SimpleString = string; /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; /** * This is a simple file */ export type SimpleFile = Blob | File; /** * This is a simple reference */ export type SimpleReference = ModelWithString; /** * This is a simple string */ export type SimpleStringWithPattern = string | null; /** * This is a simple enum with strings */ export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; /** * This is a simple enum with numbers */ export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; /** * Success=1,Warning=2,Error=3 */ export type EnumFromDescription = number; /** * This is a simple enum with numbers */ export type EnumWithExtensions = 200 | 400 | 500; export type EnumWithXEnumNames = 0 | 1 | 2; /** * This is a simple array with numbers */ export type ArrayWithNumbers = Array; /** * This is a simple array with booleans */ export type ArrayWithBooleans = Array; /** * This is a simple array with strings */ export type ArrayWithStrings = Array; /** * This is a simple array with references */ export type ArrayWithReferences = Array; /** * This is a simple array containing an array */ export type ArrayWithArray = Array>; /** * This is a simple array with properties */ export type ArrayWithProperties = Array<{ '16x16'?: CamelCaseCommentWithBreaks; bar?: string; }>; /** * This is a simple array with any of properties */ export type ArrayWithAnyOfProperties = Array<{ foo?: string; } | { bar?: string; }>; export type AnyOfAnyAndNull = { data?: unknown | null; }; /** * This is a simple array with any of properties */ export type AnyOfArrays = { results?: Array<{ foo?: string; } | { bar?: string; }>; }; /** * This is a string dictionary */ export type DictionaryWithString = { [key: string]: string; }; export type DictionaryWithPropertiesAndAdditionalProperties = { foo?: number; bar?: boolean; [key: string]: string | number | boolean | undefined; }; /** * This is a string reference */ export type DictionaryWithReference = { [key: string]: ModelWithString; }; /** * This is a complex dictionary */ export type DictionaryWithArray = { [key: string]: Array; }; /** * This is a string dictionary */ export type DictionaryWithDictionary = { [key: string]: { [key: string]: string; }; }; /** * This is a complex dictionary */ export type DictionaryWithProperties = { [key: string]: { foo?: string; bar?: string; }; }; /** * This is a model with one number property */ export type ModelWithInteger = { /** * This is a simple number property */ prop?: number; }; /** * This is a model with one boolean property */ export type ModelWithBoolean = { /** * This is a simple boolean property */ prop?: boolean; }; /** * This is a model with one string property */ export type ModelWithString = { /** * This is a simple string property */ prop?: string; }; /** * This is a model with one string property */ export type ModelWithStringError = { /** * This is a simple string property */ prop?: string; }; /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export type ModelFromZendesk = string; /** * This is a model with one string property */ export type ModelWithNullableString = { /** * This is a simple string property */ nullableProp1?: string | null; /** * This is a simple string property */ nullableRequiredProp1: string | null; /** * This is a simple string property */ nullableProp2?: string | null; /** * This is a simple string property */ nullableRequiredProp2: string | null; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one enum */ export type ModelWithEnum = { /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; /** * These are the HTTP error code enums */ statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; /** * Simple boolean enum */ bool?: true; }; /** * This is a model with one enum with escaped name */ export type ModelWithEnumWithHyphen = { /** * Foo-Bar-Baz-Qux */ 'foo-bar-baz-qux'?: '3.0'; }; /** * This is a model with one enum */ export type ModelWithEnumFromDescription = { /** * Success=1,Warning=2,Error=3 */ test?: number; }; /** * This is a model with nested enums */ export type ModelWithNestedEnums = { dictionaryWithEnum?: { [key: string]: 'Success' | 'Warning' | 'Error'; }; dictionaryWithEnumFromDescription?: { [key: string]: number; }; arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; arrayWithDescription?: Array; /** * This is a simple enum with strings */ 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; }; /** * This is a model with one property containing a reference */ export type ModelWithReference = { prop?: ModelWithProperties; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnly = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing an array */ export type ModelWithArray = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one property containing a dictionary */ export type ModelWithDictionary = { prop?: { [key: string]: string; }; }; /** * This is a deprecated model with a deprecated property * * @deprecated */ export type DeprecatedModel = { /** * This is a deprecated property * * @deprecated */ prop?: string; }; /** * This is a model with one property containing a circular reference */ export type ModelWithCircularReference = { prop?: ModelWithCircularReference; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * Circle */ export type ModelCircle = { kind: string; radius?: number; }; /** * Square */ export type ModelSquare = { kind: string; sideLength?: number; }; /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export type CompositionWithOneOfDiscriminator = ({ kind: 'circle'; } & ModelCircle) | ({ kind: 'square'; } & ModelSquare); /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOf = { propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; }; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithAnyOfAnonymous = { propA?: { propA?: string; } | string | number; }; /** * This is a model with nested 'any of' property with a type null */ export type CompositionWithNestedAnyAndTypeNull = { propA?: Array | Array; }; export type _3eNum1Период = 'Bird' | 'Dog'; export type ConstValue = 'ConstValue'; /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export type CompositionWithNestedAnyOfAndNull = { /** * Scopes */ propA?: Array<_3eNum1Период | ConstValue> | null; }; /** * This is a model with one property with a 'one of' relationship */ export type CompositionWithOneOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a model that contains a simple dictionary within composition */ export type CompositionWithOneOfAndSimpleDictionary = { propA?: boolean | { [key: string]: number; }; }; /** * This is a model that contains a dictionary of simple arrays within composition */ export type CompositionWithOneOfAndSimpleArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export type CompositionWithOneOfAndComplexArrayDictionary = { propA?: boolean | { [key: string]: Array; }; }; /** * This is a model with one property with a 'all of' relationship */ export type CompositionWithAllOfAndNullable = { propA?: ({ boolean?: boolean; } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; }; /** * This is a model with one property with a 'any of' relationship */ export type CompositionWithAnyOfAndNullable = { propA?: { boolean?: boolean; } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; }; /** * This is a base model with two simple optional properties */ export type CompositionBaseModel = { firstName?: string; lastname?: string; }; /** * This is a model that extends the base model */ export type CompositionExtendedModel = CompositionBaseModel & { age: number; firstName: string; lastname: string; }; /** * This is a model with one nested property */ export type ModelWithProperties = { required: string; readonly requiredAndReadOnly: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; }; /** * This is a model with one nested property */ export type ModelWithNestedProperties = { readonly first: { readonly second: { readonly third: string | null; } | null; } | null; }; /** * This is a model with duplicated properties */ export type ModelWithDuplicateProperties = { prop?: ModelWithString; }; /** * This is a model with ordered properties */ export type ModelWithOrderedProperties = { zebra?: string; apple?: string; hawaii?: string; }; /** * This is a model with duplicated imports */ export type ModelWithDuplicateImports = { propA?: ModelWithString; propB?: ModelWithString; propC?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtends = ModelWithString & { propExtendsA?: string; propExtendsB?: ModelWithString; }; /** * This is a model that extends another model */ export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { propExtendsC?: string; propExtendsD?: ModelWithString; }; /** * This is a model that contains a some patterns */ export type ModelWithPattern = { key: string; name: string; readonly enabled?: boolean; readonly modified?: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type File = { /** * Id */ readonly id?: string; /** * Updated at */ readonly updated_at?: string; /** * Created at */ readonly created_at?: string; /** * Mime */ mime: string; /** * File */ readonly file?: string; }; export type Default = { name?: string; }; export type Pageable = { page?: number; size?: number; sort?: Array; }; /** * This is a free-form object without additionalProperties. */ export type FreeFormObjectWithoutAdditionalProperties = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: true. */ export type FreeFormObjectWithAdditionalPropertiesEqTrue = { [key: string]: unknown; }; /** * This is a free-form object with additionalProperties: {}. */ export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { [key: string]: unknown; }; export type ModelWithConst = { String?: 'String'; number?: 0; null?: null; withType?: 'Some string'; }; /** * This is a model with one property and additionalProperties: true */ export type ModelWithAdditionalPropertiesEqTrue = { /** * This is a simple string property */ prop?: string; [key: string]: unknown; }; export type NestedAnyOfArraysNullable = { nullableArray?: Array | null; }; export type CompositionWithOneOfAndProperties = ({ foo: SimpleParameter; } | { bar: NonAsciiStringæøåÆøÅöôêÊ字符串; }) & { baz: number | null; qux: number; }; /** * An object that can be null */ export type NullableObject = { foo?: string; } | null; /** * Some % character */ export type CharactersInDescription = string; export type ModelWithNullableObject = { data?: NullableObject; }; /** * An object with additional properties that can be null (anyOf ref + null) */ export type ModelWithAdditionalPropertiesRef = { [key: string]: NullableObject | null; }; export type ModelWithOneOfEnum = { foo: 'Bar'; } | { foo: 'Baz'; } | { foo: 'Qux'; } | { content: string; foo: 'Quux'; } | { content: [ string, string ]; foo: 'Corge'; }; export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; export type ModelWithNestedArrayEnumsData = { foo?: Array; bar?: Array; }; export type ModelWithNestedArrayEnums = { array_strings?: Array; data?: ModelWithNestedArrayEnumsData; }; export type ModelWithNestedCompositionEnums = { foo?: ModelWithNestedArrayEnumsDataFoo; }; export type ModelWithReadOnlyAndWriteOnly = { foo: string; readonly bar: string; }; export type ModelWithConstantSizeArray = [ number, number ]; export type ModelWithAnyOfConstantSizeArray = [ number | string, number | string, number | string ]; export type ModelWithPrefixItemsConstantSizeArray = [ ModelWithInteger, number | string, string ]; export type ModelWithAnyOfConstantSizeArrayNullable = [ number | null | string, number | null | string, number | null | string ]; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ number | Import, number | Import ]; export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ number & string, number & string ]; export type ModelWithNumericEnumUnion = { /** * Период */ value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; }; /** * Some description with `back ticks` */ export type ModelWithBackticksInDescription = { /** * The template `that` should be used for parsing and importing the contents of the CSV file. * *

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    *
         * [
         * {
         * "resourceType": "Asset",
         * "identifier": {
         * "name": "${1}",
         * "domain": {
         * "name": "${2}",
         * "community": {
         * "name": "Some Community"
         * }
         * }
         * },
         * "attributes" : {
         * "00000000-0000-0000-0000-000000003115" : [ {
         * "value" : "${3}"
         * } ],
         * "00000000-0000-0000-0000-000000000222" : [ {
         * "value" : "${4}"
         * } ]
         * }
         * }
         * ]
         * 
    */ template?: string; }; export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { baz: number | null; qux: number; }; /** * Model used to test deduplication strategy (unused) */ export type ParameterSimpleParameterUnused = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse = string; /** * Model used to test deduplication strategy */ export type PostServiceWithEmptyTagResponse2 = string; /** * Model used to test deduplication strategy */ export type DeleteFooData = string; /** * Model used to test deduplication strategy */ export type DeleteFooData2 = string; /** * Model with restricted keyword name */ export type Import = string; export type SchemaWithFormRestrictedKeys = { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; object?: { description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }; array?: Array<{ description?: string; 'x-enum-descriptions'?: string; 'x-enum-varnames'?: string; 'x-enumNames'?: string; title?: string; }>; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { /** * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; }; /** * This schema was giving PascalCase transformations a hard time */ export type IoK8sApimachineryPkgApisMetaV1Preconditions = { /** * Specifies the target ResourceVersion */ resourceVersion?: string; /** * Specifies the target UID. */ uid?: string; }; export type AdditionalPropertiesUnknownIssue = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue2 = { [key: string]: string | number; }; export type AdditionalPropertiesUnknownIssue3 = string & { entries: { [key: string]: AdditionalPropertiesUnknownIssue; }; }; export type AdditionalPropertiesIntegerIssue = { value: number; [key: string]: number; }; export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBoolean = { item?: boolean; error?: string | null; readonly hasError?: boolean; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemString = { item?: string | null; error?: string | null; readonly hasError?: boolean; }; export type ExternalSharedModel = { id: string; name?: string; }; /** * This is a model with one property containing a reference */ export type ModelWithReferenceWritable = { prop?: ModelWithPropertiesWritable; }; /** * This is a model with one property containing an array */ export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { prop?: Array; propWithFile?: Array; propWithNumber?: Array; }; /** * This is a model with one nested property */ export type ModelWithPropertiesWritable = { required: string; requiredAndNullable: string | null; string?: string; number?: number; boolean?: boolean; reference?: ModelWithString; 'property with space'?: string; default?: string; try?: string; }; /** * This is a model that contains a some patterns */ export type ModelWithPatternWritable = { key: string; name: string; id?: string; text?: string; patternWithSingleQuotes?: string; patternWithNewline?: string; patternWithBacktick?: string; patternWithUnicode?: string; }; export type FileWritable = { /** * Mime */ mime: string; }; export type ModelWithReadOnlyAndWriteOnlyWritable = { foo: string; baz: string; }; export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ number | Import, number | Import ]; export type AdditionalPropertiesUnknownIssueWritable = { [key: string]: string | number; }; export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { item?: boolean; error?: string | null; data?: { [key: string]: never; }; }; export type GenericSchemaDuplicateIssue1SystemStringWritable = { item?: string | null; error?: string | null; }; /** * This is a reusable parameter */ export type SimpleParameter = string; /** * Parameter with illegal characters */ export type XFooBar = ModelWithString; /** * A reusable request body */ export type SimpleRequestBody = ModelWithString; /** * A reusable request body */ export type SimpleFormData = ModelWithString; export type ExportData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type PatchApiVbyApiVersionNoTagResponses = { /** * OK */ default: unknown; }; export type ImportData = { body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type ImportResponses = { /** * Success */ 200: ModelFromZendesk; /** * Default success response */ default: ModelWithReadOnlyAndWriteOnly; }; export type ImportResponse = ImportResponses[keyof ImportResponses]; export type FooWowData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no+tag'; }; export type FooWowResponses = { /** * OK */ default: unknown; }; export type ApiVVersionODataControllerCountData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple/$count'; }; export type ApiVVersionODataControllerCountResponses = { /** * Success */ 200: ModelFromZendesk; }; export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; export type GetApiVbyApiVersionSimpleOperationData = { body?: never; path: { /** * foo in method */ foo_param: string; }; query?: never; url: '/api/v{api-version}/simple:operation'; }; export type GetApiVbyApiVersionSimpleOperationErrors = { /** * Default error response */ default: ModelWithBoolean; }; export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; export type GetApiVbyApiVersionSimpleOperationResponses = { /** * Response is a simple number */ 200: number; }; export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; export type DeleteCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type GetCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type HeadCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type OptionsCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PatchCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PostCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type PutCallWithoutParametersAndResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/simple'; }; export type DeleteFooData3 = { body?: never; headers: { /** * Parameter with illegal characters */ 'x-Foo-Bar': ModelWithString; }; path: { /** * foo in method */ foo_param: string; /** * bar in method */ BarParam: string; }; query?: never; url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; }; export type CallWithDescriptionsData = { body?: never; path?: never; query?: { /** * Testing multiline comments in string: First line * Second line * * Fourth line */ parameterWithBreaks?: string; /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ parameterWithBackticks?: string; /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ parameterWithSlashes?: string; /** * Testing expression placeholders in string: ${expression} should work */ parameterWithExpressionPlaceholders?: string; /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ parameterWithQuotes?: string; /** * Testing reserved characters in string: * inline * and ** inline ** should work */ parameterWithReservedCharacters?: string; }; url: '/api/v{api-version}/descriptions'; }; export type DeprecatedCallData = { body?: never; headers: { /** * This parameter is deprecated * * @deprecated */ parameter: DeprecatedModel | null; }; path?: never; query?: never; url: '/api/v{api-version}/parameters/deprecated'; }; export type CallWithParametersData = { /** * This is the parameter that goes into the body */ body: { [key: string]: unknown; } | null; headers: { /** * This is the parameter that goes into the header */ parameterHeader: string | null; }; path: { /** * This is the parameter that goes into the path */ parameterPath: string | null; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; /** * This is the parameter that goes into the query params */ cursor: string | null; }; url: '/api/v{api-version}/parameters/{parameterPath}'; }; export type CallWithWeirdParameterNamesData = { /** * This is the parameter that goes into the body */ body: ModelWithString | null; headers: { /** * This is the parameter that goes into the request header */ 'parameter.header': string | null; }; path: { /** * This is the parameter that goes into the path */ 'parameter.path.1'?: string; /** * This is the parameter that goes into the path */ 'parameter-path-2'?: string; /** * This is the parameter that goes into the path */ 'PARAMETER-PATH-3'?: string; /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query: { /** * This is the parameter with a reserved keyword */ default?: string; /** * This is the parameter that goes into the request query params */ 'parameter-query': string | null; }; url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; }; export type GetCallWithOptionalParamData = { /** * This is a required parameter */ body: ModelWithOneOfEnum; path?: never; query?: { /** * This is an optional parameter */ page?: number; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamData = { /** * This is an optional parameter */ body?: { offset?: number | null; }; path?: never; query: { /** * This is a required parameter */ parameter: Pageable; }; url: '/api/v{api-version}/parameters'; }; export type PostCallWithOptionalParamResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; export type PostApiVbyApiVersionRequestBodyData = { /** * A reusable request body */ body?: SimpleRequestBody; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/requestBody'; }; export type PostApiVbyApiVersionFormDataData = { /** * A reusable request body */ body?: SimpleFormData; path?: never; query?: { /** * This is a reusable parameter */ parameter?: string; }; url: '/api/v{api-version}/formData'; }; export type CallWithDefaultParametersData = { body?: never; path?: never; query?: { /** * This is a simple string with default value */ parameterString?: string | null; /** * This is a simple number with default value */ parameterNumber?: number | null; /** * This is a simple boolean with default value */ parameterBoolean?: boolean | null; /** * This is a simple enum with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model with default value */ parameterModel?: ModelWithString | null; }; url: '/api/v{api-version}/defaults'; }; export type CallWithDefaultOptionalParametersData = { body?: never; path?: never; query?: { /** * This is a simple string that is optional with default value */ parameterString?: string; /** * This is a simple number that is optional with default value */ parameterNumber?: number; /** * This is a simple boolean that is optional with default value */ parameterBoolean?: boolean; /** * This is a simple enum that is optional with default value */ parameterEnum?: 'Success' | 'Warning' | 'Error'; /** * This is a simple model that is optional with default value */ parameterModel?: ModelWithString; }; url: '/api/v{api-version}/defaults'; }; export type CallToTestOrderOfParamsData = { body?: never; path?: never; query: { /** * This is a optional string with default */ parameterOptionalStringWithDefault?: string; /** * This is a optional string with empty default */ parameterOptionalStringWithEmptyDefault?: string; /** * This is a optional string with no default */ parameterOptionalStringWithNoDefault?: string; /** * This is a string with default */ parameterStringWithDefault: string; /** * This is a string with empty default */ parameterStringWithEmptyDefault: string; /** * This is a string with no default */ parameterStringWithNoDefault: string; /** * This is a string that can be null with no default */ parameterStringNullableWithNoDefault?: string | null; /** * This is a string that can be null with default */ parameterStringNullableWithDefault?: string | null; }; url: '/api/v{api-version}/defaults'; }; export type DuplicateNameData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName2Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName3Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type DuplicateName4Data = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/duplicate'; }; export type CallWithNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/no-content'; }; export type CallWithNoContentResponseResponses = { /** * Success */ 204: void; }; export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; export type CallWithResponseAndNoContentResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/response-and-no-content'; }; export type CallWithResponseAndNoContentResponseResponses = { /** * Response is a simple number */ 200: number; /** * Success */ 204: void; }; export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; export type DummyAData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/a'; }; export type DummyAResponses = { 200: _400; }; export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; export type DummyBData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multiple-tags/b'; }; export type DummyBResponses = { /** * Success */ 204: void; }; export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; export type CallWithResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponseResponses = { default: Import; }; export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; export type CallWithDuplicateResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithDuplicateResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for 4XX errors */ '4XX': DictionaryWithArray; /** * Default error response */ default: ModelWithBoolean; }; export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; export type CallWithDuplicateResponsesResponses = { /** * Message for 200 response */ 200: ModelWithBoolean & ModelWithInteger; /** * Message for 201 response */ 201: ModelWithString; /** * Message for 202 response */ 202: ModelWithString; }; export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; export type CallWithResponsesData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/response'; }; export type CallWithResponsesErrors = { /** * Message for 500 error */ 500: ModelWithStringError; /** * Message for 501 error */ 501: ModelWithStringError; /** * Message for 502 error */ 502: ModelWithStringError; /** * Message for default response */ default: ModelWithStringError; }; export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; export type CallWithResponsesResponses = { /** * Message for 200 response */ 200: { readonly '@namespace.string'?: string; readonly '@namespace.integer'?: number; readonly value?: Array; }; /** * Message for 201 response */ 201: ModelThatExtends; /** * Message for 202 response */ 202: ModelThatExtendsExtends; }; export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; export type CollectionFormatData = { body?: never; path?: never; query: { /** * This is an array parameter that is sent as csv format (comma-separated values) */ parameterArrayCSV: Array | null; /** * This is an array parameter that is sent as ssv format (space-separated values) */ parameterArraySSV: Array | null; /** * This is an array parameter that is sent as tsv format (tab-separated values) */ parameterArrayTSV: Array | null; /** * This is an array parameter that is sent as pipes format (pipe-separated values) */ parameterArrayPipes: Array | null; /** * This is an array parameter that is sent as multi format (multiple parameter instances) */ parameterArrayMulti: Array | null; }; url: '/api/v{api-version}/collectionFormat'; }; export type TypesData = { body?: never; path?: { /** * This is a number parameter */ id?: number; }; query: { /** * This is a number parameter */ parameterNumber: number; /** * This is a string parameter */ parameterString: string | null; /** * This is a boolean parameter */ parameterBoolean: boolean | null; /** * This is an object parameter */ parameterObject: { [key: string]: unknown; } | null; /** * This is an array parameter */ parameterArray: Array | null; /** * This is a dictionary parameter */ parameterDictionary: { [key: string]: unknown; } | null; /** * This is an enum parameter */ parameterEnum: 'Success' | 'Warning' | 'Error' | null; }; url: '/api/v{api-version}/types'; }; export type TypesResponses = { /** * Response is a simple number */ 200: number; /** * Response is a simple string */ 201: string; /** * Response is a simple boolean */ 202: boolean; /** * Response is a simple object */ 203: { [key: string]: unknown; }; }; export type TypesResponse = TypesResponses[keyof TypesResponses]; export type UploadFileData = { body: Blob | File; path: { /** * api-version should be required in standalone clients */ 'api-version': string | null; }; query?: never; url: '/api/v{api-version}/upload'; }; export type UploadFileResponses = { 200: boolean; }; export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; export type FileResponseData = { body?: never; path: { id: string; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/file/{id}'; }; export type FileResponseResponses = { /** * Success */ 200: Blob | File; }; export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; export type ComplexTypesData = { body?: never; path?: never; query: { /** * Parameter containing object */ parameterObject: { first?: { second?: { third?: string; }; }; }; /** * Parameter containing reference */ parameterReference: ModelWithString; }; url: '/api/v{api-version}/complex'; }; export type ComplexTypesErrors = { /** * 400 `server` error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type ComplexTypesResponses = { /** * Successful response */ 200: Array; }; export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; export type MultipartResponseData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type MultipartResponseResponses = { /** * OK */ 200: { file?: Blob | File; metadata?: { foo?: string; bar?: string; }; }; }; export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; export type MultipartRequestData = { body?: { content?: Blob | File; data?: ModelWithString | null; }; path?: never; query?: never; url: '/api/v{api-version}/multipart'; }; export type ComplexParamsData = { body?: { readonly key: string | null; name: string | null; enabled?: boolean; type: 'Monkey' | 'Horse' | 'Bird'; listOfModels?: Array | null; listOfStrings?: Array | null; parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; readonly user?: { readonly id?: number; readonly name?: string | null; }; }; path: { id: number; /** * api-version should be required in standalone clients */ 'api-version': string; }; query?: never; url: '/api/v{api-version}/complex/{id}'; }; export type ComplexParamsResponses = { /** * Success */ 200: ModelWithString; }; export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; export type CallWithResultFromHeaderData = { body?: never; path?: never; query?: never; url: '/api/v{api-version}/header'; }; export type CallWithResultFromHeaderErrors = { /** * 400 server error */ 400: unknown; /** * 500 server error */ 500: unknown; }; export type CallWithResultFromHeaderResponses = { /** * Successful response */ 200: unknown; }; export type TestErrorCodeData = { body?: never; path?: never; query: { /** * Status code to return */ status: number; }; url: '/api/v{api-version}/error'; }; export type TestErrorCodeErrors = { /** * Custom message: Internal Server Error */ 500: unknown; /** * Custom message: Not Implemented */ 501: unknown; /** * Custom message: Bad Gateway */ 502: unknown; /** * Custom message: Service Unavailable */ 503: unknown; }; export type TestErrorCodeResponses = { /** * Custom message: Successful response */ 200: unknown; }; export type NonAsciiæøåÆøÅöôêÊ字符串Data = { body?: never; path?: never; query: { /** * Dummy input param */ nonAsciiParamæøåÆØÅöôêÊ: number; }; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { /** * Successful response */ 200: Array; }; export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; export type PutWithFormUrlEncodedData = { body: ArrayWithStrings; path?: never; query?: never; url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; }; ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/package.json ================================================ { "name": "@test/openapi-ts-nestjs-v11", "version": "0.0.0", "private": true, "type": "module", "scripts": { "typecheck": "tsgo --noEmit" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "typescript": "5.9.3" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/test/plugins.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createClient, type UserConfig } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const versions = ['2.0.x', '3.0.x', '3.1.x']; for (const version of versions) { const outputDir = path.join(__dirname, '..', '.gen', 'snapshots', version); const snapshotsDir = path.join(__dirname, '..', '__snapshots__', version); describe(`OpenAPI ${version} nestjs`, () => { const createConfig = ( userConfig: Omit & Pick, 'plugins'> & Pick, 'input'>, ) => ({ ...userConfig, input: path.join( getSpecsPath(), version, typeof userConfig.input === 'string' ? userConfig.input : 'full.yaml', ), logs: { level: 'silent', }, output: path.join( outputDir, typeof userConfig.output === 'string' ? userConfig.output : '', ), plugins: userConfig.plugins ?? ['@hey-api/client-fetch'], }) as const satisfies UserConfig; const scenarios = [ { config: createConfig({ output: 'default', plugins: ['nestjs'], }), description: 'generate NestJS types with NestJS plugin', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["test/**/*", "__snapshots__/**/*"], "exclude": [".gen/**/*"], "references": [{ "path": "../../../openapi-ts" }] } ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/turbo.json ================================================ { "$schema": "../../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts-tests/nestjs/v11/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-ts-tests/orpc/v1/.gitignore ================================================ .DS_Store .idea .tmp logs node_modules .env coverage dist ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.0.x/custom-names/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { vCreatePostData, vCreatePostResponse, vCreateUserData, vCreateUserResponse, vDeleteUserData, vGetPostByIdData, vGetPostByIdResponse, vGetPostsData, vGetPostsResponse, vGetUserByIdData, vGetUserByIdResponse, vGetUsersData, vGetUsersResponse, vUpdateUserData, vUpdateUserResponse } from './valibot.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const getUsersRpc = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(vGetUsersData).output(vGetUsersResponse); /** * Create a new user */ export const createUserRpc = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(vCreateUserData).output(vCreateUserResponse); /** * Delete a user */ export const deleteUserRpc = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(vDeleteUserData); /** * Get a user by ID */ export const getUserByIdRpc = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(vGetUserByIdData).output(vGetUserByIdResponse); /** * Update a user */ export const updateUserRpc = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(vUpdateUserData).output(vUpdateUserResponse); /** * Get all posts */ export const getPostsRpc = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(vGetPostsData).output(vGetPostsResponse); /** * Create a new post */ export const createPostRpc = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(vCreatePostData).output(vCreatePostResponse); /** * Get a post by ID */ export const getPostByIdRpc = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(vGetPostByIdData).output(vGetPostByIdResponse); export const rpcContract = { getUsersRpc, createUserRpc, deleteUserRpc, getUserByIdRpc, updateUserRpc, getPostsRpc, createPostRpc, getPostByIdRpc }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.0.x/custom-names/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vUser = v.object({ id: v.string(), email: v.pipe(v.string(), v.email()), name: v.string(), createdAt: v.optional(v.pipe(v.string(), v.isoTimestamp())) }); export const vCreateUserInput = v.object({ email: v.pipe(v.string(), v.email()), name: v.string(), password: v.optional(v.pipe(v.string(), v.minLength(8))) }); export const vUpdateUserInput = v.object({ email: v.optional(v.pipe(v.string(), v.email())), name: v.optional(v.string()) }); export const vPost = v.object({ id: v.string(), title: v.string(), content: v.string(), authorId: v.string(), status: v.optional(v.picklist([ 'draft', 'published', 'archived' ])), createdAt: v.optional(v.pipe(v.string(), v.isoTimestamp())) }); export const vCreatePostInput = v.object({ title: v.string(), content: v.string(), status: v.optional(v.picklist(['draft', 'published'])) }); export const vGetUsersData = v.object({ body: v.optional(v.never()), path: v.optional(v.never()), query: v.optional(v.object({ limit: v.optional(v.pipe(v.number(), v.integer()), 10), offset: v.optional(v.pipe(v.number(), v.integer()), 0) })) }); /** * List of users */ export const vGetUsersResponse = v.array(vUser); export const vCreateUserData = v.object({ body: vCreateUserInput, path: v.optional(v.never()), query: v.optional(v.never()) }); /** * User created */ export const vCreateUserResponse = vUser; export const vDeleteUserData = v.object({ body: v.optional(v.never()), path: v.object({ userId: v.string() }), query: v.optional(v.never()), headers: v.optional(v.object({ 'X-Request-Id': v.optional(v.string()) })) }); /** * User deleted */ export const vDeleteUserResponse = v.void(); export const vGetUserByIdData = v.object({ body: v.optional(v.never()), path: v.object({ userId: v.string() }), query: v.optional(v.never()) }); /** * User found */ export const vGetUserByIdResponse = vUser; export const vUpdateUserData = v.object({ body: vUpdateUserInput, path: v.object({ userId: v.string() }), query: v.optional(v.never()) }); /** * User updated */ export const vUpdateUserResponse = vUser; export const vGetPostsData = v.object({ body: v.optional(v.never()), path: v.optional(v.never()), query: v.optional(v.object({ authorId: v.optional(v.string()), status: v.optional(v.picklist([ 'draft', 'published', 'archived' ])) })) }); /** * List of posts */ export const vGetPostsResponse = v.array(vPost); export const vCreatePostData = v.object({ body: vCreatePostInput, path: v.optional(v.never()), query: v.optional(v.never()), headers: v.object({ 'X-Author-Id': v.string() }) }); /** * Post created */ export const vCreatePostResponse = vPost; export const vGetPostByIdData = v.object({ body: v.optional(v.never()), path: v.object({ postId: v.string() }), query: v.optional(v.object({ includeComments: v.optional(v.boolean(), false) })) }); /** * Post found */ export const vGetPostByIdResponse = vPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.0.x/default/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { zCreatePostData, zCreatePostResponse, zCreateUserData, zCreateUserResponse, zDeleteUserData, zGetPostByIdData, zGetPostByIdResponse, zGetPostsData, zGetPostsResponse, zGetUserByIdData, zGetUserByIdResponse, zGetUsersData, zGetUsersResponse, zUpdateUserData, zUpdateUserResponse } from './zod.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const getUsers = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(zGetUsersData).output(zGetUsersResponse); /** * Create a new user */ export const createUser = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(zCreateUserData).output(zCreateUserResponse); /** * Delete a user */ export const deleteUser = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(zDeleteUserData); /** * Get a user by ID */ export const getUserById = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(zGetUserByIdData).output(zGetUserByIdResponse); /** * Update a user */ export const updateUser = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(zUpdateUserData).output(zUpdateUserResponse); /** * Get all posts */ export const getPosts = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(zGetPostsData).output(zGetPostsResponse); /** * Create a new post */ export const createPost = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(zCreatePostData).output(zCreatePostResponse); /** * Get a post by ID */ export const getPostById = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(zGetPostByIdData).output(zGetPostByIdResponse); export const contract = { getUsers, createUser, deleteUser, getUserById, updateUser, getPosts, createPost, getPostById }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.0.x/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zUser = z.object({ id: z.string(), email: z.email(), name: z.string(), createdAt: z.iso.datetime().optional() }); export const zCreateUserInput = z.object({ email: z.email(), name: z.string(), password: z.string().min(8).optional() }); export const zUpdateUserInput = z.object({ email: z.email().optional(), name: z.string().optional() }); export const zPost = z.object({ id: z.string(), title: z.string(), content: z.string(), authorId: z.string(), status: z.enum([ 'draft', 'published', 'archived' ]).optional(), createdAt: z.iso.datetime().optional() }); export const zCreatePostInput = z.object({ title: z.string(), content: z.string(), status: z.enum(['draft', 'published']).optional() }); export const zGetUsersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ limit: z.int().optional().default(10), offset: z.int().optional().default(0) }).optional() }); /** * List of users */ export const zGetUsersResponse = z.array(zUser); export const zCreateUserData = z.object({ body: zCreateUserInput, path: z.never().optional(), query: z.never().optional() }); /** * User created */ export const zCreateUserResponse = zUser; export const zDeleteUserData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional(), headers: z.object({ 'X-Request-Id': z.string().optional() }).optional() }); /** * User deleted */ export const zDeleteUserResponse = z.void(); export const zGetUserByIdData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User found */ export const zGetUserByIdResponse = zUser; export const zUpdateUserData = z.object({ body: zUpdateUserInput, path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User updated */ export const zUpdateUserResponse = zUser; export const zGetPostsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ authorId: z.string().optional(), status: z.enum([ 'draft', 'published', 'archived' ]).optional() }).optional() }); /** * List of posts */ export const zGetPostsResponse = z.array(zPost); export const zCreatePostData = z.object({ body: zCreatePostInput, path: z.never().optional(), query: z.never().optional(), headers: z.object({ 'X-Author-Id': z.string() }) }); /** * Post created */ export const zCreatePostResponse = zPost; export const zGetPostByIdData = z.object({ body: z.never().optional(), path: z.object({ postId: z.string() }), query: z.object({ includeComments: z.boolean().optional().default(false) }).optional() }); /** * Post found */ export const zGetPostByIdResponse = zPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-custom-naming/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { zCreatePostData, zCreatePostResponse, zCreateUserData, zCreateUserResponse, zDeleteUserData, zGetPostByIdData, zGetPostByIdResponse, zGetPostsData, zGetPostsResponse, zGetUserByIdData, zGetUserByIdResponse, zGetUsersData, zGetUsersResponse, zUpdateUserData, zUpdateUserResponse } from './zod.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const GetUsers = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(zGetUsersData).output(zGetUsersResponse); /** * Create a new user */ export const CreateUser = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(zCreateUserData).output(zCreateUserResponse); /** * Delete a user */ export const DeleteUser = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(zDeleteUserData); /** * Get a user by ID */ export const GetUserById = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(zGetUserByIdData).output(zGetUserByIdResponse); /** * Update a user */ export const UpdateUser = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(zUpdateUserData).output(zUpdateUserResponse); export const usersContracts = { GetUsers, CreateUser, DeleteUser, GetUserById, UpdateUser }; /** * Get all posts */ export const GetPosts = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(zGetPostsData).output(zGetPostsResponse); /** * Create a new post */ export const CreatePost = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(zCreatePostData).output(zCreatePostResponse); /** * Get a post by ID */ export const GetPostById = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(zGetPostByIdData).output(zGetPostByIdResponse); export const postsContracts = { GetPosts, CreatePost, GetPostById }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-custom-naming/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zUser = z.object({ id: z.string(), email: z.email(), name: z.string(), createdAt: z.iso.datetime().optional() }); export const zCreateUserInput = z.object({ email: z.email(), name: z.string(), password: z.string().min(8).optional() }); export const zUpdateUserInput = z.object({ email: z.email().optional(), name: z.string().optional() }); export const zPost = z.object({ id: z.string(), title: z.string(), content: z.string(), authorId: z.string(), status: z.enum([ 'draft', 'published', 'archived' ]).optional(), createdAt: z.iso.datetime().optional() }); export const zCreatePostInput = z.object({ title: z.string(), content: z.string(), status: z.enum(['draft', 'published']).optional() }); export const zGetUsersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ limit: z.int().optional().default(10), offset: z.int().optional().default(0) }).optional() }); /** * List of users */ export const zGetUsersResponse = z.array(zUser); export const zCreateUserData = z.object({ body: zCreateUserInput, path: z.never().optional(), query: z.never().optional() }); /** * User created */ export const zCreateUserResponse = zUser; export const zDeleteUserData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional(), headers: z.object({ 'X-Request-Id': z.string().optional() }).optional() }); /** * User deleted */ export const zDeleteUserResponse = z.void(); export const zGetUserByIdData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User found */ export const zGetUserByIdResponse = zUser; export const zUpdateUserData = z.object({ body: zUpdateUserInput, path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User updated */ export const zUpdateUserResponse = zUser; export const zGetPostsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ authorId: z.string().optional(), status: z.enum([ 'draft', 'published', 'archived' ]).optional() }).optional() }); /** * List of posts */ export const zGetPostsResponse = z.array(zPost); export const zCreatePostData = z.object({ body: zCreatePostInput, path: z.never().optional(), query: z.never().optional(), headers: z.object({ 'X-Author-Id': z.string() }) }); /** * Post created */ export const zCreatePostResponse = zPost; export const zGetPostByIdData = z.object({ body: z.never().optional(), path: z.object({ postId: z.string() }), query: z.object({ includeComments: z.boolean().optional().default(false) }).optional() }); /** * Post found */ export const zGetPostByIdResponse = zPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-nesting-id/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { zCreatePostData, zCreatePostResponse, zCreateUserData, zCreateUserResponse, zDeleteUserData, zGetPostByIdData, zGetPostByIdResponse, zGetPostsData, zGetPostsResponse, zGetUserByIdData, zGetUserByIdResponse, zGetUsersData, zGetUsersResponse, zUpdateUserData, zUpdateUserResponse } from './zod.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const getUsers = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(zGetUsersData).output(zGetUsersResponse); /** * Create a new user */ export const createUser = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(zCreateUserData).output(zCreateUserResponse); /** * Delete a user */ export const deleteUser = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(zDeleteUserData); /** * Get a user by ID */ export const getUserById = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(zGetUserByIdData).output(zGetUserByIdResponse); /** * Update a user */ export const updateUser = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(zUpdateUserData).output(zUpdateUserResponse); export const users = { getUsers, createUser, deleteUser, getUserById, updateUser }; /** * Get all posts */ export const getPosts = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(zGetPostsData).output(zGetPostsResponse); /** * Create a new post */ export const createPost = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(zCreatePostData).output(zCreatePostResponse); /** * Get a post by ID */ export const getPostById = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(zGetPostByIdData).output(zGetPostByIdResponse); export const posts = { getPosts, createPost, getPostById }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-nesting-id/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zUser = z.object({ id: z.string(), email: z.email(), name: z.string(), createdAt: z.iso.datetime().optional() }); export const zCreateUserInput = z.object({ email: z.email(), name: z.string(), password: z.string().min(8).optional() }); export const zUpdateUserInput = z.object({ email: z.email().optional(), name: z.string().optional() }); export const zPost = z.object({ id: z.string(), title: z.string(), content: z.string(), authorId: z.string(), status: z.enum([ 'draft', 'published', 'archived' ]).optional(), createdAt: z.iso.datetime().optional() }); export const zCreatePostInput = z.object({ title: z.string(), content: z.string(), status: z.enum(['draft', 'published']).optional() }); export const zGetUsersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ limit: z.int().optional().default(10), offset: z.int().optional().default(0) }).optional() }); /** * List of users */ export const zGetUsersResponse = z.array(zUser); export const zCreateUserData = z.object({ body: zCreateUserInput, path: z.never().optional(), query: z.never().optional() }); /** * User created */ export const zCreateUserResponse = zUser; export const zDeleteUserData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional(), headers: z.object({ 'X-Request-Id': z.string().optional() }).optional() }); /** * User deleted */ export const zDeleteUserResponse = z.void(); export const zGetUserByIdData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User found */ export const zGetUserByIdResponse = zUser; export const zUpdateUserData = z.object({ body: zUpdateUserInput, path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User updated */ export const zUpdateUserResponse = zUser; export const zGetPostsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ authorId: z.string().optional(), status: z.enum([ 'draft', 'published', 'archived' ]).optional() }).optional() }); /** * List of posts */ export const zGetPostsResponse = z.array(zPost); export const zCreatePostData = z.object({ body: zCreatePostInput, path: z.never().optional(), query: z.never().optional(), headers: z.object({ 'X-Author-Id': z.string() }) }); /** * Post created */ export const zCreatePostResponse = zPost; export const zGetPostByIdData = z.object({ body: z.never().optional(), path: z.object({ postId: z.string() }), query: z.object({ includeComments: z.boolean().optional().default(false) }).optional() }); /** * Post found */ export const zGetPostByIdResponse = zPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-strategy-by-tags/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { zCreatePostData, zCreatePostResponse, zCreateUserData, zCreateUserResponse, zDeleteUserData, zGetPostByIdData, zGetPostByIdResponse, zGetPostsData, zGetPostsResponse, zGetUserByIdData, zGetUserByIdResponse, zGetUsersData, zGetUsersResponse, zUpdateUserData, zUpdateUserResponse } from './zod.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const getUsers = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(zGetUsersData).output(zGetUsersResponse); /** * Create a new user */ export const createUser = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(zCreateUserData).output(zCreateUserResponse); /** * Delete a user */ export const deleteUser = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(zDeleteUserData); /** * Get a user by ID */ export const getUserById = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(zGetUserByIdData).output(zGetUserByIdResponse); /** * Update a user */ export const updateUser = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(zUpdateUserData).output(zUpdateUserResponse); export const users = { getUsers, createUser, deleteUser, getUserById, updateUser }; /** * Get all posts */ export const getPosts = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(zGetPostsData).output(zGetPostsResponse); /** * Create a new post */ export const createPost = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(zCreatePostData).output(zCreatePostResponse); /** * Get a post by ID */ export const getPostById = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(zGetPostByIdData).output(zGetPostByIdResponse); export const posts = { getPosts, createPost, getPostById }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-strategy-by-tags/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zUser = z.object({ id: z.string(), email: z.email(), name: z.string(), createdAt: z.iso.datetime().optional() }); export const zCreateUserInput = z.object({ email: z.email(), name: z.string(), password: z.string().min(8).optional() }); export const zUpdateUserInput = z.object({ email: z.email().optional(), name: z.string().optional() }); export const zPost = z.object({ id: z.string(), title: z.string(), content: z.string(), authorId: z.string(), status: z.enum([ 'draft', 'published', 'archived' ]).optional(), createdAt: z.iso.datetime().optional() }); export const zCreatePostInput = z.object({ title: z.string(), content: z.string(), status: z.enum(['draft', 'published']).optional() }); export const zGetUsersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ limit: z.int().optional().default(10), offset: z.int().optional().default(0) }).optional() }); /** * List of users */ export const zGetUsersResponse = z.array(zUser); export const zCreateUserData = z.object({ body: zCreateUserInput, path: z.never().optional(), query: z.never().optional() }); /** * User created */ export const zCreateUserResponse = zUser; export const zDeleteUserData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional(), headers: z.object({ 'X-Request-Id': z.string().optional() }).optional() }); /** * User deleted */ export const zDeleteUserResponse = z.void(); export const zGetUserByIdData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User found */ export const zGetUserByIdResponse = zUser; export const zUpdateUserData = z.object({ body: zUpdateUserInput, path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User updated */ export const zUpdateUserResponse = zUser; export const zGetPostsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ authorId: z.string().optional(), status: z.enum([ 'draft', 'published', 'archived' ]).optional() }).optional() }); /** * List of posts */ export const zGetPostsResponse = z.array(zPost); export const zCreatePostData = z.object({ body: zCreatePostInput, path: z.never().optional(), query: z.never().optional(), headers: z.object({ 'X-Author-Id': z.string() }) }); /** * Post created */ export const zCreatePostResponse = zPost; export const zGetPostByIdData = z.object({ body: z.never().optional(), path: z.object({ postId: z.string() }), query: z.object({ includeComments: z.boolean().optional().default(false) }).optional() }); /** * Post found */ export const zGetPostByIdResponse = zPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-strategy-single/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { zCreatePostData, zCreatePostResponse, zCreateUserData, zCreateUserResponse, zDeleteUserData, zGetPostByIdData, zGetPostByIdResponse, zGetPostsData, zGetPostsResponse, zGetUserByIdData, zGetUserByIdResponse, zGetUsersData, zGetUsersResponse, zUpdateUserData, zUpdateUserResponse } from './zod.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const getUsers = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(zGetUsersData).output(zGetUsersResponse); /** * Create a new user */ export const createUser = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(zCreateUserData).output(zCreateUserResponse); /** * Delete a user */ export const deleteUser = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(zDeleteUserData); /** * Get a user by ID */ export const getUserById = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(zGetUserByIdData).output(zGetUserByIdResponse); /** * Update a user */ export const updateUser = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(zUpdateUserData).output(zUpdateUserResponse); /** * Get all posts */ export const getPosts = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(zGetPostsData).output(zGetPostsResponse); /** * Create a new post */ export const createPost = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(zCreatePostData).output(zCreatePostResponse); /** * Get a post by ID */ export const getPostById = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(zGetPostByIdData).output(zGetPostByIdResponse); export const api = { getUsers, createUser, deleteUser, getUserById, updateUser, getPosts, createPost, getPostById }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/contracts-strategy-single/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zUser = z.object({ id: z.string(), email: z.email(), name: z.string(), createdAt: z.iso.datetime().optional() }); export const zCreateUserInput = z.object({ email: z.email(), name: z.string(), password: z.string().min(8).optional() }); export const zUpdateUserInput = z.object({ email: z.email().optional(), name: z.string().optional() }); export const zPost = z.object({ id: z.string(), title: z.string(), content: z.string(), authorId: z.string(), status: z.enum([ 'draft', 'published', 'archived' ]).optional(), createdAt: z.iso.datetime().optional() }); export const zCreatePostInput = z.object({ title: z.string(), content: z.string(), status: z.enum(['draft', 'published']).optional() }); export const zGetUsersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ limit: z.int().optional().default(10), offset: z.int().optional().default(0) }).optional() }); /** * List of users */ export const zGetUsersResponse = z.array(zUser); export const zCreateUserData = z.object({ body: zCreateUserInput, path: z.never().optional(), query: z.never().optional() }); /** * User created */ export const zCreateUserResponse = zUser; export const zDeleteUserData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional(), headers: z.object({ 'X-Request-Id': z.string().optional() }).optional() }); /** * User deleted */ export const zDeleteUserResponse = z.void(); export const zGetUserByIdData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User found */ export const zGetUserByIdResponse = zUser; export const zUpdateUserData = z.object({ body: zUpdateUserInput, path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User updated */ export const zUpdateUserResponse = zUser; export const zGetPostsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ authorId: z.string().optional(), status: z.enum([ 'draft', 'published', 'archived' ]).optional() }).optional() }); /** * List of posts */ export const zGetPostsResponse = z.array(zPost); export const zCreatePostData = z.object({ body: zCreatePostInput, path: z.never().optional(), query: z.never().optional(), headers: z.object({ 'X-Author-Id': z.string() }) }); /** * Post created */ export const zCreatePostResponse = zPost; export const zGetPostByIdData = z.object({ body: z.never().optional(), path: z.object({ postId: z.string() }), query: z.object({ includeComments: z.boolean().optional().default(false) }).optional() }); /** * Post found */ export const zGetPostByIdResponse = zPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/custom-names/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { vCreatePostData, vCreatePostResponse, vCreateUserData, vCreateUserResponse, vDeleteUserData, vGetPostByIdData, vGetPostByIdResponse, vGetPostsData, vGetPostsResponse, vGetUserByIdData, vGetUserByIdResponse, vGetUsersData, vGetUsersResponse, vUpdateUserData, vUpdateUserResponse } from './valibot.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const getUsersRpc = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(vGetUsersData).output(vGetUsersResponse); /** * Create a new user */ export const createUserRpc = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(vCreateUserData).output(vCreateUserResponse); /** * Delete a user */ export const deleteUserRpc = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(vDeleteUserData); /** * Get a user by ID */ export const getUserByIdRpc = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(vGetUserByIdData).output(vGetUserByIdResponse); /** * Update a user */ export const updateUserRpc = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(vUpdateUserData).output(vUpdateUserResponse); /** * Get all posts */ export const getPostsRpc = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(vGetPostsData).output(vGetPostsResponse); /** * Create a new post */ export const createPostRpc = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(vCreatePostData).output(vCreatePostResponse); /** * Get a post by ID */ export const getPostByIdRpc = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(vGetPostByIdData).output(vGetPostByIdResponse); export const rpcContract = { getUsersRpc, createUserRpc, deleteUserRpc, getUserByIdRpc, updateUserRpc, getPostsRpc, createPostRpc, getPostByIdRpc }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/custom-names/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vUser = v.object({ id: v.string(), email: v.pipe(v.string(), v.email()), name: v.string(), createdAt: v.optional(v.pipe(v.string(), v.isoTimestamp())) }); export const vCreateUserInput = v.object({ email: v.pipe(v.string(), v.email()), name: v.string(), password: v.optional(v.pipe(v.string(), v.minLength(8))) }); export const vUpdateUserInput = v.object({ email: v.optional(v.pipe(v.string(), v.email())), name: v.optional(v.string()) }); export const vPost = v.object({ id: v.string(), title: v.string(), content: v.string(), authorId: v.string(), status: v.optional(v.picklist([ 'draft', 'published', 'archived' ])), createdAt: v.optional(v.pipe(v.string(), v.isoTimestamp())) }); export const vCreatePostInput = v.object({ title: v.string(), content: v.string(), status: v.optional(v.picklist(['draft', 'published'])) }); export const vGetUsersData = v.object({ body: v.optional(v.never()), path: v.optional(v.never()), query: v.optional(v.object({ limit: v.optional(v.pipe(v.number(), v.integer()), 10), offset: v.optional(v.pipe(v.number(), v.integer()), 0) })) }); /** * List of users */ export const vGetUsersResponse = v.array(vUser); export const vCreateUserData = v.object({ body: vCreateUserInput, path: v.optional(v.never()), query: v.optional(v.never()) }); /** * User created */ export const vCreateUserResponse = vUser; export const vDeleteUserData = v.object({ body: v.optional(v.never()), path: v.object({ userId: v.string() }), query: v.optional(v.never()), headers: v.optional(v.object({ 'X-Request-Id': v.optional(v.string()) })) }); /** * User deleted */ export const vDeleteUserResponse = v.void(); export const vGetUserByIdData = v.object({ body: v.optional(v.never()), path: v.object({ userId: v.string() }), query: v.optional(v.never()) }); /** * User found */ export const vGetUserByIdResponse = vUser; export const vUpdateUserData = v.object({ body: vUpdateUserInput, path: v.object({ userId: v.string() }), query: v.optional(v.never()) }); /** * User updated */ export const vUpdateUserResponse = vUser; export const vGetPostsData = v.object({ body: v.optional(v.never()), path: v.optional(v.never()), query: v.optional(v.object({ authorId: v.optional(v.string()), status: v.optional(v.picklist([ 'draft', 'published', 'archived' ])) })) }); /** * List of posts */ export const vGetPostsResponse = v.array(vPost); export const vCreatePostData = v.object({ body: vCreatePostInput, path: v.optional(v.never()), query: v.optional(v.never()), headers: v.object({ 'X-Author-Id': v.string() }) }); /** * Post created */ export const vCreatePostResponse = vPost; export const vGetPostByIdData = v.object({ body: v.optional(v.never()), path: v.object({ postId: v.string() }), query: v.optional(v.object({ includeComments: v.optional(v.boolean(), false) })) }); /** * Post found */ export const vGetPostByIdResponse = vPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/default/orpc.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { oc } from '@orpc/contract'; import { zCreatePostData, zCreatePostResponse, zCreateUserData, zCreateUserResponse, zDeleteUserData, zGetPostByIdData, zGetPostByIdResponse, zGetPostsData, zGetPostsResponse, zGetUserByIdData, zGetUserByIdResponse, zGetUsersData, zGetUsersResponse, zUpdateUserData, zUpdateUserResponse } from './zod.gen'; export const base = oc.$route({ inputStructure: 'detailed' }); /** * Get all users */ export const getUsers = base.route({ method: 'GET', operationId: 'getUsers', path: '/users', summary: 'Get all users', tags: ['users'] }).input(zGetUsersData).output(zGetUsersResponse); /** * Create a new user */ export const createUser = base.route({ method: 'POST', operationId: 'createUser', path: '/users', successStatus: 201, summary: 'Create a new user', tags: ['users'] }).input(zCreateUserData).output(zCreateUserResponse); /** * Delete a user */ export const deleteUser = base.route({ method: 'DELETE', operationId: 'deleteUser', path: '/users/{userId}', summary: 'Delete a user', tags: ['users'] }).input(zDeleteUserData); /** * Get a user by ID */ export const getUserById = base.route({ method: 'GET', operationId: 'getUserById', path: '/users/{userId}', summary: 'Get a user by ID', tags: ['users'] }).input(zGetUserByIdData).output(zGetUserByIdResponse); /** * Update a user */ export const updateUser = base.route({ method: 'PUT', operationId: 'updateUser', path: '/users/{userId}', summary: 'Update a user', tags: ['users'] }).input(zUpdateUserData).output(zUpdateUserResponse); /** * Get all posts */ export const getPosts = base.route({ method: 'GET', operationId: 'getPosts', path: '/posts', summary: 'Get all posts', tags: ['posts'] }).input(zGetPostsData).output(zGetPostsResponse); /** * Create a new post */ export const createPost = base.route({ method: 'POST', operationId: 'createPost', path: '/posts', successStatus: 201, summary: 'Create a new post', tags: ['posts'] }).input(zCreatePostData).output(zCreatePostResponse); /** * Get a post by ID */ export const getPostById = base.route({ method: 'GET', operationId: 'getPostById', path: '/posts/{postId}', summary: 'Get a post by ID', tags: ['posts'] }).input(zGetPostByIdData).output(zGetPostByIdResponse); export const contract = { getUsers, createUser, deleteUser, getUserById, updateUser, getPosts, createPost, getPostById }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/__snapshots__/3.1.x/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zUser = z.object({ id: z.string(), email: z.email(), name: z.string(), createdAt: z.iso.datetime().optional() }); export const zCreateUserInput = z.object({ email: z.email(), name: z.string(), password: z.string().min(8).optional() }); export const zUpdateUserInput = z.object({ email: z.email().optional(), name: z.string().optional() }); export const zPost = z.object({ id: z.string(), title: z.string(), content: z.string(), authorId: z.string(), status: z.enum([ 'draft', 'published', 'archived' ]).optional(), createdAt: z.iso.datetime().optional() }); export const zCreatePostInput = z.object({ title: z.string(), content: z.string(), status: z.enum(['draft', 'published']).optional() }); export const zGetUsersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ limit: z.int().optional().default(10), offset: z.int().optional().default(0) }).optional() }); /** * List of users */ export const zGetUsersResponse = z.array(zUser); export const zCreateUserData = z.object({ body: zCreateUserInput, path: z.never().optional(), query: z.never().optional() }); /** * User created */ export const zCreateUserResponse = zUser; export const zDeleteUserData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional(), headers: z.object({ 'X-Request-Id': z.string().optional() }).optional() }); /** * User deleted */ export const zDeleteUserResponse = z.void(); export const zGetUserByIdData = z.object({ body: z.never().optional(), path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User found */ export const zGetUserByIdResponse = zUser; export const zUpdateUserData = z.object({ body: zUpdateUserInput, path: z.object({ userId: z.string() }), query: z.never().optional() }); /** * User updated */ export const zUpdateUserResponse = zUser; export const zGetPostsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ authorId: z.string().optional(), status: z.enum([ 'draft', 'published', 'archived' ]).optional() }).optional() }); /** * List of posts */ export const zGetPostsResponse = z.array(zPost); export const zCreatePostData = z.object({ body: zCreatePostInput, path: z.never().optional(), query: z.never().optional(), headers: z.object({ 'X-Author-Id': z.string() }) }); /** * Post created */ export const zCreatePostResponse = zPost; export const zGetPostByIdData = z.object({ body: z.never().optional(), path: z.object({ postId: z.string() }), query: z.object({ includeComments: z.boolean().optional().default(false) }).optional() }); /** * Post found */ export const zGetPostByIdResponse = zPost; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/package.json ================================================ { "name": "@test/openapi-ts-orpc-v1", "version": "0.0.0", "private": true, "type": "module", "scripts": { "typecheck": "tsgo --noEmit" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "@orpc/contract": "1.13.4", "typescript": "5.9.3", "valibot": "1.2.0", "zod": "4.3.6" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts-tests/orpc/v1/test/3.0.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { snapshotsDir, tmpDir } from './constants'; import { createOrpcConfig } from './utils'; const version = '3.0.x'; const outputDir = path.join(tmpDir, version); describe(`OpenAPI ${version}`, () => { const createConfig = createOrpcConfig({ openApiVersion: version, outputDir }); const scenarios = [ { config: createConfig({ input: 'orpc.yaml', output: 'default', plugins: ['orpc', 'zod'], }), description: 'generate oRPC contracts with Zod schemas', }, { config: createConfig({ input: 'orpc.yaml', output: 'custom-names', plugins: [ 'valibot', { contracts: { containerName: 'rpcContract', contractName: '{{name}}Rpc', }, name: 'orpc', }, ], }), description: 'generate oRPC contracts with custom names and Valibot schemas', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const outputString = config.output as string; const filePaths = getFilePaths(outputString); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, version, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/orpc/v1/test/3.1.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { snapshotsDir, tmpDir } from './constants'; import { createOrpcConfig } from './utils'; const version = '3.1.x'; const outputDir = path.join(tmpDir, version); describe(`OpenAPI ${version}`, () => { const createConfig = createOrpcConfig({ openApiVersion: version, outputDir }); const scenarios = [ { config: createConfig({ input: 'orpc.yaml', output: 'default', plugins: ['orpc', 'zod'], }), description: 'generate oRPC contracts with Zod schemas', }, { config: createConfig({ input: 'orpc.yaml', output: 'custom-names', plugins: [ 'valibot', { contracts: { containerName: 'rpcContract', contractName: '{{name}}Rpc', }, name: 'orpc', }, ], }), description: 'generate oRPC contracts with custom names and Valibot schemas', }, { config: createConfig({ input: 'orpc.yaml', output: 'contracts-strategy-by-tags', plugins: [ 'zod', { contracts: { strategy: 'byTags', }, name: 'orpc', }, ], }), description: 'generate oRPC contracts grouped by tags', }, { config: createConfig({ input: 'orpc.yaml', output: 'contracts-strategy-single', plugins: [ 'zod', { contracts: { containerName: 'api', strategy: 'single', }, name: 'orpc', }, ], }), description: 'generate oRPC contracts in a single container', }, { config: createConfig({ input: 'orpc.yaml', output: 'contracts-nesting-id', plugins: [ 'zod', { contracts: { nesting: 'id', strategy: 'byTags', }, name: 'orpc', }, ], }), description: 'generate oRPC contracts without operationId nesting', }, { config: createConfig({ input: 'orpc.yaml', output: 'contracts-custom-naming', plugins: [ 'zod', { contracts: { containerName: '{{name}}Contracts', contractName: { casing: 'PascalCase' }, segmentName: { casing: 'PascalCase' }, strategy: 'byTags', }, name: 'orpc', }, ], }), description: 'generate oRPC contracts with custom naming', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output as string); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, version, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/orpc/v1/test/constants.ts ================================================ import path from 'node:path'; export const snapshotsDir = path.join(__dirname, '..', '__snapshots__'); export const tmpDir = path.join(__dirname, '..', '.tmp'); ================================================ FILE: packages/openapi-ts-tests/orpc/v1/test/globalTeardown.ts ================================================ import fs from 'node:fs'; import { tmpDir } from './constants'; export function teardown() { fs.rmSync(tmpDir, { force: true, recursive: true }); } ================================================ FILE: packages/openapi-ts-tests/orpc/v1/test/utils.ts ================================================ import path from 'node:path'; import type { UserConfig } from '@hey-api/openapi-ts'; import { getSpecsPath } from '../../../utils'; export const createOrpcConfig = ({ openApiVersion, outputDir }: { openApiVersion: string; outputDir: string }) => (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0]! : userConfig.input; const inputPath = path.join( getSpecsPath(), openApiVersion, typeof input === 'string' ? input : (input.path as string), ); const output = userConfig.output instanceof Array ? userConfig.output[0]! : userConfig.output; const outputPath = typeof output === 'string' ? output : (output?.path ?? ''); return { plugins: ['orpc'], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', path: './logs' }, output: path.join(outputDir, outputPath), } as UserConfig; }; ================================================ FILE: packages/openapi-ts-tests/orpc/v1/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["test/**/*", "__snapshots__/**/*"], "references": [{ "path": "../../../openapi-ts" }] } ================================================ FILE: packages/openapi-ts-tests/orpc/v1/turbo.json ================================================ { "$schema": "../../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts-tests/orpc/v1/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-ts-tests/sdks/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client'; import { client } from './client.gen'; import type { ApiVVersionApiVersionOdataAccountingCompaniesCountData, ApiVVersionApiVersionOdataAccountingCompaniesCountResponses, ApiVVersionApiVersionOdataAccountingCompaniesData, ApiVVersionApiVersionOdataAccountingCompaniesResponses, ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountData, ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses, ApiVVersionApiVersionOdataAccountingCompanyMembershipsData, ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses, ApiVVersionApiVersionOdataBankAccountsCountData, ApiVVersionApiVersionOdataBankAccountsCountResponses, ApiVVersionApiVersionOdataBankAccountsData, ApiVVersionApiVersionOdataBankAccountsResponses, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountData, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsData, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses, ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountData, ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses, ApiVVersionApiVersionOdataBusinessDocumentActivitiesData, ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses, ApiVVersionApiVersionOdataBusinessDocumentsCountData, ApiVVersionApiVersionOdataBusinessDocumentsCountResponses, ApiVVersionApiVersionOdataBusinessDocumentsData, ApiVVersionApiVersionOdataBusinessDocumentsResponses, ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountData, ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses, ApiVVersionApiVersionOdataBusinessDocumentsSummariesData, ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses, ApiVVersionApiVersionOdataBusinessesCountData, ApiVVersionApiVersionOdataBusinessesCountResponses, ApiVVersionApiVersionOdataBusinessesData, ApiVVersionApiVersionOdataBusinessesKey2Data, ApiVVersionApiVersionOdataBusinessesKey2Responses, ApiVVersionApiVersionOdataBusinessesKeyData, ApiVVersionApiVersionOdataBusinessesKeyResponses, ApiVVersionApiVersionOdataBusinessesResponses, ApiVVersionApiVersionOdataBusinessSummariesCountData, ApiVVersionApiVersionOdataBusinessSummariesCountResponses, ApiVVersionApiVersionOdataBusinessSummariesData, ApiVVersionApiVersionOdataBusinessSummariesResponses, ApiVVersionApiVersionOdataCounterpartiesCountData, ApiVVersionApiVersionOdataCounterpartiesCountResponses, ApiVVersionApiVersionOdataCounterpartiesData, ApiVVersionApiVersionOdataCounterpartiesResponses, ApiVVersionApiVersionOdataDataBoxCredentialsCountData, ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses, ApiVVersionApiVersionOdataDataBoxCredentialsData, ApiVVersionApiVersionOdataDataBoxCredentialsResponses, ApiVVersionApiVersionOdataDocumentTypesCountData, ApiVVersionApiVersionOdataDocumentTypesCountResponses, ApiVVersionApiVersionOdataDocumentTypesData, ApiVVersionApiVersionOdataDocumentTypesResponses, ApiVVersionApiVersionOdataInvitationsCountData, ApiVVersionApiVersionOdataInvitationsCountResponses, ApiVVersionApiVersionOdataInvitationsData, ApiVVersionApiVersionOdataInvitationsResponses, ApiVVersionApiVersionOdataInvoicesCountData, ApiVVersionApiVersionOdataInvoicesCountResponses, ApiVVersionApiVersionOdataInvoicesData, ApiVVersionApiVersionOdataInvoiceSettingsCountData, ApiVVersionApiVersionOdataInvoiceSettingsCountResponses, ApiVVersionApiVersionOdataInvoiceSettingsData, ApiVVersionApiVersionOdataInvoiceSettingsResponses, ApiVVersionApiVersionOdataInvoicesResponses, ApiVVersionApiVersionOdataLicensesCountData, ApiVVersionApiVersionOdataLicensesCountResponses, ApiVVersionApiVersionOdataLicensesData, ApiVVersionApiVersionOdataLicensesResponses, ApiVVersionApiVersionOdataPersonalDocumentsCountData, ApiVVersionApiVersionOdataPersonalDocumentsCountResponses, ApiVVersionApiVersionOdataPersonalDocumentsData, ApiVVersionApiVersionOdataPersonalDocumentsResponses, ApiVVersionApiVersionOdataRecurringTasksCountData, ApiVVersionApiVersionOdataRecurringTasksCountResponses, ApiVVersionApiVersionOdataRecurringTasksData, ApiVVersionApiVersionOdataRecurringTasksResponses, ApiVVersionApiVersionOdataTasksCountData, ApiVVersionApiVersionOdataTasksCountResponses, ApiVVersionApiVersionOdataTasksData, ApiVVersionApiVersionOdataTasksKey2Data, ApiVVersionApiVersionOdataTasksKey2Responses, ApiVVersionApiVersionOdataTasksKeyData, ApiVVersionApiVersionOdataTasksKeyResponses, ApiVVersionApiVersionOdataTasksResponses, DeleteApiV1AccountingCompaniesByIdData, DeleteApiV1AccountingCompaniesByIdResponses, DeleteApiV1AccountingCompanyMembershipsByIdData, DeleteApiV1AccountingCompanyMembershipsByIdResponses, DeleteApiV1BankAccountsByIdData, DeleteApiV1BankAccountsByIdResponses, DeleteApiV1BusinessAccountantAssignmentsByIdData, DeleteApiV1BusinessAccountantAssignmentsByIdResponses, DeleteApiV1BusinessDocumentsByIdData, DeleteApiV1BusinessDocumentsByIdResponses, DeleteApiV1BusinessesByIdData, DeleteApiV1BusinessesByIdResponses, DeleteApiV1CounterpartiesByIdData, DeleteApiV1CounterpartiesByIdResponses, DeleteApiV1DataBoxCredentialsByIdData, DeleteApiV1DataBoxCredentialsByIdResponses, DeleteApiV1InvitationsByIdData, DeleteApiV1InvitationsByIdResponses, DeleteApiV1InvoicesByIdData, DeleteApiV1InvoicesByIdResponses, DeleteApiV1NotificationsDeviceTokensData, DeleteApiV1NotificationsDeviceTokensResponses, DeleteApiV1PersonalDocumentsByIdData, DeleteApiV1PersonalDocumentsByIdResponses, DeleteApiV1RecurringTasksByIdData, DeleteApiV1RecurringTasksByIdResponses, DeleteApiV1UserData, DeleteApiV1UserResponses, GetApiDevConfirmEmailData, GetApiDevConfirmEmailResponses, GetApiDevData, GetApiDevDbCreateData, GetApiDevDbCreateResponses, GetApiDevDbReset2Data, GetApiDevDbReset2Responses, GetApiDevDbResetData, GetApiDevDbResetResponses, GetApiDevDbTouchData, GetApiDevDbTouchResponses, GetApiDevEmailSendTestData, GetApiDevEmailSendTestResponses, GetApiDevJobProcessRecurringTasksData, GetApiDevJobProcessRecurringTasksResponses, GetApiDevNotificationsSendTestData, GetApiDevNotificationsSendTestResponses, GetApiDevReseedDbData, GetApiDevReseedDbResponses, GetApiDevResponses, GetApiDevSeedAllData, GetApiDevSeedAllResponses, GetApiDevSeedData, GetApiDevSeedProdData, GetApiDevSeedProdResponses, GetApiDevSeedResponses, GetApiV1BusinessDocumentsByIdRawData, GetApiV1BusinessDocumentsByIdRawResponses, GetApiV1BusinessesByIdDocumentTypesSummaryData, GetApiV1BusinessesByIdDocumentTypesSummaryResponses, GetApiV1InvoicesByIdPreviewData, GetApiV1InvoicesByIdPreviewResponses, GetApiV1PersonalDocumentsByIdRawData, GetApiV1PersonalDocumentsByIdRawResponses, GetApiV1PersonalDocumentsSummaryData, GetApiV1PersonalDocumentsSummaryResponses, GetApiV1TasksByIdCommentsData, GetApiV1TasksByIdCommentsResponses, GetApiV1TasksByIdDocumentsData, GetApiV1TasksByIdDocumentsResponses, GetApiV1UserDocumentsSummaryData, GetApiV1UserDocumentsSummaryResponses, GetApiV1UserManageInfoData, GetApiV1UserManageInfoErrors, GetApiV1UserManageInfoResponses, GetApiV1UsersMeData, GetApiV1UsersMeResponses, GetData, GetResponses, MapIdentityApiApiVVersionApiVersionUserConfirmEmailData, MapIdentityApiApiVVersionApiVersionUserConfirmEmailResponses, PatchApiV1CounterpartiesByIdData, PatchApiV1CounterpartiesByIdResponses, PatchApiV1InvitationsByIdData, PatchApiV1InvitationsByIdResponses, PatchApiV1InvoicesByIdData, PatchApiV1InvoicesByIdResponses, PatchApiV1RecurringTasksByIdData, PatchApiV1RecurringTasksByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdResponses, PostApiV1AccountingCompaniesByIdData, PostApiV1AccountingCompaniesByIdResponses, PostApiV1AccountingCompaniesData, PostApiV1AccountingCompaniesResponses, PostApiV1BusinessDocumentsByIdApproveData, PostApiV1BusinessDocumentsByIdApproveResponses, PostApiV1BusinessDocumentsByIdMoveToBusinessData, PostApiV1BusinessDocumentsByIdMoveToBusinessResponses, PostApiV1BusinessDocumentsByIdMoveToPersonalData, PostApiV1BusinessDocumentsByIdMoveToPersonalResponses, PostApiV1BusinessDocumentsByIdUnapproveData, PostApiV1BusinessDocumentsByIdUnapproveResponses, PostApiV1BusinessDocumentsData, PostApiV1BusinessDocumentsResponses, PostApiV1BusinessesByIdDisconnectData, PostApiV1BusinessesByIdDisconnectResponses, PostApiV1BusinessesData, PostApiV1BusinessesResponses, PostApiV1CounterpartiesData, PostApiV1CounterpartiesResponses, PostApiV1FeedbackData, PostApiV1FeedbackResponses, PostApiV1InvitationsByIdAcceptData, PostApiV1InvitationsByIdAcceptResponses, PostApiV1InvitationsByIdRejectData, PostApiV1InvitationsByIdRejectResponses, PostApiV1InvitationsData, PostApiV1InvitationsResponses, PostApiV1InvoicesByIdSendData, PostApiV1InvoicesByIdSendResponses, PostApiV1InvoicesByIdSnapshotData, PostApiV1InvoicesByIdSnapshotResponses, PostApiV1InvoicesData, PostApiV1InvoicesResponses, PostApiV1NotificationsTestData, PostApiV1NotificationsTestResponses, PostApiV1PersonalDocumentsByIdMoveToBusinessData, PostApiV1PersonalDocumentsByIdMoveToBusinessResponses, PostApiV1PersonalDocumentsData, PostApiV1PersonalDocumentsResponses, PostApiV1RecurringTasksData, PostApiV1RecurringTasksResponses, PostApiV1TasksByIdApproveData, PostApiV1TasksByIdApproveResponses, PostApiV1TasksByIdRejectData, PostApiV1TasksByIdRejectResponses, PostApiV1TasksByIdSubmitData, PostApiV1TasksByIdSubmitResponses, PostApiV1TasksData, PostApiV1TasksResponses, PostApiV1UserForgotPasswordData, PostApiV1UserForgotPasswordErrors, PostApiV1UserForgotPasswordResponses, PostApiV1UserLoginData, PostApiV1UserLoginResponses, PostApiV1UserLogoutData, PostApiV1UserLogoutResponses, PostApiV1UserManage2FaData, PostApiV1UserManage2FaErrors, PostApiV1UserManage2FaResponses, PostApiV1UserManageInfoData, PostApiV1UserManageInfoErrors, PostApiV1UserManageInfoResponses, PostApiV1UserRefreshData, PostApiV1UserRefreshResponses, PostApiV1UserRegisterData, PostApiV1UserRegisterErrors, PostApiV1UserRegisterResponses, PostApiV1UserResendConfirmationEmailData, PostApiV1UserResendConfirmationEmailResponses, PostApiV1UserResetPasswordData, PostApiV1UserResetPasswordErrors, PostApiV1UserResetPasswordResponses, PutApiV1AccountingCompanyMembershipsData, PutApiV1AccountingCompanyMembershipsResponses, PutApiV1BankAccountsData, PutApiV1BankAccountsResponses, PutApiV1BusinessAccountantAssignmentsData, PutApiV1BusinessAccountantAssignmentsResponses, PutApiV1BusinessDocumentsByIdData, PutApiV1BusinessDocumentsByIdResponses, PutApiV1BusinessesByIdContactData, PutApiV1BusinessesByIdContactResponses, PutApiV1BusinessesByIdData, PutApiV1BusinessesByIdResponses, PutApiV1BusinessMembershipsData, PutApiV1BusinessMembershipsResponses, PutApiV1DataBoxCredentialsData, PutApiV1DataBoxCredentialsResponses, PutApiV1InvoiceSettingsData, PutApiV1InvoiceSettingsResponses, PutApiV1NotificationsDeviceTokensData, PutApiV1NotificationsDeviceTokensResponses, PutApiV1TasksByIdData, PutApiV1TasksByIdResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export class AccountingCompanies { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanies/$count', ...options }); } } export class Odata { public static accountingCompanies(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanies', ...options }); } static accountingCompanies2 = AccountingCompanies; } export class VVersionApiVersion { static odata = Odata; } export class Api { static vVersionApiVersion = VVersionApiVersion; } export class AccountingCompanies2 { public static postApiV1AccountingCompanies(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/accounting-companies', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1AccountingCompaniesById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/accounting-companies/{id}', ...options }); } public static postApiV1AccountingCompaniesById(options: Options) { return (options.client ?? client).post({ url: '/api/v1/accounting-companies/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } static api = Api; } export class AccountingCompanyMemberships { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanyMemberships/$count', ...options }); } } export class Odata2 { public static accountingCompanyMemberships(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanyMemberships', ...options }); } static accountingCompanyMemberships2 = AccountingCompanyMemberships; } export class VVersionApiVersion2 { static odata = Odata2; } export class Api2 { static vVersionApiVersion = VVersionApiVersion2; } export class AccountingCompanyMemberships2 { public static putApiV1AccountingCompanyMemberships(options?: Options) { return (options?.client ?? client).put({ url: '/api/v1/accounting-company-memberships', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1AccountingCompanyMembershipsById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/accounting-company-memberships/{id}', ...options }); } static api = Api2; } export class BankAccounts { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BankAccounts/$count', ...options }); } } export class Odata3 { public static bankAccounts(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BankAccounts', ...options }); } static bankAccounts2 = BankAccounts; } export class VVersionApiVersion3 { static odata = Odata3; } export class Api3 { static vVersionApiVersion = VVersionApiVersion3; } export class BankAccounts2 { public static putApiV1BankAccounts(options?: Options) { return (options?.client ?? client).put({ url: '/api/v1/bank-accounts', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1BankAccountsById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/bank-accounts/{id}', ...options }); } static api = Api3; } export class BusinessAccountantAssignments { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessAccountantAssignments/$count', ...options }); } } export class Odata4 { public static businessAccountantAssignments(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessAccountantAssignments', ...options }); } static businessAccountantAssignments2 = BusinessAccountantAssignments; } export class VVersionApiVersion4 { static odata = Odata4; } export class Api4 { static vVersionApiVersion = VVersionApiVersion4; } export class BusinessAccountantAssignments2 { public static putApiV1BusinessAccountantAssignments(options?: Options) { return (options?.client ?? client).put({ url: '/api/v1/business-accountant-assignments', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1BusinessAccountantAssignmentsById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/business-accountant-assignments/{id}', ...options }); } static api = Api4; } export class BusinessDocumentActivities { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentActivities/$count', ...options }); } } export class BusinessDocuments { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocuments/$count', ...options }); } } export class Odata5 { public static businessDocumentActivities(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentActivities', ...options }); } public static businessDocuments(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocuments', ...options }); } static businessDocumentActivities2 = BusinessDocumentActivities; static businessDocuments2 = BusinessDocuments; } export class VVersionApiVersion5 { static odata = Odata5; } export class Api5 { static vVersionApiVersion = VVersionApiVersion5; } export class BusinessDocuments2 { public static getApiV1BusinessDocumentsByIdRaw(options: Options) { return (options.client ?? client).get({ url: '/api/v1/business-documents/{id}/raw', ...options }); } public static postApiV1BusinessDocuments(options?: Options) { return (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v1/business-documents', ...options, headers: { 'Content-Type': null, ...options?.headers } }); } public static deleteApiV1BusinessDocumentsById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/business-documents/{id}', ...options }); } public static putApiV1BusinessDocumentsById(options: Options) { return (options.client ?? client).put({ url: '/api/v1/business-documents/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static postApiV1BusinessDocumentsByIdApprove(options: Options) { return (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/approve', ...options }); } public static postApiV1BusinessDocumentsByIdUnapprove(options: Options) { return (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/unapprove', ...options }); } public static postApiV1BusinessDocumentsByIdMoveToPersonal(options: Options) { return (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/move-to-personal', ...options }); } public static postApiV1BusinessDocumentsByIdMoveToBusiness(options: Options) { return (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/move-to-business', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } static api = Api5; } export class BusinessDocumentsSummaries { /** * @deprecated */ public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentsSummaries/$count', ...options }); } } export class Odata6 { /** * @deprecated */ public static businessDocumentsSummaries(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentsSummaries', ...options }); } static businessDocumentsSummaries2 = BusinessDocumentsSummaries; } export class VVersionApiVersion6 { static odata = Odata6; } export class Api6 { static vVersionApiVersion = VVersionApiVersion6; } export class BusinessDocumentsSummaries2 { static api = Api6; } export class Businesses { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Businesses/$count', ...options }); } public static key(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Businesses/{key}', ...options }); } } export class Odata7 { public static businesses(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Businesses', ...options }); } public static businessesKey(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Businesses({key})', ...options }); } static businesses2 = Businesses; } export class VVersionApiVersion7 { static odata = Odata7; } export class Api7 { static vVersionApiVersion = VVersionApiVersion7; } export class Businesses2 { public static getApiV1BusinessesByIdDocumentTypesSummary(options: Options) { return (options.client ?? client).get({ url: '/api/v1/businesses/{id}/document-types-summary', ...options }); } public static postApiV1Businesses(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/businesses', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1BusinessesById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/businesses/{id}', ...options }); } public static putApiV1BusinessesById(options: Options) { return (options.client ?? client).put({ url: '/api/v1/businesses/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static putApiV1BusinessesByIdContact(options: Options) { return (options.client ?? client).put({ url: '/api/v1/businesses/{id}/contact', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static postApiV1BusinessesByIdDisconnect(options: Options) { return (options.client ?? client).post({ url: '/api/v1/businesses/{id}/disconnect', ...options }); } static api = Api7; } export class BusinessesMemberships { public static putApiV1BusinessMemberships(options?: Options) { return (options?.client ?? client).put({ url: '/api/v1/business-memberships', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } } export class BusinessSummaries { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessSummaries/$count', ...options }); } } export class Odata8 { public static businessSummaries(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/BusinessSummaries', ...options }); } static businessSummaries2 = BusinessSummaries; } export class VVersionApiVersion8 { static odata = Odata8; } export class Api8 { static vVersionApiVersion = VVersionApiVersion8; } export class BusinessSummaries2 { static api = Api8; } export class Counterparties { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Counterparties/$count', ...options }); } } export class Odata9 { public static counterparties(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Counterparties', ...options }); } static counterparties2 = Counterparties; } export class VVersionApiVersion9 { static odata = Odata9; } export class Api9 { static vVersionApiVersion = VVersionApiVersion9; } export class Counterparties2 { public static postApiV1Counterparties(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/counterparties', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1CounterpartiesById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/counterparties/{id}', ...options }); } public static patchApiV1CounterpartiesById(options: Options) { return (options.client ?? client).patch({ url: '/api/v1/counterparties/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } static api = Api9; } export class DataBoxCredentials { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/DataBoxCredentials/$count', ...options }); } } export class Odata10 { public static dataBoxCredentials(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/DataBoxCredentials', ...options }); } static dataBoxCredentials2 = DataBoxCredentials; } export class VVersionApiVersion10 { static odata = Odata10; } export class Api10 { static vVersionApiVersion = VVersionApiVersion10; } export class DataBoxCredentials2 { public static putApiV1DataBoxCredentials(options?: Options) { return (options?.client ?? client).put({ url: '/api/v1/data-box-credentials', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1DataBoxCredentialsById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/data-box-credentials/{id}', ...options }); } static api = Api10; } export class Dev { public static getApiDev(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev', ...options }); } public static getApiDevReseedDb(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/reseed-db', ...options }); } public static getApiDevDbReset(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/db-reset', ...options }); } public static getApiDevDbReset2(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/db/reset', ...options }); } public static getApiDevDbCreate(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/db/create', ...options }); } public static getApiDevDbTouch(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/db/touch', ...options }); } public static getApiDevSeed(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/seed', ...options }); } public static getApiDevSeedAll(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/seed-all', ...options }); } public static getApiDevSeedProd(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/seed-prod', ...options }); } public static getApiDevJobProcessRecurringTasks(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/job/process-recurring-tasks', ...options }); } public static getApiDevNotificationsSendTest(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/notifications/send-test', ...options }); } public static getApiDevConfirmEmail(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/confirm-email', ...options }); } public static getApiDevEmailSendTest(options?: Options) { return (options?.client ?? client).get({ url: '/api/dev/email/send-test', ...options }); } } export class DeviceTokens { public static deleteApiV1NotificationsDeviceTokens(options?: Options) { return (options?.client ?? client).delete({ url: '/api/v1/notifications/device-tokens', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static putApiV1NotificationsDeviceTokens(options?: Options) { return (options?.client ?? client).put({ url: '/api/v1/notifications/device-tokens', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } } export class DocumentTypes { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/DocumentTypes/$count', ...options }); } } export class Odata11 { public static documentTypes(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/DocumentTypes', ...options }); } static documentTypes2 = DocumentTypes; } export class VVersionApiVersion11 { static odata = Odata11; } export class Api11 { static vVersionApiVersion = VVersionApiVersion11; } export class DocumentTypes2 { static api = Api11; } export class Feedback { public static postApiV1Feedback(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/feedback', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } } export class Invitations { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Invitations/$count', ...options }); } } export class Odata12 { public static invitations(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Invitations', ...options }); } static invitations2 = Invitations; } export class VVersionApiVersion12 { static odata = Odata12; } export class Api12 { static vVersionApiVersion = VVersionApiVersion12; } export class Invitations2 { public static postApiV1Invitations(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/invitations', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static postApiV1InvitationsByIdAccept(options: Options) { return (options.client ?? client).post({ url: '/api/v1/invitations/{id}/accept', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static postApiV1InvitationsByIdReject(options: Options) { return (options.client ?? client).post({ url: '/api/v1/invitations/{id}/reject', ...options }); } public static deleteApiV1InvitationsById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/invitations/{id}', ...options }); } public static patchApiV1InvitationsById(options: Options) { return (options.client ?? client).patch({ url: '/api/v1/invitations/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } static api = Api12; } export class Invoices { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Invoices/$count', ...options }); } } export class Odata13 { public static invoices(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Invoices', ...options }); } static invoices2 = Invoices; } export class VVersionApiVersion13 { static odata = Odata13; } export class Api13 { static vVersionApiVersion = VVersionApiVersion13; } export class Invoices2 { public static postApiV1Invoices(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/invoices', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1InvoicesById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/invoices/{id}', ...options }); } public static patchApiV1InvoicesById(options: Options) { return (options.client ?? client).patch({ url: '/api/v1/invoices/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static getApiV1InvoicesByIdPreview(options: Options) { return (options.client ?? client).get({ url: '/api/v1/invoices/{id}/preview', ...options }); } public static postApiV1InvoicesByIdSend(options: Options) { return (options.client ?? client).post({ url: '/api/v1/invoices/{id}/send', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static postApiV1InvoicesByIdSnapshot(options: Options) { return (options.client ?? client).post({ url: '/api/v1/invoices/{id}/snapshot', ...options }); } static api = Api13; } export class InvoiceSettings { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/InvoiceSettings/$count', ...options }); } } export class Odata14 { public static invoiceSettings(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/InvoiceSettings', ...options }); } static invoiceSettings2 = InvoiceSettings; } export class VVersionApiVersion14 { static odata = Odata14; } export class Api14 { static vVersionApiVersion = VVersionApiVersion14; } export class InvoiceSettings2 { public static putApiV1InvoiceSettings(options?: Options) { return (options?.client ?? client).put({ url: '/api/v1/invoice-settings', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } static api = Api14; } export class Licenses { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Licenses/$count', ...options }); } } export class Odata15 { public static licenses(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Licenses', ...options }); } static licenses2 = Licenses; } export class VVersionApiVersion15 { static odata = Odata15; } export class Api15 { static vVersionApiVersion = VVersionApiVersion15; } export class Licenses2 { static api = Api15; } export class Notifications { public static postApiV1NotificationsTest(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/notifications/test', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } } export class PersonalDocuments { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/PersonalDocuments/$count', ...options }); } } export class Odata16 { public static personalDocuments(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/PersonalDocuments', ...options }); } static personalDocuments2 = PersonalDocuments; } export class VVersionApiVersion16 { static odata = Odata16; } export class Api16 { static vVersionApiVersion = VVersionApiVersion16; } export class PersonalDocuments2 { public static getApiV1PersonalDocumentsByIdRaw(options: Options) { return (options.client ?? client).get({ url: '/api/v1/personal-documents/{id}/raw', ...options }); } public static postApiV1PersonalDocuments(options?: Options) { return (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v1/personal-documents', ...options, headers: { 'Content-Type': null, ...options?.headers } }); } public static postApiV1PersonalDocumentsByIdMoveToBusiness(options: Options) { return (options.client ?? client).post({ url: '/api/v1/personal-documents/{id}/move-to-business', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static deleteApiV1PersonalDocumentsById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/personal-documents/{id}', ...options }); } public static getApiV1PersonalDocumentsSummary(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/personal-documents/summary', ...options }); } static api = Api16; } export class RecurringTasks { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/RecurringTasks/$count', ...options }); } } export class Odata17 { public static recurringTasks(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/RecurringTasks', ...options }); } static recurringTasks2 = RecurringTasks; } export class VVersionApiVersion17 { static odata = Odata17; } export class Api17 { static vVersionApiVersion = VVersionApiVersion17; } export class RecurringTasks2 { public static postApiV1RecurringTasks(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/recurring-tasks', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static deleteApiV1RecurringTasksById(options: Options) { return (options.client ?? client).delete({ url: '/api/v1/recurring-tasks/{id}', ...options }); } public static patchApiV1RecurringTasksById(options: Options) { return (options.client ?? client).patch({ url: '/api/v1/recurring-tasks/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } static api = Api17; } export class Root { public static get(options?: Options) { return (options?.client ?? client).get({ url: '/', ...options }); } } export class Tasks { public static count(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Tasks/$count', ...options }); } public static key(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Tasks/{key}', ...options }); } } export class Odata18 { public static tasks(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Tasks', ...options }); } public static tasksKey(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/odata/Tasks({key})', ...options }); } static tasks2 = Tasks; } export class VVersionApiVersion18 { static odata = Odata18; } export class Api18 { static vVersionApiVersion = VVersionApiVersion18; } export class Tasks2 { public static postApiV1Tasks(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/tasks', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public static putApiV1TasksById(options: Options) { return (options.client ?? client).put({ url: '/api/v1/tasks/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static postApiV1TasksByIdSubmit(options: Options) { return (options.client ?? client).post({ url: '/api/v1/tasks/{id}/submit', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static postApiV1TasksByIdApprove(options: Options) { return (options.client ?? client).post({ url: '/api/v1/tasks/{id}/approve', ...options }); } public static postApiV1TasksByIdReject(options: Options) { return (options.client ?? client).post({ url: '/api/v1/tasks/{id}/reject', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public static getApiV1TasksByIdComments(options: Options) { return (options.client ?? client).get({ url: '/api/v1/tasks/{id}/comments', ...options }); } public static getApiV1TasksByIdDocuments(options: Options) { return (options.client ?? client).get({ url: '/api/v1/tasks/{id}/documents', ...options }); } static api = Api18; } export class User { public static confirmEmail(options: Options) { return (options.client ?? client).get({ url: '/api/v1/user/confirmEmail', ...options }); } } export class VVersionApiVersion19 { static user = User; } export class Api19 { static vVersionApiVersion = VVersionApiVersion19; } export class MapIdentityApi { static api = Api19; } export class User2 { public static postApiV1UserRegister(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/register', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static postApiV1UserLogin(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/login', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static postApiV1UserRefresh(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/refresh', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static postApiV1UserResendConfirmationEmail(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/resendConfirmationEmail', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static postApiV1UserForgotPassword(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/forgotPassword', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static postApiV1UserResetPassword(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/resetPassword', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static postApiV1UserManage2Fa(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/manage/2fa', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static getApiV1UserManageInfo(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/user/manage/info', ...options }); } public static postApiV1UserManageInfo(options: Options) { return (options.client ?? client).post({ url: '/api/v1/user/manage/info', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public static postApiV1UserLogout(options?: Options) { return (options?.client ?? client).post({ url: '/api/v1/user/logout', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } /** * @deprecated */ public static getApiV1UserDocumentsSummary(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/user/documents-summary', ...options }); } public static deleteApiV1User(options?: Options) { return (options?.client ?? client).delete({ url: '/api/v1/user', ...options }); } static mapIdentityApi = MapIdentityApi; } export class Users { public static getApiV1UsersMe(options?: Options) { return (options?.client ?? client).get({ url: '/api/v1/users/me', ...options }); } public static patchApiV1UsersById(options: Options) { return (options.client ?? client).patch({ url: '/api/v1/users/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/class/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type AccessTokenResponse = { readonly tokenType?: string; accessToken: string; expiresIn: number; refreshToken: string; }; export type AccountingCompany = { id: number; name: string; identificationNumber: string; /** * @deprecated */ countryCode?: string; country: Country; }; export type AccountingCompanyCreateDto = { name: string; identificationNumber: string; }; export type AccountingCompanyMembership = { id: number; accountingCompanyId: number; accountingCompanyName: string; userId: number; userFullName: string; roleName: string; }; export type AccountingCompanyMembershipUpsertDto = { accountingCompanyId: number; email: string; roleName: string; }; export type AccountingCompanyUpdateDto = { name: string; identificationNumber: string; }; export type AddressDto = { street: string; city: string; postalCode: string; country: string; }; export type AnnualInvoicesCount = 'Tens' | 'Hundred' | 'Thousands' | 'TenThousands' | 'HundredThousands'; export type BankAccount = { id: number; businessId: number; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; createdAt: string; updatedAt?: string | null; }; export type BankAccountUpsertDto = { businessId: number; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; }; export type Business = { id: number; name: string; identificationNumber: string; vatNumber: string | null; country: Country; /** * @deprecated */ countryCode?: string; deletedAt: string | null; fullAddress: string | null; accountingCompany: BusinessAccountingCompany; contactPerson: BusinessContactPerson; }; export type BusinessAccountantAssignment = { id: number; businessId: number; businessName: string; accountantId: number; accountantName: string; }; export type BusinessAccountantAssignmentUpsert = { businessId: number; accountantId: number; }; export type BusinessAccountingCompany = { id: number; name: string; }; export type BusinessAresAddress = { street: string; houseNumber: number; guidanceNumber?: number | null; city: string; postalCode: number; }; export type BusinessChangeContactDto = { userId: number | null; }; export type BusinessContactPerson = { id: number; fullName: string; email: string | null; phoneNumber: string | null; }; export type BusinessCreateDto = { name: string; identificationNumber: string; vatNumber?: string | null; address?: BusinessAresAddress; }; export type BusinessDocumentMoveToBusinessDocumentsDto = { businessId: number; documentTypeId?: number | null; }; export type BusinessDocumentUpdateDto = { name: string | null; documentTypeId: number | null; }; export type BusinessDocumentsSummary = { id: number; name: string; documentsCount: number; documentsSize: number; lastUploadAt: string | null; maxStorageSize: number; }; export type BusinessMembershipDto = { id: number; userId: number; userFullName: string; businessId: number; businessName: string; roleId: number; roleName: string; }; export type BusinessMembershipUpsertDto = { businessId: number; email: string; roleName: string; }; export type BusinessSummary = { id: number; name: string; documentsCount: number; documentsSize: number; lastUploadAt: string | null; /** * @deprecated */ maxStorageSize?: number; pendingTasksCount: number; pendingDocumentsCount: number; }; export type BusinessUpdateDto = { name: string; identificationNumber: string; vatNumber?: string | null; address?: BusinessAresAddress; }; export type Counterparty = { id: number; businessId: number; name: string; identificationNumber: string | null; vatNumber: string | null; address: AddressDto; email: string | null; privateNote: string | null; isFavourite: boolean | null; createdAt: string; updatedAt?: string | null; }; export type CounterpartyCreateDto = { businessId: number; identificationNumber: string; name: string; vatNumber: string | null; address: AddressDto; email: string | null; privateNote?: string | null; isFavourite?: boolean | null; }; export type CounterpartyUpdateDto = { identificationNumber?: string | null; name?: string | null; vatNumber?: string | null; address?: AddressDto; email?: string | null; privateNote?: string | null; isFavourite?: boolean | null; }; export type Country = 'Czechia' | 'Slovakia'; export type CreateInvoiceClientDto = { counterpartyId: number; }; export type Currency = 'CZK' | 'EUR' | 'USD' | 'GBP'; export type DataBoxCredentials = { id?: number; username: string; password: string | null; businessId: number; businessName: string; userId: number; }; export type DataBoxCredentialsUpsertDto = { businessId: number; username: string | null; password: string | null; }; export type DocumentAction = 'Uploaded'; export type DocumentBusiness = { id: number; /** * @deprecated */ name?: string; documentName: string; originalFileName: string; extension: string | null; size: number; businessId: number | null; businessName: string | null; documentTypeId: number; documentTypeName: string; approvedAt: string | null; approverId: number | null; approverFullName: string | null; taskId: number | null; uploadedAt: string; uploaderId: number | null; deletedAt?: string | null; }; export type DocumentBusinessActivity = { documentId: number; documentName: string; businessId: number; businessName: string; action: DocumentAction; happenedAt: string; performedByUserId: number | null; performedByUserFullName: string | null; }; export type DocumentPersonal = { id: number; name: string; extension: string | null; size: number; userId: number; userFullName: string; uploadedAt?: string; deletedAt?: string | null; }; export type DocumentPersonalMoveToBusinessDocumentsDto = { businessId: number; documentTypeId?: number; }; export type DocumentType = { id: number; name: string; }; export type DocumentTypesSummary = { documentTypeId: number; documentTypeName: string; documentsCount: number; }; export type FeedbackType = 'Feedback' | 'Bug'; export type ForgotPasswordRequest = { email: string; }; export type HttpValidationProblemDetails = { type?: string | null; title?: string | null; status?: number | null; detail?: string | null; instance?: string | null; errors?: { [key: string]: Array; }; [key: string]: unknown; }; export type InfoRequest = { newEmail?: string | null; newPassword?: string | null; oldPassword?: string | null; }; export type InfoResponse = { email: string; isEmailConfirmed: boolean; }; export type Invitation = { id: number; accountingCompanyName: string; status: InvitationStatus; expiresAt: string; email: string; }; export type InvitationAcceptDto = { businessId: number; }; export type InvitationCreateDto = { accountingCompanyId: number; email: string; }; export type InvitationStatus = 'Pending' | 'Expired' | 'Rejected'; export type InvitationUpdateDto = { email?: string | null; }; export type Invoice = { id: number; businessId: number; supplier: InvoiceSupplier; client: InvoiceClient; bankAccount: InvoiceBankAccount; hideBankAccount: boolean; type: InvoiceType; number: string; status: InvoiceStatus; paymentMethod: PaymentMethod; currency: Currency; reversedVatCharge: boolean; variableSymbol: string | null; constantSymbol: string | null; issuedAt: string; dueAt: string; taxPointAt: string | null; sentAt: string | null; snapshotAt: string | null; noteBeforeLines: string | null; lines: Array; footerNote: string | null; totalPriceExcludingVat: number; totalVatAmount: number; totalPriceIncludingVat: number; createdAt: string; updatedAt: string | null; }; export type InvoiceBankAccount = { swift: string; iban: string; accountNumber: string; bankCode: string; currency: Currency; }; export type InvoiceBankAccountUpdateDto = { swift: string; iban: string; accountNumber: string; bankCode: string; currency: Currency; }; export type InvoiceClient = { /** * @deprecated */ id?: number | null; counterpartyId: number | null; name: string; registrationNumber: string | null; identificationNumber: string | null; vatNumber: string | null; email: string | null; address: InvoiceClientAddress; deliveryName: string | null; deliveryAddress: InvoiceClientDeliveryAddress; }; export type InvoiceClientAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceClientDeliveryAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceCreateDto = { client: CreateInvoiceClientDto; type: InvoiceType; number: string; status: InvoiceStatus; paymentMethod: PaymentMethod; hideBankAccount: boolean; reversedVatCharge: boolean; variableSymbol?: string | null; constantSymbol?: string | null; issuedAt: string; dueAt: string; taxPointAt: string; noteBeforeLines?: string | null; lines: Array; footerNote?: string | null; businessId: number; }; export type InvoiceLine = { id?: number; description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; totalPriceExcludingVat: number; vatAmount: number; totalPriceIncludingVat: number; }; export type InvoiceLineCreateDto = { description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; }; export type InvoiceLineUpdateDto = { id: number | null; description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; }; export type InvoiceSendDto = { customRecipientEmail: string | null; message: string; }; export type InvoiceSetting = { businessId: number; isVatPayer: boolean; template: InvoiceTemplate; bankAccount?: InvoiceSettingsBankAccount; numberingSetting: NumberingSetting; createdAt: string; updatedAt?: string | null; }; export type InvoiceSettingUpsertDto = { businessId: number; isVatPayer: boolean; template: InvoiceTemplateUpsertDto; bankAccount?: InvoiceSettingsBankAccountUpsertDto; numberingSetting: NumberingSettingUpsertDto; }; export type InvoiceSettingsBankAccount = { id: number; businessId: number; /** * @deprecated */ number: string; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; createdAt: string; updatedAt?: string | null; }; export type InvoiceSettingsBankAccountUpsertDto = { accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; }; export type InvoiceStatus = 'Draft' | 'Issued' | 'Paid' | 'Overdue' | 'Cancelled' | 'Snapshot'; export type InvoiceSupplier = { name: string; registrationNumber: string; identificationNumber: string; vatNumber: string | null; address: InvoiceSupplierAddress; }; export type InvoiceSupplierAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceTemplate = { currency: Currency; textBeforeLines: string | null; footerText: string | null; }; export type InvoiceTemplateUpsertDto = { currency: Currency; textBeforeLines: string | null; footerText: string | null; }; export type InvoiceType = 'Regular' | 'Corrective' | 'Advance'; export type InvoiceUpdateClientDto = { counterpartyId: number | null; name: string | null; registrationNumber: string | null; vatNumber: string | null; email: string | null; address: AddressDto; deliveryName: string | null; deliveryAddress: AddressDto; }; export type InvoiceUpdateDto = { client: InvoiceUpdateClientDto; bankAccount: InvoiceBankAccountUpdateDto; hideBankAccount: boolean | null; type: InvoiceType; number: string | null; status: InvoiceStatus; paymentMethod: PaymentMethod; currency: Currency; reversedVatCharge: boolean | null; variableSymbol: string | null; constantSymbol: string | null; issuedAt: string | null; dueAt: string | null; taxPointAt: string | null; noteBeforeLines: string | null; lines: Array | null; footerNote: string | null; }; export type LicenseDto = { id: number; tierId: number; tierName: string; businessId: number | null; /** * @deprecated */ maxStorageSize?: number; maxBusinessStorageSize: number; maxBusinessMembersCount: number; maxContactsCount: number; }; export type LoginRequest = { email: string; password: string; twoFactorCode?: string | null; twoFactorRecoveryCode?: string | null; }; export type NotificationsDeviceTokenDeleteDto = { token: string; }; export type NotificationsDeviceTokenUpsertDto = { provider: PushNotificationsProvider; token: string; }; export type NotificationsTestSendDto = { token: string | null; }; export type NumberingSetting = { id: number; businessId: number; yearFormat: YearFormat; isMonthIncluded: boolean; useHyphen: boolean; prefix?: string | null; suffix?: string | null; sequencePosition: SequencePosition; annualInvoicesCount: AnnualInvoicesCount; format: string; lastExternalInvoiceSequenceNumber: number | null; createdAt: string; updatedAt?: string | null; }; export type NumberingSettingUpsertDto = { yearFormat: YearFormat; isMonthIncluded: boolean; useHyphen: boolean; prefix: string | null; suffix: string | null; sequencePosition: SequencePosition; annualInvoicesCount: AnnualInvoicesCount; lastExternalInvoiceSequenceNumber?: number | null; }; export type PaymentMethod = 'Cash' | 'BankTransfer'; export type PersonalDocumentsSummary = { documentsCount: number; documentsSize: number; maxStorageSize: number; }; export type PushNotificationsProvider = 1 | 2; export type RecurrenceType = 'Daily' | 'Weekly' | 'Monthly' | 'Yearly'; export type RecurringTask = { id: number; title: string; details: string; accountingCompanyId: number; accountingCompanyName: string; accountantId: number | null; accountantFullName: string | null; recurrenceType?: RecurrenceType; period: RecurrenceType; interval: number; executeAt: string; isActive: boolean; businesses: Array; documentTypeId: number; documentTypeName: string; }; export type RecurringTaskBusiness = { id: number; name: string; }; export type RecurringTaskCreateDto = { title: string; details: string; recurrenceType: RecurrenceType; interval?: number; firstTaskDueAt: string; accountingCompanyId: number; businessIds: Array; documentTypeId: number; }; export type RecurringTaskUpdateDto = { title?: string | null; details?: string | null; isActive?: boolean | null; recurrenceType?: RecurrenceType; interval?: number | null; nextTasksCreateAt?: string | null; documentTypeId?: number | null; }; export type RefreshRequest = { refreshToken: string; }; export type RegisterRequest = { email: string; password: string; }; export type ResendConfirmationEmailRequest = { email: string; }; export type ResetPasswordRequest = { email: string; resetCode: string; newPassword: string; }; export type SendFeedbackRequest = { type: FeedbackType; subject: string; message: string; platform: string; deviceInfo?: string | null; appVersion?: string | null; traceId?: string | null; }; export type SequencePosition = 'Start' | 'End'; export type Task = { id: number; title: string; details: string; dueAt: string; status: TaskStatus; businessId: number; businessName: string; documentTypeId: number; documentTypeName: string; }; export type TaskComment = { id: number; taskId: number | null; content: string; authorId: number | null; authorFullName: string | null; createdAt: string; }; export type TaskRejectDto = { reason: string; }; export type TaskStatus = 'PendingClient' | 'PendingAccountant' | 'Completed' | 'Canceled'; export type TaskSubmitDto = { answer: string | null; }; export type TaskUpdateDto = { title: string; details: string; dueAt: string; documentTypeId?: number | null; }; export type TasksCreateDto = { businessIds: Array; documentTypeId?: number; title: string; details: string; dueAt: string; }; export type TwoFactorRequest = { enable?: boolean | null; twoFactorCode?: string | null; resetSharedKey?: boolean; resetRecoveryCodes?: boolean; forgetMachine?: boolean; }; export type TwoFactorResponse = { sharedKey: string; recoveryCodesLeft: number; recoveryCodes?: Array | null; isTwoFactorEnabled: boolean; isMachineRemembered: boolean; }; export type User = { id: number; email: string | null; emailConfirmed: boolean; fullName: string; phoneNumber: string | null; isAccountant: boolean; }; export type UserUpdateDto = { firstName?: string | null; lastName?: string | null; phoneNumber?: string | null; }; export type YearFormat = 'Full' | 'Short'; export type AccessTokenResponseWritable = { accessToken: string; expiresIn: number; refreshToken: string; }; export type PostApiV1AccountingCompaniesData = { body?: AccountingCompanyCreateDto; path?: never; query?: never; url: '/api/v1/accounting-companies'; }; export type PostApiV1AccountingCompaniesResponses = { /** * OK */ 200: AccountingCompany; }; export type PostApiV1AccountingCompaniesResponse = PostApiV1AccountingCompaniesResponses[keyof PostApiV1AccountingCompaniesResponses]; export type DeleteApiV1AccountingCompaniesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/accounting-companies/{id}'; }; export type DeleteApiV1AccountingCompaniesByIdResponses = { /** * OK */ 200: unknown; }; export type PostApiV1AccountingCompaniesByIdData = { body?: AccountingCompanyUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/accounting-companies/{id}'; }; export type PostApiV1AccountingCompaniesByIdResponses = { /** * OK */ 200: AccountingCompany; }; export type PostApiV1AccountingCompaniesByIdResponse = PostApiV1AccountingCompaniesByIdResponses[keyof PostApiV1AccountingCompaniesByIdResponses]; export type ApiVVersionApiVersionOdataAccountingCompaniesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanies'; }; export type ApiVVersionApiVersionOdataAccountingCompaniesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompaniesResponse = ApiVVersionApiVersionOdataAccountingCompaniesResponses[keyof ApiVVersionApiVersionOdataAccountingCompaniesResponses]; export type ApiVVersionApiVersionOdataAccountingCompaniesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanies/$count'; }; export type ApiVVersionApiVersionOdataAccountingCompaniesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompaniesCountResponse = ApiVVersionApiVersionOdataAccountingCompaniesCountResponses[keyof ApiVVersionApiVersionOdataAccountingCompaniesCountResponses]; export type PutApiV1AccountingCompanyMembershipsData = { body?: AccountingCompanyMembershipUpsertDto; path?: never; query?: never; url: '/api/v1/accounting-company-memberships'; }; export type PutApiV1AccountingCompanyMembershipsResponses = { /** * OK */ 200: AccountingCompanyMembership; }; export type PutApiV1AccountingCompanyMembershipsResponse = PutApiV1AccountingCompanyMembershipsResponses[keyof PutApiV1AccountingCompanyMembershipsResponses]; export type DeleteApiV1AccountingCompanyMembershipsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/accounting-company-memberships/{id}'; }; export type DeleteApiV1AccountingCompanyMembershipsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanyMemberships'; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponse = ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses[keyof ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses]; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanyMemberships/$count'; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponse = ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses[keyof ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses]; export type PutApiV1BankAccountsData = { body?: BankAccountUpsertDto; path?: never; query?: never; url: '/api/v1/bank-accounts'; }; export type PutApiV1BankAccountsResponses = { /** * OK */ 200: BankAccount; }; export type PutApiV1BankAccountsResponse = PutApiV1BankAccountsResponses[keyof PutApiV1BankAccountsResponses]; export type DeleteApiV1BankAccountsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/bank-accounts/{id}'; }; export type DeleteApiV1BankAccountsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataBankAccountsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BankAccounts'; }; export type ApiVVersionApiVersionOdataBankAccountsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBankAccountsResponse = ApiVVersionApiVersionOdataBankAccountsResponses[keyof ApiVVersionApiVersionOdataBankAccountsResponses]; export type ApiVVersionApiVersionOdataBankAccountsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BankAccounts/$count'; }; export type ApiVVersionApiVersionOdataBankAccountsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBankAccountsCountResponse = ApiVVersionApiVersionOdataBankAccountsCountResponses[keyof ApiVVersionApiVersionOdataBankAccountsCountResponses]; export type PutApiV1BusinessAccountantAssignmentsData = { body?: BusinessAccountantAssignmentUpsert; path?: never; query?: never; url: '/api/v1/business-accountant-assignments'; }; export type PutApiV1BusinessAccountantAssignmentsResponses = { /** * OK */ 200: BusinessAccountantAssignment; }; export type PutApiV1BusinessAccountantAssignmentsResponse = PutApiV1BusinessAccountantAssignmentsResponses[keyof PutApiV1BusinessAccountantAssignmentsResponses]; export type DeleteApiV1BusinessAccountantAssignmentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-accountant-assignments/{id}'; }; export type DeleteApiV1BusinessAccountantAssignmentsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessAccountantAssignments'; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponse = ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses[keyof ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses]; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessAccountantAssignments/$count'; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponse = ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses[keyof ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses]; export type GetApiV1BusinessDocumentsByIdRawData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/raw'; }; export type GetApiV1BusinessDocumentsByIdRawResponses = { /** * OK */ 200: unknown; /** * No Content */ 204: void; }; export type GetApiV1BusinessDocumentsByIdRawResponse = GetApiV1BusinessDocumentsByIdRawResponses[keyof GetApiV1BusinessDocumentsByIdRawResponses]; export type PostApiV1BusinessDocumentsData = { body?: { BusinessId: number; DocumentTypeId: number; File: Blob | File; DocumentName: string; TaskId: number; }; path?: never; query?: never; url: '/api/v1/business-documents'; }; export type PostApiV1BusinessDocumentsResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsResponse = PostApiV1BusinessDocumentsResponses[keyof PostApiV1BusinessDocumentsResponses]; export type DeleteApiV1BusinessDocumentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}'; }; export type DeleteApiV1BusinessDocumentsByIdResponses = { /** * OK */ 200: DocumentBusiness; }; export type DeleteApiV1BusinessDocumentsByIdResponse = DeleteApiV1BusinessDocumentsByIdResponses[keyof DeleteApiV1BusinessDocumentsByIdResponses]; export type PutApiV1BusinessDocumentsByIdData = { body?: BusinessDocumentUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}'; }; export type PutApiV1BusinessDocumentsByIdResponses = { /** * OK */ 200: DocumentBusiness; }; export type PutApiV1BusinessDocumentsByIdResponse = PutApiV1BusinessDocumentsByIdResponses[keyof PutApiV1BusinessDocumentsByIdResponses]; export type PostApiV1BusinessDocumentsByIdApproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/approve'; }; export type PostApiV1BusinessDocumentsByIdApproveResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdApproveResponse = PostApiV1BusinessDocumentsByIdApproveResponses[keyof PostApiV1BusinessDocumentsByIdApproveResponses]; export type PostApiV1BusinessDocumentsByIdUnapproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/unapprove'; }; export type PostApiV1BusinessDocumentsByIdUnapproveResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdUnapproveResponse = PostApiV1BusinessDocumentsByIdUnapproveResponses[keyof PostApiV1BusinessDocumentsByIdUnapproveResponses]; export type PostApiV1BusinessDocumentsByIdMoveToPersonalData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/move-to-personal'; }; export type PostApiV1BusinessDocumentsByIdMoveToPersonalResponses = { /** * OK */ 200: unknown; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessData = { body?: BusinessDocumentMoveToBusinessDocumentsDto; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/move-to-business'; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessResponse = PostApiV1BusinessDocumentsByIdMoveToBusinessResponses[keyof PostApiV1BusinessDocumentsByIdMoveToBusinessResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentActivities'; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponse = ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentActivities/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponse = ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocuments'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsResponse = ApiVVersionApiVersionOdataBusinessDocumentsResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocuments/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsCountResponse = ApiVVersionApiVersionOdataBusinessDocumentsCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsCountResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentsSummaries'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponse = ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentsSummaries/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponse = ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses]; export type GetApiV1BusinessesByIdDocumentTypesSummaryData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/document-types-summary'; }; export type GetApiV1BusinessesByIdDocumentTypesSummaryResponses = { /** * OK */ 200: Array; }; export type GetApiV1BusinessesByIdDocumentTypesSummaryResponse = GetApiV1BusinessesByIdDocumentTypesSummaryResponses[keyof GetApiV1BusinessesByIdDocumentTypesSummaryResponses]; export type PostApiV1BusinessesData = { body?: BusinessCreateDto; path?: never; query?: never; url: '/api/v1/businesses'; }; export type PostApiV1BusinessesResponses = { /** * OK */ 200: Business; }; export type PostApiV1BusinessesResponse = PostApiV1BusinessesResponses[keyof PostApiV1BusinessesResponses]; export type DeleteApiV1BusinessesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}'; }; export type DeleteApiV1BusinessesByIdResponses = { /** * OK */ 200: unknown; }; export type PutApiV1BusinessesByIdData = { body?: BusinessUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}'; }; export type PutApiV1BusinessesByIdResponses = { /** * OK */ 200: Business; }; export type PutApiV1BusinessesByIdResponse = PutApiV1BusinessesByIdResponses[keyof PutApiV1BusinessesByIdResponses]; export type PutApiV1BusinessesByIdContactData = { body?: BusinessChangeContactDto; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/contact'; }; export type PutApiV1BusinessesByIdContactResponses = { /** * OK */ 200: unknown; }; export type PostApiV1BusinessesByIdDisconnectData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/disconnect'; }; export type PostApiV1BusinessesByIdDisconnectResponses = { /** * OK */ 200: Business; }; export type PostApiV1BusinessesByIdDisconnectResponse = PostApiV1BusinessesByIdDisconnectResponses[keyof PostApiV1BusinessesByIdDisconnectResponses]; export type ApiVVersionApiVersionOdataBusinessesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Businesses'; }; export type ApiVVersionApiVersionOdataBusinessesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessesResponse = ApiVVersionApiVersionOdataBusinessesResponses[keyof ApiVVersionApiVersionOdataBusinessesResponses]; export type ApiVVersionApiVersionOdataBusinessesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Businesses/$count'; }; export type ApiVVersionApiVersionOdataBusinessesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessesCountResponse = ApiVVersionApiVersionOdataBusinessesCountResponses[keyof ApiVVersionApiVersionOdataBusinessesCountResponses]; export type ApiVVersionApiVersionOdataBusinessesKeyData = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Businesses({key})'; }; export type ApiVVersionApiVersionOdataBusinessesKeyResponses = { /** * OK */ 200: Business; }; export type ApiVVersionApiVersionOdataBusinessesKeyResponse = ApiVVersionApiVersionOdataBusinessesKeyResponses[keyof ApiVVersionApiVersionOdataBusinessesKeyResponses]; export type ApiVVersionApiVersionOdataBusinessesKey2Data = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Businesses/{key}'; }; export type ApiVVersionApiVersionOdataBusinessesKey2Responses = { /** * OK */ 200: Business; }; export type ApiVVersionApiVersionOdataBusinessesKey2Response = ApiVVersionApiVersionOdataBusinessesKey2Responses[keyof ApiVVersionApiVersionOdataBusinessesKey2Responses]; export type PutApiV1BusinessMembershipsData = { body?: BusinessMembershipUpsertDto; path?: never; query?: never; url: '/api/v1/business-memberships'; }; export type PutApiV1BusinessMembershipsResponses = { /** * OK */ 200: BusinessMembershipDto; }; export type PutApiV1BusinessMembershipsResponse = PutApiV1BusinessMembershipsResponses[keyof PutApiV1BusinessMembershipsResponses]; export type ApiVVersionApiVersionOdataBusinessSummariesData = { body?: never; path?: never; query?: { role?: string; accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessSummaries'; }; export type ApiVVersionApiVersionOdataBusinessSummariesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessSummariesResponse = ApiVVersionApiVersionOdataBusinessSummariesResponses[keyof ApiVVersionApiVersionOdataBusinessSummariesResponses]; export type ApiVVersionApiVersionOdataBusinessSummariesCountData = { body?: never; path?: never; query?: { role?: string; accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessSummaries/$count'; }; export type ApiVVersionApiVersionOdataBusinessSummariesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessSummariesCountResponse = ApiVVersionApiVersionOdataBusinessSummariesCountResponses[keyof ApiVVersionApiVersionOdataBusinessSummariesCountResponses]; export type PostApiV1CounterpartiesData = { body?: CounterpartyCreateDto; path?: never; query?: never; url: '/api/v1/counterparties'; }; export type PostApiV1CounterpartiesResponses = { /** * OK */ 200: Counterparty; }; export type PostApiV1CounterpartiesResponse = PostApiV1CounterpartiesResponses[keyof PostApiV1CounterpartiesResponses]; export type DeleteApiV1CounterpartiesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/counterparties/{id}'; }; export type DeleteApiV1CounterpartiesByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1CounterpartiesByIdData = { body?: CounterpartyUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/counterparties/{id}'; }; export type PatchApiV1CounterpartiesByIdResponses = { /** * OK */ 200: Counterparty; }; export type PatchApiV1CounterpartiesByIdResponse = PatchApiV1CounterpartiesByIdResponses[keyof PatchApiV1CounterpartiesByIdResponses]; export type ApiVVersionApiVersionOdataCounterpartiesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Counterparties'; }; export type ApiVVersionApiVersionOdataCounterpartiesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataCounterpartiesResponse = ApiVVersionApiVersionOdataCounterpartiesResponses[keyof ApiVVersionApiVersionOdataCounterpartiesResponses]; export type ApiVVersionApiVersionOdataCounterpartiesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Counterparties/$count'; }; export type ApiVVersionApiVersionOdataCounterpartiesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataCounterpartiesCountResponse = ApiVVersionApiVersionOdataCounterpartiesCountResponses[keyof ApiVVersionApiVersionOdataCounterpartiesCountResponses]; export type PutApiV1DataBoxCredentialsData = { body?: DataBoxCredentialsUpsertDto; path?: never; query?: never; url: '/api/v1/data-box-credentials'; }; export type PutApiV1DataBoxCredentialsResponses = { /** * OK */ 200: DataBoxCredentials; }; export type PutApiV1DataBoxCredentialsResponse = PutApiV1DataBoxCredentialsResponses[keyof PutApiV1DataBoxCredentialsResponses]; export type DeleteApiV1DataBoxCredentialsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/data-box-credentials/{id}'; }; export type DeleteApiV1DataBoxCredentialsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsData = { body?: never; path?: never; query?: { includePassword?: boolean; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DataBoxCredentials'; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsResponse = ApiVVersionApiVersionOdataDataBoxCredentialsResponses[keyof ApiVVersionApiVersionOdataDataBoxCredentialsResponses]; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountData = { body?: never; path?: never; query?: { includePassword?: boolean; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DataBoxCredentials/$count'; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountResponse = ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses[keyof ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses]; export type GetApiDevData = { body?: never; path?: never; query?: never; url: '/api/dev'; }; export type GetApiDevResponses = { /** * OK */ 200: unknown; }; export type GetApiDevReseedDbData = { body?: never; path?: never; query?: never; url: '/api/dev/reseed-db'; }; export type GetApiDevReseedDbResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbResetData = { body?: never; path?: never; query?: never; url: '/api/dev/db-reset'; }; export type GetApiDevDbResetResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbReset2Data = { body?: never; path?: never; query?: never; url: '/api/dev/db/reset'; }; export type GetApiDevDbReset2Responses = { /** * OK */ 200: unknown; }; export type GetApiDevDbCreateData = { body?: never; path?: never; query?: never; url: '/api/dev/db/create'; }; export type GetApiDevDbCreateResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbTouchData = { body?: never; path?: never; query?: never; url: '/api/dev/db/touch'; }; export type GetApiDevDbTouchResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedData = { body?: never; path?: never; query?: never; url: '/api/dev/seed'; }; export type GetApiDevSeedResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedAllData = { body?: never; path?: never; query?: never; url: '/api/dev/seed-all'; }; export type GetApiDevSeedAllResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedProdData = { body?: never; path?: never; query?: never; url: '/api/dev/seed-prod'; }; export type GetApiDevSeedProdResponses = { /** * OK */ 200: unknown; }; export type GetApiDevJobProcessRecurringTasksData = { body?: never; path?: never; query?: { refDay?: string; }; url: '/api/dev/job/process-recurring-tasks'; }; export type GetApiDevJobProcessRecurringTasksResponses = { /** * OK */ 200: unknown; }; export type GetApiDevNotificationsSendTestData = { body?: never; path?: never; query?: { userId?: number; }; url: '/api/dev/notifications/send-test'; }; export type GetApiDevNotificationsSendTestResponses = { /** * OK */ 200: unknown; }; export type GetApiDevConfirmEmailData = { body?: never; path?: never; query?: { email?: string; }; url: '/api/dev/confirm-email'; }; export type GetApiDevConfirmEmailResponses = { /** * OK */ 200: unknown; }; export type GetApiDevEmailSendTestData = { body?: never; path?: never; query?: { to?: string; subject?: string; message?: string; }; url: '/api/dev/email/send-test'; }; export type GetApiDevEmailSendTestResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1NotificationsDeviceTokensData = { body?: NotificationsDeviceTokenDeleteDto; path?: never; query?: never; url: '/api/v1/notifications/device-tokens'; }; export type DeleteApiV1NotificationsDeviceTokensResponses = { /** * OK */ 200: unknown; }; export type PutApiV1NotificationsDeviceTokensData = { body?: NotificationsDeviceTokenUpsertDto; path?: never; query?: never; url: '/api/v1/notifications/device-tokens'; }; export type PutApiV1NotificationsDeviceTokensResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataDocumentTypesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DocumentTypes'; }; export type ApiVVersionApiVersionOdataDocumentTypesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDocumentTypesResponse = ApiVVersionApiVersionOdataDocumentTypesResponses[keyof ApiVVersionApiVersionOdataDocumentTypesResponses]; export type ApiVVersionApiVersionOdataDocumentTypesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DocumentTypes/$count'; }; export type ApiVVersionApiVersionOdataDocumentTypesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDocumentTypesCountResponse = ApiVVersionApiVersionOdataDocumentTypesCountResponses[keyof ApiVVersionApiVersionOdataDocumentTypesCountResponses]; export type PostApiV1FeedbackData = { body?: SendFeedbackRequest; path?: never; query?: never; url: '/api/v1/feedback'; }; export type PostApiV1FeedbackResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvitationsData = { body?: InvitationCreateDto; path?: never; query?: never; url: '/api/v1/invitations'; }; export type PostApiV1InvitationsResponses = { /** * OK */ 200: Invitation; }; export type PostApiV1InvitationsResponse = PostApiV1InvitationsResponses[keyof PostApiV1InvitationsResponses]; export type PostApiV1InvitationsByIdAcceptData = { body?: InvitationAcceptDto; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}/accept'; }; export type PostApiV1InvitationsByIdAcceptResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvitationsByIdRejectData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}/reject'; }; export type PostApiV1InvitationsByIdRejectResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1InvitationsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}'; }; export type DeleteApiV1InvitationsByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1InvitationsByIdData = { body?: InvitationUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}'; }; export type PatchApiV1InvitationsByIdResponses = { /** * OK */ 200: Invitation; }; export type PatchApiV1InvitationsByIdResponse = PatchApiV1InvitationsByIdResponses[keyof PatchApiV1InvitationsByIdResponses]; export type ApiVVersionApiVersionOdataInvitationsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invitations'; }; export type ApiVVersionApiVersionOdataInvitationsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvitationsResponse = ApiVVersionApiVersionOdataInvitationsResponses[keyof ApiVVersionApiVersionOdataInvitationsResponses]; export type ApiVVersionApiVersionOdataInvitationsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invitations/$count'; }; export type ApiVVersionApiVersionOdataInvitationsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvitationsCountResponse = ApiVVersionApiVersionOdataInvitationsCountResponses[keyof ApiVVersionApiVersionOdataInvitationsCountResponses]; export type PostApiV1InvoicesData = { body?: InvoiceCreateDto; path?: never; query?: never; url: '/api/v1/invoices'; }; export type PostApiV1InvoicesResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesResponse = PostApiV1InvoicesResponses[keyof PostApiV1InvoicesResponses]; export type DeleteApiV1InvoicesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}'; }; export type DeleteApiV1InvoicesByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1InvoicesByIdData = { body?: InvoiceUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}'; }; export type PatchApiV1InvoicesByIdResponses = { /** * OK */ 200: Invoice; }; export type PatchApiV1InvoicesByIdResponse = PatchApiV1InvoicesByIdResponses[keyof PatchApiV1InvoicesByIdResponses]; export type GetApiV1InvoicesByIdPreviewData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/preview'; }; export type GetApiV1InvoicesByIdPreviewResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvoicesByIdSendData = { body?: InvoiceSendDto; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/send'; }; export type PostApiV1InvoicesByIdSendResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesByIdSendResponse = PostApiV1InvoicesByIdSendResponses[keyof PostApiV1InvoicesByIdSendResponses]; export type PostApiV1InvoicesByIdSnapshotData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/snapshot'; }; export type PostApiV1InvoicesByIdSnapshotResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesByIdSnapshotResponse = PostApiV1InvoicesByIdSnapshotResponses[keyof PostApiV1InvoicesByIdSnapshotResponses]; export type ApiVVersionApiVersionOdataInvoicesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invoices'; }; export type ApiVVersionApiVersionOdataInvoicesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoicesResponse = ApiVVersionApiVersionOdataInvoicesResponses[keyof ApiVVersionApiVersionOdataInvoicesResponses]; export type ApiVVersionApiVersionOdataInvoicesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invoices/$count'; }; export type ApiVVersionApiVersionOdataInvoicesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoicesCountResponse = ApiVVersionApiVersionOdataInvoicesCountResponses[keyof ApiVVersionApiVersionOdataInvoicesCountResponses]; export type PutApiV1InvoiceSettingsData = { body?: InvoiceSettingUpsertDto; path?: never; query?: never; url: '/api/v1/invoice-settings'; }; export type PutApiV1InvoiceSettingsResponses = { /** * OK */ 200: InvoiceSetting; }; export type PutApiV1InvoiceSettingsResponse = PutApiV1InvoiceSettingsResponses[keyof PutApiV1InvoiceSettingsResponses]; export type ApiVVersionApiVersionOdataInvoiceSettingsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/InvoiceSettings'; }; export type ApiVVersionApiVersionOdataInvoiceSettingsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoiceSettingsResponse = ApiVVersionApiVersionOdataInvoiceSettingsResponses[keyof ApiVVersionApiVersionOdataInvoiceSettingsResponses]; export type ApiVVersionApiVersionOdataInvoiceSettingsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/InvoiceSettings/$count'; }; export type ApiVVersionApiVersionOdataInvoiceSettingsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoiceSettingsCountResponse = ApiVVersionApiVersionOdataInvoiceSettingsCountResponses[keyof ApiVVersionApiVersionOdataInvoiceSettingsCountResponses]; export type ApiVVersionApiVersionOdataLicensesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Licenses'; }; export type ApiVVersionApiVersionOdataLicensesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataLicensesResponse = ApiVVersionApiVersionOdataLicensesResponses[keyof ApiVVersionApiVersionOdataLicensesResponses]; export type ApiVVersionApiVersionOdataLicensesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Licenses/$count'; }; export type ApiVVersionApiVersionOdataLicensesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataLicensesCountResponse = ApiVVersionApiVersionOdataLicensesCountResponses[keyof ApiVVersionApiVersionOdataLicensesCountResponses]; export type PostApiV1NotificationsTestData = { body?: NotificationsTestSendDto; path?: never; query?: never; url: '/api/v1/notifications/test'; }; export type PostApiV1NotificationsTestResponses = { /** * OK */ 200: unknown; }; export type GetApiV1PersonalDocumentsByIdRawData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}/raw'; }; export type GetApiV1PersonalDocumentsByIdRawResponses = { /** * OK */ 200: unknown; /** * No Content */ 204: void; }; export type GetApiV1PersonalDocumentsByIdRawResponse = GetApiV1PersonalDocumentsByIdRawResponses[keyof GetApiV1PersonalDocumentsByIdRawResponses]; export type PostApiV1PersonalDocumentsData = { body?: { File: Blob | File; DocumentName: string; }; path?: never; query?: never; url: '/api/v1/personal-documents'; }; export type PostApiV1PersonalDocumentsResponses = { /** * OK */ 200: DocumentPersonal; }; export type PostApiV1PersonalDocumentsResponse = PostApiV1PersonalDocumentsResponses[keyof PostApiV1PersonalDocumentsResponses]; export type PostApiV1PersonalDocumentsByIdMoveToBusinessData = { body?: DocumentPersonalMoveToBusinessDocumentsDto; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}/move-to-business'; }; export type PostApiV1PersonalDocumentsByIdMoveToBusinessResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1PersonalDocumentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}'; }; export type DeleteApiV1PersonalDocumentsByIdResponses = { /** * OK */ 200: DocumentPersonal; }; export type DeleteApiV1PersonalDocumentsByIdResponse = DeleteApiV1PersonalDocumentsByIdResponses[keyof DeleteApiV1PersonalDocumentsByIdResponses]; export type GetApiV1PersonalDocumentsSummaryData = { body?: never; path?: never; query?: never; url: '/api/v1/personal-documents/summary'; }; export type GetApiV1PersonalDocumentsSummaryResponses = { /** * OK */ 200: PersonalDocumentsSummary; }; export type GetApiV1PersonalDocumentsSummaryResponse = GetApiV1PersonalDocumentsSummaryResponses[keyof GetApiV1PersonalDocumentsSummaryResponses]; export type ApiVVersionApiVersionOdataPersonalDocumentsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/PersonalDocuments'; }; export type ApiVVersionApiVersionOdataPersonalDocumentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataPersonalDocumentsResponse = ApiVVersionApiVersionOdataPersonalDocumentsResponses[keyof ApiVVersionApiVersionOdataPersonalDocumentsResponses]; export type ApiVVersionApiVersionOdataPersonalDocumentsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/PersonalDocuments/$count'; }; export type ApiVVersionApiVersionOdataPersonalDocumentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataPersonalDocumentsCountResponse = ApiVVersionApiVersionOdataPersonalDocumentsCountResponses[keyof ApiVVersionApiVersionOdataPersonalDocumentsCountResponses]; export type PostApiV1RecurringTasksData = { body?: RecurringTaskCreateDto; path?: never; query?: never; url: '/api/v1/recurring-tasks'; }; export type PostApiV1RecurringTasksResponses = { /** * OK */ 200: RecurringTask; }; export type PostApiV1RecurringTasksResponse = PostApiV1RecurringTasksResponses[keyof PostApiV1RecurringTasksResponses]; export type DeleteApiV1RecurringTasksByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/recurring-tasks/{id}'; }; export type DeleteApiV1RecurringTasksByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1RecurringTasksByIdData = { body?: RecurringTaskUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/recurring-tasks/{id}'; }; export type PatchApiV1RecurringTasksByIdResponses = { /** * OK */ 200: RecurringTask; }; export type PatchApiV1RecurringTasksByIdResponse = PatchApiV1RecurringTasksByIdResponses[keyof PatchApiV1RecurringTasksByIdResponses]; export type ApiVVersionApiVersionOdataRecurringTasksData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/RecurringTasks'; }; export type ApiVVersionApiVersionOdataRecurringTasksResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataRecurringTasksResponse = ApiVVersionApiVersionOdataRecurringTasksResponses[keyof ApiVVersionApiVersionOdataRecurringTasksResponses]; export type ApiVVersionApiVersionOdataRecurringTasksCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/RecurringTasks/$count'; }; export type ApiVVersionApiVersionOdataRecurringTasksCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataRecurringTasksCountResponse = ApiVVersionApiVersionOdataRecurringTasksCountResponses[keyof ApiVVersionApiVersionOdataRecurringTasksCountResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/'; }; export type GetResponses = { /** * OK */ 200: unknown; }; export type PostApiV1TasksData = { body?: TasksCreateDto; path?: never; query?: never; url: '/api/v1/tasks'; }; export type PostApiV1TasksResponses = { /** * OK */ 200: Array; }; export type PostApiV1TasksResponse = PostApiV1TasksResponses[keyof PostApiV1TasksResponses]; export type PutApiV1TasksByIdData = { body?: TaskUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}'; }; export type PutApiV1TasksByIdResponses = { /** * OK */ 200: Task; }; export type PutApiV1TasksByIdResponse = PutApiV1TasksByIdResponses[keyof PutApiV1TasksByIdResponses]; export type PostApiV1TasksByIdSubmitData = { body?: TaskSubmitDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/submit'; }; export type PostApiV1TasksByIdSubmitResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdSubmitResponse = PostApiV1TasksByIdSubmitResponses[keyof PostApiV1TasksByIdSubmitResponses]; export type PostApiV1TasksByIdApproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/approve'; }; export type PostApiV1TasksByIdApproveResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdApproveResponse = PostApiV1TasksByIdApproveResponses[keyof PostApiV1TasksByIdApproveResponses]; export type PostApiV1TasksByIdRejectData = { body?: TaskRejectDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/reject'; }; export type PostApiV1TasksByIdRejectResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdRejectResponse = PostApiV1TasksByIdRejectResponses[keyof PostApiV1TasksByIdRejectResponses]; export type GetApiV1TasksByIdCommentsData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/comments'; }; export type GetApiV1TasksByIdCommentsResponses = { /** * OK */ 200: Array; }; export type GetApiV1TasksByIdCommentsResponse = GetApiV1TasksByIdCommentsResponses[keyof GetApiV1TasksByIdCommentsResponses]; export type GetApiV1TasksByIdDocumentsData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/documents'; }; export type GetApiV1TasksByIdDocumentsResponses = { /** * OK */ 200: Array; }; export type GetApiV1TasksByIdDocumentsResponse = GetApiV1TasksByIdDocumentsResponses[keyof GetApiV1TasksByIdDocumentsResponses]; export type ApiVVersionApiVersionOdataTasksData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Tasks'; }; export type ApiVVersionApiVersionOdataTasksResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataTasksResponse = ApiVVersionApiVersionOdataTasksResponses[keyof ApiVVersionApiVersionOdataTasksResponses]; export type ApiVVersionApiVersionOdataTasksCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Tasks/$count'; }; export type ApiVVersionApiVersionOdataTasksCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataTasksCountResponse = ApiVVersionApiVersionOdataTasksCountResponses[keyof ApiVVersionApiVersionOdataTasksCountResponses]; export type ApiVVersionApiVersionOdataTasksKeyData = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Tasks({key})'; }; export type ApiVVersionApiVersionOdataTasksKeyResponses = { /** * OK */ 200: Task; }; export type ApiVVersionApiVersionOdataTasksKeyResponse = ApiVVersionApiVersionOdataTasksKeyResponses[keyof ApiVVersionApiVersionOdataTasksKeyResponses]; export type ApiVVersionApiVersionOdataTasksKey2Data = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Tasks/{key}'; }; export type ApiVVersionApiVersionOdataTasksKey2Responses = { /** * OK */ 200: Task; }; export type ApiVVersionApiVersionOdataTasksKey2Response = ApiVVersionApiVersionOdataTasksKey2Responses[keyof ApiVVersionApiVersionOdataTasksKey2Responses]; export type PostApiV1UserRegisterData = { body: RegisterRequest; path?: never; query?: never; url: '/api/v1/user/register'; }; export type PostApiV1UserRegisterErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserRegisterError = PostApiV1UserRegisterErrors[keyof PostApiV1UserRegisterErrors]; export type PostApiV1UserRegisterResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserLoginData = { body: LoginRequest; path?: never; query?: { useCookies?: boolean; useSessionCookies?: boolean; }; url: '/api/v1/user/login'; }; export type PostApiV1UserLoginResponses = { /** * OK */ 200: AccessTokenResponse; }; export type PostApiV1UserLoginResponse = PostApiV1UserLoginResponses[keyof PostApiV1UserLoginResponses]; export type PostApiV1UserRefreshData = { body: RefreshRequest; path?: never; query?: never; url: '/api/v1/user/refresh'; }; export type PostApiV1UserRefreshResponses = { /** * OK */ 200: AccessTokenResponse; }; export type PostApiV1UserRefreshResponse = PostApiV1UserRefreshResponses[keyof PostApiV1UserRefreshResponses]; export type MapIdentityApiApiVVersionApiVersionUserConfirmEmailData = { body?: never; path?: never; query: { userId: string; code: string; changedEmail?: string; }; url: '/api/v1/user/confirmEmail'; }; export type MapIdentityApiApiVVersionApiVersionUserConfirmEmailResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserResendConfirmationEmailData = { body: ResendConfirmationEmailRequest; path?: never; query?: never; url: '/api/v1/user/resendConfirmationEmail'; }; export type PostApiV1UserResendConfirmationEmailResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserForgotPasswordData = { body: ForgotPasswordRequest; path?: never; query?: never; url: '/api/v1/user/forgotPassword'; }; export type PostApiV1UserForgotPasswordErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserForgotPasswordError = PostApiV1UserForgotPasswordErrors[keyof PostApiV1UserForgotPasswordErrors]; export type PostApiV1UserForgotPasswordResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserResetPasswordData = { body: ResetPasswordRequest; path?: never; query?: never; url: '/api/v1/user/resetPassword'; }; export type PostApiV1UserResetPasswordErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserResetPasswordError = PostApiV1UserResetPasswordErrors[keyof PostApiV1UserResetPasswordErrors]; export type PostApiV1UserResetPasswordResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserManage2FaData = { body: TwoFactorRequest; path?: never; query?: never; url: '/api/v1/user/manage/2fa'; }; export type PostApiV1UserManage2FaErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type PostApiV1UserManage2FaError = PostApiV1UserManage2FaErrors[keyof PostApiV1UserManage2FaErrors]; export type PostApiV1UserManage2FaResponses = { /** * OK */ 200: TwoFactorResponse; }; export type PostApiV1UserManage2FaResponse = PostApiV1UserManage2FaResponses[keyof PostApiV1UserManage2FaResponses]; export type GetApiV1UserManageInfoData = { body?: never; path?: never; query?: never; url: '/api/v1/user/manage/info'; }; export type GetApiV1UserManageInfoErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type GetApiV1UserManageInfoError = GetApiV1UserManageInfoErrors[keyof GetApiV1UserManageInfoErrors]; export type GetApiV1UserManageInfoResponses = { /** * OK */ 200: InfoResponse; }; export type GetApiV1UserManageInfoResponse = GetApiV1UserManageInfoResponses[keyof GetApiV1UserManageInfoResponses]; export type PostApiV1UserManageInfoData = { body: InfoRequest; path?: never; query?: never; url: '/api/v1/user/manage/info'; }; export type PostApiV1UserManageInfoErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type PostApiV1UserManageInfoError = PostApiV1UserManageInfoErrors[keyof PostApiV1UserManageInfoErrors]; export type PostApiV1UserManageInfoResponses = { /** * OK */ 200: InfoResponse; }; export type PostApiV1UserManageInfoResponse = PostApiV1UserManageInfoResponses[keyof PostApiV1UserManageInfoResponses]; export type PostApiV1UserLogoutData = { body?: unknown; path?: never; query?: never; url: '/api/v1/user/logout'; }; export type PostApiV1UserLogoutResponses = { /** * OK */ 200: unknown; }; export type GetApiV1UserDocumentsSummaryData = { body?: never; path?: never; query?: never; url: '/api/v1/user/documents-summary'; }; export type GetApiV1UserDocumentsSummaryResponses = { /** * OK */ 200: PersonalDocumentsSummary; }; export type GetApiV1UserDocumentsSummaryResponse = GetApiV1UserDocumentsSummaryResponses[keyof GetApiV1UserDocumentsSummaryResponses]; export type DeleteApiV1UserData = { body?: never; path?: never; query?: never; url: '/api/v1/user'; }; export type DeleteApiV1UserResponses = { /** * OK */ 200: unknown; }; export type GetApiV1UsersMeData = { body?: never; path?: never; query?: never; url: '/api/v1/users/me'; }; export type GetApiV1UsersMeResponses = { /** * OK */ 200: User; }; export type GetApiV1UsersMeResponse = GetApiV1UsersMeResponses[keyof GetApiV1UsersMeResponses]; export type PatchApiV1UsersByIdData = { body?: UserUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/users/{id}'; }; export type PatchApiV1UsersByIdResponses = { /** * OK */ 200: User; }; export type PatchApiV1UsersByIdResponse = PatchApiV1UsersByIdResponses[keyof PatchApiV1UsersByIdResponses]; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client'; import { client } from './client.gen'; import type { ApiVVersionApiVersionOdataAccountingCompaniesCountData, ApiVVersionApiVersionOdataAccountingCompaniesCountResponses, ApiVVersionApiVersionOdataAccountingCompaniesData, ApiVVersionApiVersionOdataAccountingCompaniesResponses, ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountData, ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses, ApiVVersionApiVersionOdataAccountingCompanyMembershipsData, ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses, ApiVVersionApiVersionOdataBankAccountsCountData, ApiVVersionApiVersionOdataBankAccountsCountResponses, ApiVVersionApiVersionOdataBankAccountsData, ApiVVersionApiVersionOdataBankAccountsResponses, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountData, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsData, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses, ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountData, ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses, ApiVVersionApiVersionOdataBusinessDocumentActivitiesData, ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses, ApiVVersionApiVersionOdataBusinessDocumentsCountData, ApiVVersionApiVersionOdataBusinessDocumentsCountResponses, ApiVVersionApiVersionOdataBusinessDocumentsData, ApiVVersionApiVersionOdataBusinessDocumentsResponses, ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountData, ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses, ApiVVersionApiVersionOdataBusinessDocumentsSummariesData, ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses, ApiVVersionApiVersionOdataBusinessesCountData, ApiVVersionApiVersionOdataBusinessesCountResponses, ApiVVersionApiVersionOdataBusinessesData, ApiVVersionApiVersionOdataBusinessesKey2Data, ApiVVersionApiVersionOdataBusinessesKey2Responses, ApiVVersionApiVersionOdataBusinessesKeyData, ApiVVersionApiVersionOdataBusinessesKeyResponses, ApiVVersionApiVersionOdataBusinessesResponses, ApiVVersionApiVersionOdataBusinessSummariesCountData, ApiVVersionApiVersionOdataBusinessSummariesCountResponses, ApiVVersionApiVersionOdataBusinessSummariesData, ApiVVersionApiVersionOdataBusinessSummariesResponses, ApiVVersionApiVersionOdataCounterpartiesCountData, ApiVVersionApiVersionOdataCounterpartiesCountResponses, ApiVVersionApiVersionOdataCounterpartiesData, ApiVVersionApiVersionOdataCounterpartiesResponses, ApiVVersionApiVersionOdataDataBoxCredentialsCountData, ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses, ApiVVersionApiVersionOdataDataBoxCredentialsData, ApiVVersionApiVersionOdataDataBoxCredentialsResponses, ApiVVersionApiVersionOdataDocumentTypesCountData, ApiVVersionApiVersionOdataDocumentTypesCountResponses, ApiVVersionApiVersionOdataDocumentTypesData, ApiVVersionApiVersionOdataDocumentTypesResponses, ApiVVersionApiVersionOdataInvitationsCountData, ApiVVersionApiVersionOdataInvitationsCountResponses, ApiVVersionApiVersionOdataInvitationsData, ApiVVersionApiVersionOdataInvitationsResponses, ApiVVersionApiVersionOdataInvoicesCountData, ApiVVersionApiVersionOdataInvoicesCountResponses, ApiVVersionApiVersionOdataInvoicesData, ApiVVersionApiVersionOdataInvoiceSettingsCountData, ApiVVersionApiVersionOdataInvoiceSettingsCountResponses, ApiVVersionApiVersionOdataInvoiceSettingsData, ApiVVersionApiVersionOdataInvoiceSettingsResponses, ApiVVersionApiVersionOdataInvoicesResponses, ApiVVersionApiVersionOdataLicensesCountData, ApiVVersionApiVersionOdataLicensesCountResponses, ApiVVersionApiVersionOdataLicensesData, ApiVVersionApiVersionOdataLicensesResponses, ApiVVersionApiVersionOdataPersonalDocumentsCountData, ApiVVersionApiVersionOdataPersonalDocumentsCountResponses, ApiVVersionApiVersionOdataPersonalDocumentsData, ApiVVersionApiVersionOdataPersonalDocumentsResponses, ApiVVersionApiVersionOdataRecurringTasksCountData, ApiVVersionApiVersionOdataRecurringTasksCountResponses, ApiVVersionApiVersionOdataRecurringTasksData, ApiVVersionApiVersionOdataRecurringTasksResponses, ApiVVersionApiVersionOdataTasksCountData, ApiVVersionApiVersionOdataTasksCountResponses, ApiVVersionApiVersionOdataTasksData, ApiVVersionApiVersionOdataTasksKey2Data, ApiVVersionApiVersionOdataTasksKey2Responses, ApiVVersionApiVersionOdataTasksKeyData, ApiVVersionApiVersionOdataTasksKeyResponses, ApiVVersionApiVersionOdataTasksResponses, DeleteApiV1AccountingCompaniesByIdData, DeleteApiV1AccountingCompaniesByIdResponses, DeleteApiV1AccountingCompanyMembershipsByIdData, DeleteApiV1AccountingCompanyMembershipsByIdResponses, DeleteApiV1BankAccountsByIdData, DeleteApiV1BankAccountsByIdResponses, DeleteApiV1BusinessAccountantAssignmentsByIdData, DeleteApiV1BusinessAccountantAssignmentsByIdResponses, DeleteApiV1BusinessDocumentsByIdData, DeleteApiV1BusinessDocumentsByIdResponses, DeleteApiV1BusinessesByIdData, DeleteApiV1BusinessesByIdResponses, DeleteApiV1CounterpartiesByIdData, DeleteApiV1CounterpartiesByIdResponses, DeleteApiV1DataBoxCredentialsByIdData, DeleteApiV1DataBoxCredentialsByIdResponses, DeleteApiV1InvitationsByIdData, DeleteApiV1InvitationsByIdResponses, DeleteApiV1InvoicesByIdData, DeleteApiV1InvoicesByIdResponses, DeleteApiV1NotificationsDeviceTokensData, DeleteApiV1NotificationsDeviceTokensResponses, DeleteApiV1PersonalDocumentsByIdData, DeleteApiV1PersonalDocumentsByIdResponses, DeleteApiV1RecurringTasksByIdData, DeleteApiV1RecurringTasksByIdResponses, DeleteApiV1UserData, DeleteApiV1UserResponses, GetApiDevConfirmEmailData, GetApiDevConfirmEmailResponses, GetApiDevData, GetApiDevDbCreateData, GetApiDevDbCreateResponses, GetApiDevDbReset2Data, GetApiDevDbReset2Responses, GetApiDevDbResetData, GetApiDevDbResetResponses, GetApiDevDbTouchData, GetApiDevDbTouchResponses, GetApiDevEmailSendTestData, GetApiDevEmailSendTestResponses, GetApiDevJobProcessRecurringTasksData, GetApiDevJobProcessRecurringTasksResponses, GetApiDevNotificationsSendTestData, GetApiDevNotificationsSendTestResponses, GetApiDevReseedDbData, GetApiDevReseedDbResponses, GetApiDevResponses, GetApiDevSeedAllData, GetApiDevSeedAllResponses, GetApiDevSeedData, GetApiDevSeedProdData, GetApiDevSeedProdResponses, GetApiDevSeedResponses, GetApiV1BusinessDocumentsByIdRawData, GetApiV1BusinessDocumentsByIdRawResponses, GetApiV1BusinessesByIdDocumentTypesSummaryData, GetApiV1BusinessesByIdDocumentTypesSummaryResponses, GetApiV1InvoicesByIdPreviewData, GetApiV1InvoicesByIdPreviewResponses, GetApiV1PersonalDocumentsByIdRawData, GetApiV1PersonalDocumentsByIdRawResponses, GetApiV1PersonalDocumentsSummaryData, GetApiV1PersonalDocumentsSummaryResponses, GetApiV1TasksByIdCommentsData, GetApiV1TasksByIdCommentsResponses, GetApiV1TasksByIdDocumentsData, GetApiV1TasksByIdDocumentsResponses, GetApiV1UserDocumentsSummaryData, GetApiV1UserDocumentsSummaryResponses, GetApiV1UserManageInfoData, GetApiV1UserManageInfoErrors, GetApiV1UserManageInfoResponses, GetApiV1UsersMeData, GetApiV1UsersMeResponses, GetData, GetResponses, MapIdentityApiApiVVersionApiVersionUserConfirmEmailData, MapIdentityApiApiVVersionApiVersionUserConfirmEmailResponses, PatchApiV1CounterpartiesByIdData, PatchApiV1CounterpartiesByIdResponses, PatchApiV1InvitationsByIdData, PatchApiV1InvitationsByIdResponses, PatchApiV1InvoicesByIdData, PatchApiV1InvoicesByIdResponses, PatchApiV1RecurringTasksByIdData, PatchApiV1RecurringTasksByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdResponses, PostApiV1AccountingCompaniesByIdData, PostApiV1AccountingCompaniesByIdResponses, PostApiV1AccountingCompaniesData, PostApiV1AccountingCompaniesResponses, PostApiV1BusinessDocumentsByIdApproveData, PostApiV1BusinessDocumentsByIdApproveResponses, PostApiV1BusinessDocumentsByIdMoveToBusinessData, PostApiV1BusinessDocumentsByIdMoveToBusinessResponses, PostApiV1BusinessDocumentsByIdMoveToPersonalData, PostApiV1BusinessDocumentsByIdMoveToPersonalResponses, PostApiV1BusinessDocumentsByIdUnapproveData, PostApiV1BusinessDocumentsByIdUnapproveResponses, PostApiV1BusinessDocumentsData, PostApiV1BusinessDocumentsResponses, PostApiV1BusinessesByIdDisconnectData, PostApiV1BusinessesByIdDisconnectResponses, PostApiV1BusinessesData, PostApiV1BusinessesResponses, PostApiV1CounterpartiesData, PostApiV1CounterpartiesResponses, PostApiV1FeedbackData, PostApiV1FeedbackResponses, PostApiV1InvitationsByIdAcceptData, PostApiV1InvitationsByIdAcceptResponses, PostApiV1InvitationsByIdRejectData, PostApiV1InvitationsByIdRejectResponses, PostApiV1InvitationsData, PostApiV1InvitationsResponses, PostApiV1InvoicesByIdSendData, PostApiV1InvoicesByIdSendResponses, PostApiV1InvoicesByIdSnapshotData, PostApiV1InvoicesByIdSnapshotResponses, PostApiV1InvoicesData, PostApiV1InvoicesResponses, PostApiV1NotificationsTestData, PostApiV1NotificationsTestResponses, PostApiV1PersonalDocumentsByIdMoveToBusinessData, PostApiV1PersonalDocumentsByIdMoveToBusinessResponses, PostApiV1PersonalDocumentsData, PostApiV1PersonalDocumentsResponses, PostApiV1RecurringTasksData, PostApiV1RecurringTasksResponses, PostApiV1TasksByIdApproveData, PostApiV1TasksByIdApproveResponses, PostApiV1TasksByIdRejectData, PostApiV1TasksByIdRejectResponses, PostApiV1TasksByIdSubmitData, PostApiV1TasksByIdSubmitResponses, PostApiV1TasksData, PostApiV1TasksResponses, PostApiV1UserForgotPasswordData, PostApiV1UserForgotPasswordErrors, PostApiV1UserForgotPasswordResponses, PostApiV1UserLoginData, PostApiV1UserLoginResponses, PostApiV1UserLogoutData, PostApiV1UserLogoutResponses, PostApiV1UserManage2FaData, PostApiV1UserManage2FaErrors, PostApiV1UserManage2FaResponses, PostApiV1UserManageInfoData, PostApiV1UserManageInfoErrors, PostApiV1UserManageInfoResponses, PostApiV1UserRefreshData, PostApiV1UserRefreshResponses, PostApiV1UserRegisterData, PostApiV1UserRegisterErrors, PostApiV1UserRegisterResponses, PostApiV1UserResendConfirmationEmailData, PostApiV1UserResendConfirmationEmailResponses, PostApiV1UserResetPasswordData, PostApiV1UserResetPasswordErrors, PostApiV1UserResetPasswordResponses, PutApiV1AccountingCompanyMembershipsData, PutApiV1AccountingCompanyMembershipsResponses, PutApiV1BankAccountsData, PutApiV1BankAccountsResponses, PutApiV1BusinessAccountantAssignmentsData, PutApiV1BusinessAccountantAssignmentsResponses, PutApiV1BusinessDocumentsByIdData, PutApiV1BusinessDocumentsByIdResponses, PutApiV1BusinessesByIdContactData, PutApiV1BusinessesByIdContactResponses, PutApiV1BusinessesByIdData, PutApiV1BusinessesByIdResponses, PutApiV1BusinessMembershipsData, PutApiV1BusinessMembershipsResponses, PutApiV1DataBoxCredentialsData, PutApiV1DataBoxCredentialsResponses, PutApiV1InvoiceSettingsData, PutApiV1InvoiceSettingsResponses, PutApiV1NotificationsDeviceTokensData, PutApiV1NotificationsDeviceTokensResponses, PutApiV1TasksByIdData, PutApiV1TasksByIdResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postApiV1AccountingCompanies = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/accounting-companies', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1AccountingCompaniesById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/accounting-companies/{id}', ...options }); export const postApiV1AccountingCompaniesById = (options: Options) => (options.client ?? client).post({ url: '/api/v1/accounting-companies/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const apiVVersionApiVersionOdataAccountingCompanies = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanies', ...options }); export const apiVVersionApiVersionOdataAccountingCompaniesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanies/$count', ...options }); export const putApiV1AccountingCompanyMemberships = (options?: Options) => (options?.client ?? client).put({ url: '/api/v1/accounting-company-memberships', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1AccountingCompanyMembershipsById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/accounting-company-memberships/{id}', ...options }); export const apiVVersionApiVersionOdataAccountingCompanyMemberships = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanyMemberships', ...options }); export const apiVVersionApiVersionOdataAccountingCompanyMembershipsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/AccountingCompanyMemberships/$count', ...options }); export const putApiV1BankAccounts = (options?: Options) => (options?.client ?? client).put({ url: '/api/v1/bank-accounts', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1BankAccountsById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/bank-accounts/{id}', ...options }); export const apiVVersionApiVersionOdataBankAccounts = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BankAccounts', ...options }); export const apiVVersionApiVersionOdataBankAccountsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BankAccounts/$count', ...options }); export const putApiV1BusinessAccountantAssignments = (options?: Options) => (options?.client ?? client).put({ url: '/api/v1/business-accountant-assignments', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1BusinessAccountantAssignmentsById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/business-accountant-assignments/{id}', ...options }); export const apiVVersionApiVersionOdataBusinessAccountantAssignments = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessAccountantAssignments', ...options }); export const apiVVersionApiVersionOdataBusinessAccountantAssignmentsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessAccountantAssignments/$count', ...options }); export const getApiV1BusinessDocumentsByIdRaw = (options: Options) => (options.client ?? client).get({ url: '/api/v1/business-documents/{id}/raw', ...options }); export const postApiV1BusinessDocuments = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v1/business-documents', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const deleteApiV1BusinessDocumentsById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/business-documents/{id}', ...options }); export const putApiV1BusinessDocumentsById = (options: Options) => (options.client ?? client).put({ url: '/api/v1/business-documents/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const postApiV1BusinessDocumentsByIdApprove = (options: Options) => (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/approve', ...options }); export const postApiV1BusinessDocumentsByIdUnapprove = (options: Options) => (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/unapprove', ...options }); export const postApiV1BusinessDocumentsByIdMoveToPersonal = (options: Options) => (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/move-to-personal', ...options }); export const postApiV1BusinessDocumentsByIdMoveToBusiness = (options: Options) => (options.client ?? client).post({ url: '/api/v1/business-documents/{id}/move-to-business', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const apiVVersionApiVersionOdataBusinessDocumentActivities = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentActivities', ...options }); export const apiVVersionApiVersionOdataBusinessDocumentActivitiesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentActivities/$count', ...options }); export const apiVVersionApiVersionOdataBusinessDocuments = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocuments', ...options }); export const apiVVersionApiVersionOdataBusinessDocumentsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocuments/$count', ...options }); /** * @deprecated */ export const apiVVersionApiVersionOdataBusinessDocumentsSummaries = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentsSummaries', ...options }); /** * @deprecated */ export const apiVVersionApiVersionOdataBusinessDocumentsSummariesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessDocumentsSummaries/$count', ...options }); export const getApiV1BusinessesByIdDocumentTypesSummary = (options: Options) => (options.client ?? client).get({ url: '/api/v1/businesses/{id}/document-types-summary', ...options }); export const postApiV1Businesses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/businesses', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1BusinessesById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/businesses/{id}', ...options }); export const putApiV1BusinessesById = (options: Options) => (options.client ?? client).put({ url: '/api/v1/businesses/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const putApiV1BusinessesByIdContact = (options: Options) => (options.client ?? client).put({ url: '/api/v1/businesses/{id}/contact', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const postApiV1BusinessesByIdDisconnect = (options: Options) => (options.client ?? client).post({ url: '/api/v1/businesses/{id}/disconnect', ...options }); export const apiVVersionApiVersionOdataBusinesses = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Businesses', ...options }); export const apiVVersionApiVersionOdataBusinessesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Businesses/$count', ...options }); export const apiVVersionApiVersionOdataBusinessesKey = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Businesses({key})', ...options }); export const apiVVersionApiVersionOdataBusinessesKey2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Businesses/{key}', ...options }); export const putApiV1BusinessMemberships = (options?: Options) => (options?.client ?? client).put({ url: '/api/v1/business-memberships', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const apiVVersionApiVersionOdataBusinessSummaries = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessSummaries', ...options }); export const apiVVersionApiVersionOdataBusinessSummariesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/BusinessSummaries/$count', ...options }); export const postApiV1Counterparties = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/counterparties', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1CounterpartiesById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/counterparties/{id}', ...options }); export const patchApiV1CounterpartiesById = (options: Options) => (options.client ?? client).patch({ url: '/api/v1/counterparties/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const apiVVersionApiVersionOdataCounterparties = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Counterparties', ...options }); export const apiVVersionApiVersionOdataCounterpartiesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Counterparties/$count', ...options }); export const putApiV1DataBoxCredentials = (options?: Options) => (options?.client ?? client).put({ url: '/api/v1/data-box-credentials', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1DataBoxCredentialsById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/data-box-credentials/{id}', ...options }); export const apiVVersionApiVersionOdataDataBoxCredentials = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/DataBoxCredentials', ...options }); export const apiVVersionApiVersionOdataDataBoxCredentialsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/DataBoxCredentials/$count', ...options }); export const getApiDev = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev', ...options }); export const getApiDevReseedDb = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/reseed-db', ...options }); export const getApiDevDbReset = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/db-reset', ...options }); export const getApiDevDbReset2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/db/reset', ...options }); export const getApiDevDbCreate = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/db/create', ...options }); export const getApiDevDbTouch = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/db/touch', ...options }); export const getApiDevSeed = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/seed', ...options }); export const getApiDevSeedAll = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/seed-all', ...options }); export const getApiDevSeedProd = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/seed-prod', ...options }); export const getApiDevJobProcessRecurringTasks = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/job/process-recurring-tasks', ...options }); export const getApiDevNotificationsSendTest = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/notifications/send-test', ...options }); export const getApiDevConfirmEmail = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/confirm-email', ...options }); export const getApiDevEmailSendTest = (options?: Options) => (options?.client ?? client).get({ url: '/api/dev/email/send-test', ...options }); export const deleteApiV1NotificationsDeviceTokens = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v1/notifications/device-tokens', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const putApiV1NotificationsDeviceTokens = (options?: Options) => (options?.client ?? client).put({ url: '/api/v1/notifications/device-tokens', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const apiVVersionApiVersionOdataDocumentTypes = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/DocumentTypes', ...options }); export const apiVVersionApiVersionOdataDocumentTypesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/DocumentTypes/$count', ...options }); export const postApiV1Feedback = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/feedback', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const postApiV1Invitations = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/invitations', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const postApiV1InvitationsByIdAccept = (options: Options) => (options.client ?? client).post({ url: '/api/v1/invitations/{id}/accept', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const postApiV1InvitationsByIdReject = (options: Options) => (options.client ?? client).post({ url: '/api/v1/invitations/{id}/reject', ...options }); export const deleteApiV1InvitationsById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/invitations/{id}', ...options }); export const patchApiV1InvitationsById = (options: Options) => (options.client ?? client).patch({ url: '/api/v1/invitations/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const apiVVersionApiVersionOdataInvitations = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Invitations', ...options }); export const apiVVersionApiVersionOdataInvitationsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Invitations/$count', ...options }); export const postApiV1Invoices = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/invoices', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1InvoicesById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/invoices/{id}', ...options }); export const patchApiV1InvoicesById = (options: Options) => (options.client ?? client).patch({ url: '/api/v1/invoices/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const getApiV1InvoicesByIdPreview = (options: Options) => (options.client ?? client).get({ url: '/api/v1/invoices/{id}/preview', ...options }); export const postApiV1InvoicesByIdSend = (options: Options) => (options.client ?? client).post({ url: '/api/v1/invoices/{id}/send', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const postApiV1InvoicesByIdSnapshot = (options: Options) => (options.client ?? client).post({ url: '/api/v1/invoices/{id}/snapshot', ...options }); export const apiVVersionApiVersionOdataInvoices = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Invoices', ...options }); export const apiVVersionApiVersionOdataInvoicesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Invoices/$count', ...options }); export const putApiV1InvoiceSettings = (options?: Options) => (options?.client ?? client).put({ url: '/api/v1/invoice-settings', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const apiVVersionApiVersionOdataInvoiceSettings = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/InvoiceSettings', ...options }); export const apiVVersionApiVersionOdataInvoiceSettingsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/InvoiceSettings/$count', ...options }); export const apiVVersionApiVersionOdataLicenses = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Licenses', ...options }); export const apiVVersionApiVersionOdataLicensesCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Licenses/$count', ...options }); export const postApiV1NotificationsTest = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/notifications/test', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const getApiV1PersonalDocumentsByIdRaw = (options: Options) => (options.client ?? client).get({ url: '/api/v1/personal-documents/{id}/raw', ...options }); export const postApiV1PersonalDocuments = (options?: Options) => (options?.client ?? client).post({ ...formDataBodySerializer, url: '/api/v1/personal-documents', ...options, headers: { 'Content-Type': null, ...options?.headers } }); export const postApiV1PersonalDocumentsByIdMoveToBusiness = (options: Options) => (options.client ?? client).post({ url: '/api/v1/personal-documents/{id}/move-to-business', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const deleteApiV1PersonalDocumentsById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/personal-documents/{id}', ...options }); export const getApiV1PersonalDocumentsSummary = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/personal-documents/summary', ...options }); export const apiVVersionApiVersionOdataPersonalDocuments = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/PersonalDocuments', ...options }); export const apiVVersionApiVersionOdataPersonalDocumentsCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/PersonalDocuments/$count', ...options }); export const postApiV1RecurringTasks = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/recurring-tasks', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const deleteApiV1RecurringTasksById = (options: Options) => (options.client ?? client).delete({ url: '/api/v1/recurring-tasks/{id}', ...options }); export const patchApiV1RecurringTasksById = (options: Options) => (options.client ?? client).patch({ url: '/api/v1/recurring-tasks/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const apiVVersionApiVersionOdataRecurringTasks = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/RecurringTasks', ...options }); export const apiVVersionApiVersionOdataRecurringTasksCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/RecurringTasks/$count', ...options }); export const get = (options?: Options) => (options?.client ?? client).get({ url: '/', ...options }); export const postApiV1Tasks = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/tasks', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); export const putApiV1TasksById = (options: Options) => (options.client ?? client).put({ url: '/api/v1/tasks/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const postApiV1TasksByIdSubmit = (options: Options) => (options.client ?? client).post({ url: '/api/v1/tasks/{id}/submit', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const postApiV1TasksByIdApprove = (options: Options) => (options.client ?? client).post({ url: '/api/v1/tasks/{id}/approve', ...options }); export const postApiV1TasksByIdReject = (options: Options) => (options.client ?? client).post({ url: '/api/v1/tasks/{id}/reject', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); export const getApiV1TasksByIdComments = (options: Options) => (options.client ?? client).get({ url: '/api/v1/tasks/{id}/comments', ...options }); export const getApiV1TasksByIdDocuments = (options: Options) => (options.client ?? client).get({ url: '/api/v1/tasks/{id}/documents', ...options }); export const apiVVersionApiVersionOdataTasks = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Tasks', ...options }); export const apiVVersionApiVersionOdataTasksCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Tasks/$count', ...options }); export const apiVVersionApiVersionOdataTasksKey = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Tasks({key})', ...options }); export const apiVVersionApiVersionOdataTasksKey2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/odata/Tasks/{key}', ...options }); export const postApiV1UserRegister = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/register', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiV1UserLogin = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/login', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiV1UserRefresh = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/refresh', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const mapIdentityApiApiVVersionApiVersionUserConfirmEmail = (options: Options) => (options.client ?? client).get({ url: '/api/v1/user/confirmEmail', ...options }); export const postApiV1UserResendConfirmationEmail = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/resendConfirmationEmail', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiV1UserForgotPassword = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/forgotPassword', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiV1UserResetPassword = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/resetPassword', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiV1UserManage2Fa = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/manage/2fa', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const getApiV1UserManageInfo = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/user/manage/info', ...options }); export const postApiV1UserManageInfo = (options: Options) => (options.client ?? client).post({ url: '/api/v1/user/manage/info', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); export const postApiV1UserLogout = (options?: Options) => (options?.client ?? client).post({ url: '/api/v1/user/logout', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); /** * @deprecated */ export const getApiV1UserDocumentsSummary = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/user/documents-summary', ...options }); export const deleteApiV1User = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v1/user', ...options }); export const getApiV1UsersMe = (options?: Options) => (options?.client ?? client).get({ url: '/api/v1/users/me', ...options }); export const patchApiV1UsersById = (options: Options) => (options.client ?? client).patch({ url: '/api/v1/users/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/flat/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type AccessTokenResponse = { readonly tokenType?: string; accessToken: string; expiresIn: number; refreshToken: string; }; export type AccountingCompany = { id: number; name: string; identificationNumber: string; /** * @deprecated */ countryCode?: string; country: Country; }; export type AccountingCompanyCreateDto = { name: string; identificationNumber: string; }; export type AccountingCompanyMembership = { id: number; accountingCompanyId: number; accountingCompanyName: string; userId: number; userFullName: string; roleName: string; }; export type AccountingCompanyMembershipUpsertDto = { accountingCompanyId: number; email: string; roleName: string; }; export type AccountingCompanyUpdateDto = { name: string; identificationNumber: string; }; export type AddressDto = { street: string; city: string; postalCode: string; country: string; }; export type AnnualInvoicesCount = 'Tens' | 'Hundred' | 'Thousands' | 'TenThousands' | 'HundredThousands'; export type BankAccount = { id: number; businessId: number; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; createdAt: string; updatedAt?: string | null; }; export type BankAccountUpsertDto = { businessId: number; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; }; export type Business = { id: number; name: string; identificationNumber: string; vatNumber: string | null; country: Country; /** * @deprecated */ countryCode?: string; deletedAt: string | null; fullAddress: string | null; accountingCompany: BusinessAccountingCompany; contactPerson: BusinessContactPerson; }; export type BusinessAccountantAssignment = { id: number; businessId: number; businessName: string; accountantId: number; accountantName: string; }; export type BusinessAccountantAssignmentUpsert = { businessId: number; accountantId: number; }; export type BusinessAccountingCompany = { id: number; name: string; }; export type BusinessAresAddress = { street: string; houseNumber: number; guidanceNumber?: number | null; city: string; postalCode: number; }; export type BusinessChangeContactDto = { userId: number | null; }; export type BusinessContactPerson = { id: number; fullName: string; email: string | null; phoneNumber: string | null; }; export type BusinessCreateDto = { name: string; identificationNumber: string; vatNumber?: string | null; address?: BusinessAresAddress; }; export type BusinessDocumentMoveToBusinessDocumentsDto = { businessId: number; documentTypeId?: number | null; }; export type BusinessDocumentUpdateDto = { name: string | null; documentTypeId: number | null; }; export type BusinessDocumentsSummary = { id: number; name: string; documentsCount: number; documentsSize: number; lastUploadAt: string | null; maxStorageSize: number; }; export type BusinessMembershipDto = { id: number; userId: number; userFullName: string; businessId: number; businessName: string; roleId: number; roleName: string; }; export type BusinessMembershipUpsertDto = { businessId: number; email: string; roleName: string; }; export type BusinessSummary = { id: number; name: string; documentsCount: number; documentsSize: number; lastUploadAt: string | null; /** * @deprecated */ maxStorageSize?: number; pendingTasksCount: number; pendingDocumentsCount: number; }; export type BusinessUpdateDto = { name: string; identificationNumber: string; vatNumber?: string | null; address?: BusinessAresAddress; }; export type Counterparty = { id: number; businessId: number; name: string; identificationNumber: string | null; vatNumber: string | null; address: AddressDto; email: string | null; privateNote: string | null; isFavourite: boolean | null; createdAt: string; updatedAt?: string | null; }; export type CounterpartyCreateDto = { businessId: number; identificationNumber: string; name: string; vatNumber: string | null; address: AddressDto; email: string | null; privateNote?: string | null; isFavourite?: boolean | null; }; export type CounterpartyUpdateDto = { identificationNumber?: string | null; name?: string | null; vatNumber?: string | null; address?: AddressDto; email?: string | null; privateNote?: string | null; isFavourite?: boolean | null; }; export type Country = 'Czechia' | 'Slovakia'; export type CreateInvoiceClientDto = { counterpartyId: number; }; export type Currency = 'CZK' | 'EUR' | 'USD' | 'GBP'; export type DataBoxCredentials = { id?: number; username: string; password: string | null; businessId: number; businessName: string; userId: number; }; export type DataBoxCredentialsUpsertDto = { businessId: number; username: string | null; password: string | null; }; export type DocumentAction = 'Uploaded'; export type DocumentBusiness = { id: number; /** * @deprecated */ name?: string; documentName: string; originalFileName: string; extension: string | null; size: number; businessId: number | null; businessName: string | null; documentTypeId: number; documentTypeName: string; approvedAt: string | null; approverId: number | null; approverFullName: string | null; taskId: number | null; uploadedAt: string; uploaderId: number | null; deletedAt?: string | null; }; export type DocumentBusinessActivity = { documentId: number; documentName: string; businessId: number; businessName: string; action: DocumentAction; happenedAt: string; performedByUserId: number | null; performedByUserFullName: string | null; }; export type DocumentPersonal = { id: number; name: string; extension: string | null; size: number; userId: number; userFullName: string; uploadedAt?: string; deletedAt?: string | null; }; export type DocumentPersonalMoveToBusinessDocumentsDto = { businessId: number; documentTypeId?: number; }; export type DocumentType = { id: number; name: string; }; export type DocumentTypesSummary = { documentTypeId: number; documentTypeName: string; documentsCount: number; }; export type FeedbackType = 'Feedback' | 'Bug'; export type ForgotPasswordRequest = { email: string; }; export type HttpValidationProblemDetails = { type?: string | null; title?: string | null; status?: number | null; detail?: string | null; instance?: string | null; errors?: { [key: string]: Array; }; [key: string]: unknown; }; export type InfoRequest = { newEmail?: string | null; newPassword?: string | null; oldPassword?: string | null; }; export type InfoResponse = { email: string; isEmailConfirmed: boolean; }; export type Invitation = { id: number; accountingCompanyName: string; status: InvitationStatus; expiresAt: string; email: string; }; export type InvitationAcceptDto = { businessId: number; }; export type InvitationCreateDto = { accountingCompanyId: number; email: string; }; export type InvitationStatus = 'Pending' | 'Expired' | 'Rejected'; export type InvitationUpdateDto = { email?: string | null; }; export type Invoice = { id: number; businessId: number; supplier: InvoiceSupplier; client: InvoiceClient; bankAccount: InvoiceBankAccount; hideBankAccount: boolean; type: InvoiceType; number: string; status: InvoiceStatus; paymentMethod: PaymentMethod; currency: Currency; reversedVatCharge: boolean; variableSymbol: string | null; constantSymbol: string | null; issuedAt: string; dueAt: string; taxPointAt: string | null; sentAt: string | null; snapshotAt: string | null; noteBeforeLines: string | null; lines: Array; footerNote: string | null; totalPriceExcludingVat: number; totalVatAmount: number; totalPriceIncludingVat: number; createdAt: string; updatedAt: string | null; }; export type InvoiceBankAccount = { swift: string; iban: string; accountNumber: string; bankCode: string; currency: Currency; }; export type InvoiceBankAccountUpdateDto = { swift: string; iban: string; accountNumber: string; bankCode: string; currency: Currency; }; export type InvoiceClient = { /** * @deprecated */ id?: number | null; counterpartyId: number | null; name: string; registrationNumber: string | null; identificationNumber: string | null; vatNumber: string | null; email: string | null; address: InvoiceClientAddress; deliveryName: string | null; deliveryAddress: InvoiceClientDeliveryAddress; }; export type InvoiceClientAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceClientDeliveryAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceCreateDto = { client: CreateInvoiceClientDto; type: InvoiceType; number: string; status: InvoiceStatus; paymentMethod: PaymentMethod; hideBankAccount: boolean; reversedVatCharge: boolean; variableSymbol?: string | null; constantSymbol?: string | null; issuedAt: string; dueAt: string; taxPointAt: string; noteBeforeLines?: string | null; lines: Array; footerNote?: string | null; businessId: number; }; export type InvoiceLine = { id?: number; description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; totalPriceExcludingVat: number; vatAmount: number; totalPriceIncludingVat: number; }; export type InvoiceLineCreateDto = { description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; }; export type InvoiceLineUpdateDto = { id: number | null; description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; }; export type InvoiceSendDto = { customRecipientEmail: string | null; message: string; }; export type InvoiceSetting = { businessId: number; isVatPayer: boolean; template: InvoiceTemplate; bankAccount?: InvoiceSettingsBankAccount; numberingSetting: NumberingSetting; createdAt: string; updatedAt?: string | null; }; export type InvoiceSettingUpsertDto = { businessId: number; isVatPayer: boolean; template: InvoiceTemplateUpsertDto; bankAccount?: InvoiceSettingsBankAccountUpsertDto; numberingSetting: NumberingSettingUpsertDto; }; export type InvoiceSettingsBankAccount = { id: number; businessId: number; /** * @deprecated */ number: string; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; createdAt: string; updatedAt?: string | null; }; export type InvoiceSettingsBankAccountUpsertDto = { accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; }; export type InvoiceStatus = 'Draft' | 'Issued' | 'Paid' | 'Overdue' | 'Cancelled' | 'Snapshot'; export type InvoiceSupplier = { name: string; registrationNumber: string; identificationNumber: string; vatNumber: string | null; address: InvoiceSupplierAddress; }; export type InvoiceSupplierAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceTemplate = { currency: Currency; textBeforeLines: string | null; footerText: string | null; }; export type InvoiceTemplateUpsertDto = { currency: Currency; textBeforeLines: string | null; footerText: string | null; }; export type InvoiceType = 'Regular' | 'Corrective' | 'Advance'; export type InvoiceUpdateClientDto = { counterpartyId: number | null; name: string | null; registrationNumber: string | null; vatNumber: string | null; email: string | null; address: AddressDto; deliveryName: string | null; deliveryAddress: AddressDto; }; export type InvoiceUpdateDto = { client: InvoiceUpdateClientDto; bankAccount: InvoiceBankAccountUpdateDto; hideBankAccount: boolean | null; type: InvoiceType; number: string | null; status: InvoiceStatus; paymentMethod: PaymentMethod; currency: Currency; reversedVatCharge: boolean | null; variableSymbol: string | null; constantSymbol: string | null; issuedAt: string | null; dueAt: string | null; taxPointAt: string | null; noteBeforeLines: string | null; lines: Array | null; footerNote: string | null; }; export type LicenseDto = { id: number; tierId: number; tierName: string; businessId: number | null; /** * @deprecated */ maxStorageSize?: number; maxBusinessStorageSize: number; maxBusinessMembersCount: number; maxContactsCount: number; }; export type LoginRequest = { email: string; password: string; twoFactorCode?: string | null; twoFactorRecoveryCode?: string | null; }; export type NotificationsDeviceTokenDeleteDto = { token: string; }; export type NotificationsDeviceTokenUpsertDto = { provider: PushNotificationsProvider; token: string; }; export type NotificationsTestSendDto = { token: string | null; }; export type NumberingSetting = { id: number; businessId: number; yearFormat: YearFormat; isMonthIncluded: boolean; useHyphen: boolean; prefix?: string | null; suffix?: string | null; sequencePosition: SequencePosition; annualInvoicesCount: AnnualInvoicesCount; format: string; lastExternalInvoiceSequenceNumber: number | null; createdAt: string; updatedAt?: string | null; }; export type NumberingSettingUpsertDto = { yearFormat: YearFormat; isMonthIncluded: boolean; useHyphen: boolean; prefix: string | null; suffix: string | null; sequencePosition: SequencePosition; annualInvoicesCount: AnnualInvoicesCount; lastExternalInvoiceSequenceNumber?: number | null; }; export type PaymentMethod = 'Cash' | 'BankTransfer'; export type PersonalDocumentsSummary = { documentsCount: number; documentsSize: number; maxStorageSize: number; }; export type PushNotificationsProvider = 1 | 2; export type RecurrenceType = 'Daily' | 'Weekly' | 'Monthly' | 'Yearly'; export type RecurringTask = { id: number; title: string; details: string; accountingCompanyId: number; accountingCompanyName: string; accountantId: number | null; accountantFullName: string | null; recurrenceType?: RecurrenceType; period: RecurrenceType; interval: number; executeAt: string; isActive: boolean; businesses: Array; documentTypeId: number; documentTypeName: string; }; export type RecurringTaskBusiness = { id: number; name: string; }; export type RecurringTaskCreateDto = { title: string; details: string; recurrenceType: RecurrenceType; interval?: number; firstTaskDueAt: string; accountingCompanyId: number; businessIds: Array; documentTypeId: number; }; export type RecurringTaskUpdateDto = { title?: string | null; details?: string | null; isActive?: boolean | null; recurrenceType?: RecurrenceType; interval?: number | null; nextTasksCreateAt?: string | null; documentTypeId?: number | null; }; export type RefreshRequest = { refreshToken: string; }; export type RegisterRequest = { email: string; password: string; }; export type ResendConfirmationEmailRequest = { email: string; }; export type ResetPasswordRequest = { email: string; resetCode: string; newPassword: string; }; export type SendFeedbackRequest = { type: FeedbackType; subject: string; message: string; platform: string; deviceInfo?: string | null; appVersion?: string | null; traceId?: string | null; }; export type SequencePosition = 'Start' | 'End'; export type Task = { id: number; title: string; details: string; dueAt: string; status: TaskStatus; businessId: number; businessName: string; documentTypeId: number; documentTypeName: string; }; export type TaskComment = { id: number; taskId: number | null; content: string; authorId: number | null; authorFullName: string | null; createdAt: string; }; export type TaskRejectDto = { reason: string; }; export type TaskStatus = 'PendingClient' | 'PendingAccountant' | 'Completed' | 'Canceled'; export type TaskSubmitDto = { answer: string | null; }; export type TaskUpdateDto = { title: string; details: string; dueAt: string; documentTypeId?: number | null; }; export type TasksCreateDto = { businessIds: Array; documentTypeId?: number; title: string; details: string; dueAt: string; }; export type TwoFactorRequest = { enable?: boolean | null; twoFactorCode?: string | null; resetSharedKey?: boolean; resetRecoveryCodes?: boolean; forgetMachine?: boolean; }; export type TwoFactorResponse = { sharedKey: string; recoveryCodesLeft: number; recoveryCodes?: Array | null; isTwoFactorEnabled: boolean; isMachineRemembered: boolean; }; export type User = { id: number; email: string | null; emailConfirmed: boolean; fullName: string; phoneNumber: string | null; isAccountant: boolean; }; export type UserUpdateDto = { firstName?: string | null; lastName?: string | null; phoneNumber?: string | null; }; export type YearFormat = 'Full' | 'Short'; export type AccessTokenResponseWritable = { accessToken: string; expiresIn: number; refreshToken: string; }; export type PostApiV1AccountingCompaniesData = { body?: AccountingCompanyCreateDto; path?: never; query?: never; url: '/api/v1/accounting-companies'; }; export type PostApiV1AccountingCompaniesResponses = { /** * OK */ 200: AccountingCompany; }; export type PostApiV1AccountingCompaniesResponse = PostApiV1AccountingCompaniesResponses[keyof PostApiV1AccountingCompaniesResponses]; export type DeleteApiV1AccountingCompaniesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/accounting-companies/{id}'; }; export type DeleteApiV1AccountingCompaniesByIdResponses = { /** * OK */ 200: unknown; }; export type PostApiV1AccountingCompaniesByIdData = { body?: AccountingCompanyUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/accounting-companies/{id}'; }; export type PostApiV1AccountingCompaniesByIdResponses = { /** * OK */ 200: AccountingCompany; }; export type PostApiV1AccountingCompaniesByIdResponse = PostApiV1AccountingCompaniesByIdResponses[keyof PostApiV1AccountingCompaniesByIdResponses]; export type ApiVVersionApiVersionOdataAccountingCompaniesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanies'; }; export type ApiVVersionApiVersionOdataAccountingCompaniesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompaniesResponse = ApiVVersionApiVersionOdataAccountingCompaniesResponses[keyof ApiVVersionApiVersionOdataAccountingCompaniesResponses]; export type ApiVVersionApiVersionOdataAccountingCompaniesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanies/$count'; }; export type ApiVVersionApiVersionOdataAccountingCompaniesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompaniesCountResponse = ApiVVersionApiVersionOdataAccountingCompaniesCountResponses[keyof ApiVVersionApiVersionOdataAccountingCompaniesCountResponses]; export type PutApiV1AccountingCompanyMembershipsData = { body?: AccountingCompanyMembershipUpsertDto; path?: never; query?: never; url: '/api/v1/accounting-company-memberships'; }; export type PutApiV1AccountingCompanyMembershipsResponses = { /** * OK */ 200: AccountingCompanyMembership; }; export type PutApiV1AccountingCompanyMembershipsResponse = PutApiV1AccountingCompanyMembershipsResponses[keyof PutApiV1AccountingCompanyMembershipsResponses]; export type DeleteApiV1AccountingCompanyMembershipsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/accounting-company-memberships/{id}'; }; export type DeleteApiV1AccountingCompanyMembershipsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanyMemberships'; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponse = ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses[keyof ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses]; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanyMemberships/$count'; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponse = ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses[keyof ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses]; export type PutApiV1BankAccountsData = { body?: BankAccountUpsertDto; path?: never; query?: never; url: '/api/v1/bank-accounts'; }; export type PutApiV1BankAccountsResponses = { /** * OK */ 200: BankAccount; }; export type PutApiV1BankAccountsResponse = PutApiV1BankAccountsResponses[keyof PutApiV1BankAccountsResponses]; export type DeleteApiV1BankAccountsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/bank-accounts/{id}'; }; export type DeleteApiV1BankAccountsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataBankAccountsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BankAccounts'; }; export type ApiVVersionApiVersionOdataBankAccountsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBankAccountsResponse = ApiVVersionApiVersionOdataBankAccountsResponses[keyof ApiVVersionApiVersionOdataBankAccountsResponses]; export type ApiVVersionApiVersionOdataBankAccountsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BankAccounts/$count'; }; export type ApiVVersionApiVersionOdataBankAccountsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBankAccountsCountResponse = ApiVVersionApiVersionOdataBankAccountsCountResponses[keyof ApiVVersionApiVersionOdataBankAccountsCountResponses]; export type PutApiV1BusinessAccountantAssignmentsData = { body?: BusinessAccountantAssignmentUpsert; path?: never; query?: never; url: '/api/v1/business-accountant-assignments'; }; export type PutApiV1BusinessAccountantAssignmentsResponses = { /** * OK */ 200: BusinessAccountantAssignment; }; export type PutApiV1BusinessAccountantAssignmentsResponse = PutApiV1BusinessAccountantAssignmentsResponses[keyof PutApiV1BusinessAccountantAssignmentsResponses]; export type DeleteApiV1BusinessAccountantAssignmentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-accountant-assignments/{id}'; }; export type DeleteApiV1BusinessAccountantAssignmentsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessAccountantAssignments'; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponse = ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses[keyof ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses]; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessAccountantAssignments/$count'; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponse = ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses[keyof ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses]; export type GetApiV1BusinessDocumentsByIdRawData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/raw'; }; export type GetApiV1BusinessDocumentsByIdRawResponses = { /** * OK */ 200: unknown; /** * No Content */ 204: void; }; export type GetApiV1BusinessDocumentsByIdRawResponse = GetApiV1BusinessDocumentsByIdRawResponses[keyof GetApiV1BusinessDocumentsByIdRawResponses]; export type PostApiV1BusinessDocumentsData = { body?: { BusinessId: number; DocumentTypeId: number; File: Blob | File; DocumentName: string; TaskId: number; }; path?: never; query?: never; url: '/api/v1/business-documents'; }; export type PostApiV1BusinessDocumentsResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsResponse = PostApiV1BusinessDocumentsResponses[keyof PostApiV1BusinessDocumentsResponses]; export type DeleteApiV1BusinessDocumentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}'; }; export type DeleteApiV1BusinessDocumentsByIdResponses = { /** * OK */ 200: DocumentBusiness; }; export type DeleteApiV1BusinessDocumentsByIdResponse = DeleteApiV1BusinessDocumentsByIdResponses[keyof DeleteApiV1BusinessDocumentsByIdResponses]; export type PutApiV1BusinessDocumentsByIdData = { body?: BusinessDocumentUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}'; }; export type PutApiV1BusinessDocumentsByIdResponses = { /** * OK */ 200: DocumentBusiness; }; export type PutApiV1BusinessDocumentsByIdResponse = PutApiV1BusinessDocumentsByIdResponses[keyof PutApiV1BusinessDocumentsByIdResponses]; export type PostApiV1BusinessDocumentsByIdApproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/approve'; }; export type PostApiV1BusinessDocumentsByIdApproveResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdApproveResponse = PostApiV1BusinessDocumentsByIdApproveResponses[keyof PostApiV1BusinessDocumentsByIdApproveResponses]; export type PostApiV1BusinessDocumentsByIdUnapproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/unapprove'; }; export type PostApiV1BusinessDocumentsByIdUnapproveResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdUnapproveResponse = PostApiV1BusinessDocumentsByIdUnapproveResponses[keyof PostApiV1BusinessDocumentsByIdUnapproveResponses]; export type PostApiV1BusinessDocumentsByIdMoveToPersonalData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/move-to-personal'; }; export type PostApiV1BusinessDocumentsByIdMoveToPersonalResponses = { /** * OK */ 200: unknown; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessData = { body?: BusinessDocumentMoveToBusinessDocumentsDto; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/move-to-business'; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessResponse = PostApiV1BusinessDocumentsByIdMoveToBusinessResponses[keyof PostApiV1BusinessDocumentsByIdMoveToBusinessResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentActivities'; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponse = ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentActivities/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponse = ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocuments'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsResponse = ApiVVersionApiVersionOdataBusinessDocumentsResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocuments/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsCountResponse = ApiVVersionApiVersionOdataBusinessDocumentsCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsCountResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentsSummaries'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponse = ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentsSummaries/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponse = ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses]; export type GetApiV1BusinessesByIdDocumentTypesSummaryData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/document-types-summary'; }; export type GetApiV1BusinessesByIdDocumentTypesSummaryResponses = { /** * OK */ 200: Array; }; export type GetApiV1BusinessesByIdDocumentTypesSummaryResponse = GetApiV1BusinessesByIdDocumentTypesSummaryResponses[keyof GetApiV1BusinessesByIdDocumentTypesSummaryResponses]; export type PostApiV1BusinessesData = { body?: BusinessCreateDto; path?: never; query?: never; url: '/api/v1/businesses'; }; export type PostApiV1BusinessesResponses = { /** * OK */ 200: Business; }; export type PostApiV1BusinessesResponse = PostApiV1BusinessesResponses[keyof PostApiV1BusinessesResponses]; export type DeleteApiV1BusinessesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}'; }; export type DeleteApiV1BusinessesByIdResponses = { /** * OK */ 200: unknown; }; export type PutApiV1BusinessesByIdData = { body?: BusinessUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}'; }; export type PutApiV1BusinessesByIdResponses = { /** * OK */ 200: Business; }; export type PutApiV1BusinessesByIdResponse = PutApiV1BusinessesByIdResponses[keyof PutApiV1BusinessesByIdResponses]; export type PutApiV1BusinessesByIdContactData = { body?: BusinessChangeContactDto; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/contact'; }; export type PutApiV1BusinessesByIdContactResponses = { /** * OK */ 200: unknown; }; export type PostApiV1BusinessesByIdDisconnectData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/disconnect'; }; export type PostApiV1BusinessesByIdDisconnectResponses = { /** * OK */ 200: Business; }; export type PostApiV1BusinessesByIdDisconnectResponse = PostApiV1BusinessesByIdDisconnectResponses[keyof PostApiV1BusinessesByIdDisconnectResponses]; export type ApiVVersionApiVersionOdataBusinessesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Businesses'; }; export type ApiVVersionApiVersionOdataBusinessesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessesResponse = ApiVVersionApiVersionOdataBusinessesResponses[keyof ApiVVersionApiVersionOdataBusinessesResponses]; export type ApiVVersionApiVersionOdataBusinessesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Businesses/$count'; }; export type ApiVVersionApiVersionOdataBusinessesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessesCountResponse = ApiVVersionApiVersionOdataBusinessesCountResponses[keyof ApiVVersionApiVersionOdataBusinessesCountResponses]; export type ApiVVersionApiVersionOdataBusinessesKeyData = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Businesses({key})'; }; export type ApiVVersionApiVersionOdataBusinessesKeyResponses = { /** * OK */ 200: Business; }; export type ApiVVersionApiVersionOdataBusinessesKeyResponse = ApiVVersionApiVersionOdataBusinessesKeyResponses[keyof ApiVVersionApiVersionOdataBusinessesKeyResponses]; export type ApiVVersionApiVersionOdataBusinessesKey2Data = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Businesses/{key}'; }; export type ApiVVersionApiVersionOdataBusinessesKey2Responses = { /** * OK */ 200: Business; }; export type ApiVVersionApiVersionOdataBusinessesKey2Response = ApiVVersionApiVersionOdataBusinessesKey2Responses[keyof ApiVVersionApiVersionOdataBusinessesKey2Responses]; export type PutApiV1BusinessMembershipsData = { body?: BusinessMembershipUpsertDto; path?: never; query?: never; url: '/api/v1/business-memberships'; }; export type PutApiV1BusinessMembershipsResponses = { /** * OK */ 200: BusinessMembershipDto; }; export type PutApiV1BusinessMembershipsResponse = PutApiV1BusinessMembershipsResponses[keyof PutApiV1BusinessMembershipsResponses]; export type ApiVVersionApiVersionOdataBusinessSummariesData = { body?: never; path?: never; query?: { role?: string; accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessSummaries'; }; export type ApiVVersionApiVersionOdataBusinessSummariesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessSummariesResponse = ApiVVersionApiVersionOdataBusinessSummariesResponses[keyof ApiVVersionApiVersionOdataBusinessSummariesResponses]; export type ApiVVersionApiVersionOdataBusinessSummariesCountData = { body?: never; path?: never; query?: { role?: string; accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessSummaries/$count'; }; export type ApiVVersionApiVersionOdataBusinessSummariesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessSummariesCountResponse = ApiVVersionApiVersionOdataBusinessSummariesCountResponses[keyof ApiVVersionApiVersionOdataBusinessSummariesCountResponses]; export type PostApiV1CounterpartiesData = { body?: CounterpartyCreateDto; path?: never; query?: never; url: '/api/v1/counterparties'; }; export type PostApiV1CounterpartiesResponses = { /** * OK */ 200: Counterparty; }; export type PostApiV1CounterpartiesResponse = PostApiV1CounterpartiesResponses[keyof PostApiV1CounterpartiesResponses]; export type DeleteApiV1CounterpartiesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/counterparties/{id}'; }; export type DeleteApiV1CounterpartiesByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1CounterpartiesByIdData = { body?: CounterpartyUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/counterparties/{id}'; }; export type PatchApiV1CounterpartiesByIdResponses = { /** * OK */ 200: Counterparty; }; export type PatchApiV1CounterpartiesByIdResponse = PatchApiV1CounterpartiesByIdResponses[keyof PatchApiV1CounterpartiesByIdResponses]; export type ApiVVersionApiVersionOdataCounterpartiesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Counterparties'; }; export type ApiVVersionApiVersionOdataCounterpartiesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataCounterpartiesResponse = ApiVVersionApiVersionOdataCounterpartiesResponses[keyof ApiVVersionApiVersionOdataCounterpartiesResponses]; export type ApiVVersionApiVersionOdataCounterpartiesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Counterparties/$count'; }; export type ApiVVersionApiVersionOdataCounterpartiesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataCounterpartiesCountResponse = ApiVVersionApiVersionOdataCounterpartiesCountResponses[keyof ApiVVersionApiVersionOdataCounterpartiesCountResponses]; export type PutApiV1DataBoxCredentialsData = { body?: DataBoxCredentialsUpsertDto; path?: never; query?: never; url: '/api/v1/data-box-credentials'; }; export type PutApiV1DataBoxCredentialsResponses = { /** * OK */ 200: DataBoxCredentials; }; export type PutApiV1DataBoxCredentialsResponse = PutApiV1DataBoxCredentialsResponses[keyof PutApiV1DataBoxCredentialsResponses]; export type DeleteApiV1DataBoxCredentialsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/data-box-credentials/{id}'; }; export type DeleteApiV1DataBoxCredentialsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsData = { body?: never; path?: never; query?: { includePassword?: boolean; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DataBoxCredentials'; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsResponse = ApiVVersionApiVersionOdataDataBoxCredentialsResponses[keyof ApiVVersionApiVersionOdataDataBoxCredentialsResponses]; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountData = { body?: never; path?: never; query?: { includePassword?: boolean; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DataBoxCredentials/$count'; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountResponse = ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses[keyof ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses]; export type GetApiDevData = { body?: never; path?: never; query?: never; url: '/api/dev'; }; export type GetApiDevResponses = { /** * OK */ 200: unknown; }; export type GetApiDevReseedDbData = { body?: never; path?: never; query?: never; url: '/api/dev/reseed-db'; }; export type GetApiDevReseedDbResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbResetData = { body?: never; path?: never; query?: never; url: '/api/dev/db-reset'; }; export type GetApiDevDbResetResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbReset2Data = { body?: never; path?: never; query?: never; url: '/api/dev/db/reset'; }; export type GetApiDevDbReset2Responses = { /** * OK */ 200: unknown; }; export type GetApiDevDbCreateData = { body?: never; path?: never; query?: never; url: '/api/dev/db/create'; }; export type GetApiDevDbCreateResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbTouchData = { body?: never; path?: never; query?: never; url: '/api/dev/db/touch'; }; export type GetApiDevDbTouchResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedData = { body?: never; path?: never; query?: never; url: '/api/dev/seed'; }; export type GetApiDevSeedResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedAllData = { body?: never; path?: never; query?: never; url: '/api/dev/seed-all'; }; export type GetApiDevSeedAllResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedProdData = { body?: never; path?: never; query?: never; url: '/api/dev/seed-prod'; }; export type GetApiDevSeedProdResponses = { /** * OK */ 200: unknown; }; export type GetApiDevJobProcessRecurringTasksData = { body?: never; path?: never; query?: { refDay?: string; }; url: '/api/dev/job/process-recurring-tasks'; }; export type GetApiDevJobProcessRecurringTasksResponses = { /** * OK */ 200: unknown; }; export type GetApiDevNotificationsSendTestData = { body?: never; path?: never; query?: { userId?: number; }; url: '/api/dev/notifications/send-test'; }; export type GetApiDevNotificationsSendTestResponses = { /** * OK */ 200: unknown; }; export type GetApiDevConfirmEmailData = { body?: never; path?: never; query?: { email?: string; }; url: '/api/dev/confirm-email'; }; export type GetApiDevConfirmEmailResponses = { /** * OK */ 200: unknown; }; export type GetApiDevEmailSendTestData = { body?: never; path?: never; query?: { to?: string; subject?: string; message?: string; }; url: '/api/dev/email/send-test'; }; export type GetApiDevEmailSendTestResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1NotificationsDeviceTokensData = { body?: NotificationsDeviceTokenDeleteDto; path?: never; query?: never; url: '/api/v1/notifications/device-tokens'; }; export type DeleteApiV1NotificationsDeviceTokensResponses = { /** * OK */ 200: unknown; }; export type PutApiV1NotificationsDeviceTokensData = { body?: NotificationsDeviceTokenUpsertDto; path?: never; query?: never; url: '/api/v1/notifications/device-tokens'; }; export type PutApiV1NotificationsDeviceTokensResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataDocumentTypesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DocumentTypes'; }; export type ApiVVersionApiVersionOdataDocumentTypesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDocumentTypesResponse = ApiVVersionApiVersionOdataDocumentTypesResponses[keyof ApiVVersionApiVersionOdataDocumentTypesResponses]; export type ApiVVersionApiVersionOdataDocumentTypesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DocumentTypes/$count'; }; export type ApiVVersionApiVersionOdataDocumentTypesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDocumentTypesCountResponse = ApiVVersionApiVersionOdataDocumentTypesCountResponses[keyof ApiVVersionApiVersionOdataDocumentTypesCountResponses]; export type PostApiV1FeedbackData = { body?: SendFeedbackRequest; path?: never; query?: never; url: '/api/v1/feedback'; }; export type PostApiV1FeedbackResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvitationsData = { body?: InvitationCreateDto; path?: never; query?: never; url: '/api/v1/invitations'; }; export type PostApiV1InvitationsResponses = { /** * OK */ 200: Invitation; }; export type PostApiV1InvitationsResponse = PostApiV1InvitationsResponses[keyof PostApiV1InvitationsResponses]; export type PostApiV1InvitationsByIdAcceptData = { body?: InvitationAcceptDto; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}/accept'; }; export type PostApiV1InvitationsByIdAcceptResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvitationsByIdRejectData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}/reject'; }; export type PostApiV1InvitationsByIdRejectResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1InvitationsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}'; }; export type DeleteApiV1InvitationsByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1InvitationsByIdData = { body?: InvitationUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}'; }; export type PatchApiV1InvitationsByIdResponses = { /** * OK */ 200: Invitation; }; export type PatchApiV1InvitationsByIdResponse = PatchApiV1InvitationsByIdResponses[keyof PatchApiV1InvitationsByIdResponses]; export type ApiVVersionApiVersionOdataInvitationsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invitations'; }; export type ApiVVersionApiVersionOdataInvitationsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvitationsResponse = ApiVVersionApiVersionOdataInvitationsResponses[keyof ApiVVersionApiVersionOdataInvitationsResponses]; export type ApiVVersionApiVersionOdataInvitationsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invitations/$count'; }; export type ApiVVersionApiVersionOdataInvitationsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvitationsCountResponse = ApiVVersionApiVersionOdataInvitationsCountResponses[keyof ApiVVersionApiVersionOdataInvitationsCountResponses]; export type PostApiV1InvoicesData = { body?: InvoiceCreateDto; path?: never; query?: never; url: '/api/v1/invoices'; }; export type PostApiV1InvoicesResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesResponse = PostApiV1InvoicesResponses[keyof PostApiV1InvoicesResponses]; export type DeleteApiV1InvoicesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}'; }; export type DeleteApiV1InvoicesByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1InvoicesByIdData = { body?: InvoiceUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}'; }; export type PatchApiV1InvoicesByIdResponses = { /** * OK */ 200: Invoice; }; export type PatchApiV1InvoicesByIdResponse = PatchApiV1InvoicesByIdResponses[keyof PatchApiV1InvoicesByIdResponses]; export type GetApiV1InvoicesByIdPreviewData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/preview'; }; export type GetApiV1InvoicesByIdPreviewResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvoicesByIdSendData = { body?: InvoiceSendDto; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/send'; }; export type PostApiV1InvoicesByIdSendResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesByIdSendResponse = PostApiV1InvoicesByIdSendResponses[keyof PostApiV1InvoicesByIdSendResponses]; export type PostApiV1InvoicesByIdSnapshotData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/snapshot'; }; export type PostApiV1InvoicesByIdSnapshotResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesByIdSnapshotResponse = PostApiV1InvoicesByIdSnapshotResponses[keyof PostApiV1InvoicesByIdSnapshotResponses]; export type ApiVVersionApiVersionOdataInvoicesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invoices'; }; export type ApiVVersionApiVersionOdataInvoicesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoicesResponse = ApiVVersionApiVersionOdataInvoicesResponses[keyof ApiVVersionApiVersionOdataInvoicesResponses]; export type ApiVVersionApiVersionOdataInvoicesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invoices/$count'; }; export type ApiVVersionApiVersionOdataInvoicesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoicesCountResponse = ApiVVersionApiVersionOdataInvoicesCountResponses[keyof ApiVVersionApiVersionOdataInvoicesCountResponses]; export type PutApiV1InvoiceSettingsData = { body?: InvoiceSettingUpsertDto; path?: never; query?: never; url: '/api/v1/invoice-settings'; }; export type PutApiV1InvoiceSettingsResponses = { /** * OK */ 200: InvoiceSetting; }; export type PutApiV1InvoiceSettingsResponse = PutApiV1InvoiceSettingsResponses[keyof PutApiV1InvoiceSettingsResponses]; export type ApiVVersionApiVersionOdataInvoiceSettingsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/InvoiceSettings'; }; export type ApiVVersionApiVersionOdataInvoiceSettingsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoiceSettingsResponse = ApiVVersionApiVersionOdataInvoiceSettingsResponses[keyof ApiVVersionApiVersionOdataInvoiceSettingsResponses]; export type ApiVVersionApiVersionOdataInvoiceSettingsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/InvoiceSettings/$count'; }; export type ApiVVersionApiVersionOdataInvoiceSettingsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoiceSettingsCountResponse = ApiVVersionApiVersionOdataInvoiceSettingsCountResponses[keyof ApiVVersionApiVersionOdataInvoiceSettingsCountResponses]; export type ApiVVersionApiVersionOdataLicensesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Licenses'; }; export type ApiVVersionApiVersionOdataLicensesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataLicensesResponse = ApiVVersionApiVersionOdataLicensesResponses[keyof ApiVVersionApiVersionOdataLicensesResponses]; export type ApiVVersionApiVersionOdataLicensesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Licenses/$count'; }; export type ApiVVersionApiVersionOdataLicensesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataLicensesCountResponse = ApiVVersionApiVersionOdataLicensesCountResponses[keyof ApiVVersionApiVersionOdataLicensesCountResponses]; export type PostApiV1NotificationsTestData = { body?: NotificationsTestSendDto; path?: never; query?: never; url: '/api/v1/notifications/test'; }; export type PostApiV1NotificationsTestResponses = { /** * OK */ 200: unknown; }; export type GetApiV1PersonalDocumentsByIdRawData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}/raw'; }; export type GetApiV1PersonalDocumentsByIdRawResponses = { /** * OK */ 200: unknown; /** * No Content */ 204: void; }; export type GetApiV1PersonalDocumentsByIdRawResponse = GetApiV1PersonalDocumentsByIdRawResponses[keyof GetApiV1PersonalDocumentsByIdRawResponses]; export type PostApiV1PersonalDocumentsData = { body?: { File: Blob | File; DocumentName: string; }; path?: never; query?: never; url: '/api/v1/personal-documents'; }; export type PostApiV1PersonalDocumentsResponses = { /** * OK */ 200: DocumentPersonal; }; export type PostApiV1PersonalDocumentsResponse = PostApiV1PersonalDocumentsResponses[keyof PostApiV1PersonalDocumentsResponses]; export type PostApiV1PersonalDocumentsByIdMoveToBusinessData = { body?: DocumentPersonalMoveToBusinessDocumentsDto; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}/move-to-business'; }; export type PostApiV1PersonalDocumentsByIdMoveToBusinessResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1PersonalDocumentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}'; }; export type DeleteApiV1PersonalDocumentsByIdResponses = { /** * OK */ 200: DocumentPersonal; }; export type DeleteApiV1PersonalDocumentsByIdResponse = DeleteApiV1PersonalDocumentsByIdResponses[keyof DeleteApiV1PersonalDocumentsByIdResponses]; export type GetApiV1PersonalDocumentsSummaryData = { body?: never; path?: never; query?: never; url: '/api/v1/personal-documents/summary'; }; export type GetApiV1PersonalDocumentsSummaryResponses = { /** * OK */ 200: PersonalDocumentsSummary; }; export type GetApiV1PersonalDocumentsSummaryResponse = GetApiV1PersonalDocumentsSummaryResponses[keyof GetApiV1PersonalDocumentsSummaryResponses]; export type ApiVVersionApiVersionOdataPersonalDocumentsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/PersonalDocuments'; }; export type ApiVVersionApiVersionOdataPersonalDocumentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataPersonalDocumentsResponse = ApiVVersionApiVersionOdataPersonalDocumentsResponses[keyof ApiVVersionApiVersionOdataPersonalDocumentsResponses]; export type ApiVVersionApiVersionOdataPersonalDocumentsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/PersonalDocuments/$count'; }; export type ApiVVersionApiVersionOdataPersonalDocumentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataPersonalDocumentsCountResponse = ApiVVersionApiVersionOdataPersonalDocumentsCountResponses[keyof ApiVVersionApiVersionOdataPersonalDocumentsCountResponses]; export type PostApiV1RecurringTasksData = { body?: RecurringTaskCreateDto; path?: never; query?: never; url: '/api/v1/recurring-tasks'; }; export type PostApiV1RecurringTasksResponses = { /** * OK */ 200: RecurringTask; }; export type PostApiV1RecurringTasksResponse = PostApiV1RecurringTasksResponses[keyof PostApiV1RecurringTasksResponses]; export type DeleteApiV1RecurringTasksByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/recurring-tasks/{id}'; }; export type DeleteApiV1RecurringTasksByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1RecurringTasksByIdData = { body?: RecurringTaskUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/recurring-tasks/{id}'; }; export type PatchApiV1RecurringTasksByIdResponses = { /** * OK */ 200: RecurringTask; }; export type PatchApiV1RecurringTasksByIdResponse = PatchApiV1RecurringTasksByIdResponses[keyof PatchApiV1RecurringTasksByIdResponses]; export type ApiVVersionApiVersionOdataRecurringTasksData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/RecurringTasks'; }; export type ApiVVersionApiVersionOdataRecurringTasksResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataRecurringTasksResponse = ApiVVersionApiVersionOdataRecurringTasksResponses[keyof ApiVVersionApiVersionOdataRecurringTasksResponses]; export type ApiVVersionApiVersionOdataRecurringTasksCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/RecurringTasks/$count'; }; export type ApiVVersionApiVersionOdataRecurringTasksCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataRecurringTasksCountResponse = ApiVVersionApiVersionOdataRecurringTasksCountResponses[keyof ApiVVersionApiVersionOdataRecurringTasksCountResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/'; }; export type GetResponses = { /** * OK */ 200: unknown; }; export type PostApiV1TasksData = { body?: TasksCreateDto; path?: never; query?: never; url: '/api/v1/tasks'; }; export type PostApiV1TasksResponses = { /** * OK */ 200: Array; }; export type PostApiV1TasksResponse = PostApiV1TasksResponses[keyof PostApiV1TasksResponses]; export type PutApiV1TasksByIdData = { body?: TaskUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}'; }; export type PutApiV1TasksByIdResponses = { /** * OK */ 200: Task; }; export type PutApiV1TasksByIdResponse = PutApiV1TasksByIdResponses[keyof PutApiV1TasksByIdResponses]; export type PostApiV1TasksByIdSubmitData = { body?: TaskSubmitDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/submit'; }; export type PostApiV1TasksByIdSubmitResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdSubmitResponse = PostApiV1TasksByIdSubmitResponses[keyof PostApiV1TasksByIdSubmitResponses]; export type PostApiV1TasksByIdApproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/approve'; }; export type PostApiV1TasksByIdApproveResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdApproveResponse = PostApiV1TasksByIdApproveResponses[keyof PostApiV1TasksByIdApproveResponses]; export type PostApiV1TasksByIdRejectData = { body?: TaskRejectDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/reject'; }; export type PostApiV1TasksByIdRejectResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdRejectResponse = PostApiV1TasksByIdRejectResponses[keyof PostApiV1TasksByIdRejectResponses]; export type GetApiV1TasksByIdCommentsData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/comments'; }; export type GetApiV1TasksByIdCommentsResponses = { /** * OK */ 200: Array; }; export type GetApiV1TasksByIdCommentsResponse = GetApiV1TasksByIdCommentsResponses[keyof GetApiV1TasksByIdCommentsResponses]; export type GetApiV1TasksByIdDocumentsData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/documents'; }; export type GetApiV1TasksByIdDocumentsResponses = { /** * OK */ 200: Array; }; export type GetApiV1TasksByIdDocumentsResponse = GetApiV1TasksByIdDocumentsResponses[keyof GetApiV1TasksByIdDocumentsResponses]; export type ApiVVersionApiVersionOdataTasksData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Tasks'; }; export type ApiVVersionApiVersionOdataTasksResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataTasksResponse = ApiVVersionApiVersionOdataTasksResponses[keyof ApiVVersionApiVersionOdataTasksResponses]; export type ApiVVersionApiVersionOdataTasksCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Tasks/$count'; }; export type ApiVVersionApiVersionOdataTasksCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataTasksCountResponse = ApiVVersionApiVersionOdataTasksCountResponses[keyof ApiVVersionApiVersionOdataTasksCountResponses]; export type ApiVVersionApiVersionOdataTasksKeyData = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Tasks({key})'; }; export type ApiVVersionApiVersionOdataTasksKeyResponses = { /** * OK */ 200: Task; }; export type ApiVVersionApiVersionOdataTasksKeyResponse = ApiVVersionApiVersionOdataTasksKeyResponses[keyof ApiVVersionApiVersionOdataTasksKeyResponses]; export type ApiVVersionApiVersionOdataTasksKey2Data = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Tasks/{key}'; }; export type ApiVVersionApiVersionOdataTasksKey2Responses = { /** * OK */ 200: Task; }; export type ApiVVersionApiVersionOdataTasksKey2Response = ApiVVersionApiVersionOdataTasksKey2Responses[keyof ApiVVersionApiVersionOdataTasksKey2Responses]; export type PostApiV1UserRegisterData = { body: RegisterRequest; path?: never; query?: never; url: '/api/v1/user/register'; }; export type PostApiV1UserRegisterErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserRegisterError = PostApiV1UserRegisterErrors[keyof PostApiV1UserRegisterErrors]; export type PostApiV1UserRegisterResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserLoginData = { body: LoginRequest; path?: never; query?: { useCookies?: boolean; useSessionCookies?: boolean; }; url: '/api/v1/user/login'; }; export type PostApiV1UserLoginResponses = { /** * OK */ 200: AccessTokenResponse; }; export type PostApiV1UserLoginResponse = PostApiV1UserLoginResponses[keyof PostApiV1UserLoginResponses]; export type PostApiV1UserRefreshData = { body: RefreshRequest; path?: never; query?: never; url: '/api/v1/user/refresh'; }; export type PostApiV1UserRefreshResponses = { /** * OK */ 200: AccessTokenResponse; }; export type PostApiV1UserRefreshResponse = PostApiV1UserRefreshResponses[keyof PostApiV1UserRefreshResponses]; export type MapIdentityApiApiVVersionApiVersionUserConfirmEmailData = { body?: never; path?: never; query: { userId: string; code: string; changedEmail?: string; }; url: '/api/v1/user/confirmEmail'; }; export type MapIdentityApiApiVVersionApiVersionUserConfirmEmailResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserResendConfirmationEmailData = { body: ResendConfirmationEmailRequest; path?: never; query?: never; url: '/api/v1/user/resendConfirmationEmail'; }; export type PostApiV1UserResendConfirmationEmailResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserForgotPasswordData = { body: ForgotPasswordRequest; path?: never; query?: never; url: '/api/v1/user/forgotPassword'; }; export type PostApiV1UserForgotPasswordErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserForgotPasswordError = PostApiV1UserForgotPasswordErrors[keyof PostApiV1UserForgotPasswordErrors]; export type PostApiV1UserForgotPasswordResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserResetPasswordData = { body: ResetPasswordRequest; path?: never; query?: never; url: '/api/v1/user/resetPassword'; }; export type PostApiV1UserResetPasswordErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserResetPasswordError = PostApiV1UserResetPasswordErrors[keyof PostApiV1UserResetPasswordErrors]; export type PostApiV1UserResetPasswordResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserManage2FaData = { body: TwoFactorRequest; path?: never; query?: never; url: '/api/v1/user/manage/2fa'; }; export type PostApiV1UserManage2FaErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type PostApiV1UserManage2FaError = PostApiV1UserManage2FaErrors[keyof PostApiV1UserManage2FaErrors]; export type PostApiV1UserManage2FaResponses = { /** * OK */ 200: TwoFactorResponse; }; export type PostApiV1UserManage2FaResponse = PostApiV1UserManage2FaResponses[keyof PostApiV1UserManage2FaResponses]; export type GetApiV1UserManageInfoData = { body?: never; path?: never; query?: never; url: '/api/v1/user/manage/info'; }; export type GetApiV1UserManageInfoErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type GetApiV1UserManageInfoError = GetApiV1UserManageInfoErrors[keyof GetApiV1UserManageInfoErrors]; export type GetApiV1UserManageInfoResponses = { /** * OK */ 200: InfoResponse; }; export type GetApiV1UserManageInfoResponse = GetApiV1UserManageInfoResponses[keyof GetApiV1UserManageInfoResponses]; export type PostApiV1UserManageInfoData = { body: InfoRequest; path?: never; query?: never; url: '/api/v1/user/manage/info'; }; export type PostApiV1UserManageInfoErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type PostApiV1UserManageInfoError = PostApiV1UserManageInfoErrors[keyof PostApiV1UserManageInfoErrors]; export type PostApiV1UserManageInfoResponses = { /** * OK */ 200: InfoResponse; }; export type PostApiV1UserManageInfoResponse = PostApiV1UserManageInfoResponses[keyof PostApiV1UserManageInfoResponses]; export type PostApiV1UserLogoutData = { body?: unknown; path?: never; query?: never; url: '/api/v1/user/logout'; }; export type PostApiV1UserLogoutResponses = { /** * OK */ 200: unknown; }; export type GetApiV1UserDocumentsSummaryData = { body?: never; path?: never; query?: never; url: '/api/v1/user/documents-summary'; }; export type GetApiV1UserDocumentsSummaryResponses = { /** * OK */ 200: PersonalDocumentsSummary; }; export type GetApiV1UserDocumentsSummaryResponse = GetApiV1UserDocumentsSummaryResponses[keyof GetApiV1UserDocumentsSummaryResponses]; export type DeleteApiV1UserData = { body?: never; path?: never; query?: never; url: '/api/v1/user'; }; export type DeleteApiV1UserResponses = { /** * OK */ 200: unknown; }; export type GetApiV1UsersMeData = { body?: never; path?: never; query?: never; url: '/api/v1/users/me'; }; export type GetApiV1UsersMeResponses = { /** * OK */ 200: User; }; export type GetApiV1UsersMeResponse = GetApiV1UsersMeResponses[keyof GetApiV1UsersMeResponses]; export type PatchApiV1UsersByIdData = { body?: UserUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/users/{id}'; }; export type PatchApiV1UsersByIdResponses = { /** * OK */ 200: User; }; export type PatchApiV1UsersByIdResponse = PatchApiV1UsersByIdResponses[keyof PatchApiV1UsersByIdResponses]; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client'; import { client } from './client.gen'; import type { ApiVVersionApiVersionOdataAccountingCompaniesCountData, ApiVVersionApiVersionOdataAccountingCompaniesCountResponses, ApiVVersionApiVersionOdataAccountingCompaniesData, ApiVVersionApiVersionOdataAccountingCompaniesResponses, ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountData, ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses, ApiVVersionApiVersionOdataAccountingCompanyMembershipsData, ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses, ApiVVersionApiVersionOdataBankAccountsCountData, ApiVVersionApiVersionOdataBankAccountsCountResponses, ApiVVersionApiVersionOdataBankAccountsData, ApiVVersionApiVersionOdataBankAccountsResponses, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountData, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsData, ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses, ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountData, ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses, ApiVVersionApiVersionOdataBusinessDocumentActivitiesData, ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses, ApiVVersionApiVersionOdataBusinessDocumentsCountData, ApiVVersionApiVersionOdataBusinessDocumentsCountResponses, ApiVVersionApiVersionOdataBusinessDocumentsData, ApiVVersionApiVersionOdataBusinessDocumentsResponses, ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountData, ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses, ApiVVersionApiVersionOdataBusinessDocumentsSummariesData, ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses, ApiVVersionApiVersionOdataBusinessesCountData, ApiVVersionApiVersionOdataBusinessesCountResponses, ApiVVersionApiVersionOdataBusinessesData, ApiVVersionApiVersionOdataBusinessesKey2Data, ApiVVersionApiVersionOdataBusinessesKey2Responses, ApiVVersionApiVersionOdataBusinessesKeyData, ApiVVersionApiVersionOdataBusinessesKeyResponses, ApiVVersionApiVersionOdataBusinessesResponses, ApiVVersionApiVersionOdataBusinessSummariesCountData, ApiVVersionApiVersionOdataBusinessSummariesCountResponses, ApiVVersionApiVersionOdataBusinessSummariesData, ApiVVersionApiVersionOdataBusinessSummariesResponses, ApiVVersionApiVersionOdataCounterpartiesCountData, ApiVVersionApiVersionOdataCounterpartiesCountResponses, ApiVVersionApiVersionOdataCounterpartiesData, ApiVVersionApiVersionOdataCounterpartiesResponses, ApiVVersionApiVersionOdataDataBoxCredentialsCountData, ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses, ApiVVersionApiVersionOdataDataBoxCredentialsData, ApiVVersionApiVersionOdataDataBoxCredentialsResponses, ApiVVersionApiVersionOdataDocumentTypesCountData, ApiVVersionApiVersionOdataDocumentTypesCountResponses, ApiVVersionApiVersionOdataDocumentTypesData, ApiVVersionApiVersionOdataDocumentTypesResponses, ApiVVersionApiVersionOdataInvitationsCountData, ApiVVersionApiVersionOdataInvitationsCountResponses, ApiVVersionApiVersionOdataInvitationsData, ApiVVersionApiVersionOdataInvitationsResponses, ApiVVersionApiVersionOdataInvoicesCountData, ApiVVersionApiVersionOdataInvoicesCountResponses, ApiVVersionApiVersionOdataInvoicesData, ApiVVersionApiVersionOdataInvoiceSettingsCountData, ApiVVersionApiVersionOdataInvoiceSettingsCountResponses, ApiVVersionApiVersionOdataInvoiceSettingsData, ApiVVersionApiVersionOdataInvoiceSettingsResponses, ApiVVersionApiVersionOdataInvoicesResponses, ApiVVersionApiVersionOdataLicensesCountData, ApiVVersionApiVersionOdataLicensesCountResponses, ApiVVersionApiVersionOdataLicensesData, ApiVVersionApiVersionOdataLicensesResponses, ApiVVersionApiVersionOdataPersonalDocumentsCountData, ApiVVersionApiVersionOdataPersonalDocumentsCountResponses, ApiVVersionApiVersionOdataPersonalDocumentsData, ApiVVersionApiVersionOdataPersonalDocumentsResponses, ApiVVersionApiVersionOdataRecurringTasksCountData, ApiVVersionApiVersionOdataRecurringTasksCountResponses, ApiVVersionApiVersionOdataRecurringTasksData, ApiVVersionApiVersionOdataRecurringTasksResponses, ApiVVersionApiVersionOdataTasksCountData, ApiVVersionApiVersionOdataTasksCountResponses, ApiVVersionApiVersionOdataTasksData, ApiVVersionApiVersionOdataTasksKey2Data, ApiVVersionApiVersionOdataTasksKey2Responses, ApiVVersionApiVersionOdataTasksKeyData, ApiVVersionApiVersionOdataTasksKeyResponses, ApiVVersionApiVersionOdataTasksResponses, DeleteApiV1AccountingCompaniesByIdData, DeleteApiV1AccountingCompaniesByIdResponses, DeleteApiV1AccountingCompanyMembershipsByIdData, DeleteApiV1AccountingCompanyMembershipsByIdResponses, DeleteApiV1BankAccountsByIdData, DeleteApiV1BankAccountsByIdResponses, DeleteApiV1BusinessAccountantAssignmentsByIdData, DeleteApiV1BusinessAccountantAssignmentsByIdResponses, DeleteApiV1BusinessDocumentsByIdData, DeleteApiV1BusinessDocumentsByIdResponses, DeleteApiV1BusinessesByIdData, DeleteApiV1BusinessesByIdResponses, DeleteApiV1CounterpartiesByIdData, DeleteApiV1CounterpartiesByIdResponses, DeleteApiV1DataBoxCredentialsByIdData, DeleteApiV1DataBoxCredentialsByIdResponses, DeleteApiV1InvitationsByIdData, DeleteApiV1InvitationsByIdResponses, DeleteApiV1InvoicesByIdData, DeleteApiV1InvoicesByIdResponses, DeleteApiV1NotificationsDeviceTokensData, DeleteApiV1NotificationsDeviceTokensResponses, DeleteApiV1PersonalDocumentsByIdData, DeleteApiV1PersonalDocumentsByIdResponses, DeleteApiV1RecurringTasksByIdData, DeleteApiV1RecurringTasksByIdResponses, DeleteApiV1UserData, DeleteApiV1UserResponses, GetApiDevConfirmEmailData, GetApiDevConfirmEmailResponses, GetApiDevData, GetApiDevDbCreateData, GetApiDevDbCreateResponses, GetApiDevDbReset2Data, GetApiDevDbReset2Responses, GetApiDevDbResetData, GetApiDevDbResetResponses, GetApiDevDbTouchData, GetApiDevDbTouchResponses, GetApiDevEmailSendTestData, GetApiDevEmailSendTestResponses, GetApiDevJobProcessRecurringTasksData, GetApiDevJobProcessRecurringTasksResponses, GetApiDevNotificationsSendTestData, GetApiDevNotificationsSendTestResponses, GetApiDevReseedDbData, GetApiDevReseedDbResponses, GetApiDevResponses, GetApiDevSeedAllData, GetApiDevSeedAllResponses, GetApiDevSeedData, GetApiDevSeedProdData, GetApiDevSeedProdResponses, GetApiDevSeedResponses, GetApiV1BusinessDocumentsByIdRawData, GetApiV1BusinessDocumentsByIdRawResponses, GetApiV1BusinessesByIdDocumentTypesSummaryData, GetApiV1BusinessesByIdDocumentTypesSummaryResponses, GetApiV1InvoicesByIdPreviewData, GetApiV1InvoicesByIdPreviewResponses, GetApiV1PersonalDocumentsByIdRawData, GetApiV1PersonalDocumentsByIdRawResponses, GetApiV1PersonalDocumentsSummaryData, GetApiV1PersonalDocumentsSummaryResponses, GetApiV1TasksByIdCommentsData, GetApiV1TasksByIdCommentsResponses, GetApiV1TasksByIdDocumentsData, GetApiV1TasksByIdDocumentsResponses, GetApiV1UserDocumentsSummaryData, GetApiV1UserDocumentsSummaryResponses, GetApiV1UserManageInfoData, GetApiV1UserManageInfoErrors, GetApiV1UserManageInfoResponses, GetApiV1UsersMeData, GetApiV1UsersMeResponses, GetData, GetResponses, MapIdentityApiApiVVersionApiVersionUserConfirmEmailData, MapIdentityApiApiVVersionApiVersionUserConfirmEmailResponses, PatchApiV1CounterpartiesByIdData, PatchApiV1CounterpartiesByIdResponses, PatchApiV1InvitationsByIdData, PatchApiV1InvitationsByIdResponses, PatchApiV1InvoicesByIdData, PatchApiV1InvoicesByIdResponses, PatchApiV1RecurringTasksByIdData, PatchApiV1RecurringTasksByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdResponses, PostApiV1AccountingCompaniesByIdData, PostApiV1AccountingCompaniesByIdResponses, PostApiV1AccountingCompaniesData, PostApiV1AccountingCompaniesResponses, PostApiV1BusinessDocumentsByIdApproveData, PostApiV1BusinessDocumentsByIdApproveResponses, PostApiV1BusinessDocumentsByIdMoveToBusinessData, PostApiV1BusinessDocumentsByIdMoveToBusinessResponses, PostApiV1BusinessDocumentsByIdMoveToPersonalData, PostApiV1BusinessDocumentsByIdMoveToPersonalResponses, PostApiV1BusinessDocumentsByIdUnapproveData, PostApiV1BusinessDocumentsByIdUnapproveResponses, PostApiV1BusinessDocumentsData, PostApiV1BusinessDocumentsResponses, PostApiV1BusinessesByIdDisconnectData, PostApiV1BusinessesByIdDisconnectResponses, PostApiV1BusinessesData, PostApiV1BusinessesResponses, PostApiV1CounterpartiesData, PostApiV1CounterpartiesResponses, PostApiV1FeedbackData, PostApiV1FeedbackResponses, PostApiV1InvitationsByIdAcceptData, PostApiV1InvitationsByIdAcceptResponses, PostApiV1InvitationsByIdRejectData, PostApiV1InvitationsByIdRejectResponses, PostApiV1InvitationsData, PostApiV1InvitationsResponses, PostApiV1InvoicesByIdSendData, PostApiV1InvoicesByIdSendResponses, PostApiV1InvoicesByIdSnapshotData, PostApiV1InvoicesByIdSnapshotResponses, PostApiV1InvoicesData, PostApiV1InvoicesResponses, PostApiV1NotificationsTestData, PostApiV1NotificationsTestResponses, PostApiV1PersonalDocumentsByIdMoveToBusinessData, PostApiV1PersonalDocumentsByIdMoveToBusinessResponses, PostApiV1PersonalDocumentsData, PostApiV1PersonalDocumentsResponses, PostApiV1RecurringTasksData, PostApiV1RecurringTasksResponses, PostApiV1TasksByIdApproveData, PostApiV1TasksByIdApproveResponses, PostApiV1TasksByIdRejectData, PostApiV1TasksByIdRejectResponses, PostApiV1TasksByIdSubmitData, PostApiV1TasksByIdSubmitResponses, PostApiV1TasksData, PostApiV1TasksResponses, PostApiV1UserForgotPasswordData, PostApiV1UserForgotPasswordErrors, PostApiV1UserForgotPasswordResponses, PostApiV1UserLoginData, PostApiV1UserLoginResponses, PostApiV1UserLogoutData, PostApiV1UserLogoutResponses, PostApiV1UserManage2FaData, PostApiV1UserManage2FaErrors, PostApiV1UserManage2FaResponses, PostApiV1UserManageInfoData, PostApiV1UserManageInfoErrors, PostApiV1UserManageInfoResponses, PostApiV1UserRefreshData, PostApiV1UserRefreshResponses, PostApiV1UserRegisterData, PostApiV1UserRegisterErrors, PostApiV1UserRegisterResponses, PostApiV1UserResendConfirmationEmailData, PostApiV1UserResendConfirmationEmailResponses, PostApiV1UserResetPasswordData, PostApiV1UserResetPasswordErrors, PostApiV1UserResetPasswordResponses, PutApiV1AccountingCompanyMembershipsData, PutApiV1AccountingCompanyMembershipsResponses, PutApiV1BankAccountsData, PutApiV1BankAccountsResponses, PutApiV1BusinessAccountantAssignmentsData, PutApiV1BusinessAccountantAssignmentsResponses, PutApiV1BusinessDocumentsByIdData, PutApiV1BusinessDocumentsByIdResponses, PutApiV1BusinessesByIdContactData, PutApiV1BusinessesByIdContactResponses, PutApiV1BusinessesByIdData, PutApiV1BusinessesByIdResponses, PutApiV1BusinessMembershipsData, PutApiV1BusinessMembershipsResponses, PutApiV1DataBoxCredentialsData, PutApiV1DataBoxCredentialsResponses, PutApiV1InvoiceSettingsData, PutApiV1InvoiceSettingsResponses, PutApiV1NotificationsDeviceTokensData, PutApiV1NotificationsDeviceTokensResponses, PutApiV1TasksByIdData, PutApiV1TasksByIdResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; class HeyApiClient { protected client: Client; constructor(args?: { client?: Client; }) { this.client = args?.client ?? client; } } class HeyApiRegistry { private readonly defaultKey = 'default'; private readonly instances: Map = new Map(); get(key?: string): T { const instance = this.instances.get(key ?? this.defaultKey); if (!instance) { throw new Error(`No SDK client found. Create one with "new Sdk()" to fix this error.`); } return instance; } set(value: T, key?: string): void { this.instances.set(key ?? this.defaultKey, value); } } export class AccountingCompanies extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/AccountingCompanies/$count', ...options }); } } export class AccountingCompanyMemberships extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/AccountingCompanyMemberships/$count', ...options }); } } export class BankAccounts extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BankAccounts/$count', ...options }); } } export class BusinessAccountantAssignments extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessAccountantAssignments/$count', ...options }); } } export class BusinessDocumentActivities extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessDocumentActivities/$count', ...options }); } } export class BusinessDocuments extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessDocuments/$count', ...options }); } } export class BusinessDocumentsSummaries extends HeyApiClient { /** * @deprecated */ public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessDocumentsSummaries/$count', ...options }); } } export class Businesses extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Businesses/$count', ...options }); } public key(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Businesses/{key}', ...options }); } } export class BusinessSummaries extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessSummaries/$count', ...options }); } } export class Counterparties extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Counterparties/$count', ...options }); } } export class DataBoxCredentials extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/DataBoxCredentials/$count', ...options }); } } export class DocumentTypes extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/DocumentTypes/$count', ...options }); } } export class Invitations extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Invitations/$count', ...options }); } } export class Invoices extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Invoices/$count', ...options }); } } export class InvoiceSettings extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/InvoiceSettings/$count', ...options }); } } export class Licenses extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Licenses/$count', ...options }); } } export class PersonalDocuments extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/PersonalDocuments/$count', ...options }); } } export class RecurringTasks extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/RecurringTasks/$count', ...options }); } } export class Tasks extends HeyApiClient { public count(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Tasks/$count', ...options }); } public key(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Tasks/{key}', ...options }); } } export class Odata extends HeyApiClient { public accountingCompanies(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/AccountingCompanies', ...options }); } public accountingCompanyMemberships(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/AccountingCompanyMemberships', ...options }); } public bankAccounts(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BankAccounts', ...options }); } public businessAccountantAssignments(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessAccountantAssignments', ...options }); } public businessDocumentActivities(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessDocumentActivities', ...options }); } public businessDocuments(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessDocuments', ...options }); } /** * @deprecated */ public businessDocumentsSummaries(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessDocumentsSummaries', ...options }); } public businesses(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Businesses', ...options }); } public businessesKey(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Businesses({key})', ...options }); } public businessSummaries(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/BusinessSummaries', ...options }); } public counterparties(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Counterparties', ...options }); } public dataBoxCredentials(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/DataBoxCredentials', ...options }); } public documentTypes(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/DocumentTypes', ...options }); } public invitations(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Invitations', ...options }); } public invoices(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Invoices', ...options }); } public invoiceSettings(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/InvoiceSettings', ...options }); } public licenses(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Licenses', ...options }); } public personalDocuments(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/PersonalDocuments', ...options }); } public recurringTasks(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/RecurringTasks', ...options }); } public tasks(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Tasks', ...options }); } public tasksKey(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/odata/Tasks({key})', ...options }); } private _accountingCompanies?: AccountingCompanies; get accountingCompanies2(): AccountingCompanies { return this._accountingCompanies ??= new AccountingCompanies({ client: this.client }); } private _accountingCompanyMemberships?: AccountingCompanyMemberships; get accountingCompanyMemberships2(): AccountingCompanyMemberships { return this._accountingCompanyMemberships ??= new AccountingCompanyMemberships({ client: this.client }); } private _bankAccounts?: BankAccounts; get bankAccounts2(): BankAccounts { return this._bankAccounts ??= new BankAccounts({ client: this.client }); } private _businessAccountantAssignments?: BusinessAccountantAssignments; get businessAccountantAssignments2(): BusinessAccountantAssignments { return this._businessAccountantAssignments ??= new BusinessAccountantAssignments({ client: this.client }); } private _businessDocumentActivities?: BusinessDocumentActivities; get businessDocumentActivities2(): BusinessDocumentActivities { return this._businessDocumentActivities ??= new BusinessDocumentActivities({ client: this.client }); } private _businessDocuments?: BusinessDocuments; get businessDocuments2(): BusinessDocuments { return this._businessDocuments ??= new BusinessDocuments({ client: this.client }); } private _businessDocumentsSummaries?: BusinessDocumentsSummaries; get businessDocumentsSummaries2(): BusinessDocumentsSummaries { return this._businessDocumentsSummaries ??= new BusinessDocumentsSummaries({ client: this.client }); } private _businesses?: Businesses; get businesses2(): Businesses { return this._businesses ??= new Businesses({ client: this.client }); } private _businessSummaries?: BusinessSummaries; get businessSummaries2(): BusinessSummaries { return this._businessSummaries ??= new BusinessSummaries({ client: this.client }); } private _counterparties?: Counterparties; get counterparties2(): Counterparties { return this._counterparties ??= new Counterparties({ client: this.client }); } private _dataBoxCredentials?: DataBoxCredentials; get dataBoxCredentials2(): DataBoxCredentials { return this._dataBoxCredentials ??= new DataBoxCredentials({ client: this.client }); } private _documentTypes?: DocumentTypes; get documentTypes2(): DocumentTypes { return this._documentTypes ??= new DocumentTypes({ client: this.client }); } private _invitations?: Invitations; get invitations2(): Invitations { return this._invitations ??= new Invitations({ client: this.client }); } private _invoices?: Invoices; get invoices2(): Invoices { return this._invoices ??= new Invoices({ client: this.client }); } private _invoiceSettings?: InvoiceSettings; get invoiceSettings2(): InvoiceSettings { return this._invoiceSettings ??= new InvoiceSettings({ client: this.client }); } private _licenses?: Licenses; get licenses2(): Licenses { return this._licenses ??= new Licenses({ client: this.client }); } private _personalDocuments?: PersonalDocuments; get personalDocuments2(): PersonalDocuments { return this._personalDocuments ??= new PersonalDocuments({ client: this.client }); } private _recurringTasks?: RecurringTasks; get recurringTasks2(): RecurringTasks { return this._recurringTasks ??= new RecurringTasks({ client: this.client }); } private _tasks?: Tasks; get tasks2(): Tasks { return this._tasks ??= new Tasks({ client: this.client }); } } export class VVersionApiVersion extends HeyApiClient { private _odata?: Odata; get odata(): Odata { return this._odata ??= new Odata({ client: this.client }); } } export class Api extends HeyApiClient { private _vVersionApiVersion?: VVersionApiVersion; get vVersionApiVersion(): VVersionApiVersion { return this._vVersionApiVersion ??= new VVersionApiVersion({ client: this.client }); } } export class User extends HeyApiClient { public confirmEmail(options: Options) { return (options.client ?? this.client).get({ url: '/api/v1/user/confirmEmail', ...options }); } } export class VVersionApiVersion2 extends HeyApiClient { private _user?: User; get user(): User { return this._user ??= new User({ client: this.client }); } } export class Api2 extends HeyApiClient { private _vVersionApiVersion?: VVersionApiVersion2; get vVersionApiVersion(): VVersionApiVersion2 { return this._vVersionApiVersion ??= new VVersionApiVersion2({ client: this.client }); } } export class MapIdentityApi extends HeyApiClient { private _api?: Api2; get api(): Api2 { return this._api ??= new Api2({ client: this.client }); } } export class Sdk extends HeyApiClient { public static readonly __registry = new HeyApiRegistry(); constructor(args?: { client?: Client; key?: string; }) { super(args); Sdk.__registry.set(this, args?.key); } public postApiV1AccountingCompanies(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/accounting-companies', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1AccountingCompaniesById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/accounting-companies/{id}', ...options }); } public postApiV1AccountingCompaniesById(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/accounting-companies/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public putApiV1AccountingCompanyMemberships(options?: Options) { return (options?.client ?? this.client).put({ url: '/api/v1/accounting-company-memberships', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1AccountingCompanyMembershipsById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/accounting-company-memberships/{id}', ...options }); } public putApiV1BankAccounts(options?: Options) { return (options?.client ?? this.client).put({ url: '/api/v1/bank-accounts', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1BankAccountsById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/bank-accounts/{id}', ...options }); } public putApiV1BusinessAccountantAssignments(options?: Options) { return (options?.client ?? this.client).put({ url: '/api/v1/business-accountant-assignments', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1BusinessAccountantAssignmentsById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/business-accountant-assignments/{id}', ...options }); } public getApiV1BusinessDocumentsByIdRaw(options: Options) { return (options.client ?? this.client).get({ url: '/api/v1/business-documents/{id}/raw', ...options }); } public postApiV1BusinessDocuments(options?: Options) { return (options?.client ?? this.client).post({ ...formDataBodySerializer, url: '/api/v1/business-documents', ...options, headers: { 'Content-Type': null, ...options?.headers } }); } public deleteApiV1BusinessDocumentsById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/business-documents/{id}', ...options }); } public putApiV1BusinessDocumentsById(options: Options) { return (options.client ?? this.client).put({ url: '/api/v1/business-documents/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public postApiV1BusinessDocumentsByIdApprove(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/business-documents/{id}/approve', ...options }); } public postApiV1BusinessDocumentsByIdUnapprove(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/business-documents/{id}/unapprove', ...options }); } public postApiV1BusinessDocumentsByIdMoveToPersonal(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/business-documents/{id}/move-to-personal', ...options }); } public postApiV1BusinessDocumentsByIdMoveToBusiness(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/business-documents/{id}/move-to-business', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public getApiV1BusinessesByIdDocumentTypesSummary(options: Options) { return (options.client ?? this.client).get({ url: '/api/v1/businesses/{id}/document-types-summary', ...options }); } public postApiV1Businesses(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/businesses', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1BusinessesById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/businesses/{id}', ...options }); } public putApiV1BusinessesById(options: Options) { return (options.client ?? this.client).put({ url: '/api/v1/businesses/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public putApiV1BusinessesByIdContact(options: Options) { return (options.client ?? this.client).put({ url: '/api/v1/businesses/{id}/contact', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public postApiV1BusinessesByIdDisconnect(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/businesses/{id}/disconnect', ...options }); } public putApiV1BusinessMemberships(options?: Options) { return (options?.client ?? this.client).put({ url: '/api/v1/business-memberships', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public postApiV1Counterparties(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/counterparties', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1CounterpartiesById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/counterparties/{id}', ...options }); } public patchApiV1CounterpartiesById(options: Options) { return (options.client ?? this.client).patch({ url: '/api/v1/counterparties/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public putApiV1DataBoxCredentials(options?: Options) { return (options?.client ?? this.client).put({ url: '/api/v1/data-box-credentials', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1DataBoxCredentialsById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/data-box-credentials/{id}', ...options }); } public getApiDev(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev', ...options }); } public getApiDevReseedDb(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/reseed-db', ...options }); } public getApiDevDbReset(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/db-reset', ...options }); } public getApiDevDbReset2(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/db/reset', ...options }); } public getApiDevDbCreate(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/db/create', ...options }); } public getApiDevDbTouch(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/db/touch', ...options }); } public getApiDevSeed(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/seed', ...options }); } public getApiDevSeedAll(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/seed-all', ...options }); } public getApiDevSeedProd(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/seed-prod', ...options }); } public getApiDevJobProcessRecurringTasks(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/job/process-recurring-tasks', ...options }); } public getApiDevNotificationsSendTest(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/notifications/send-test', ...options }); } public getApiDevConfirmEmail(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/confirm-email', ...options }); } public getApiDevEmailSendTest(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/dev/email/send-test', ...options }); } public deleteApiV1NotificationsDeviceTokens(options?: Options) { return (options?.client ?? this.client).delete({ url: '/api/v1/notifications/device-tokens', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public putApiV1NotificationsDeviceTokens(options?: Options) { return (options?.client ?? this.client).put({ url: '/api/v1/notifications/device-tokens', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public postApiV1Feedback(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/feedback', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public postApiV1Invitations(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/invitations', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public postApiV1InvitationsByIdAccept(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/invitations/{id}/accept', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public postApiV1InvitationsByIdReject(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/invitations/{id}/reject', ...options }); } public deleteApiV1InvitationsById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/invitations/{id}', ...options }); } public patchApiV1InvitationsById(options: Options) { return (options.client ?? this.client).patch({ url: '/api/v1/invitations/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public postApiV1Invoices(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/invoices', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1InvoicesById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/invoices/{id}', ...options }); } public patchApiV1InvoicesById(options: Options) { return (options.client ?? this.client).patch({ url: '/api/v1/invoices/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public getApiV1InvoicesByIdPreview(options: Options) { return (options.client ?? this.client).get({ url: '/api/v1/invoices/{id}/preview', ...options }); } public postApiV1InvoicesByIdSend(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/invoices/{id}/send', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public postApiV1InvoicesByIdSnapshot(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/invoices/{id}/snapshot', ...options }); } public putApiV1InvoiceSettings(options?: Options) { return (options?.client ?? this.client).put({ url: '/api/v1/invoice-settings', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public postApiV1NotificationsTest(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/notifications/test', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public getApiV1PersonalDocumentsByIdRaw(options: Options) { return (options.client ?? this.client).get({ url: '/api/v1/personal-documents/{id}/raw', ...options }); } public postApiV1PersonalDocuments(options?: Options) { return (options?.client ?? this.client).post({ ...formDataBodySerializer, url: '/api/v1/personal-documents', ...options, headers: { 'Content-Type': null, ...options?.headers } }); } public postApiV1PersonalDocumentsByIdMoveToBusiness(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/personal-documents/{id}/move-to-business', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public deleteApiV1PersonalDocumentsById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/personal-documents/{id}', ...options }); } public getApiV1PersonalDocumentsSummary(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/personal-documents/summary', ...options }); } public postApiV1RecurringTasks(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/recurring-tasks', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public deleteApiV1RecurringTasksById(options: Options) { return (options.client ?? this.client).delete({ url: '/api/v1/recurring-tasks/{id}', ...options }); } public patchApiV1RecurringTasksById(options: Options) { return (options.client ?? this.client).patch({ url: '/api/v1/recurring-tasks/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public get(options?: Options) { return (options?.client ?? this.client).get({ url: '/', ...options }); } public postApiV1Tasks(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/tasks', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } public putApiV1TasksById(options: Options) { return (options.client ?? this.client).put({ url: '/api/v1/tasks/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public postApiV1TasksByIdSubmit(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/tasks/{id}/submit', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public postApiV1TasksByIdApprove(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/tasks/{id}/approve', ...options }); } public postApiV1TasksByIdReject(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/tasks/{id}/reject', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } public getApiV1TasksByIdComments(options: Options) { return (options.client ?? this.client).get({ url: '/api/v1/tasks/{id}/comments', ...options }); } public getApiV1TasksByIdDocuments(options: Options) { return (options.client ?? this.client).get({ url: '/api/v1/tasks/{id}/documents', ...options }); } public postApiV1UserRegister(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/register', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public postApiV1UserLogin(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/login', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public postApiV1UserRefresh(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/refresh', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public postApiV1UserResendConfirmationEmail(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/resendConfirmationEmail', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public postApiV1UserForgotPassword(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/forgotPassword', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public postApiV1UserResetPassword(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/resetPassword', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public postApiV1UserManage2Fa(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/manage/2fa', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public getApiV1UserManageInfo(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/user/manage/info', ...options }); } public postApiV1UserManageInfo(options: Options) { return (options.client ?? this.client).post({ url: '/api/v1/user/manage/info', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); } public postApiV1UserLogout(options?: Options) { return (options?.client ?? this.client).post({ url: '/api/v1/user/logout', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options?.headers } }); } /** * @deprecated */ public getApiV1UserDocumentsSummary(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/user/documents-summary', ...options }); } public deleteApiV1User(options?: Options) { return (options?.client ?? this.client).delete({ url: '/api/v1/user', ...options }); } public getApiV1UsersMe(options?: Options) { return (options?.client ?? this.client).get({ url: '/api/v1/users/me', ...options }); } public patchApiV1UsersById(options: Options) { return (options.client ?? this.client).patch({ url: '/api/v1/users/{id}', ...options, headers: { 'Content-Type': 'application/json;odata.metadata=minimal;odata.streaming=true', ...options.headers } }); } private _api?: Api; get api(): Api { return this._api ??= new Api({ client: this.client }); } private _mapIdentityApi?: MapIdentityApi; get mapIdentityApi(): MapIdentityApi { return this._mapIdentityApi ??= new MapIdentityApi({ client: this.client }); } } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/method-class-conflict/instance/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type AccessTokenResponse = { readonly tokenType?: string; accessToken: string; expiresIn: number; refreshToken: string; }; export type AccountingCompany = { id: number; name: string; identificationNumber: string; /** * @deprecated */ countryCode?: string; country: Country; }; export type AccountingCompanyCreateDto = { name: string; identificationNumber: string; }; export type AccountingCompanyMembership = { id: number; accountingCompanyId: number; accountingCompanyName: string; userId: number; userFullName: string; roleName: string; }; export type AccountingCompanyMembershipUpsertDto = { accountingCompanyId: number; email: string; roleName: string; }; export type AccountingCompanyUpdateDto = { name: string; identificationNumber: string; }; export type AddressDto = { street: string; city: string; postalCode: string; country: string; }; export type AnnualInvoicesCount = 'Tens' | 'Hundred' | 'Thousands' | 'TenThousands' | 'HundredThousands'; export type BankAccount = { id: number; businessId: number; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; createdAt: string; updatedAt?: string | null; }; export type BankAccountUpsertDto = { businessId: number; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; }; export type Business = { id: number; name: string; identificationNumber: string; vatNumber: string | null; country: Country; /** * @deprecated */ countryCode?: string; deletedAt: string | null; fullAddress: string | null; accountingCompany: BusinessAccountingCompany; contactPerson: BusinessContactPerson; }; export type BusinessAccountantAssignment = { id: number; businessId: number; businessName: string; accountantId: number; accountantName: string; }; export type BusinessAccountantAssignmentUpsert = { businessId: number; accountantId: number; }; export type BusinessAccountingCompany = { id: number; name: string; }; export type BusinessAresAddress = { street: string; houseNumber: number; guidanceNumber?: number | null; city: string; postalCode: number; }; export type BusinessChangeContactDto = { userId: number | null; }; export type BusinessContactPerson = { id: number; fullName: string; email: string | null; phoneNumber: string | null; }; export type BusinessCreateDto = { name: string; identificationNumber: string; vatNumber?: string | null; address?: BusinessAresAddress; }; export type BusinessDocumentMoveToBusinessDocumentsDto = { businessId: number; documentTypeId?: number | null; }; export type BusinessDocumentUpdateDto = { name: string | null; documentTypeId: number | null; }; export type BusinessDocumentsSummary = { id: number; name: string; documentsCount: number; documentsSize: number; lastUploadAt: string | null; maxStorageSize: number; }; export type BusinessMembershipDto = { id: number; userId: number; userFullName: string; businessId: number; businessName: string; roleId: number; roleName: string; }; export type BusinessMembershipUpsertDto = { businessId: number; email: string; roleName: string; }; export type BusinessSummary = { id: number; name: string; documentsCount: number; documentsSize: number; lastUploadAt: string | null; /** * @deprecated */ maxStorageSize?: number; pendingTasksCount: number; pendingDocumentsCount: number; }; export type BusinessUpdateDto = { name: string; identificationNumber: string; vatNumber?: string | null; address?: BusinessAresAddress; }; export type Counterparty = { id: number; businessId: number; name: string; identificationNumber: string | null; vatNumber: string | null; address: AddressDto; email: string | null; privateNote: string | null; isFavourite: boolean | null; createdAt: string; updatedAt?: string | null; }; export type CounterpartyCreateDto = { businessId: number; identificationNumber: string; name: string; vatNumber: string | null; address: AddressDto; email: string | null; privateNote?: string | null; isFavourite?: boolean | null; }; export type CounterpartyUpdateDto = { identificationNumber?: string | null; name?: string | null; vatNumber?: string | null; address?: AddressDto; email?: string | null; privateNote?: string | null; isFavourite?: boolean | null; }; export type Country = 'Czechia' | 'Slovakia'; export type CreateInvoiceClientDto = { counterpartyId: number; }; export type Currency = 'CZK' | 'EUR' | 'USD' | 'GBP'; export type DataBoxCredentials = { id?: number; username: string; password: string | null; businessId: number; businessName: string; userId: number; }; export type DataBoxCredentialsUpsertDto = { businessId: number; username: string | null; password: string | null; }; export type DocumentAction = 'Uploaded'; export type DocumentBusiness = { id: number; /** * @deprecated */ name?: string; documentName: string; originalFileName: string; extension: string | null; size: number; businessId: number | null; businessName: string | null; documentTypeId: number; documentTypeName: string; approvedAt: string | null; approverId: number | null; approverFullName: string | null; taskId: number | null; uploadedAt: string; uploaderId: number | null; deletedAt?: string | null; }; export type DocumentBusinessActivity = { documentId: number; documentName: string; businessId: number; businessName: string; action: DocumentAction; happenedAt: string; performedByUserId: number | null; performedByUserFullName: string | null; }; export type DocumentPersonal = { id: number; name: string; extension: string | null; size: number; userId: number; userFullName: string; uploadedAt?: string; deletedAt?: string | null; }; export type DocumentPersonalMoveToBusinessDocumentsDto = { businessId: number; documentTypeId?: number; }; export type DocumentType = { id: number; name: string; }; export type DocumentTypesSummary = { documentTypeId: number; documentTypeName: string; documentsCount: number; }; export type FeedbackType = 'Feedback' | 'Bug'; export type ForgotPasswordRequest = { email: string; }; export type HttpValidationProblemDetails = { type?: string | null; title?: string | null; status?: number | null; detail?: string | null; instance?: string | null; errors?: { [key: string]: Array; }; [key: string]: unknown; }; export type InfoRequest = { newEmail?: string | null; newPassword?: string | null; oldPassword?: string | null; }; export type InfoResponse = { email: string; isEmailConfirmed: boolean; }; export type Invitation = { id: number; accountingCompanyName: string; status: InvitationStatus; expiresAt: string; email: string; }; export type InvitationAcceptDto = { businessId: number; }; export type InvitationCreateDto = { accountingCompanyId: number; email: string; }; export type InvitationStatus = 'Pending' | 'Expired' | 'Rejected'; export type InvitationUpdateDto = { email?: string | null; }; export type Invoice = { id: number; businessId: number; supplier: InvoiceSupplier; client: InvoiceClient; bankAccount: InvoiceBankAccount; hideBankAccount: boolean; type: InvoiceType; number: string; status: InvoiceStatus; paymentMethod: PaymentMethod; currency: Currency; reversedVatCharge: boolean; variableSymbol: string | null; constantSymbol: string | null; issuedAt: string; dueAt: string; taxPointAt: string | null; sentAt: string | null; snapshotAt: string | null; noteBeforeLines: string | null; lines: Array; footerNote: string | null; totalPriceExcludingVat: number; totalVatAmount: number; totalPriceIncludingVat: number; createdAt: string; updatedAt: string | null; }; export type InvoiceBankAccount = { swift: string; iban: string; accountNumber: string; bankCode: string; currency: Currency; }; export type InvoiceBankAccountUpdateDto = { swift: string; iban: string; accountNumber: string; bankCode: string; currency: Currency; }; export type InvoiceClient = { /** * @deprecated */ id?: number | null; counterpartyId: number | null; name: string; registrationNumber: string | null; identificationNumber: string | null; vatNumber: string | null; email: string | null; address: InvoiceClientAddress; deliveryName: string | null; deliveryAddress: InvoiceClientDeliveryAddress; }; export type InvoiceClientAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceClientDeliveryAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceCreateDto = { client: CreateInvoiceClientDto; type: InvoiceType; number: string; status: InvoiceStatus; paymentMethod: PaymentMethod; hideBankAccount: boolean; reversedVatCharge: boolean; variableSymbol?: string | null; constantSymbol?: string | null; issuedAt: string; dueAt: string; taxPointAt: string; noteBeforeLines?: string | null; lines: Array; footerNote?: string | null; businessId: number; }; export type InvoiceLine = { id?: number; description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; totalPriceExcludingVat: number; vatAmount: number; totalPriceIncludingVat: number; }; export type InvoiceLineCreateDto = { description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; }; export type InvoiceLineUpdateDto = { id: number | null; description: string; quantity: number; unit: string; unitPrice: number; vatRate: number; }; export type InvoiceSendDto = { customRecipientEmail: string | null; message: string; }; export type InvoiceSetting = { businessId: number; isVatPayer: boolean; template: InvoiceTemplate; bankAccount?: InvoiceSettingsBankAccount; numberingSetting: NumberingSetting; createdAt: string; updatedAt?: string | null; }; export type InvoiceSettingUpsertDto = { businessId: number; isVatPayer: boolean; template: InvoiceTemplateUpsertDto; bankAccount?: InvoiceSettingsBankAccountUpsertDto; numberingSetting: NumberingSettingUpsertDto; }; export type InvoiceSettingsBankAccount = { id: number; businessId: number; /** * @deprecated */ number: string; accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; createdAt: string; updatedAt?: string | null; }; export type InvoiceSettingsBankAccountUpsertDto = { accountNumber: string; bankCode: string; swift: string; iban: string; currency: Currency; }; export type InvoiceStatus = 'Draft' | 'Issued' | 'Paid' | 'Overdue' | 'Cancelled' | 'Snapshot'; export type InvoiceSupplier = { name: string; registrationNumber: string; identificationNumber: string; vatNumber: string | null; address: InvoiceSupplierAddress; }; export type InvoiceSupplierAddress = { street: string; city: string; postalCode: string; country: string; }; export type InvoiceTemplate = { currency: Currency; textBeforeLines: string | null; footerText: string | null; }; export type InvoiceTemplateUpsertDto = { currency: Currency; textBeforeLines: string | null; footerText: string | null; }; export type InvoiceType = 'Regular' | 'Corrective' | 'Advance'; export type InvoiceUpdateClientDto = { counterpartyId: number | null; name: string | null; registrationNumber: string | null; vatNumber: string | null; email: string | null; address: AddressDto; deliveryName: string | null; deliveryAddress: AddressDto; }; export type InvoiceUpdateDto = { client: InvoiceUpdateClientDto; bankAccount: InvoiceBankAccountUpdateDto; hideBankAccount: boolean | null; type: InvoiceType; number: string | null; status: InvoiceStatus; paymentMethod: PaymentMethod; currency: Currency; reversedVatCharge: boolean | null; variableSymbol: string | null; constantSymbol: string | null; issuedAt: string | null; dueAt: string | null; taxPointAt: string | null; noteBeforeLines: string | null; lines: Array | null; footerNote: string | null; }; export type LicenseDto = { id: number; tierId: number; tierName: string; businessId: number | null; /** * @deprecated */ maxStorageSize?: number; maxBusinessStorageSize: number; maxBusinessMembersCount: number; maxContactsCount: number; }; export type LoginRequest = { email: string; password: string; twoFactorCode?: string | null; twoFactorRecoveryCode?: string | null; }; export type NotificationsDeviceTokenDeleteDto = { token: string; }; export type NotificationsDeviceTokenUpsertDto = { provider: PushNotificationsProvider; token: string; }; export type NotificationsTestSendDto = { token: string | null; }; export type NumberingSetting = { id: number; businessId: number; yearFormat: YearFormat; isMonthIncluded: boolean; useHyphen: boolean; prefix?: string | null; suffix?: string | null; sequencePosition: SequencePosition; annualInvoicesCount: AnnualInvoicesCount; format: string; lastExternalInvoiceSequenceNumber: number | null; createdAt: string; updatedAt?: string | null; }; export type NumberingSettingUpsertDto = { yearFormat: YearFormat; isMonthIncluded: boolean; useHyphen: boolean; prefix: string | null; suffix: string | null; sequencePosition: SequencePosition; annualInvoicesCount: AnnualInvoicesCount; lastExternalInvoiceSequenceNumber?: number | null; }; export type PaymentMethod = 'Cash' | 'BankTransfer'; export type PersonalDocumentsSummary = { documentsCount: number; documentsSize: number; maxStorageSize: number; }; export type PushNotificationsProvider = 1 | 2; export type RecurrenceType = 'Daily' | 'Weekly' | 'Monthly' | 'Yearly'; export type RecurringTask = { id: number; title: string; details: string; accountingCompanyId: number; accountingCompanyName: string; accountantId: number | null; accountantFullName: string | null; recurrenceType?: RecurrenceType; period: RecurrenceType; interval: number; executeAt: string; isActive: boolean; businesses: Array; documentTypeId: number; documentTypeName: string; }; export type RecurringTaskBusiness = { id: number; name: string; }; export type RecurringTaskCreateDto = { title: string; details: string; recurrenceType: RecurrenceType; interval?: number; firstTaskDueAt: string; accountingCompanyId: number; businessIds: Array; documentTypeId: number; }; export type RecurringTaskUpdateDto = { title?: string | null; details?: string | null; isActive?: boolean | null; recurrenceType?: RecurrenceType; interval?: number | null; nextTasksCreateAt?: string | null; documentTypeId?: number | null; }; export type RefreshRequest = { refreshToken: string; }; export type RegisterRequest = { email: string; password: string; }; export type ResendConfirmationEmailRequest = { email: string; }; export type ResetPasswordRequest = { email: string; resetCode: string; newPassword: string; }; export type SendFeedbackRequest = { type: FeedbackType; subject: string; message: string; platform: string; deviceInfo?: string | null; appVersion?: string | null; traceId?: string | null; }; export type SequencePosition = 'Start' | 'End'; export type Task = { id: number; title: string; details: string; dueAt: string; status: TaskStatus; businessId: number; businessName: string; documentTypeId: number; documentTypeName: string; }; export type TaskComment = { id: number; taskId: number | null; content: string; authorId: number | null; authorFullName: string | null; createdAt: string; }; export type TaskRejectDto = { reason: string; }; export type TaskStatus = 'PendingClient' | 'PendingAccountant' | 'Completed' | 'Canceled'; export type TaskSubmitDto = { answer: string | null; }; export type TaskUpdateDto = { title: string; details: string; dueAt: string; documentTypeId?: number | null; }; export type TasksCreateDto = { businessIds: Array; documentTypeId?: number; title: string; details: string; dueAt: string; }; export type TwoFactorRequest = { enable?: boolean | null; twoFactorCode?: string | null; resetSharedKey?: boolean; resetRecoveryCodes?: boolean; forgetMachine?: boolean; }; export type TwoFactorResponse = { sharedKey: string; recoveryCodesLeft: number; recoveryCodes?: Array | null; isTwoFactorEnabled: boolean; isMachineRemembered: boolean; }; export type User = { id: number; email: string | null; emailConfirmed: boolean; fullName: string; phoneNumber: string | null; isAccountant: boolean; }; export type UserUpdateDto = { firstName?: string | null; lastName?: string | null; phoneNumber?: string | null; }; export type YearFormat = 'Full' | 'Short'; export type AccessTokenResponseWritable = { accessToken: string; expiresIn: number; refreshToken: string; }; export type PostApiV1AccountingCompaniesData = { body?: AccountingCompanyCreateDto; path?: never; query?: never; url: '/api/v1/accounting-companies'; }; export type PostApiV1AccountingCompaniesResponses = { /** * OK */ 200: AccountingCompany; }; export type PostApiV1AccountingCompaniesResponse = PostApiV1AccountingCompaniesResponses[keyof PostApiV1AccountingCompaniesResponses]; export type DeleteApiV1AccountingCompaniesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/accounting-companies/{id}'; }; export type DeleteApiV1AccountingCompaniesByIdResponses = { /** * OK */ 200: unknown; }; export type PostApiV1AccountingCompaniesByIdData = { body?: AccountingCompanyUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/accounting-companies/{id}'; }; export type PostApiV1AccountingCompaniesByIdResponses = { /** * OK */ 200: AccountingCompany; }; export type PostApiV1AccountingCompaniesByIdResponse = PostApiV1AccountingCompaniesByIdResponses[keyof PostApiV1AccountingCompaniesByIdResponses]; export type ApiVVersionApiVersionOdataAccountingCompaniesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanies'; }; export type ApiVVersionApiVersionOdataAccountingCompaniesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompaniesResponse = ApiVVersionApiVersionOdataAccountingCompaniesResponses[keyof ApiVVersionApiVersionOdataAccountingCompaniesResponses]; export type ApiVVersionApiVersionOdataAccountingCompaniesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanies/$count'; }; export type ApiVVersionApiVersionOdataAccountingCompaniesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompaniesCountResponse = ApiVVersionApiVersionOdataAccountingCompaniesCountResponses[keyof ApiVVersionApiVersionOdataAccountingCompaniesCountResponses]; export type PutApiV1AccountingCompanyMembershipsData = { body?: AccountingCompanyMembershipUpsertDto; path?: never; query?: never; url: '/api/v1/accounting-company-memberships'; }; export type PutApiV1AccountingCompanyMembershipsResponses = { /** * OK */ 200: AccountingCompanyMembership; }; export type PutApiV1AccountingCompanyMembershipsResponse = PutApiV1AccountingCompanyMembershipsResponses[keyof PutApiV1AccountingCompanyMembershipsResponses]; export type DeleteApiV1AccountingCompanyMembershipsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/accounting-company-memberships/{id}'; }; export type DeleteApiV1AccountingCompanyMembershipsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanyMemberships'; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponse = ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses[keyof ApiVVersionApiVersionOdataAccountingCompanyMembershipsResponses]; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/AccountingCompanyMemberships/$count'; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponse = ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses[keyof ApiVVersionApiVersionOdataAccountingCompanyMembershipsCountResponses]; export type PutApiV1BankAccountsData = { body?: BankAccountUpsertDto; path?: never; query?: never; url: '/api/v1/bank-accounts'; }; export type PutApiV1BankAccountsResponses = { /** * OK */ 200: BankAccount; }; export type PutApiV1BankAccountsResponse = PutApiV1BankAccountsResponses[keyof PutApiV1BankAccountsResponses]; export type DeleteApiV1BankAccountsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/bank-accounts/{id}'; }; export type DeleteApiV1BankAccountsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataBankAccountsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BankAccounts'; }; export type ApiVVersionApiVersionOdataBankAccountsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBankAccountsResponse = ApiVVersionApiVersionOdataBankAccountsResponses[keyof ApiVVersionApiVersionOdataBankAccountsResponses]; export type ApiVVersionApiVersionOdataBankAccountsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BankAccounts/$count'; }; export type ApiVVersionApiVersionOdataBankAccountsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBankAccountsCountResponse = ApiVVersionApiVersionOdataBankAccountsCountResponses[keyof ApiVVersionApiVersionOdataBankAccountsCountResponses]; export type PutApiV1BusinessAccountantAssignmentsData = { body?: BusinessAccountantAssignmentUpsert; path?: never; query?: never; url: '/api/v1/business-accountant-assignments'; }; export type PutApiV1BusinessAccountantAssignmentsResponses = { /** * OK */ 200: BusinessAccountantAssignment; }; export type PutApiV1BusinessAccountantAssignmentsResponse = PutApiV1BusinessAccountantAssignmentsResponses[keyof PutApiV1BusinessAccountantAssignmentsResponses]; export type DeleteApiV1BusinessAccountantAssignmentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-accountant-assignments/{id}'; }; export type DeleteApiV1BusinessAccountantAssignmentsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessAccountantAssignments'; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponse = ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses[keyof ApiVVersionApiVersionOdataBusinessAccountantAssignmentsResponses]; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessAccountantAssignments/$count'; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponse = ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses[keyof ApiVVersionApiVersionOdataBusinessAccountantAssignmentsCountResponses]; export type GetApiV1BusinessDocumentsByIdRawData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/raw'; }; export type GetApiV1BusinessDocumentsByIdRawResponses = { /** * OK */ 200: unknown; /** * No Content */ 204: void; }; export type GetApiV1BusinessDocumentsByIdRawResponse = GetApiV1BusinessDocumentsByIdRawResponses[keyof GetApiV1BusinessDocumentsByIdRawResponses]; export type PostApiV1BusinessDocumentsData = { body?: { BusinessId: number; DocumentTypeId: number; File: Blob | File; DocumentName: string; TaskId: number; }; path?: never; query?: never; url: '/api/v1/business-documents'; }; export type PostApiV1BusinessDocumentsResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsResponse = PostApiV1BusinessDocumentsResponses[keyof PostApiV1BusinessDocumentsResponses]; export type DeleteApiV1BusinessDocumentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}'; }; export type DeleteApiV1BusinessDocumentsByIdResponses = { /** * OK */ 200: DocumentBusiness; }; export type DeleteApiV1BusinessDocumentsByIdResponse = DeleteApiV1BusinessDocumentsByIdResponses[keyof DeleteApiV1BusinessDocumentsByIdResponses]; export type PutApiV1BusinessDocumentsByIdData = { body?: BusinessDocumentUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}'; }; export type PutApiV1BusinessDocumentsByIdResponses = { /** * OK */ 200: DocumentBusiness; }; export type PutApiV1BusinessDocumentsByIdResponse = PutApiV1BusinessDocumentsByIdResponses[keyof PutApiV1BusinessDocumentsByIdResponses]; export type PostApiV1BusinessDocumentsByIdApproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/approve'; }; export type PostApiV1BusinessDocumentsByIdApproveResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdApproveResponse = PostApiV1BusinessDocumentsByIdApproveResponses[keyof PostApiV1BusinessDocumentsByIdApproveResponses]; export type PostApiV1BusinessDocumentsByIdUnapproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/unapprove'; }; export type PostApiV1BusinessDocumentsByIdUnapproveResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdUnapproveResponse = PostApiV1BusinessDocumentsByIdUnapproveResponses[keyof PostApiV1BusinessDocumentsByIdUnapproveResponses]; export type PostApiV1BusinessDocumentsByIdMoveToPersonalData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/move-to-personal'; }; export type PostApiV1BusinessDocumentsByIdMoveToPersonalResponses = { /** * OK */ 200: unknown; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessData = { body?: BusinessDocumentMoveToBusinessDocumentsDto; path: { id: number; }; query?: never; url: '/api/v1/business-documents/{id}/move-to-business'; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessResponses = { /** * OK */ 200: DocumentBusiness; }; export type PostApiV1BusinessDocumentsByIdMoveToBusinessResponse = PostApiV1BusinessDocumentsByIdMoveToBusinessResponses[keyof PostApiV1BusinessDocumentsByIdMoveToBusinessResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentActivities'; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponse = ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentActivitiesResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentActivities/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponse = ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentActivitiesCountResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocuments'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsResponse = ApiVVersionApiVersionOdataBusinessDocumentsResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocuments/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsCountResponse = ApiVVersionApiVersionOdataBusinessDocumentsCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsCountResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentsSummaries'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponse = ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsSummariesResponses]; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessDocumentsSummaries/$count'; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponse = ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses[keyof ApiVVersionApiVersionOdataBusinessDocumentsSummariesCountResponses]; export type GetApiV1BusinessesByIdDocumentTypesSummaryData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/document-types-summary'; }; export type GetApiV1BusinessesByIdDocumentTypesSummaryResponses = { /** * OK */ 200: Array; }; export type GetApiV1BusinessesByIdDocumentTypesSummaryResponse = GetApiV1BusinessesByIdDocumentTypesSummaryResponses[keyof GetApiV1BusinessesByIdDocumentTypesSummaryResponses]; export type PostApiV1BusinessesData = { body?: BusinessCreateDto; path?: never; query?: never; url: '/api/v1/businesses'; }; export type PostApiV1BusinessesResponses = { /** * OK */ 200: Business; }; export type PostApiV1BusinessesResponse = PostApiV1BusinessesResponses[keyof PostApiV1BusinessesResponses]; export type DeleteApiV1BusinessesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}'; }; export type DeleteApiV1BusinessesByIdResponses = { /** * OK */ 200: unknown; }; export type PutApiV1BusinessesByIdData = { body?: BusinessUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}'; }; export type PutApiV1BusinessesByIdResponses = { /** * OK */ 200: Business; }; export type PutApiV1BusinessesByIdResponse = PutApiV1BusinessesByIdResponses[keyof PutApiV1BusinessesByIdResponses]; export type PutApiV1BusinessesByIdContactData = { body?: BusinessChangeContactDto; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/contact'; }; export type PutApiV1BusinessesByIdContactResponses = { /** * OK */ 200: unknown; }; export type PostApiV1BusinessesByIdDisconnectData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/businesses/{id}/disconnect'; }; export type PostApiV1BusinessesByIdDisconnectResponses = { /** * OK */ 200: Business; }; export type PostApiV1BusinessesByIdDisconnectResponse = PostApiV1BusinessesByIdDisconnectResponses[keyof PostApiV1BusinessesByIdDisconnectResponses]; export type ApiVVersionApiVersionOdataBusinessesData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Businesses'; }; export type ApiVVersionApiVersionOdataBusinessesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessesResponse = ApiVVersionApiVersionOdataBusinessesResponses[keyof ApiVVersionApiVersionOdataBusinessesResponses]; export type ApiVVersionApiVersionOdataBusinessesCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Businesses/$count'; }; export type ApiVVersionApiVersionOdataBusinessesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessesCountResponse = ApiVVersionApiVersionOdataBusinessesCountResponses[keyof ApiVVersionApiVersionOdataBusinessesCountResponses]; export type ApiVVersionApiVersionOdataBusinessesKeyData = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Businesses({key})'; }; export type ApiVVersionApiVersionOdataBusinessesKeyResponses = { /** * OK */ 200: Business; }; export type ApiVVersionApiVersionOdataBusinessesKeyResponse = ApiVVersionApiVersionOdataBusinessesKeyResponses[keyof ApiVVersionApiVersionOdataBusinessesKeyResponses]; export type ApiVVersionApiVersionOdataBusinessesKey2Data = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Businesses/{key}'; }; export type ApiVVersionApiVersionOdataBusinessesKey2Responses = { /** * OK */ 200: Business; }; export type ApiVVersionApiVersionOdataBusinessesKey2Response = ApiVVersionApiVersionOdataBusinessesKey2Responses[keyof ApiVVersionApiVersionOdataBusinessesKey2Responses]; export type PutApiV1BusinessMembershipsData = { body?: BusinessMembershipUpsertDto; path?: never; query?: never; url: '/api/v1/business-memberships'; }; export type PutApiV1BusinessMembershipsResponses = { /** * OK */ 200: BusinessMembershipDto; }; export type PutApiV1BusinessMembershipsResponse = PutApiV1BusinessMembershipsResponses[keyof PutApiV1BusinessMembershipsResponses]; export type ApiVVersionApiVersionOdataBusinessSummariesData = { body?: never; path?: never; query?: { role?: string; accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessSummaries'; }; export type ApiVVersionApiVersionOdataBusinessSummariesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessSummariesResponse = ApiVVersionApiVersionOdataBusinessSummariesResponses[keyof ApiVVersionApiVersionOdataBusinessSummariesResponses]; export type ApiVVersionApiVersionOdataBusinessSummariesCountData = { body?: never; path?: never; query?: { role?: string; accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/BusinessSummaries/$count'; }; export type ApiVVersionApiVersionOdataBusinessSummariesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataBusinessSummariesCountResponse = ApiVVersionApiVersionOdataBusinessSummariesCountResponses[keyof ApiVVersionApiVersionOdataBusinessSummariesCountResponses]; export type PostApiV1CounterpartiesData = { body?: CounterpartyCreateDto; path?: never; query?: never; url: '/api/v1/counterparties'; }; export type PostApiV1CounterpartiesResponses = { /** * OK */ 200: Counterparty; }; export type PostApiV1CounterpartiesResponse = PostApiV1CounterpartiesResponses[keyof PostApiV1CounterpartiesResponses]; export type DeleteApiV1CounterpartiesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/counterparties/{id}'; }; export type DeleteApiV1CounterpartiesByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1CounterpartiesByIdData = { body?: CounterpartyUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/counterparties/{id}'; }; export type PatchApiV1CounterpartiesByIdResponses = { /** * OK */ 200: Counterparty; }; export type PatchApiV1CounterpartiesByIdResponse = PatchApiV1CounterpartiesByIdResponses[keyof PatchApiV1CounterpartiesByIdResponses]; export type ApiVVersionApiVersionOdataCounterpartiesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Counterparties'; }; export type ApiVVersionApiVersionOdataCounterpartiesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataCounterpartiesResponse = ApiVVersionApiVersionOdataCounterpartiesResponses[keyof ApiVVersionApiVersionOdataCounterpartiesResponses]; export type ApiVVersionApiVersionOdataCounterpartiesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Counterparties/$count'; }; export type ApiVVersionApiVersionOdataCounterpartiesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataCounterpartiesCountResponse = ApiVVersionApiVersionOdataCounterpartiesCountResponses[keyof ApiVVersionApiVersionOdataCounterpartiesCountResponses]; export type PutApiV1DataBoxCredentialsData = { body?: DataBoxCredentialsUpsertDto; path?: never; query?: never; url: '/api/v1/data-box-credentials'; }; export type PutApiV1DataBoxCredentialsResponses = { /** * OK */ 200: DataBoxCredentials; }; export type PutApiV1DataBoxCredentialsResponse = PutApiV1DataBoxCredentialsResponses[keyof PutApiV1DataBoxCredentialsResponses]; export type DeleteApiV1DataBoxCredentialsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/data-box-credentials/{id}'; }; export type DeleteApiV1DataBoxCredentialsByIdResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsData = { body?: never; path?: never; query?: { includePassword?: boolean; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DataBoxCredentials'; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsResponse = ApiVVersionApiVersionOdataDataBoxCredentialsResponses[keyof ApiVVersionApiVersionOdataDataBoxCredentialsResponses]; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountData = { body?: never; path?: never; query?: { includePassword?: boolean; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DataBoxCredentials/$count'; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDataBoxCredentialsCountResponse = ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses[keyof ApiVVersionApiVersionOdataDataBoxCredentialsCountResponses]; export type GetApiDevData = { body?: never; path?: never; query?: never; url: '/api/dev'; }; export type GetApiDevResponses = { /** * OK */ 200: unknown; }; export type GetApiDevReseedDbData = { body?: never; path?: never; query?: never; url: '/api/dev/reseed-db'; }; export type GetApiDevReseedDbResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbResetData = { body?: never; path?: never; query?: never; url: '/api/dev/db-reset'; }; export type GetApiDevDbResetResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbReset2Data = { body?: never; path?: never; query?: never; url: '/api/dev/db/reset'; }; export type GetApiDevDbReset2Responses = { /** * OK */ 200: unknown; }; export type GetApiDevDbCreateData = { body?: never; path?: never; query?: never; url: '/api/dev/db/create'; }; export type GetApiDevDbCreateResponses = { /** * OK */ 200: unknown; }; export type GetApiDevDbTouchData = { body?: never; path?: never; query?: never; url: '/api/dev/db/touch'; }; export type GetApiDevDbTouchResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedData = { body?: never; path?: never; query?: never; url: '/api/dev/seed'; }; export type GetApiDevSeedResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedAllData = { body?: never; path?: never; query?: never; url: '/api/dev/seed-all'; }; export type GetApiDevSeedAllResponses = { /** * OK */ 200: unknown; }; export type GetApiDevSeedProdData = { body?: never; path?: never; query?: never; url: '/api/dev/seed-prod'; }; export type GetApiDevSeedProdResponses = { /** * OK */ 200: unknown; }; export type GetApiDevJobProcessRecurringTasksData = { body?: never; path?: never; query?: { refDay?: string; }; url: '/api/dev/job/process-recurring-tasks'; }; export type GetApiDevJobProcessRecurringTasksResponses = { /** * OK */ 200: unknown; }; export type GetApiDevNotificationsSendTestData = { body?: never; path?: never; query?: { userId?: number; }; url: '/api/dev/notifications/send-test'; }; export type GetApiDevNotificationsSendTestResponses = { /** * OK */ 200: unknown; }; export type GetApiDevConfirmEmailData = { body?: never; path?: never; query?: { email?: string; }; url: '/api/dev/confirm-email'; }; export type GetApiDevConfirmEmailResponses = { /** * OK */ 200: unknown; }; export type GetApiDevEmailSendTestData = { body?: never; path?: never; query?: { to?: string; subject?: string; message?: string; }; url: '/api/dev/email/send-test'; }; export type GetApiDevEmailSendTestResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1NotificationsDeviceTokensData = { body?: NotificationsDeviceTokenDeleteDto; path?: never; query?: never; url: '/api/v1/notifications/device-tokens'; }; export type DeleteApiV1NotificationsDeviceTokensResponses = { /** * OK */ 200: unknown; }; export type PutApiV1NotificationsDeviceTokensData = { body?: NotificationsDeviceTokenUpsertDto; path?: never; query?: never; url: '/api/v1/notifications/device-tokens'; }; export type PutApiV1NotificationsDeviceTokensResponses = { /** * OK */ 200: unknown; }; export type ApiVVersionApiVersionOdataDocumentTypesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DocumentTypes'; }; export type ApiVVersionApiVersionOdataDocumentTypesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDocumentTypesResponse = ApiVVersionApiVersionOdataDocumentTypesResponses[keyof ApiVVersionApiVersionOdataDocumentTypesResponses]; export type ApiVVersionApiVersionOdataDocumentTypesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/DocumentTypes/$count'; }; export type ApiVVersionApiVersionOdataDocumentTypesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataDocumentTypesCountResponse = ApiVVersionApiVersionOdataDocumentTypesCountResponses[keyof ApiVVersionApiVersionOdataDocumentTypesCountResponses]; export type PostApiV1FeedbackData = { body?: SendFeedbackRequest; path?: never; query?: never; url: '/api/v1/feedback'; }; export type PostApiV1FeedbackResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvitationsData = { body?: InvitationCreateDto; path?: never; query?: never; url: '/api/v1/invitations'; }; export type PostApiV1InvitationsResponses = { /** * OK */ 200: Invitation; }; export type PostApiV1InvitationsResponse = PostApiV1InvitationsResponses[keyof PostApiV1InvitationsResponses]; export type PostApiV1InvitationsByIdAcceptData = { body?: InvitationAcceptDto; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}/accept'; }; export type PostApiV1InvitationsByIdAcceptResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvitationsByIdRejectData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}/reject'; }; export type PostApiV1InvitationsByIdRejectResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1InvitationsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}'; }; export type DeleteApiV1InvitationsByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1InvitationsByIdData = { body?: InvitationUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/invitations/{id}'; }; export type PatchApiV1InvitationsByIdResponses = { /** * OK */ 200: Invitation; }; export type PatchApiV1InvitationsByIdResponse = PatchApiV1InvitationsByIdResponses[keyof PatchApiV1InvitationsByIdResponses]; export type ApiVVersionApiVersionOdataInvitationsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invitations'; }; export type ApiVVersionApiVersionOdataInvitationsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvitationsResponse = ApiVVersionApiVersionOdataInvitationsResponses[keyof ApiVVersionApiVersionOdataInvitationsResponses]; export type ApiVVersionApiVersionOdataInvitationsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invitations/$count'; }; export type ApiVVersionApiVersionOdataInvitationsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvitationsCountResponse = ApiVVersionApiVersionOdataInvitationsCountResponses[keyof ApiVVersionApiVersionOdataInvitationsCountResponses]; export type PostApiV1InvoicesData = { body?: InvoiceCreateDto; path?: never; query?: never; url: '/api/v1/invoices'; }; export type PostApiV1InvoicesResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesResponse = PostApiV1InvoicesResponses[keyof PostApiV1InvoicesResponses]; export type DeleteApiV1InvoicesByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}'; }; export type DeleteApiV1InvoicesByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1InvoicesByIdData = { body?: InvoiceUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}'; }; export type PatchApiV1InvoicesByIdResponses = { /** * OK */ 200: Invoice; }; export type PatchApiV1InvoicesByIdResponse = PatchApiV1InvoicesByIdResponses[keyof PatchApiV1InvoicesByIdResponses]; export type GetApiV1InvoicesByIdPreviewData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/preview'; }; export type GetApiV1InvoicesByIdPreviewResponses = { /** * OK */ 200: unknown; }; export type PostApiV1InvoicesByIdSendData = { body?: InvoiceSendDto; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/send'; }; export type PostApiV1InvoicesByIdSendResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesByIdSendResponse = PostApiV1InvoicesByIdSendResponses[keyof PostApiV1InvoicesByIdSendResponses]; export type PostApiV1InvoicesByIdSnapshotData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/invoices/{id}/snapshot'; }; export type PostApiV1InvoicesByIdSnapshotResponses = { /** * OK */ 200: Invoice; }; export type PostApiV1InvoicesByIdSnapshotResponse = PostApiV1InvoicesByIdSnapshotResponses[keyof PostApiV1InvoicesByIdSnapshotResponses]; export type ApiVVersionApiVersionOdataInvoicesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invoices'; }; export type ApiVVersionApiVersionOdataInvoicesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoicesResponse = ApiVVersionApiVersionOdataInvoicesResponses[keyof ApiVVersionApiVersionOdataInvoicesResponses]; export type ApiVVersionApiVersionOdataInvoicesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Invoices/$count'; }; export type ApiVVersionApiVersionOdataInvoicesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoicesCountResponse = ApiVVersionApiVersionOdataInvoicesCountResponses[keyof ApiVVersionApiVersionOdataInvoicesCountResponses]; export type PutApiV1InvoiceSettingsData = { body?: InvoiceSettingUpsertDto; path?: never; query?: never; url: '/api/v1/invoice-settings'; }; export type PutApiV1InvoiceSettingsResponses = { /** * OK */ 200: InvoiceSetting; }; export type PutApiV1InvoiceSettingsResponse = PutApiV1InvoiceSettingsResponses[keyof PutApiV1InvoiceSettingsResponses]; export type ApiVVersionApiVersionOdataInvoiceSettingsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/InvoiceSettings'; }; export type ApiVVersionApiVersionOdataInvoiceSettingsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoiceSettingsResponse = ApiVVersionApiVersionOdataInvoiceSettingsResponses[keyof ApiVVersionApiVersionOdataInvoiceSettingsResponses]; export type ApiVVersionApiVersionOdataInvoiceSettingsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/InvoiceSettings/$count'; }; export type ApiVVersionApiVersionOdataInvoiceSettingsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataInvoiceSettingsCountResponse = ApiVVersionApiVersionOdataInvoiceSettingsCountResponses[keyof ApiVVersionApiVersionOdataInvoiceSettingsCountResponses]; export type ApiVVersionApiVersionOdataLicensesData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Licenses'; }; export type ApiVVersionApiVersionOdataLicensesResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataLicensesResponse = ApiVVersionApiVersionOdataLicensesResponses[keyof ApiVVersionApiVersionOdataLicensesResponses]; export type ApiVVersionApiVersionOdataLicensesCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Licenses/$count'; }; export type ApiVVersionApiVersionOdataLicensesCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataLicensesCountResponse = ApiVVersionApiVersionOdataLicensesCountResponses[keyof ApiVVersionApiVersionOdataLicensesCountResponses]; export type PostApiV1NotificationsTestData = { body?: NotificationsTestSendDto; path?: never; query?: never; url: '/api/v1/notifications/test'; }; export type PostApiV1NotificationsTestResponses = { /** * OK */ 200: unknown; }; export type GetApiV1PersonalDocumentsByIdRawData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}/raw'; }; export type GetApiV1PersonalDocumentsByIdRawResponses = { /** * OK */ 200: unknown; /** * No Content */ 204: void; }; export type GetApiV1PersonalDocumentsByIdRawResponse = GetApiV1PersonalDocumentsByIdRawResponses[keyof GetApiV1PersonalDocumentsByIdRawResponses]; export type PostApiV1PersonalDocumentsData = { body?: { File: Blob | File; DocumentName: string; }; path?: never; query?: never; url: '/api/v1/personal-documents'; }; export type PostApiV1PersonalDocumentsResponses = { /** * OK */ 200: DocumentPersonal; }; export type PostApiV1PersonalDocumentsResponse = PostApiV1PersonalDocumentsResponses[keyof PostApiV1PersonalDocumentsResponses]; export type PostApiV1PersonalDocumentsByIdMoveToBusinessData = { body?: DocumentPersonalMoveToBusinessDocumentsDto; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}/move-to-business'; }; export type PostApiV1PersonalDocumentsByIdMoveToBusinessResponses = { /** * OK */ 200: unknown; }; export type DeleteApiV1PersonalDocumentsByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/personal-documents/{id}'; }; export type DeleteApiV1PersonalDocumentsByIdResponses = { /** * OK */ 200: DocumentPersonal; }; export type DeleteApiV1PersonalDocumentsByIdResponse = DeleteApiV1PersonalDocumentsByIdResponses[keyof DeleteApiV1PersonalDocumentsByIdResponses]; export type GetApiV1PersonalDocumentsSummaryData = { body?: never; path?: never; query?: never; url: '/api/v1/personal-documents/summary'; }; export type GetApiV1PersonalDocumentsSummaryResponses = { /** * OK */ 200: PersonalDocumentsSummary; }; export type GetApiV1PersonalDocumentsSummaryResponse = GetApiV1PersonalDocumentsSummaryResponses[keyof GetApiV1PersonalDocumentsSummaryResponses]; export type ApiVVersionApiVersionOdataPersonalDocumentsData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/PersonalDocuments'; }; export type ApiVVersionApiVersionOdataPersonalDocumentsResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataPersonalDocumentsResponse = ApiVVersionApiVersionOdataPersonalDocumentsResponses[keyof ApiVVersionApiVersionOdataPersonalDocumentsResponses]; export type ApiVVersionApiVersionOdataPersonalDocumentsCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/PersonalDocuments/$count'; }; export type ApiVVersionApiVersionOdataPersonalDocumentsCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataPersonalDocumentsCountResponse = ApiVVersionApiVersionOdataPersonalDocumentsCountResponses[keyof ApiVVersionApiVersionOdataPersonalDocumentsCountResponses]; export type PostApiV1RecurringTasksData = { body?: RecurringTaskCreateDto; path?: never; query?: never; url: '/api/v1/recurring-tasks'; }; export type PostApiV1RecurringTasksResponses = { /** * OK */ 200: RecurringTask; }; export type PostApiV1RecurringTasksResponse = PostApiV1RecurringTasksResponses[keyof PostApiV1RecurringTasksResponses]; export type DeleteApiV1RecurringTasksByIdData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/recurring-tasks/{id}'; }; export type DeleteApiV1RecurringTasksByIdResponses = { /** * OK */ 200: unknown; }; export type PatchApiV1RecurringTasksByIdData = { body?: RecurringTaskUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/recurring-tasks/{id}'; }; export type PatchApiV1RecurringTasksByIdResponses = { /** * OK */ 200: RecurringTask; }; export type PatchApiV1RecurringTasksByIdResponse = PatchApiV1RecurringTasksByIdResponses[keyof PatchApiV1RecurringTasksByIdResponses]; export type ApiVVersionApiVersionOdataRecurringTasksData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/RecurringTasks'; }; export type ApiVVersionApiVersionOdataRecurringTasksResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataRecurringTasksResponse = ApiVVersionApiVersionOdataRecurringTasksResponses[keyof ApiVVersionApiVersionOdataRecurringTasksResponses]; export type ApiVVersionApiVersionOdataRecurringTasksCountData = { body?: never; path?: never; query?: { /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/RecurringTasks/$count'; }; export type ApiVVersionApiVersionOdataRecurringTasksCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataRecurringTasksCountResponse = ApiVVersionApiVersionOdataRecurringTasksCountResponses[keyof ApiVVersionApiVersionOdataRecurringTasksCountResponses]; export type GetData = { body?: never; path?: never; query?: never; url: '/'; }; export type GetResponses = { /** * OK */ 200: unknown; }; export type PostApiV1TasksData = { body?: TasksCreateDto; path?: never; query?: never; url: '/api/v1/tasks'; }; export type PostApiV1TasksResponses = { /** * OK */ 200: Array; }; export type PostApiV1TasksResponse = PostApiV1TasksResponses[keyof PostApiV1TasksResponses]; export type PutApiV1TasksByIdData = { body?: TaskUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}'; }; export type PutApiV1TasksByIdResponses = { /** * OK */ 200: Task; }; export type PutApiV1TasksByIdResponse = PutApiV1TasksByIdResponses[keyof PutApiV1TasksByIdResponses]; export type PostApiV1TasksByIdSubmitData = { body?: TaskSubmitDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/submit'; }; export type PostApiV1TasksByIdSubmitResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdSubmitResponse = PostApiV1TasksByIdSubmitResponses[keyof PostApiV1TasksByIdSubmitResponses]; export type PostApiV1TasksByIdApproveData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/approve'; }; export type PostApiV1TasksByIdApproveResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdApproveResponse = PostApiV1TasksByIdApproveResponses[keyof PostApiV1TasksByIdApproveResponses]; export type PostApiV1TasksByIdRejectData = { body?: TaskRejectDto; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/reject'; }; export type PostApiV1TasksByIdRejectResponses = { /** * OK */ 200: Task; }; export type PostApiV1TasksByIdRejectResponse = PostApiV1TasksByIdRejectResponses[keyof PostApiV1TasksByIdRejectResponses]; export type GetApiV1TasksByIdCommentsData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/comments'; }; export type GetApiV1TasksByIdCommentsResponses = { /** * OK */ 200: Array; }; export type GetApiV1TasksByIdCommentsResponse = GetApiV1TasksByIdCommentsResponses[keyof GetApiV1TasksByIdCommentsResponses]; export type GetApiV1TasksByIdDocumentsData = { body?: never; path: { id: number; }; query?: never; url: '/api/v1/tasks/{id}/documents'; }; export type GetApiV1TasksByIdDocumentsResponses = { /** * OK */ 200: Array; }; export type GetApiV1TasksByIdDocumentsResponse = GetApiV1TasksByIdDocumentsResponses[keyof GetApiV1TasksByIdDocumentsResponses]; export type ApiVVersionApiVersionOdataTasksData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Tasks'; }; export type ApiVVersionApiVersionOdataTasksResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataTasksResponse = ApiVVersionApiVersionOdataTasksResponses[keyof ApiVVersionApiVersionOdataTasksResponses]; export type ApiVVersionApiVersionOdataTasksCountData = { body?: never; path?: never; query?: { accountants?: Array; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; /** * Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions. */ filter?: string; /** * Specifies the order in which items are returned. The maximum number of expressions is 5. */ orderby?: string; /** * Limits the number of items returned from a collection. The maximum value is 100. */ top?: number; /** * Excludes the specified number of items of the queried collection from the result. */ skip?: number; /** * Indicates whether the total count of items within a collection are returned in the result. */ count?: boolean; }; url: '/api/v1/odata/Tasks/$count'; }; export type ApiVVersionApiVersionOdataTasksCountResponses = { /** * OK */ 200: Array; }; export type ApiVVersionApiVersionOdataTasksCountResponse = ApiVVersionApiVersionOdataTasksCountResponses[keyof ApiVVersionApiVersionOdataTasksCountResponses]; export type ApiVVersionApiVersionOdataTasksKeyData = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Tasks({key})'; }; export type ApiVVersionApiVersionOdataTasksKeyResponses = { /** * OK */ 200: Task; }; export type ApiVVersionApiVersionOdataTasksKeyResponse = ApiVVersionApiVersionOdataTasksKeyResponses[keyof ApiVVersionApiVersionOdataTasksKeyResponses]; export type ApiVVersionApiVersionOdataTasksKey2Data = { body?: never; path?: never; query?: { key?: number; /** * Limits the properties returned in the result. */ select?: string; /** * Indicates the related entities to be represented inline. The maximum depth is 2. */ expand?: string; }; url: '/api/v1/odata/Tasks/{key}'; }; export type ApiVVersionApiVersionOdataTasksKey2Responses = { /** * OK */ 200: Task; }; export type ApiVVersionApiVersionOdataTasksKey2Response = ApiVVersionApiVersionOdataTasksKey2Responses[keyof ApiVVersionApiVersionOdataTasksKey2Responses]; export type PostApiV1UserRegisterData = { body: RegisterRequest; path?: never; query?: never; url: '/api/v1/user/register'; }; export type PostApiV1UserRegisterErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserRegisterError = PostApiV1UserRegisterErrors[keyof PostApiV1UserRegisterErrors]; export type PostApiV1UserRegisterResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserLoginData = { body: LoginRequest; path?: never; query?: { useCookies?: boolean; useSessionCookies?: boolean; }; url: '/api/v1/user/login'; }; export type PostApiV1UserLoginResponses = { /** * OK */ 200: AccessTokenResponse; }; export type PostApiV1UserLoginResponse = PostApiV1UserLoginResponses[keyof PostApiV1UserLoginResponses]; export type PostApiV1UserRefreshData = { body: RefreshRequest; path?: never; query?: never; url: '/api/v1/user/refresh'; }; export type PostApiV1UserRefreshResponses = { /** * OK */ 200: AccessTokenResponse; }; export type PostApiV1UserRefreshResponse = PostApiV1UserRefreshResponses[keyof PostApiV1UserRefreshResponses]; export type MapIdentityApiApiVVersionApiVersionUserConfirmEmailData = { body?: never; path?: never; query: { userId: string; code: string; changedEmail?: string; }; url: '/api/v1/user/confirmEmail'; }; export type MapIdentityApiApiVVersionApiVersionUserConfirmEmailResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserResendConfirmationEmailData = { body: ResendConfirmationEmailRequest; path?: never; query?: never; url: '/api/v1/user/resendConfirmationEmail'; }; export type PostApiV1UserResendConfirmationEmailResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserForgotPasswordData = { body: ForgotPasswordRequest; path?: never; query?: never; url: '/api/v1/user/forgotPassword'; }; export type PostApiV1UserForgotPasswordErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserForgotPasswordError = PostApiV1UserForgotPasswordErrors[keyof PostApiV1UserForgotPasswordErrors]; export type PostApiV1UserForgotPasswordResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserResetPasswordData = { body: ResetPasswordRequest; path?: never; query?: never; url: '/api/v1/user/resetPassword'; }; export type PostApiV1UserResetPasswordErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; }; export type PostApiV1UserResetPasswordError = PostApiV1UserResetPasswordErrors[keyof PostApiV1UserResetPasswordErrors]; export type PostApiV1UserResetPasswordResponses = { /** * OK */ 200: unknown; }; export type PostApiV1UserManage2FaData = { body: TwoFactorRequest; path?: never; query?: never; url: '/api/v1/user/manage/2fa'; }; export type PostApiV1UserManage2FaErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type PostApiV1UserManage2FaError = PostApiV1UserManage2FaErrors[keyof PostApiV1UserManage2FaErrors]; export type PostApiV1UserManage2FaResponses = { /** * OK */ 200: TwoFactorResponse; }; export type PostApiV1UserManage2FaResponse = PostApiV1UserManage2FaResponses[keyof PostApiV1UserManage2FaResponses]; export type GetApiV1UserManageInfoData = { body?: never; path?: never; query?: never; url: '/api/v1/user/manage/info'; }; export type GetApiV1UserManageInfoErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type GetApiV1UserManageInfoError = GetApiV1UserManageInfoErrors[keyof GetApiV1UserManageInfoErrors]; export type GetApiV1UserManageInfoResponses = { /** * OK */ 200: InfoResponse; }; export type GetApiV1UserManageInfoResponse = GetApiV1UserManageInfoResponses[keyof GetApiV1UserManageInfoResponses]; export type PostApiV1UserManageInfoData = { body: InfoRequest; path?: never; query?: never; url: '/api/v1/user/manage/info'; }; export type PostApiV1UserManageInfoErrors = { /** * Bad Request */ 400: HttpValidationProblemDetails; /** * Not Found */ 404: unknown; }; export type PostApiV1UserManageInfoError = PostApiV1UserManageInfoErrors[keyof PostApiV1UserManageInfoErrors]; export type PostApiV1UserManageInfoResponses = { /** * OK */ 200: InfoResponse; }; export type PostApiV1UserManageInfoResponse = PostApiV1UserManageInfoResponses[keyof PostApiV1UserManageInfoResponses]; export type PostApiV1UserLogoutData = { body?: unknown; path?: never; query?: never; url: '/api/v1/user/logout'; }; export type PostApiV1UserLogoutResponses = { /** * OK */ 200: unknown; }; export type GetApiV1UserDocumentsSummaryData = { body?: never; path?: never; query?: never; url: '/api/v1/user/documents-summary'; }; export type GetApiV1UserDocumentsSummaryResponses = { /** * OK */ 200: PersonalDocumentsSummary; }; export type GetApiV1UserDocumentsSummaryResponse = GetApiV1UserDocumentsSummaryResponses[keyof GetApiV1UserDocumentsSummaryResponses]; export type DeleteApiV1UserData = { body?: never; path?: never; query?: never; url: '/api/v1/user'; }; export type DeleteApiV1UserResponses = { /** * OK */ 200: unknown; }; export type GetApiV1UsersMeData = { body?: never; path?: never; query?: never; url: '/api/v1/users/me'; }; export type GetApiV1UsersMeResponses = { /** * OK */ 200: User; }; export type GetApiV1UsersMeResponse = GetApiV1UsersMeResponses[keyof GetApiV1UsersMeResponses]; export type PatchApiV1UsersByIdData = { body?: UserUpdateDto; path: { id: number; }; query?: never; url: '/api/v1/users/{id}'; }; export type PatchApiV1UsersByIdResponses = { /** * OK */ 200: User; }; export type PatchApiV1UsersByIdResponse = PatchApiV1UsersByIdResponses[keyof PatchApiV1UsersByIdResponses]; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export * from './sdk.gen'; export type * from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { buildClientParams, type Client, type Options as Options2, type TDataShape } from './client'; import { client } from './client.gen'; import type { AgentPartInput, AppAgentsResponses, AppLogErrors, AppLogResponses, Auth, AuthSetErrors, AuthSetResponses, CommandListResponses, Config, ConfigGetResponses, ConfigProvidersResponses, ConfigUpdateErrors, ConfigUpdateResponses, EventSubscribeResponses, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, FileListResponses, FilePartInput, FileReadResponses, FileStatusResponses, FindFilesResponses, FindSymbolsResponses, FindTextResponses, FormatterStatusResponses, GlobalDisposeResponses, GlobalEventResponses, GlobalHealthResponses, InstanceDisposeResponses, LspStatusResponses, McpAddErrors, McpAddResponses, McpAuthAuthenticateErrors, McpAuthAuthenticateResponses, McpAuthCallbackErrors, McpAuthCallbackResponses, McpAuthRemoveErrors, McpAuthRemoveResponses, McpAuthStartErrors, McpAuthStartResponses, McpConnectResponses, McpDisconnectResponses, McpLocalConfig, McpRemoteConfig, McpStatusResponses, Part, PartDeleteErrors, PartDeleteResponses, PartUpdateErrors, PartUpdateResponses, PathGetResponses, PermissionListResponses, PermissionReplyErrors, PermissionReplyResponses, PermissionRespondErrors, PermissionRespondResponses, PermissionRuleset, ProjectCurrentResponses, ProjectListResponses, ProjectUpdateErrors, ProjectUpdateResponses, ProviderAuthResponses, ProviderListResponses, ProviderOauthAuthorizeErrors, ProviderOauthAuthorizeResponses, ProviderOauthCallbackErrors, ProviderOauthCallbackResponses, PtyConnectErrors, PtyConnectResponses, PtyCreateErrors, PtyCreateResponses, PtyGetErrors, PtyGetResponses, PtyListResponses, PtyRemoveErrors, PtyRemoveResponses, PtyUpdateErrors, PtyUpdateResponses, SessionAbortErrors, SessionAbortResponses, SessionChildrenErrors, SessionChildrenResponses, SessionCommandErrors, SessionCommandResponses, SessionCreateErrors, SessionCreateResponses, SessionDeleteErrors, SessionDeleteResponses, SessionDiffErrors, SessionDiffResponses, SessionForkResponses, SessionGetErrors, SessionGetResponses, SessionInitErrors, SessionInitResponses, SessionListResponses, SessionMessageErrors, SessionMessageResponses, SessionMessagesErrors, SessionMessagesResponses, SessionPromptAsyncErrors, SessionPromptAsyncResponses, SessionPromptErrors, SessionPromptResponses, SessionRevertErrors, SessionRevertResponses, SessionShareErrors, SessionShareResponses, SessionShellErrors, SessionShellResponses, SessionStatusErrors, SessionStatusResponses, SessionSummarizeErrors, SessionSummarizeResponses, SessionTodoErrors, SessionTodoResponses, SessionUnrevertErrors, SessionUnrevertResponses, SessionUnshareErrors, SessionUnshareResponses, SessionUpdateErrors, SessionUpdateResponses, SubtaskPartInput, TextPartInput, ToolIdsErrors, ToolIdsResponses, ToolListErrors, ToolListResponses, TuiAppendPromptErrors, TuiAppendPromptResponses, TuiClearPromptResponses, TuiControlNextResponses, TuiControlResponseResponses, TuiExecuteCommandErrors, TuiExecuteCommandResponses, TuiOpenHelpResponses, TuiOpenModelsResponses, TuiOpenSessionsResponses, TuiOpenThemesResponses, TuiPublishErrors, TuiPublishResponses, TuiShowToastResponses, TuiSubmitPromptResponses, VcsGetResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Get health * * Get health information about the OpenCode server. */ export const globalHealth = (options?: Options) => (options?.client ?? client).get({ url: '/global/health', ...options }); /** * Get global events * * Subscribe to global events from the OpenCode system using server-sent events. */ export const globalEvent = (options?: Options) => (options?.client ?? client).sse.get({ url: '/global/event', ...options }); /** * Dispose instance * * Clean up and dispose all OpenCode instances, releasing all resources. */ export const globalDispose = (options?: Options) => (options?.client ?? client).post({ url: '/global/dispose', ...options }); /** * List all projects * * Get a list of projects that have been opened with OpenCode. */ export const projectList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/project', ...options, ...params }); }; /** * Get current project * * Retrieve the currently active project that OpenCode is working with. */ export const projectCurrent = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/project/current', ...options, ...params }); }; /** * Update project * * Update project properties such as name, icon and color. */ export const projectUpdate = (parameters: { projectID: string; directory?: string; name?: string; icon?: { url?: string; color?: string; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'projectID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'name' }, { in: 'body', key: 'icon' } ] }]); return (options?.client ?? client).patch({ url: '/project/{projectID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List PTY sessions * * Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode. */ export const ptyList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/pty', ...options, ...params }); }; /** * Create PTY session * * Create a new pseudo-terminal (PTY) session for running shell commands and processes. */ export const ptyCreate = (parameters?: { directory?: string; command?: string; args?: Array; cwd?: string; title?: string; env?: { [key: string]: string; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'command' }, { in: 'body', key: 'args' }, { in: 'body', key: 'cwd' }, { in: 'body', key: 'title' }, { in: 'body', key: 'env' } ] }]); return (options?.client ?? client).post({ url: '/pty', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Remove PTY session * * Remove and terminate a specific pseudo-terminal (PTY) session. */ export const ptyRemove = (parameters: { ptyID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/pty/{ptyID}', ...options, ...params }); }; /** * Get PTY session * * Retrieve detailed information about a specific pseudo-terminal (PTY) session. */ export const ptyGet = (parameters: { ptyID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/pty/{ptyID}', ...options, ...params }); }; /** * Update PTY session * * Update properties of an existing pseudo-terminal (PTY) session. */ export const ptyUpdate = (parameters: { ptyID: string; directory?: string; title?: string; size?: { rows: number; cols: number; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'title' }, { in: 'body', key: 'size' } ] }]); return (options?.client ?? client).put({ url: '/pty/{ptyID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Connect to PTY session * * Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time. */ export const ptyConnect = (parameters: { ptyID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/pty/{ptyID}/connect', ...options, ...params }); }; /** * Get configuration * * Retrieve the current OpenCode configuration settings and preferences. */ export const configGet = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/config', ...options, ...params }); }; /** * Update configuration * * Update OpenCode configuration settings and preferences. */ export const configUpdate = (parameters?: { directory?: string; config?: Config; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { key: 'config', map: 'body' }] }]); return (options?.client ?? client).patch({ url: '/config', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List tool IDs * * Get a list of all available tool IDs, including both built-in tools and dynamically registered tools. */ export const toolIds = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/experimental/tool/ids', ...options, ...params }); }; /** * List tools * * Get a list of available tools with their JSON schema parameters for a specific provider and model combination. */ export const toolList = (parameters: { directory?: string; provider: string; model: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'query', key: 'provider' }, { in: 'query', key: 'model' } ] }]); return (options?.client ?? client).get({ url: '/experimental/tool', ...options, ...params }); }; /** * Dispose instance * * Clean up and dispose the current OpenCode instance, releasing all resources. */ export const instanceDispose = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/instance/dispose', ...options, ...params }); }; /** * Get paths * * Retrieve the current working directory and related path information for the OpenCode instance. */ export const pathGet = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/path', ...options, ...params }); }; /** * Get VCS info * * Retrieve version control system (VCS) information for the current project, such as git branch. */ export const vcsGet = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/vcs', ...options, ...params }); }; /** * List sessions * * Get a list of all OpenCode sessions, sorted by most recently updated. */ export const sessionList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session', ...options, ...params }); }; /** * Create session * * Create a new OpenCode session for interacting with AI assistants and managing conversations. */ export const sessionCreate = (parameters?: { directory?: string; parentID?: string; title?: string; permission?: PermissionRuleset; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'parentID' }, { in: 'body', key: 'title' }, { in: 'body', key: 'permission' } ] }]); return (options?.client ?? client).post({ url: '/session', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get session status * * Retrieve the current status of all sessions, including active, idle, and completed states. */ export const sessionStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/status', ...options, ...params }); }; /** * Delete session * * Delete a session and permanently remove all associated data, including messages and history. */ export const sessionDelete = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/session/{sessionID}', ...options, ...params }); }; /** * Get session * * Retrieve detailed information about a specific OpenCode session. */ export const sessionGet = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}', ...options, ...params }); }; /** * Update session * * Update properties of an existing session, such as title or other metadata. */ export const sessionUpdate = (parameters: { sessionID: string; directory?: string; title?: string; time?: { archived?: number; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'title' }, { in: 'body', key: 'time' } ] }]); return (options?.client ?? client).patch({ url: '/session/{sessionID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get session children * * Retrieve all child sessions that were forked from the specified parent session. */ export const sessionChildren = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/children', ...options, ...params }); }; /** * Get session todos * * Retrieve the todo list associated with a specific session, showing tasks and action items. */ export const sessionTodo = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/todo', ...options, ...params }); }; /** * Initialize session * * Analyze the current application and create an AGENTS.md file with project-specific agent configurations. */ export const sessionInit = (parameters: { sessionID: string; directory?: string; modelID: string; providerID: string; messageID: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'modelID' }, { in: 'body', key: 'providerID' }, { in: 'body', key: 'messageID' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/init', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Fork session * * Create a new session by forking an existing session at a specific message point. */ export const sessionFork = (parameters: { sessionID: string; directory?: string; messageID?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/fork', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Abort session * * Abort an active session and stop any ongoing AI processing or command execution. */ export const sessionAbort = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/abort', ...options, ...params }); }; /** * Unshare session * * Remove the shareable link for a session, making it private again. */ export const sessionUnshare = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/session/{sessionID}/share', ...options, ...params }); }; /** * Share session * * Create a shareable link for a session, allowing others to view the conversation. */ export const sessionShare = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/share', ...options, ...params }); }; /** * Get session diff * * Get all file changes (diffs) made during this session. */ export const sessionDiff = (parameters: { sessionID: string; directory?: string; messageID?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'query', key: 'messageID' } ] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/diff', ...options, ...params }); }; /** * Summarize session * * Generate a concise summary of the session using AI compaction to preserve key information. */ export const sessionSummarize = (parameters: { sessionID: string; directory?: string; providerID: string; modelID: string; auto?: boolean; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'providerID' }, { in: 'body', key: 'modelID' }, { in: 'body', key: 'auto' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/summarize', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get session messages * * Retrieve all messages in a session, including user prompts and AI responses. */ export const sessionMessages = (parameters: { sessionID: string; directory?: string; limit?: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'query', key: 'limit' } ] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/message', ...options, ...params }); }; /** * Send message * * Create and send a new message to a session, streaming the AI response. */ export const sessionPrompt = (parameters: { sessionID: string; directory?: string; messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'model' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'noReply' }, { in: 'body', key: 'tools' }, { in: 'body', key: 'system' }, { in: 'body', key: 'variant' }, { in: 'body', key: 'parts' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/message', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get message * * Retrieve a specific message from a session by its message ID. */ export const sessionMessage = (parameters: { sessionID: string; messageID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'messageID' }, { in: 'query', key: 'directory' } ] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/message/{messageID}', ...options, ...params }); }; /** * Delete a part from a message */ export const partDelete = (parameters: { sessionID: string; messageID: string; partID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'messageID' }, { in: 'path', key: 'partID' }, { in: 'query', key: 'directory' } ] }]); return (options?.client ?? client).delete({ url: '/session/{sessionID}/message/{messageID}/part/{partID}', ...options, ...params }); }; /** * Update a part in a message */ export const partUpdate = (parameters: { sessionID: string; messageID: string; partID: string; directory?: string; part?: Part; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'messageID' }, { in: 'path', key: 'partID' }, { in: 'query', key: 'directory' }, { key: 'part', map: 'body' } ] }]); return (options?.client ?? client).patch({ url: '/session/{sessionID}/message/{messageID}/part/{partID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Send async message * * Create and send a new message to a session asynchronously, starting the session if needed and returning immediately. */ export const sessionPromptAsync = (parameters: { sessionID: string; directory?: string; messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'model' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'noReply' }, { in: 'body', key: 'tools' }, { in: 'body', key: 'system' }, { in: 'body', key: 'variant' }, { in: 'body', key: 'parts' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/prompt_async', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Send command * * Send a new command to a session for execution by the AI assistant. */ export const sessionCommand = (parameters: { sessionID: string; directory?: string; messageID?: string; agent?: string; model?: string; arguments: string; command: string; variant?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'model' }, { in: 'body', key: 'arguments' }, { in: 'body', key: 'command' }, { in: 'body', key: 'variant' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/command', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Run shell command * * Execute a shell command within the session context and return the AI's response. */ export const sessionShell = (parameters: { sessionID: string; directory?: string; agent: string; model?: { providerID: string; modelID: string; }; command: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'model' }, { in: 'body', key: 'command' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/shell', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Revert message * * Revert a specific message in a session, undoing its effects and restoring the previous state. */ export const sessionRevert = (parameters: { sessionID: string; directory?: string; messageID: string; partID?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'partID' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/revert', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Restore reverted messages * * Restore all previously reverted messages in a session. */ export const sessionUnrevert = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/unrevert', ...options, ...params }); }; /** * Respond to permission * * Approve or deny a permission request from the AI assistant. * * @deprecated */ export const permissionRespond = (parameters: { sessionID: string; permissionID: string; directory?: string; response: 'once' | 'always' | 'reject'; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'permissionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'response' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/permissions/{permissionID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Respond to permission request * * Approve or deny a permission request from the AI assistant. */ export const permissionReply = (parameters: { requestID: string; directory?: string; reply: 'once' | 'always' | 'reject'; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'requestID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'reply' } ] }]); return (options?.client ?? client).post({ url: '/permission/{requestID}/reply', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List pending permissions * * Get all pending permission requests across all sessions. */ export const permissionList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/permission', ...options, ...params }); }; /** * List commands * * Get a list of all available commands in the OpenCode system. */ export const commandList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/command', ...options, ...params }); }; /** * List config providers * * Get a list of all configured AI providers and their default models. */ export const configProviders = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/config/providers', ...options, ...params }); }; /** * List providers * * Get a list of all available AI providers, including both available and connected ones. */ export const providerList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/provider', ...options, ...params }); }; /** * Get provider auth methods * * Retrieve available authentication methods for all AI providers. */ export const providerAuth = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/provider/auth', ...options, ...params }); }; /** * OAuth authorize * * Initiate OAuth authorization for a specific AI provider to get an authorization URL. */ export const providerOauthAuthorize = (parameters: { providerID: string; directory?: string; method: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'providerID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'method' } ] }]); return (options?.client ?? client).post({ url: '/provider/{providerID}/oauth/authorize', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * OAuth callback * * Handle the OAuth callback from a provider after user authorization. */ export const providerOauthCallback = (parameters: { providerID: string; directory?: string; method: number; code?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'providerID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'method' }, { in: 'body', key: 'code' } ] }]); return (options?.client ?? client).post({ url: '/provider/{providerID}/oauth/callback', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Find text * * Search for text patterns across files in the project using ripgrep. */ export const findText = (parameters: { directory?: string; pattern: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'pattern' }] }]); return (options?.client ?? client).get({ url: '/find', ...options, ...params }); }; /** * Find files * * Search for files or directories by name or pattern in the project directory. */ export const findFiles = (parameters: { directory?: string; query: string; dirs?: 'true' | 'false'; type?: 'file' | 'directory'; limit?: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'query', key: 'query' }, { in: 'query', key: 'dirs' }, { in: 'query', key: 'type' }, { in: 'query', key: 'limit' } ] }]); return (options?.client ?? client).get({ url: '/find/file', ...options, ...params }); }; /** * Find symbols * * Search for workspace symbols like functions, classes, and variables using LSP. */ export const findSymbols = (parameters: { directory?: string; query: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'query' }] }]); return (options?.client ?? client).get({ url: '/find/symbol', ...options, ...params }); }; /** * List files * * List files and directories in a specified path. */ export const fileList = (parameters: { directory?: string; path: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'path' }] }]); return (options?.client ?? client).get({ url: '/file', ...options, ...params }); }; /** * Read file * * Read the content of a specified file. */ export const fileRead = (parameters: { directory?: string; path: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'path' }] }]); return (options?.client ?? client).get({ url: '/file/content', ...options, ...params }); }; /** * Get file status * * Get the git status of all files in the project. */ export const fileStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/file/status', ...options, ...params }); }; /** * Write log * * Write a log entry to the server logs with specified level and metadata. */ export const appLog = (parameters: { directory?: string; service: string; level: 'debug' | 'info' | 'error' | 'warn'; message: string; extra?: { [key: string]: unknown; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'service' }, { in: 'body', key: 'level' }, { in: 'body', key: 'message' }, { in: 'body', key: 'extra' } ] }]); return (options?.client ?? client).post({ url: '/log', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List agents * * Get a list of all available AI agents in the OpenCode system. */ export const appAgents = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/agent', ...options, ...params }); }; /** * Get MCP status * * Get the status of all Model Context Protocol (MCP) servers. */ export const mcpStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/mcp', ...options, ...params }); }; /** * Add MCP server * * Dynamically add a new Model Context Protocol (MCP) server to the system. */ export const mcpAdd = (parameters: { directory?: string; name: string; config: McpLocalConfig | McpRemoteConfig; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'name' }, { in: 'body', key: 'config' } ] }]); return (options?.client ?? client).post({ url: '/mcp', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Remove MCP OAuth * * Remove OAuth credentials for an MCP server */ export const mcpAuthRemove = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/mcp/{name}/auth', ...options, ...params }); }; /** * Start MCP OAuth * * Start OAuth authentication flow for a Model Context Protocol (MCP) server. */ export const mcpAuthStart = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/auth', ...options, ...params }); }; /** * Complete MCP OAuth * * Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code. */ export const mcpAuthCallback = (parameters: { name: string; directory?: string; code: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'name' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'code' } ] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/auth/callback', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Authenticate MCP OAuth * * Start OAuth flow and wait for callback (opens browser) */ export const mcpAuthAuthenticate = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/auth/authenticate', ...options, ...params }); }; /** * Connect an MCP server */ export const mcpConnect = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/connect', ...options, ...params }); }; /** * Disconnect an MCP server */ export const mcpDisconnect = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/disconnect', ...options, ...params }); }; /** * Get LSP status * * Get LSP server status */ export const lspStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/lsp', ...options, ...params }); }; /** * Get formatter status * * Get formatter status */ export const formatterStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/formatter', ...options, ...params }); }; /** * Append TUI prompt * * Append prompt to the TUI */ export const tuiAppendPrompt = (parameters: { directory?: string; text: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'body', key: 'text' }] }]); return (options?.client ?? client).post({ url: '/tui/append-prompt', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Open help dialog * * Open the help dialog in the TUI to display user assistance information. */ export const tuiOpenHelp = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-help', ...options, ...params }); }; /** * Open sessions dialog * * Open the session dialog */ export const tuiOpenSessions = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-sessions', ...options, ...params }); }; /** * Open themes dialog * * Open the theme dialog */ export const tuiOpenThemes = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-themes', ...options, ...params }); }; /** * Open models dialog * * Open the model dialog */ export const tuiOpenModels = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-models', ...options, ...params }); }; /** * Submit TUI prompt * * Submit the prompt */ export const tuiSubmitPrompt = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/submit-prompt', ...options, ...params }); }; /** * Clear TUI prompt * * Clear the prompt */ export const tuiClearPrompt = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/clear-prompt', ...options, ...params }); }; /** * Execute TUI command * * Execute a TUI command (e.g. agent_cycle) */ export const tuiExecuteCommand = (parameters: { directory?: string; command: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'body', key: 'command' }] }]); return (options?.client ?? client).post({ url: '/tui/execute-command', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Show TUI toast * * Show a toast notification in the TUI */ export const tuiShowToast = (parameters: { directory?: string; title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; duration?: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'title' }, { in: 'body', key: 'message' }, { in: 'body', key: 'variant' }, { in: 'body', key: 'duration' } ] }]); return (options?.client ?? client).post({ url: '/tui/show-toast', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Publish TUI event * * Publish a TUI event */ export const tuiPublish = (parameters?: { directory?: string; body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { key: 'body', map: 'body' }] }]); return (options?.client ?? client).post({ url: '/tui/publish', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get next TUI request * * Retrieve the next TUI (Terminal User Interface) request from the queue for processing. */ export const tuiControlNext = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/tui/control/next', ...options, ...params }); }; /** * Submit TUI response * * Submit a response to the TUI request queue to complete a pending request. */ export const tuiControlResponse = (parameters?: { directory?: string; body?: unknown; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { key: 'body', map: 'body' }] }]); return (options?.client ?? client).post({ url: '/tui/control/response', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Set auth credentials * * Set authentication credentials */ export const authSet = (parameters: { providerID: string; directory?: string; auth?: Auth; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'providerID' }, { in: 'query', key: 'directory' }, { key: 'auth', map: 'body' } ] }]); return (options?.client ?? client).put({ url: '/auth/{providerID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).sse.get({ url: '/event', ...options, ...params }); }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSource = FileSource | SymbolSource; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type GlobalEvent = { directory: string; payload: Event; }; export type BadRequestError = { data: unknown; errors: Array<{ [key: string]: unknown; }>; success: false; }; export type NotFoundError = { name: 'NotFoundError'; data: { message: string; }; }; /** * Custom keybind configurations */ export type KeybindsConfig = { /** * Leader key for keybind combinations */ leader?: string; /** * Exit the application */ app_exit?: string; /** * Open external editor */ editor_open?: string; /** * List available themes */ theme_list?: string; /** * Toggle sidebar */ sidebar_toggle?: string; /** * Toggle session scrollbar */ scrollbar_toggle?: string; /** * Toggle username visibility */ username_toggle?: string; /** * View status */ status_view?: string; /** * Export session to editor */ session_export?: string; /** * Create a new session */ session_new?: string; /** * List all sessions */ session_list?: string; /** * Show session timeline */ session_timeline?: string; /** * Fork session from message */ session_fork?: string; /** * Rename session */ session_rename?: string; /** * Share current session */ session_share?: string; /** * Unshare current session */ session_unshare?: string; /** * Interrupt current session */ session_interrupt?: string; /** * Compact the session */ session_compact?: string; /** * Scroll messages up by one page */ messages_page_up?: string; /** * Scroll messages down by one page */ messages_page_down?: string; /** * Scroll messages up by half page */ messages_half_page_up?: string; /** * Scroll messages down by half page */ messages_half_page_down?: string; /** * Navigate to first message */ messages_first?: string; /** * Navigate to last message */ messages_last?: string; /** * Navigate to next message */ messages_next?: string; /** * Navigate to previous message */ messages_previous?: string; /** * Navigate to last user message */ messages_last_user?: string; /** * Copy message */ messages_copy?: string; /** * Undo message */ messages_undo?: string; /** * Redo message */ messages_redo?: string; /** * Toggle code block concealment in messages */ messages_toggle_conceal?: string; /** * Toggle tool details visibility */ tool_details?: string; /** * List available models */ model_list?: string; /** * Next recently used model */ model_cycle_recent?: string; /** * Previous recently used model */ model_cycle_recent_reverse?: string; /** * Next favorite model */ model_cycle_favorite?: string; /** * Previous favorite model */ model_cycle_favorite_reverse?: string; /** * List available commands */ command_list?: string; /** * List agents */ agent_list?: string; /** * Next agent */ agent_cycle?: string; /** * Previous agent */ agent_cycle_reverse?: string; /** * Cycle model variants */ variant_cycle?: string; /** * Clear input field */ input_clear?: string; /** * Paste from clipboard */ input_paste?: string; /** * Submit input */ input_submit?: string; /** * Insert newline in input */ input_newline?: string; /** * Move cursor left in input */ input_move_left?: string; /** * Move cursor right in input */ input_move_right?: string; /** * Move cursor up in input */ input_move_up?: string; /** * Move cursor down in input */ input_move_down?: string; /** * Select left in input */ input_select_left?: string; /** * Select right in input */ input_select_right?: string; /** * Select up in input */ input_select_up?: string; /** * Select down in input */ input_select_down?: string; /** * Move to start of line in input */ input_line_home?: string; /** * Move to end of line in input */ input_line_end?: string; /** * Select to start of line in input */ input_select_line_home?: string; /** * Select to end of line in input */ input_select_line_end?: string; /** * Move to start of visual line in input */ input_visual_line_home?: string; /** * Move to end of visual line in input */ input_visual_line_end?: string; /** * Select to start of visual line in input */ input_select_visual_line_home?: string; /** * Select to end of visual line in input */ input_select_visual_line_end?: string; /** * Move to start of buffer in input */ input_buffer_home?: string; /** * Move to end of buffer in input */ input_buffer_end?: string; /** * Select to start of buffer in input */ input_select_buffer_home?: string; /** * Select to end of buffer in input */ input_select_buffer_end?: string; /** * Delete line in input */ input_delete_line?: string; /** * Delete to end of line in input */ input_delete_to_line_end?: string; /** * Delete to start of line in input */ input_delete_to_line_start?: string; /** * Backspace in input */ input_backspace?: string; /** * Delete character in input */ input_delete?: string; /** * Undo in input */ input_undo?: string; /** * Redo in input */ input_redo?: string; /** * Move word forward in input */ input_word_forward?: string; /** * Move word backward in input */ input_word_backward?: string; /** * Select word forward in input */ input_select_word_forward?: string; /** * Select word backward in input */ input_select_word_backward?: string; /** * Delete word forward in input */ input_delete_word_forward?: string; /** * Delete word backward in input */ input_delete_word_backward?: string; /** * Previous history item */ history_previous?: string; /** * Next history item */ history_next?: string; /** * Next child session */ session_child_cycle?: string; /** * Previous child session */ session_child_cycle_reverse?: string; /** * Go to parent session */ session_parent?: string; /** * Suspend terminal */ terminal_suspend?: string; /** * Toggle terminal title */ terminal_title_toggle?: string; /** * Toggle tips on home screen */ tips_toggle?: string; }; /** * Log level */ export type LogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'; /** * Server configuration for opencode serve and web commands */ export type ServerConfig = { /** * Port to listen on */ port?: number; /** * Hostname to listen on */ hostname?: string; /** * Enable mDNS service discovery */ mdns?: boolean; /** * Additional domains to allow for CORS */ cors?: Array; }; export type PermissionActionConfig = 'ask' | 'allow' | 'deny'; export type PermissionObjectConfig = { [key: string]: PermissionActionConfig; }; export type PermissionRuleConfig = PermissionActionConfig | PermissionObjectConfig; export type PermissionConfig = { read?: PermissionRuleConfig; edit?: PermissionRuleConfig; glob?: PermissionRuleConfig; grep?: PermissionRuleConfig; list?: PermissionRuleConfig; bash?: PermissionRuleConfig; task?: PermissionRuleConfig; external_directory?: PermissionRuleConfig; todowrite?: PermissionActionConfig; todoread?: PermissionActionConfig; webfetch?: PermissionActionConfig; websearch?: PermissionActionConfig; codesearch?: PermissionActionConfig; lsp?: PermissionRuleConfig; doom_loop?: PermissionActionConfig; [key: string]: PermissionRuleConfig | PermissionActionConfig | undefined; } | PermissionActionConfig; export type AgentConfig = { model?: string; temperature?: number; top_p?: number; prompt?: string; /** * @deprecated Use 'permission' field instead */ tools?: { [key: string]: boolean; }; disable?: boolean; /** * Description of when to use the agent */ description?: string; mode?: 'subagent' | 'primary' | 'all'; options?: { [key: string]: unknown; }; /** * Hex color code for the agent (e.g., #FF5733) */ color?: string; /** * Maximum number of agentic iterations before forcing text-only response */ steps?: number; /** * @deprecated Use 'steps' field instead. */ maxSteps?: number; permission?: PermissionConfig; [key: string]: unknown; }; export type ProviderConfig = { api?: string; name?: string; env?: Array; id?: string; npm?: string; models?: { [key: string]: { id?: string; name?: string; family?: string; release_date?: string; attachment?: boolean; reasoning?: boolean; temperature?: boolean; tool_call?: boolean; interleaved?: true | { field: 'reasoning_content' | 'reasoning_details'; }; cost?: { input: number; output: number; cache_read?: number; cache_write?: number; context_over_200k?: { input: number; output: number; cache_read?: number; cache_write?: number; }; }; limit?: { context: number; output: number; }; modalities?: { input: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; output: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; }; experimental?: boolean; status?: 'alpha' | 'beta' | 'deprecated'; options?: { [key: string]: unknown; }; headers?: { [key: string]: string; }; provider?: { npm: string; }; /** * Variant-specific configuration */ variants?: { [key: string]: { /** * Disable this variant for the model */ disabled?: boolean; [key: string]: unknown; }; }; }; }; whitelist?: Array; blacklist?: Array; options?: { apiKey?: string; baseURL?: string; /** * GitHub Enterprise URL for copilot authentication */ enterpriseUrl?: string; /** * Enable promptCacheKey for this provider (default false) */ setCacheKey?: boolean; /** * Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout. */ timeout?: number | false; [key: string]: unknown; }; }; export type McpLocalConfig = { /** * Type of MCP server connection */ type: 'local'; /** * Command and arguments to run the MCP server */ command: Array; /** * Environment variables to set when running the MCP server */ environment?: { [key: string]: string; }; /** * Enable or disable the MCP server on startup */ enabled?: boolean; /** * Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. */ timeout?: number; }; export type McpOAuthConfig = { /** * OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted. */ clientId?: string; /** * OAuth client secret (if required by the authorization server) */ clientSecret?: string; /** * OAuth scopes to request during authorization */ scope?: string; }; export type McpRemoteConfig = { /** * Type of MCP server connection */ type: 'remote'; /** * URL of the remote MCP server */ url: string; /** * Enable or disable the MCP server on startup */ enabled?: boolean; /** * Headers to send with the request */ headers?: { [key: string]: string; }; /** * OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection. */ oauth?: McpOAuthConfig | false; /** * Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. */ timeout?: number; }; /** * @deprecated Always uses stretch layout. */ export type LayoutConfig = 'auto' | 'stretch'; export type Config = { /** * JSON schema reference for configuration validation */ $schema?: string; /** * Theme name to use for the interface */ theme?: string; keybinds?: KeybindsConfig; logLevel?: LogLevel; /** * TUI specific settings */ tui?: { /** * TUI scroll speed */ scroll_speed?: number; /** * Scroll acceleration settings */ scroll_acceleration?: { /** * Enable scroll acceleration */ enabled: boolean; }; /** * Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column */ diff_style?: 'auto' | 'stacked'; }; server?: ServerConfig; /** * Command configuration, see https://opencode.ai/docs/commands */ command?: { [key: string]: { template: string; description?: string; agent?: string; model?: string; subtask?: boolean; }; }; watcher?: { ignore?: Array; }; plugin?: Array; snapshot?: boolean; /** * Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing */ share?: 'manual' | 'auto' | 'disabled'; /** * @deprecated Use 'share' field instead. Share newly created sessions automatically */ autoshare?: boolean; /** * Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications */ autoupdate?: boolean | 'notify'; /** * Disable providers that are loaded automatically */ disabled_providers?: Array; /** * When set, ONLY these providers will be enabled. All other providers will be ignored */ enabled_providers?: Array; /** * Model to use in the format of provider/model, eg anthropic/claude-2 */ model?: string; /** * Small model to use for tasks like title generation in the format of provider/model */ small_model?: string; /** * Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid. */ default_agent?: string; /** * Custom username to display in conversations instead of system username */ username?: string; /** * @deprecated Use `agent` field instead. */ mode?: { build?: AgentConfig; plan?: AgentConfig; [key: string]: AgentConfig | undefined; }; /** * Agent configuration, see https://opencode.ai/docs/agent */ agent?: { plan?: AgentConfig; build?: AgentConfig; general?: AgentConfig; explore?: AgentConfig; title?: AgentConfig; summary?: AgentConfig; compaction?: AgentConfig; [key: string]: AgentConfig | undefined; }; /** * Custom provider configurations and model overrides */ provider?: { [key: string]: ProviderConfig; }; /** * MCP (Model Context Protocol) server configurations */ mcp?: { [key: string]: McpLocalConfig | McpRemoteConfig; }; formatter?: false | { [key: string]: { disabled?: boolean; command?: Array; environment?: { [key: string]: string; }; extensions?: Array; }; }; lsp?: false | { [key: string]: { disabled: true; } | { command: Array; extensions?: Array; disabled?: boolean; env?: { [key: string]: string; }; initialization?: { [key: string]: unknown; }; }; }; /** * Additional instruction files or patterns to include */ instructions?: Array; layout?: LayoutConfig; permission?: PermissionConfig; tools?: { [key: string]: boolean; }; enterprise?: { /** * Enterprise URL */ url?: string; }; compaction?: { /** * Enable automatic compaction when context is full (default: true) */ auto?: boolean; /** * Enable pruning of old tool outputs (default: true) */ prune?: boolean; }; experimental?: { hook?: { file_edited?: { [key: string]: Array<{ command: Array; environment?: { [key: string]: string; }; }>; }; session_completed?: Array<{ command: Array; environment?: { [key: string]: string; }; }>; }; /** * Number of retries for chat completions on failure */ chatMaxRetries?: number; disable_paste_summary?: boolean; /** * Enable the batch tool */ batch_tool?: boolean; /** * Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag) */ openTelemetry?: boolean; /** * Tools that should only be available to primary agents. */ primary_tools?: Array; /** * Continue the agent loop when a tool call is denied */ continue_loop_on_deny?: boolean; /** * Timeout in milliseconds for model context protocol (MCP) requests */ mcp_timeout?: number; }; }; export type ToolIds = Array; export type ToolListItem = { id: string; description: string; parameters: unknown; }; export type ToolList = Array; export type Path = { home: string; state: string; config: string; worktree: string; directory: string; }; export type VcsInfo = { branch: string; }; export type TextPartInput = { id?: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type FilePartInput = { id?: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type AgentPartInput = { id?: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type SubtaskPartInput = { id?: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; }; export type Command = { name: string; description?: string; agent?: string; model?: string; mcp?: boolean; template: string; subtask?: boolean; hints: Array; }; export type Model = { id: string; providerID: string; api: { id: string; url: string; npm: string; }; name: string; family?: string; capabilities: { temperature: boolean; reasoning: boolean; attachment: boolean; toolcall: boolean; input: { text: boolean; audio: boolean; image: boolean; video: boolean; pdf: boolean; }; output: { text: boolean; audio: boolean; image: boolean; video: boolean; pdf: boolean; }; interleaved: boolean | { field: 'reasoning_content' | 'reasoning_details'; }; }; cost: { input: number; output: number; cache: { read: number; write: number; }; experimentalOver200K?: { input: number; output: number; cache: { read: number; write: number; }; }; }; limit: { context: number; output: number; }; status: 'alpha' | 'beta' | 'deprecated' | 'active'; options: { [key: string]: unknown; }; headers: { [key: string]: string; }; release_date: string; variants?: { [key: string]: { [key: string]: unknown; }; }; }; export type Provider = { id: string; name: string; source: 'env' | 'config' | 'custom' | 'api'; env: Array; key?: string; options: { [key: string]: unknown; }; models: { [key: string]: Model; }; }; export type ProviderAuthMethod = { type: 'oauth' | 'api'; label: string; }; export type ProviderAuthAuthorization = { url: string; method: 'auto' | 'code'; instructions: string; }; export type Symbol = { name: string; kind: number; location: { uri: string; range: Range; }; }; export type FileNode = { name: string; path: string; absolute: string; type: 'file' | 'directory'; ignored: boolean; }; export type FileContent = { type: 'text'; content: string; diff?: string; patch?: { oldFileName: string; newFileName: string; oldHeader?: string; newHeader?: string; hunks: Array<{ oldStart: number; oldLines: number; newStart: number; newLines: number; lines: Array; }>; index?: string; }; encoding?: 'base64'; mimeType?: string; }; export type File = { path: string; added: number; removed: number; status: 'added' | 'deleted' | 'modified'; }; export type Agent = { name: string; description?: string; mode: 'subagent' | 'primary' | 'all'; native?: boolean; hidden?: boolean; topP?: number; temperature?: number; color?: string; permission: PermissionRuleset; model?: { modelID: string; providerID: string; }; prompt?: string; options: { [key: string]: unknown; }; steps?: number; }; export type McpStatusConnected = { status: 'connected'; }; export type McpStatusDisabled = { status: 'disabled'; }; export type McpStatusFailed = { status: 'failed'; error: string; }; export type McpStatusNeedsAuth = { status: 'needs_auth'; }; export type McpStatusNeedsClientRegistration = { status: 'needs_client_registration'; error: string; }; export type McpStatus = McpStatusConnected | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth | McpStatusNeedsClientRegistration; export type LspStatus = { id: string; name: string; root: string; status: 'connected' | 'error'; }; export type FormatterStatus = { name: string; extensions: Array; enabled: boolean; }; export type OAuth = { type: 'oauth'; refresh: string; access: string; expires: number; enterpriseUrl?: string; }; export type ApiAuth = { type: 'api'; key: string; }; export type WellKnownAuth = { type: 'wellknown'; key: string; token: string; }; export type Auth = OAuth | ApiAuth | WellKnownAuth; export type GlobalHealthData = { body?: never; path?: never; query?: never; url: '/global/health'; }; export type GlobalHealthResponses = { /** * Health information */ 200: { healthy: true; version: string; }; }; export type GlobalHealthResponse = GlobalHealthResponses[keyof GlobalHealthResponses]; export type GlobalEventData = { body?: never; path?: never; query?: never; url: '/global/event'; }; export type GlobalEventResponses = { /** * Event stream */ 200: GlobalEvent; }; export type GlobalEventResponse = GlobalEventResponses[keyof GlobalEventResponses]; export type GlobalDisposeData = { body?: never; path?: never; query?: never; url: '/global/dispose'; }; export type GlobalDisposeResponses = { /** * Global disposed */ 200: boolean; }; export type GlobalDisposeResponse = GlobalDisposeResponses[keyof GlobalDisposeResponses]; export type ProjectListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/project'; }; export type ProjectListResponses = { /** * List of projects */ 200: Array; }; export type ProjectListResponse = ProjectListResponses[keyof ProjectListResponses]; export type ProjectCurrentData = { body?: never; path?: never; query?: { directory?: string; }; url: '/project/current'; }; export type ProjectCurrentResponses = { /** * Current project information */ 200: Project; }; export type ProjectCurrentResponse = ProjectCurrentResponses[keyof ProjectCurrentResponses]; export type ProjectUpdateData = { body?: { name?: string; icon?: { url?: string; color?: string; }; }; path: { projectID: string; }; query?: { directory?: string; }; url: '/project/{projectID}'; }; export type ProjectUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type ProjectUpdateError = ProjectUpdateErrors[keyof ProjectUpdateErrors]; export type ProjectUpdateResponses = { /** * Updated project information */ 200: Project; }; export type ProjectUpdateResponse = ProjectUpdateResponses[keyof ProjectUpdateResponses]; export type PtyListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/pty'; }; export type PtyListResponses = { /** * List of sessions */ 200: Array; }; export type PtyListResponse = PtyListResponses[keyof PtyListResponses]; export type PtyCreateData = { body?: { command?: string; args?: Array; cwd?: string; title?: string; env?: { [key: string]: string; }; }; path?: never; query?: { directory?: string; }; url: '/pty'; }; export type PtyCreateErrors = { /** * Bad request */ 400: BadRequestError; }; export type PtyCreateError = PtyCreateErrors[keyof PtyCreateErrors]; export type PtyCreateResponses = { /** * Created session */ 200: Pty; }; export type PtyCreateResponse = PtyCreateResponses[keyof PtyCreateResponses]; export type PtyRemoveData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyRemoveErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyRemoveError = PtyRemoveErrors[keyof PtyRemoveErrors]; export type PtyRemoveResponses = { /** * Session removed */ 200: boolean; }; export type PtyRemoveResponse = PtyRemoveResponses[keyof PtyRemoveResponses]; export type PtyGetData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyGetErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyGetError = PtyGetErrors[keyof PtyGetErrors]; export type PtyGetResponses = { /** * Session info */ 200: Pty; }; export type PtyGetResponse = PtyGetResponses[keyof PtyGetResponses]; export type PtyUpdateData = { body?: { title?: string; size?: { rows: number; cols: number; }; }; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyUpdateErrors = { /** * Bad request */ 400: BadRequestError; }; export type PtyUpdateError = PtyUpdateErrors[keyof PtyUpdateErrors]; export type PtyUpdateResponses = { /** * Updated session */ 200: Pty; }; export type PtyUpdateResponse = PtyUpdateResponses[keyof PtyUpdateResponses]; export type PtyConnectData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}/connect'; }; export type PtyConnectErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyConnectError = PtyConnectErrors[keyof PtyConnectErrors]; export type PtyConnectResponses = { /** * Connected session */ 200: boolean; }; export type PtyConnectResponse = PtyConnectResponses[keyof PtyConnectResponses]; export type ConfigGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/config'; }; export type ConfigGetResponses = { /** * Get config info */ 200: Config; }; export type ConfigGetResponse = ConfigGetResponses[keyof ConfigGetResponses]; export type ConfigUpdateData = { body?: Config; path?: never; query?: { directory?: string; }; url: '/config'; }; export type ConfigUpdateErrors = { /** * Bad request */ 400: BadRequestError; }; export type ConfigUpdateError = ConfigUpdateErrors[keyof ConfigUpdateErrors]; export type ConfigUpdateResponses = { /** * Successfully updated config */ 200: Config; }; export type ConfigUpdateResponse = ConfigUpdateResponses[keyof ConfigUpdateResponses]; export type ToolIdsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/experimental/tool/ids'; }; export type ToolIdsErrors = { /** * Bad request */ 400: BadRequestError; }; export type ToolIdsError = ToolIdsErrors[keyof ToolIdsErrors]; export type ToolIdsResponses = { /** * Tool IDs */ 200: ToolIds; }; export type ToolIdsResponse = ToolIdsResponses[keyof ToolIdsResponses]; export type ToolListData = { body?: never; path?: never; query: { directory?: string; provider: string; model: string; }; url: '/experimental/tool'; }; export type ToolListErrors = { /** * Bad request */ 400: BadRequestError; }; export type ToolListError = ToolListErrors[keyof ToolListErrors]; export type ToolListResponses = { /** * Tools */ 200: ToolList; }; export type ToolListResponse = ToolListResponses[keyof ToolListResponses]; export type InstanceDisposeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/instance/dispose'; }; export type InstanceDisposeResponses = { /** * Instance disposed */ 200: boolean; }; export type InstanceDisposeResponse = InstanceDisposeResponses[keyof InstanceDisposeResponses]; export type PathGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/path'; }; export type PathGetResponses = { /** * Path */ 200: Path; }; export type PathGetResponse = PathGetResponses[keyof PathGetResponses]; export type VcsGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/vcs'; }; export type VcsGetResponses = { /** * VCS info */ 200: VcsInfo; }; export type VcsGetResponse = VcsGetResponses[keyof VcsGetResponses]; export type SessionListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/session'; }; export type SessionListResponses = { /** * List of sessions */ 200: Array; }; export type SessionListResponse = SessionListResponses[keyof SessionListResponses]; export type SessionCreateData = { body?: { parentID?: string; title?: string; permission?: PermissionRuleset; }; path?: never; query?: { directory?: string; }; url: '/session'; }; export type SessionCreateErrors = { /** * Bad request */ 400: BadRequestError; }; export type SessionCreateError = SessionCreateErrors[keyof SessionCreateErrors]; export type SessionCreateResponses = { /** * Successfully created session */ 200: Session; }; export type SessionCreateResponse = SessionCreateResponses[keyof SessionCreateResponses]; export type SessionStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/session/status'; }; export type SessionStatusErrors = { /** * Bad request */ 400: BadRequestError; }; export type SessionStatusError = SessionStatusErrors[keyof SessionStatusErrors]; export type SessionStatusResponses = { /** * Get session status */ 200: { [key: string]: SessionStatus; }; }; export type SessionStatusResponse = SessionStatusResponses[keyof SessionStatusResponses]; export type SessionDeleteData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionDeleteErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionDeleteError = SessionDeleteErrors[keyof SessionDeleteErrors]; export type SessionDeleteResponses = { /** * Successfully deleted session */ 200: boolean; }; export type SessionDeleteResponse = SessionDeleteResponses[keyof SessionDeleteResponses]; export type SessionGetData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionGetErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionGetError = SessionGetErrors[keyof SessionGetErrors]; export type SessionGetResponses = { /** * Get session */ 200: Session; }; export type SessionGetResponse = SessionGetResponses[keyof SessionGetResponses]; export type SessionUpdateData = { body?: { title?: string; time?: { archived?: number; }; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUpdateError = SessionUpdateErrors[keyof SessionUpdateErrors]; export type SessionUpdateResponses = { /** * Successfully updated session */ 200: Session; }; export type SessionUpdateResponse = SessionUpdateResponses[keyof SessionUpdateResponses]; export type SessionChildrenData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/children'; }; export type SessionChildrenErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionChildrenError = SessionChildrenErrors[keyof SessionChildrenErrors]; export type SessionChildrenResponses = { /** * List of children */ 200: Array; }; export type SessionChildrenResponse = SessionChildrenResponses[keyof SessionChildrenResponses]; export type SessionTodoData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/todo'; }; export type SessionTodoErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionTodoError = SessionTodoErrors[keyof SessionTodoErrors]; export type SessionTodoResponses = { /** * Todo list */ 200: Array; }; export type SessionTodoResponse = SessionTodoResponses[keyof SessionTodoResponses]; export type SessionInitData = { body?: { modelID: string; providerID: string; messageID: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/init'; }; export type SessionInitErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionInitError = SessionInitErrors[keyof SessionInitErrors]; export type SessionInitResponses = { /** * 200 */ 200: boolean; }; export type SessionInitResponse = SessionInitResponses[keyof SessionInitResponses]; export type SessionForkData = { body?: { messageID?: string; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/fork'; }; export type SessionForkResponses = { /** * 200 */ 200: Session; }; export type SessionForkResponse = SessionForkResponses[keyof SessionForkResponses]; export type SessionAbortData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/abort'; }; export type SessionAbortErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionAbortError = SessionAbortErrors[keyof SessionAbortErrors]; export type SessionAbortResponses = { /** * Aborted session */ 200: boolean; }; export type SessionAbortResponse = SessionAbortResponses[keyof SessionAbortResponses]; export type SessionUnshareData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/share'; }; export type SessionUnshareErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUnshareError = SessionUnshareErrors[keyof SessionUnshareErrors]; export type SessionUnshareResponses = { /** * Successfully unshared session */ 200: Session; }; export type SessionUnshareResponse = SessionUnshareResponses[keyof SessionUnshareResponses]; export type SessionShareData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/share'; }; export type SessionShareErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionShareError = SessionShareErrors[keyof SessionShareErrors]; export type SessionShareResponses = { /** * Successfully shared session */ 200: Session; }; export type SessionShareResponse = SessionShareResponses[keyof SessionShareResponses]; export type SessionDiffData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; messageID?: string; }; url: '/session/{sessionID}/diff'; }; export type SessionDiffErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionDiffError = SessionDiffErrors[keyof SessionDiffErrors]; export type SessionDiffResponses = { /** * List of diffs */ 200: Array; }; export type SessionDiffResponse = SessionDiffResponses[keyof SessionDiffResponses]; export type SessionSummarizeData = { body?: { providerID: string; modelID: string; auto?: boolean; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/summarize'; }; export type SessionSummarizeErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionSummarizeError = SessionSummarizeErrors[keyof SessionSummarizeErrors]; export type SessionSummarizeResponses = { /** * Summarized session */ 200: boolean; }; export type SessionSummarizeResponse = SessionSummarizeResponses[keyof SessionSummarizeResponses]; export type SessionMessagesData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; limit?: number; }; url: '/session/{sessionID}/message'; }; export type SessionMessagesErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionMessagesError = SessionMessagesErrors[keyof SessionMessagesErrors]; export type SessionMessagesResponses = { /** * List of messages */ 200: Array<{ info: Message; parts: Array; }>; }; export type SessionMessagesResponse = SessionMessagesResponses[keyof SessionMessagesResponses]; export type SessionPromptData = { body?: { messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; /** * @deprecated tools and permissions have been merged, you can set permissions on the session itself now */ tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message'; }; export type SessionPromptErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionPromptError = SessionPromptErrors[keyof SessionPromptErrors]; export type SessionPromptResponses = { /** * Created message */ 200: { info: AssistantMessage; parts: Array; }; }; export type SessionPromptResponse = SessionPromptResponses[keyof SessionPromptResponses]; export type SessionMessageData = { body?: never; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}'; }; export type SessionMessageErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionMessageError = SessionMessageErrors[keyof SessionMessageErrors]; export type SessionMessageResponses = { /** * Message */ 200: { info: Message; parts: Array; }; }; export type SessionMessageResponse = SessionMessageResponses[keyof SessionMessageResponses]; export type PartDeleteData = { body?: never; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; /** * Part ID */ partID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}/part/{partID}'; }; export type PartDeleteErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PartDeleteError = PartDeleteErrors[keyof PartDeleteErrors]; export type PartDeleteResponses = { /** * Successfully deleted part */ 200: boolean; }; export type PartDeleteResponse = PartDeleteResponses[keyof PartDeleteResponses]; export type PartUpdateData = { body?: Part; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; /** * Part ID */ partID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}/part/{partID}'; }; export type PartUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PartUpdateError = PartUpdateErrors[keyof PartUpdateErrors]; export type PartUpdateResponses = { /** * Successfully updated part */ 200: Part; }; export type PartUpdateResponse = PartUpdateResponses[keyof PartUpdateResponses]; export type SessionPromptAsyncData = { body?: { messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; /** * @deprecated tools and permissions have been merged, you can set permissions on the session itself now */ tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/prompt_async'; }; export type SessionPromptAsyncErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionPromptAsyncError = SessionPromptAsyncErrors[keyof SessionPromptAsyncErrors]; export type SessionPromptAsyncResponses = { /** * Prompt accepted */ 204: void; }; export type SessionPromptAsyncResponse = SessionPromptAsyncResponses[keyof SessionPromptAsyncResponses]; export type SessionCommandData = { body?: { messageID?: string; agent?: string; model?: string; arguments: string; command: string; variant?: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/command'; }; export type SessionCommandErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionCommandError = SessionCommandErrors[keyof SessionCommandErrors]; export type SessionCommandResponses = { /** * Created message */ 200: { info: AssistantMessage; parts: Array; }; }; export type SessionCommandResponse = SessionCommandResponses[keyof SessionCommandResponses]; export type SessionShellData = { body?: { agent: string; model?: { providerID: string; modelID: string; }; command: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/shell'; }; export type SessionShellErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionShellError = SessionShellErrors[keyof SessionShellErrors]; export type SessionShellResponses = { /** * Created message */ 200: AssistantMessage; }; export type SessionShellResponse = SessionShellResponses[keyof SessionShellResponses]; export type SessionRevertData = { body?: { messageID: string; partID?: string; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/revert'; }; export type SessionRevertErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionRevertError = SessionRevertErrors[keyof SessionRevertErrors]; export type SessionRevertResponses = { /** * Updated session */ 200: Session; }; export type SessionRevertResponse = SessionRevertResponses[keyof SessionRevertResponses]; export type SessionUnrevertData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/unrevert'; }; export type SessionUnrevertErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUnrevertError = SessionUnrevertErrors[keyof SessionUnrevertErrors]; export type SessionUnrevertResponses = { /** * Updated session */ 200: Session; }; export type SessionUnrevertResponse = SessionUnrevertResponses[keyof SessionUnrevertResponses]; export type PermissionRespondData = { body?: { response: 'once' | 'always' | 'reject'; }; path: { sessionID: string; permissionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/permissions/{permissionID}'; }; export type PermissionRespondErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PermissionRespondError = PermissionRespondErrors[keyof PermissionRespondErrors]; export type PermissionRespondResponses = { /** * Permission processed successfully */ 200: boolean; }; export type PermissionRespondResponse = PermissionRespondResponses[keyof PermissionRespondResponses]; export type PermissionReplyData = { body?: { reply: 'once' | 'always' | 'reject'; }; path: { requestID: string; }; query?: { directory?: string; }; url: '/permission/{requestID}/reply'; }; export type PermissionReplyErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PermissionReplyError = PermissionReplyErrors[keyof PermissionReplyErrors]; export type PermissionReplyResponses = { /** * Permission processed successfully */ 200: boolean; }; export type PermissionReplyResponse = PermissionReplyResponses[keyof PermissionReplyResponses]; export type PermissionListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/permission'; }; export type PermissionListResponses = { /** * List of pending permissions */ 200: Array; }; export type PermissionListResponse = PermissionListResponses[keyof PermissionListResponses]; export type CommandListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/command'; }; export type CommandListResponses = { /** * List of commands */ 200: Array; }; export type CommandListResponse = CommandListResponses[keyof CommandListResponses]; export type ConfigProvidersData = { body?: never; path?: never; query?: { directory?: string; }; url: '/config/providers'; }; export type ConfigProvidersResponses = { /** * List of providers */ 200: { providers: Array; default: { [key: string]: string; }; }; }; export type ConfigProvidersResponse = ConfigProvidersResponses[keyof ConfigProvidersResponses]; export type ProviderListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/provider'; }; export type ProviderListResponses = { /** * List of providers */ 200: { all: Array<{ api?: string; name: string; env: Array; id: string; npm?: string; models: { [key: string]: { id: string; name: string; family?: string; release_date: string; attachment: boolean; reasoning: boolean; temperature: boolean; tool_call: boolean; interleaved?: true | { field: 'reasoning_content' | 'reasoning_details'; }; cost?: { input: number; output: number; cache_read?: number; cache_write?: number; context_over_200k?: { input: number; output: number; cache_read?: number; cache_write?: number; }; }; limit: { context: number; output: number; }; modalities?: { input: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; output: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; }; experimental?: boolean; status?: 'alpha' | 'beta' | 'deprecated'; options: { [key: string]: unknown; }; headers?: { [key: string]: string; }; provider?: { npm: string; }; variants?: { [key: string]: { [key: string]: unknown; }; }; }; }; }>; default: { [key: string]: string; }; connected: Array; }; }; export type ProviderListResponse = ProviderListResponses[keyof ProviderListResponses]; export type ProviderAuthData = { body?: never; path?: never; query?: { directory?: string; }; url: '/provider/auth'; }; export type ProviderAuthResponses = { /** * Provider auth methods */ 200: { [key: string]: Array; }; }; export type ProviderAuthResponse = ProviderAuthResponses[keyof ProviderAuthResponses]; export type ProviderOauthAuthorizeData = { body?: { /** * Auth method index */ method: number; }; path: { /** * Provider ID */ providerID: string; }; query?: { directory?: string; }; url: '/provider/{providerID}/oauth/authorize'; }; export type ProviderOauthAuthorizeErrors = { /** * Bad request */ 400: BadRequestError; }; export type ProviderOauthAuthorizeError = ProviderOauthAuthorizeErrors[keyof ProviderOauthAuthorizeErrors]; export type ProviderOauthAuthorizeResponses = { /** * Authorization URL and method */ 200: ProviderAuthAuthorization; }; export type ProviderOauthAuthorizeResponse = ProviderOauthAuthorizeResponses[keyof ProviderOauthAuthorizeResponses]; export type ProviderOauthCallbackData = { body?: { /** * Auth method index */ method: number; /** * OAuth authorization code */ code?: string; }; path: { /** * Provider ID */ providerID: string; }; query?: { directory?: string; }; url: '/provider/{providerID}/oauth/callback'; }; export type ProviderOauthCallbackErrors = { /** * Bad request */ 400: BadRequestError; }; export type ProviderOauthCallbackError = ProviderOauthCallbackErrors[keyof ProviderOauthCallbackErrors]; export type ProviderOauthCallbackResponses = { /** * OAuth callback processed successfully */ 200: boolean; }; export type ProviderOauthCallbackResponse = ProviderOauthCallbackResponses[keyof ProviderOauthCallbackResponses]; export type FindTextData = { body?: never; path?: never; query: { directory?: string; pattern: string; }; url: '/find'; }; export type FindTextResponses = { /** * Matches */ 200: Array<{ path: { text: string; }; lines: { text: string; }; line_number: number; absolute_offset: number; submatches: Array<{ match: { text: string; }; start: number; end: number; }>; }>; }; export type FindTextResponse = FindTextResponses[keyof FindTextResponses]; export type FindFilesData = { body?: never; path?: never; query: { directory?: string; query: string; dirs?: 'true' | 'false'; type?: 'file' | 'directory'; limit?: number; }; url: '/find/file'; }; export type FindFilesResponses = { /** * File paths */ 200: Array; }; export type FindFilesResponse = FindFilesResponses[keyof FindFilesResponses]; export type FindSymbolsData = { body?: never; path?: never; query: { directory?: string; query: string; }; url: '/find/symbol'; }; export type FindSymbolsResponses = { /** * Symbols */ 200: Array; }; export type FindSymbolsResponse = FindSymbolsResponses[keyof FindSymbolsResponses]; export type FileListData = { body?: never; path?: never; query: { directory?: string; path: string; }; url: '/file'; }; export type FileListResponses = { /** * Files and directories */ 200: Array; }; export type FileListResponse = FileListResponses[keyof FileListResponses]; export type FileReadData = { body?: never; path?: never; query: { directory?: string; path: string; }; url: '/file/content'; }; export type FileReadResponses = { /** * File content */ 200: FileContent; }; export type FileReadResponse = FileReadResponses[keyof FileReadResponses]; export type FileStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/file/status'; }; export type FileStatusResponses = { /** * File status */ 200: Array; }; export type FileStatusResponse = FileStatusResponses[keyof FileStatusResponses]; export type AppLogData = { body?: { /** * Service name for the log entry */ service: string; /** * Log level */ level: 'debug' | 'info' | 'error' | 'warn'; /** * Log message */ message: string; /** * Additional metadata for the log entry */ extra?: { [key: string]: unknown; }; }; path?: never; query?: { directory?: string; }; url: '/log'; }; export type AppLogErrors = { /** * Bad request */ 400: BadRequestError; }; export type AppLogError = AppLogErrors[keyof AppLogErrors]; export type AppLogResponses = { /** * Log entry written successfully */ 200: boolean; }; export type AppLogResponse = AppLogResponses[keyof AppLogResponses]; export type AppAgentsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/agent'; }; export type AppAgentsResponses = { /** * List of agents */ 200: Array; }; export type AppAgentsResponse = AppAgentsResponses[keyof AppAgentsResponses]; export type McpStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/mcp'; }; export type McpStatusResponses = { /** * MCP server status */ 200: { [key: string]: McpStatus; }; }; export type McpStatusResponse = McpStatusResponses[keyof McpStatusResponses]; export type McpAddData = { body?: { name: string; config: McpLocalConfig | McpRemoteConfig; }; path?: never; query?: { directory?: string; }; url: '/mcp'; }; export type McpAddErrors = { /** * Bad request */ 400: BadRequestError; }; export type McpAddError = McpAddErrors[keyof McpAddErrors]; export type McpAddResponses = { /** * MCP server added successfully */ 200: { [key: string]: McpStatus; }; }; export type McpAddResponse = McpAddResponses[keyof McpAddResponses]; export type McpAuthRemoveData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth'; }; export type McpAuthRemoveErrors = { /** * Not found */ 404: NotFoundError; }; export type McpAuthRemoveError = McpAuthRemoveErrors[keyof McpAuthRemoveErrors]; export type McpAuthRemoveResponses = { /** * OAuth credentials removed */ 200: { success: true; }; }; export type McpAuthRemoveResponse = McpAuthRemoveResponses[keyof McpAuthRemoveResponses]; export type McpAuthStartData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth'; }; export type McpAuthStartErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthStartError = McpAuthStartErrors[keyof McpAuthStartErrors]; export type McpAuthStartResponses = { /** * OAuth flow started */ 200: { /** * URL to open in browser for authorization */ authorizationUrl: string; }; }; export type McpAuthStartResponse = McpAuthStartResponses[keyof McpAuthStartResponses]; export type McpAuthCallbackData = { body?: { /** * Authorization code from OAuth callback */ code: string; }; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth/callback'; }; export type McpAuthCallbackErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthCallbackError = McpAuthCallbackErrors[keyof McpAuthCallbackErrors]; export type McpAuthCallbackResponses = { /** * OAuth authentication completed */ 200: McpStatus; }; export type McpAuthCallbackResponse = McpAuthCallbackResponses[keyof McpAuthCallbackResponses]; export type McpAuthAuthenticateData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth/authenticate'; }; export type McpAuthAuthenticateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthAuthenticateError = McpAuthAuthenticateErrors[keyof McpAuthAuthenticateErrors]; export type McpAuthAuthenticateResponses = { /** * OAuth authentication completed */ 200: McpStatus; }; export type McpAuthAuthenticateResponse = McpAuthAuthenticateResponses[keyof McpAuthAuthenticateResponses]; export type McpConnectData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/connect'; }; export type McpConnectResponses = { /** * MCP server connected successfully */ 200: boolean; }; export type McpConnectResponse = McpConnectResponses[keyof McpConnectResponses]; export type McpDisconnectData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/disconnect'; }; export type McpDisconnectResponses = { /** * MCP server disconnected successfully */ 200: boolean; }; export type McpDisconnectResponse = McpDisconnectResponses[keyof McpDisconnectResponses]; export type LspStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/lsp'; }; export type LspStatusResponses = { /** * LSP server status */ 200: Array; }; export type LspStatusResponse = LspStatusResponses[keyof LspStatusResponses]; export type FormatterStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/formatter'; }; export type FormatterStatusResponses = { /** * Formatter status */ 200: Array; }; export type FormatterStatusResponse = FormatterStatusResponses[keyof FormatterStatusResponses]; export type TuiAppendPromptData = { body?: { text: string; }; path?: never; query?: { directory?: string; }; url: '/tui/append-prompt'; }; export type TuiAppendPromptErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiAppendPromptError = TuiAppendPromptErrors[keyof TuiAppendPromptErrors]; export type TuiAppendPromptResponses = { /** * Prompt processed successfully */ 200: boolean; }; export type TuiAppendPromptResponse = TuiAppendPromptResponses[keyof TuiAppendPromptResponses]; export type TuiOpenHelpData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-help'; }; export type TuiOpenHelpResponses = { /** * Help dialog opened successfully */ 200: boolean; }; export type TuiOpenHelpResponse = TuiOpenHelpResponses[keyof TuiOpenHelpResponses]; export type TuiOpenSessionsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-sessions'; }; export type TuiOpenSessionsResponses = { /** * Session dialog opened successfully */ 200: boolean; }; export type TuiOpenSessionsResponse = TuiOpenSessionsResponses[keyof TuiOpenSessionsResponses]; export type TuiOpenThemesData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-themes'; }; export type TuiOpenThemesResponses = { /** * Theme dialog opened successfully */ 200: boolean; }; export type TuiOpenThemesResponse = TuiOpenThemesResponses[keyof TuiOpenThemesResponses]; export type TuiOpenModelsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-models'; }; export type TuiOpenModelsResponses = { /** * Model dialog opened successfully */ 200: boolean; }; export type TuiOpenModelsResponse = TuiOpenModelsResponses[keyof TuiOpenModelsResponses]; export type TuiSubmitPromptData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/submit-prompt'; }; export type TuiSubmitPromptResponses = { /** * Prompt submitted successfully */ 200: boolean; }; export type TuiSubmitPromptResponse = TuiSubmitPromptResponses[keyof TuiSubmitPromptResponses]; export type TuiClearPromptData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/clear-prompt'; }; export type TuiClearPromptResponses = { /** * Prompt cleared successfully */ 200: boolean; }; export type TuiClearPromptResponse = TuiClearPromptResponses[keyof TuiClearPromptResponses]; export type TuiExecuteCommandData = { body?: { command: string; }; path?: never; query?: { directory?: string; }; url: '/tui/execute-command'; }; export type TuiExecuteCommandErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiExecuteCommandError = TuiExecuteCommandErrors[keyof TuiExecuteCommandErrors]; export type TuiExecuteCommandResponses = { /** * Command executed successfully */ 200: boolean; }; export type TuiExecuteCommandResponse = TuiExecuteCommandResponses[keyof TuiExecuteCommandResponses]; export type TuiShowToastData = { body?: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; path?: never; query?: { directory?: string; }; url: '/tui/show-toast'; }; export type TuiShowToastResponses = { /** * Toast notification shown successfully */ 200: boolean; }; export type TuiShowToastResponse = TuiShowToastResponses[keyof TuiShowToastResponses]; export type TuiPublishData = { body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow; path?: never; query?: { directory?: string; }; url: '/tui/publish'; }; export type TuiPublishErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiPublishError = TuiPublishErrors[keyof TuiPublishErrors]; export type TuiPublishResponses = { /** * Event published successfully */ 200: boolean; }; export type TuiPublishResponse = TuiPublishResponses[keyof TuiPublishResponses]; export type TuiControlNextData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/control/next'; }; export type TuiControlNextResponses = { /** * Next TUI request */ 200: { path: string; body: unknown; }; }; export type TuiControlNextResponse = TuiControlNextResponses[keyof TuiControlNextResponses]; export type TuiControlResponseData = { body?: unknown; path?: never; query?: { directory?: string; }; url: '/tui/control/response'; }; export type TuiControlResponseResponses = { /** * Response submitted successfully */ 200: boolean; }; export type TuiControlResponseResponse = TuiControlResponseResponses[keyof TuiControlResponseResponses]; export type AuthSetData = { body?: Auth; path: { providerID: string; }; query?: { directory?: string; }; url: '/auth/{providerID}'; }; export type AuthSetErrors = { /** * Bad request */ 400: BadRequestError; }; export type AuthSetError = AuthSetErrors[keyof AuthSetErrors]; export type AuthSetResponses = { /** * Successfully set authentication credentials */ 200: boolean; }; export type AuthSetResponse = AuthSetResponses[keyof AuthSetResponses]; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { appAgents, appLog, authSet, commandList, configGet, configProviders, configUpdate, eventSubscribe, fileList, fileRead, fileStatus, findFiles, findSymbols, findText, formatterStatus, globalDispose, globalEvent, globalHealth, instanceDispose, lspStatus, mcpAdd, mcpAuthAuthenticate, mcpAuthCallback, mcpAuthRemove, mcpAuthStart, mcpConnect, mcpDisconnect, mcpStatus, type Options, partDelete, partUpdate, pathGet, permissionList, permissionReply, permissionRespond, projectCurrent, projectList, projectUpdate, providerAuth, providerList, providerOauthAuthorize, providerOauthCallback, ptyConnect, ptyCreate, ptyGet, ptyList, ptyRemove, ptyUpdate, sessionAbort, sessionChildren, sessionCommand, sessionCreate, sessionDelete, sessionDiff, sessionFork, sessionGet, sessionInit, sessionList, sessionMessage, sessionMessages, sessionPrompt, sessionPromptAsync, sessionRevert, sessionShare, sessionShell, sessionStatus, sessionSummarize, sessionTodo, sessionUnrevert, sessionUnshare, sessionUpdate, toolIds, toolList, tuiAppendPrompt, tuiClearPrompt, tuiControlNext, tuiControlResponse, tuiExecuteCommand, tuiOpenHelp, tuiOpenModels, tuiOpenSessions, tuiOpenThemes, tuiPublish, tuiShowToast, tuiSubmitPrompt, vcsGet } from './sdk.gen'; export type { Agent, AgentConfig, AgentPart, AgentPartInput, ApiAuth, ApiError, AppAgentsData, AppAgentsResponse, AppAgentsResponses, AppLogData, AppLogError, AppLogErrors, AppLogResponse, AppLogResponses, AssistantMessage, Auth, AuthSetData, AuthSetError, AuthSetErrors, AuthSetResponse, AuthSetResponses, BadRequestError, ClientOptions, Command, CommandListData, CommandListResponse, CommandListResponses, CompactionPart, Config, ConfigGetData, ConfigGetResponse, ConfigGetResponses, ConfigProvidersData, ConfigProvidersResponse, ConfigProvidersResponses, ConfigUpdateData, ConfigUpdateError, ConfigUpdateErrors, ConfigUpdateResponse, ConfigUpdateResponses, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, File, FileContent, FileDiff, FileListData, FileListResponse, FileListResponses, FileNode, FilePart, FilePartInput, FilePartSource, FilePartSourceText, FileReadData, FileReadResponse, FileReadResponses, FileSource, FileStatusData, FileStatusResponse, FileStatusResponses, FindFilesData, FindFilesResponse, FindFilesResponses, FindSymbolsData, FindSymbolsResponse, FindSymbolsResponses, FindTextData, FindTextResponse, FindTextResponses, FormatterStatus, FormatterStatusData, FormatterStatusResponse, FormatterStatusResponses, GlobalDisposeData, GlobalDisposeResponse, GlobalDisposeResponses, GlobalEvent, GlobalEventData, GlobalEventResponse, GlobalEventResponses, GlobalHealthData, GlobalHealthResponse, GlobalHealthResponses, InstanceDisposeData, InstanceDisposeResponse, InstanceDisposeResponses, KeybindsConfig, LayoutConfig, LogLevel, LspStatus, LspStatusData, LspStatusResponse, LspStatusResponses, McpAddData, McpAddError, McpAddErrors, McpAddResponse, McpAddResponses, McpAuthAuthenticateData, McpAuthAuthenticateError, McpAuthAuthenticateErrors, McpAuthAuthenticateResponse, McpAuthAuthenticateResponses, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponse, McpAuthCallbackResponses, McpAuthRemoveData, McpAuthRemoveError, McpAuthRemoveErrors, McpAuthRemoveResponse, McpAuthRemoveResponses, McpAuthStartData, McpAuthStartError, McpAuthStartErrors, McpAuthStartResponse, McpAuthStartResponses, McpConnectData, McpConnectResponse, McpConnectResponses, McpDisconnectData, McpDisconnectResponse, McpDisconnectResponses, McpLocalConfig, McpOAuthConfig, McpRemoteConfig, McpStatus, McpStatusConnected, McpStatusData, McpStatusDisabled, McpStatusFailed, McpStatusNeedsAuth, McpStatusNeedsClientRegistration, McpStatusResponse, McpStatusResponses, Message, MessageAbortedError, MessageOutputLengthError, Model, NotFoundError, OAuth, Part, PartDeleteData, PartDeleteError, PartDeleteErrors, PartDeleteResponse, PartDeleteResponses, PartUpdateData, PartUpdateError, PartUpdateErrors, PartUpdateResponse, PartUpdateResponses, PatchPart, Path, PathGetData, PathGetResponse, PathGetResponses, PermissionAction, PermissionActionConfig, PermissionConfig, PermissionListData, PermissionListResponse, PermissionListResponses, PermissionObjectConfig, PermissionReplyData, PermissionReplyError, PermissionReplyErrors, PermissionReplyResponse, PermissionReplyResponses, PermissionRequest, PermissionRespondData, PermissionRespondError, PermissionRespondErrors, PermissionRespondResponse, PermissionRespondResponses, PermissionRule, PermissionRuleConfig, PermissionRuleset, Project, ProjectCurrentData, ProjectCurrentResponse, ProjectCurrentResponses, ProjectListData, ProjectListResponse, ProjectListResponses, ProjectUpdateData, ProjectUpdateError, ProjectUpdateErrors, ProjectUpdateResponse, ProjectUpdateResponses, Provider, ProviderAuthAuthorization, ProviderAuthData, ProviderAuthError, ProviderAuthMethod, ProviderAuthResponse, ProviderAuthResponses, ProviderConfig, ProviderListData, ProviderListResponse, ProviderListResponses, ProviderOauthAuthorizeData, ProviderOauthAuthorizeError, ProviderOauthAuthorizeErrors, ProviderOauthAuthorizeResponse, ProviderOauthAuthorizeResponses, ProviderOauthCallbackData, ProviderOauthCallbackError, ProviderOauthCallbackErrors, ProviderOauthCallbackResponse, ProviderOauthCallbackResponses, Pty, PtyConnectData, PtyConnectError, PtyConnectErrors, PtyConnectResponse, PtyConnectResponses, PtyCreateData, PtyCreateError, PtyCreateErrors, PtyCreateResponse, PtyCreateResponses, PtyGetData, PtyGetError, PtyGetErrors, PtyGetResponse, PtyGetResponses, PtyListData, PtyListResponse, PtyListResponses, PtyRemoveData, PtyRemoveError, PtyRemoveErrors, PtyRemoveResponse, PtyRemoveResponses, PtyUpdateData, PtyUpdateError, PtyUpdateErrors, PtyUpdateResponse, PtyUpdateResponses, Range, ReasoningPart, RetryPart, ServerConfig, Session, SessionAbortData, SessionAbortError, SessionAbortErrors, SessionAbortResponse, SessionAbortResponses, SessionChildrenData, SessionChildrenError, SessionChildrenErrors, SessionChildrenResponse, SessionChildrenResponses, SessionCommandData, SessionCommandError, SessionCommandErrors, SessionCommandResponse, SessionCommandResponses, SessionCreateData, SessionCreateError, SessionCreateErrors, SessionCreateResponse, SessionCreateResponses, SessionDeleteData, SessionDeleteError, SessionDeleteErrors, SessionDeleteResponse, SessionDeleteResponses, SessionDiffData, SessionDiffError, SessionDiffErrors, SessionDiffResponse, SessionDiffResponses, SessionForkData, SessionForkResponse, SessionForkResponses, SessionGetData, SessionGetError, SessionGetErrors, SessionGetResponse, SessionGetResponses, SessionInitData, SessionInitError, SessionInitErrors, SessionInitResponse, SessionInitResponses, SessionListData, SessionListResponse, SessionListResponses, SessionMessageData, SessionMessageError, SessionMessageErrors, SessionMessageResponse, SessionMessageResponses, SessionMessagesData, SessionMessagesError, SessionMessagesErrors, SessionMessagesResponse, SessionMessagesResponses, SessionPromptAsyncData, SessionPromptAsyncError, SessionPromptAsyncErrors, SessionPromptAsyncResponse, SessionPromptAsyncResponses, SessionPromptData, SessionPromptError, SessionPromptErrors, SessionPromptResponse, SessionPromptResponses, SessionRevertData, SessionRevertError, SessionRevertErrors, SessionRevertResponse, SessionRevertResponses, SessionShareData, SessionShareError, SessionShareErrors, SessionShareResponse, SessionShareResponses, SessionShellData, SessionShellError, SessionShellErrors, SessionShellResponse, SessionShellResponses, SessionStatus, SessionStatusData, SessionStatusError, SessionStatusErrors, SessionStatusResponse, SessionStatusResponses, SessionSummarizeData, SessionSummarizeError, SessionSummarizeErrors, SessionSummarizeResponse, SessionSummarizeResponses, SessionTodoData, SessionTodoError, SessionTodoErrors, SessionTodoResponse, SessionTodoResponses, SessionUnrevertData, SessionUnrevertError, SessionUnrevertErrors, SessionUnrevertResponse, SessionUnrevertResponses, SessionUnshareData, SessionUnshareError, SessionUnshareErrors, SessionUnshareResponse, SessionUnshareResponses, SessionUpdateData, SessionUpdateError, SessionUpdateErrors, SessionUpdateResponse, SessionUpdateResponses, SnapshotPart, StepFinishPart, StepStartPart, SubtaskPartInput, Symbol, SymbolSource, TextPart, TextPartInput, Todo, ToolIds, ToolIdsData, ToolIdsError, ToolIdsErrors, ToolIdsResponse, ToolIdsResponses, ToolList, ToolListData, ToolListError, ToolListErrors, ToolListItem, ToolListResponse, ToolListResponses, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, TuiAppendPromptData, TuiAppendPromptError, TuiAppendPromptErrors, TuiAppendPromptResponse, TuiAppendPromptResponses, TuiClearPromptData, TuiClearPromptResponse, TuiClearPromptResponses, TuiControlNextData, TuiControlNextResponse, TuiControlNextResponses, TuiControlResponseData, TuiControlResponseResponse, TuiControlResponseResponses, TuiExecuteCommandData, TuiExecuteCommandError, TuiExecuteCommandErrors, TuiExecuteCommandResponse, TuiExecuteCommandResponses, TuiOpenHelpData, TuiOpenHelpResponse, TuiOpenHelpResponses, TuiOpenModelsData, TuiOpenModelsResponse, TuiOpenModelsResponses, TuiOpenSessionsData, TuiOpenSessionsResponse, TuiOpenSessionsResponses, TuiOpenThemesData, TuiOpenThemesResponse, TuiOpenThemesResponses, TuiPublishData, TuiPublishError, TuiPublishErrors, TuiPublishResponse, TuiPublishResponses, TuiShowToastData, TuiShowToastResponse, TuiShowToastResponses, TuiSubmitPromptData, TuiSubmitPromptResponse, TuiSubmitPromptResponses, UnknownError, UserMessage, VcsGetData, VcsGetResponse, VcsGetResponses, VcsInfo, WellKnownAuth } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { buildClientParams, type Client, type Options as Options2, type TDataShape } from './client'; import { client } from './client.gen'; import type { AgentPartInput, AppAgentsResponses, AppLogErrors, AppLogResponses, Auth, AuthSetErrors, AuthSetResponses, CommandListResponses, Config, ConfigGetResponses, ConfigProvidersResponses, ConfigUpdateErrors, ConfigUpdateResponses, EventSubscribeResponses, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, FileListResponses, FilePartInput, FileReadResponses, FileStatusResponses, FindFilesResponses, FindSymbolsResponses, FindTextResponses, FormatterStatusResponses, GlobalDisposeResponses, GlobalEventResponses, GlobalHealthResponses, InstanceDisposeResponses, LspStatusResponses, McpAddErrors, McpAddResponses, McpAuthAuthenticateErrors, McpAuthAuthenticateResponses, McpAuthCallbackErrors, McpAuthCallbackResponses, McpAuthRemoveErrors, McpAuthRemoveResponses, McpAuthStartErrors, McpAuthStartResponses, McpConnectResponses, McpDisconnectResponses, McpLocalConfig, McpRemoteConfig, McpStatusResponses, Part, PartDeleteErrors, PartDeleteResponses, PartUpdateErrors, PartUpdateResponses, PathGetResponses, PermissionListResponses, PermissionReplyErrors, PermissionReplyResponses, PermissionRespondErrors, PermissionRespondResponses, PermissionRuleset, ProjectCurrentResponses, ProjectListResponses, ProjectUpdateErrors, ProjectUpdateResponses, ProviderAuthResponses, ProviderListResponses, ProviderOauthAuthorizeErrors, ProviderOauthAuthorizeResponses, ProviderOauthCallbackErrors, ProviderOauthCallbackResponses, PtyConnectErrors, PtyConnectResponses, PtyCreateErrors, PtyCreateResponses, PtyGetErrors, PtyGetResponses, PtyListResponses, PtyRemoveErrors, PtyRemoveResponses, PtyUpdateErrors, PtyUpdateResponses, SessionAbortErrors, SessionAbortResponses, SessionChildrenErrors, SessionChildrenResponses, SessionCommandErrors, SessionCommandResponses, SessionCreateErrors, SessionCreateResponses, SessionDeleteErrors, SessionDeleteResponses, SessionDiffErrors, SessionDiffResponses, SessionForkResponses, SessionGetErrors, SessionGetResponses, SessionInitErrors, SessionInitResponses, SessionListResponses, SessionMessageErrors, SessionMessageResponses, SessionMessagesErrors, SessionMessagesResponses, SessionPromptAsyncErrors, SessionPromptAsyncResponses, SessionPromptErrors, SessionPromptResponses, SessionRevertErrors, SessionRevertResponses, SessionShareErrors, SessionShareResponses, SessionShellErrors, SessionShellResponses, SessionStatusErrors, SessionStatusResponses, SessionSummarizeErrors, SessionSummarizeResponses, SessionTodoErrors, SessionTodoResponses, SessionUnrevertErrors, SessionUnrevertResponses, SessionUnshareErrors, SessionUnshareResponses, SessionUpdateErrors, SessionUpdateResponses, SubtaskPartInput, TextPartInput, ToolIdsErrors, ToolIdsResponses, ToolListErrors, ToolListResponses, TuiAppendPromptErrors, TuiAppendPromptResponses, TuiClearPromptResponses, TuiControlNextResponses, TuiControlResponseResponses, TuiExecuteCommandErrors, TuiExecuteCommandResponses, TuiOpenHelpResponses, TuiOpenModelsResponses, TuiOpenSessionsResponses, TuiOpenThemesResponses, TuiPublishErrors, TuiPublishResponses, TuiShowToastResponses, TuiSubmitPromptResponses, VcsGetResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Get health * * Get health information about the OpenCode server. */ export const globalHealth = (options?: Options) => (options?.client ?? client).get({ url: '/global/health', ...options }); /** * Get global events * * Subscribe to global events from the OpenCode system using server-sent events. */ export const globalEvent = (options?: Options) => (options?.client ?? client).sse.get({ url: '/global/event', ...options }); /** * Dispose instance * * Clean up and dispose all OpenCode instances, releasing all resources. */ export const globalDispose = (options?: Options) => (options?.client ?? client).post({ url: '/global/dispose', ...options }); /** * List all projects * * Get a list of projects that have been opened with OpenCode. */ export const projectList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/project', ...options, ...params }); }; /** * Get current project * * Retrieve the currently active project that OpenCode is working with. */ export const projectCurrent = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/project/current', ...options, ...params }); }; /** * Update project * * Update project properties such as name, icon and color. */ export const projectUpdate = (parameters: { projectID: string; directory?: string; name?: string; icon?: { url?: string; color?: string; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'projectID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'name' }, { in: 'body', key: 'icon' } ] }]); return (options?.client ?? client).patch({ url: '/project/{projectID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List PTY sessions * * Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode. */ export const ptyList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/pty', ...options, ...params }); }; /** * Create PTY session * * Create a new pseudo-terminal (PTY) session for running shell commands and processes. */ export const ptyCreate = (parameters?: { directory?: string; command?: string; args?: Array; cwd?: string; title?: string; env?: { [key: string]: string; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'command' }, { in: 'body', key: 'args' }, { in: 'body', key: 'cwd' }, { in: 'body', key: 'title' }, { in: 'body', key: 'env' } ] }]); return (options?.client ?? client).post({ url: '/pty', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Remove PTY session * * Remove and terminate a specific pseudo-terminal (PTY) session. */ export const ptyRemove = (parameters: { ptyID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/pty/{ptyID}', ...options, ...params }); }; /** * Get PTY session * * Retrieve detailed information about a specific pseudo-terminal (PTY) session. */ export const ptyGet = (parameters: { ptyID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/pty/{ptyID}', ...options, ...params }); }; /** * Update PTY session * * Update properties of an existing pseudo-terminal (PTY) session. */ export const ptyUpdate = (parameters: { ptyID: string; directory?: string; title?: string; size?: { rows: number; cols: number; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'title' }, { in: 'body', key: 'size' } ] }]); return (options?.client ?? client).put({ url: '/pty/{ptyID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Connect to PTY session * * Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time. */ export const ptyConnect = (parameters: { ptyID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'ptyID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/pty/{ptyID}/connect', ...options, ...params }); }; /** * Get configuration * * Retrieve the current OpenCode configuration settings and preferences. */ export const configGet = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/config', ...options, ...params }); }; /** * Update configuration * * Update OpenCode configuration settings and preferences. */ export const configUpdate = (parameters?: { directory?: string; config?: Config; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { key: 'config', map: 'body' }] }]); return (options?.client ?? client).patch({ url: '/config', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List tool IDs * * Get a list of all available tool IDs, including both built-in tools and dynamically registered tools. */ export const toolIds = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/experimental/tool/ids', ...options, ...params }); }; /** * List tools * * Get a list of available tools with their JSON schema parameters for a specific provider and model combination. */ export const toolList = (parameters: { directory?: string; provider: string; model: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'query', key: 'provider' }, { in: 'query', key: 'model' } ] }]); return (options?.client ?? client).get({ url: '/experimental/tool', ...options, ...params }); }; /** * Dispose instance * * Clean up and dispose the current OpenCode instance, releasing all resources. */ export const instanceDispose = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/instance/dispose', ...options, ...params }); }; /** * Get paths * * Retrieve the current working directory and related path information for the OpenCode instance. */ export const pathGet = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/path', ...options, ...params }); }; /** * Get VCS info * * Retrieve version control system (VCS) information for the current project, such as git branch. */ export const vcsGet = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/vcs', ...options, ...params }); }; /** * List sessions * * Get a list of all OpenCode sessions, sorted by most recently updated. */ export const sessionList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session', ...options, ...params }); }; /** * Create session * * Create a new OpenCode session for interacting with AI assistants and managing conversations. */ export const sessionCreate = (parameters?: { directory?: string; parentID?: string; title?: string; permission?: PermissionRuleset; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'parentID' }, { in: 'body', key: 'title' }, { in: 'body', key: 'permission' } ] }]); return (options?.client ?? client).post({ url: '/session', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get session status * * Retrieve the current status of all sessions, including active, idle, and completed states. */ export const sessionStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/status', ...options, ...params }); }; /** * Delete session * * Delete a session and permanently remove all associated data, including messages and history. */ export const sessionDelete = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/session/{sessionID}', ...options, ...params }); }; /** * Get session * * Retrieve detailed information about a specific OpenCode session. */ export const sessionGet = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}', ...options, ...params }); }; /** * Update session * * Update properties of an existing session, such as title or other metadata. */ export const sessionUpdate = (parameters: { sessionID: string; directory?: string; title?: string; time?: { archived?: number; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'title' }, { in: 'body', key: 'time' } ] }]); return (options?.client ?? client).patch({ url: '/session/{sessionID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get session children * * Retrieve all child sessions that were forked from the specified parent session. */ export const sessionChildren = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/children', ...options, ...params }); }; /** * Get session todos * * Retrieve the todo list associated with a specific session, showing tasks and action items. */ export const sessionTodo = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/todo', ...options, ...params }); }; /** * Initialize session * * Analyze the current application and create an AGENTS.md file with project-specific agent configurations. */ export const sessionInit = (parameters: { sessionID: string; directory?: string; modelID: string; providerID: string; messageID: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'modelID' }, { in: 'body', key: 'providerID' }, { in: 'body', key: 'messageID' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/init', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Fork session * * Create a new session by forking an existing session at a specific message point. */ export const sessionFork = (parameters: { sessionID: string; directory?: string; messageID?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/fork', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Abort session * * Abort an active session and stop any ongoing AI processing or command execution. */ export const sessionAbort = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/abort', ...options, ...params }); }; /** * Unshare session * * Remove the shareable link for a session, making it private again. */ export const sessionUnshare = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/session/{sessionID}/share', ...options, ...params }); }; /** * Share session * * Create a shareable link for a session, allowing others to view the conversation. */ export const sessionShare = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/share', ...options, ...params }); }; /** * Get session diff * * Get all file changes (diffs) made during this session. */ export const sessionDiff = (parameters: { sessionID: string; directory?: string; messageID?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'query', key: 'messageID' } ] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/diff', ...options, ...params }); }; /** * Summarize session * * Generate a concise summary of the session using AI compaction to preserve key information. */ export const sessionSummarize = (parameters: { sessionID: string; directory?: string; providerID: string; modelID: string; auto?: boolean; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'providerID' }, { in: 'body', key: 'modelID' }, { in: 'body', key: 'auto' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/summarize', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get session messages * * Retrieve all messages in a session, including user prompts and AI responses. */ export const sessionMessages = (parameters: { sessionID: string; directory?: string; limit?: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'query', key: 'limit' } ] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/message', ...options, ...params }); }; /** * Send message * * Create and send a new message to a session, streaming the AI response. */ export const sessionPrompt = (parameters: { sessionID: string; directory?: string; messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'model' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'noReply' }, { in: 'body', key: 'tools' }, { in: 'body', key: 'system' }, { in: 'body', key: 'variant' }, { in: 'body', key: 'parts' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/message', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get message * * Retrieve a specific message from a session by its message ID. */ export const sessionMessage = (parameters: { sessionID: string; messageID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'messageID' }, { in: 'query', key: 'directory' } ] }]); return (options?.client ?? client).get({ url: '/session/{sessionID}/message/{messageID}', ...options, ...params }); }; /** * Delete a part from a message */ export const partDelete = (parameters: { sessionID: string; messageID: string; partID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'messageID' }, { in: 'path', key: 'partID' }, { in: 'query', key: 'directory' } ] }]); return (options?.client ?? client).delete({ url: '/session/{sessionID}/message/{messageID}/part/{partID}', ...options, ...params }); }; /** * Update a part in a message */ export const partUpdate = (parameters: { sessionID: string; messageID: string; partID: string; directory?: string; part?: Part; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'messageID' }, { in: 'path', key: 'partID' }, { in: 'query', key: 'directory' }, { key: 'part', map: 'body' } ] }]); return (options?.client ?? client).patch({ url: '/session/{sessionID}/message/{messageID}/part/{partID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Send async message * * Create and send a new message to a session asynchronously, starting the session if needed and returning immediately. */ export const sessionPromptAsync = (parameters: { sessionID: string; directory?: string; messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'model' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'noReply' }, { in: 'body', key: 'tools' }, { in: 'body', key: 'system' }, { in: 'body', key: 'variant' }, { in: 'body', key: 'parts' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/prompt_async', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Send command * * Send a new command to a session for execution by the AI assistant. */ export const sessionCommand = (parameters: { sessionID: string; directory?: string; messageID?: string; agent?: string; model?: string; arguments: string; command: string; variant?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'model' }, { in: 'body', key: 'arguments' }, { in: 'body', key: 'command' }, { in: 'body', key: 'variant' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/command', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Run shell command * * Execute a shell command within the session context and return the AI's response. */ export const sessionShell = (parameters: { sessionID: string; directory?: string; agent: string; model?: { providerID: string; modelID: string; }; command: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'agent' }, { in: 'body', key: 'model' }, { in: 'body', key: 'command' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/shell', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Revert message * * Revert a specific message in a session, undoing its effects and restoring the previous state. */ export const sessionRevert = (parameters: { sessionID: string; directory?: string; messageID: string; partID?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'messageID' }, { in: 'body', key: 'partID' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/revert', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Restore reverted messages * * Restore all previously reverted messages in a session. */ export const sessionUnrevert = (parameters: { sessionID: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'sessionID' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/unrevert', ...options, ...params }); }; /** * Respond to permission * * Approve or deny a permission request from the AI assistant. * * @deprecated */ export const permissionRespond = (parameters: { sessionID: string; permissionID: string; directory?: string; response: 'once' | 'always' | 'reject'; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'sessionID' }, { in: 'path', key: 'permissionID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'response' } ] }]); return (options?.client ?? client).post({ url: '/session/{sessionID}/permissions/{permissionID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Respond to permission request * * Approve or deny a permission request from the AI assistant. */ export const permissionReply = (parameters: { requestID: string; directory?: string; reply: 'once' | 'always' | 'reject'; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'requestID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'reply' } ] }]); return (options?.client ?? client).post({ url: '/permission/{requestID}/reply', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List pending permissions * * Get all pending permission requests across all sessions. */ export const permissionList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/permission', ...options, ...params }); }; /** * List commands * * Get a list of all available commands in the OpenCode system. */ export const commandList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/command', ...options, ...params }); }; /** * List config providers * * Get a list of all configured AI providers and their default models. */ export const configProviders = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/config/providers', ...options, ...params }); }; /** * List providers * * Get a list of all available AI providers, including both available and connected ones. */ export const providerList = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/provider', ...options, ...params }); }; /** * Get provider auth methods * * Retrieve available authentication methods for all AI providers. */ export const providerAuth = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/provider/auth', ...options, ...params }); }; /** * OAuth authorize * * Initiate OAuth authorization for a specific AI provider to get an authorization URL. */ export const providerOauthAuthorize = (parameters: { providerID: string; directory?: string; method: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'providerID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'method' } ] }]); return (options?.client ?? client).post({ url: '/provider/{providerID}/oauth/authorize', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * OAuth callback * * Handle the OAuth callback from a provider after user authorization. */ export const providerOauthCallback = (parameters: { providerID: string; directory?: string; method: number; code?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'providerID' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'method' }, { in: 'body', key: 'code' } ] }]); return (options?.client ?? client).post({ url: '/provider/{providerID}/oauth/callback', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Find text * * Search for text patterns across files in the project using ripgrep. */ export const findText = (parameters: { directory?: string; pattern: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'pattern' }] }]); return (options?.client ?? client).get({ url: '/find', ...options, ...params }); }; /** * Find files * * Search for files or directories by name or pattern in the project directory. */ export const findFiles = (parameters: { directory?: string; query: string; dirs?: 'true' | 'false'; type?: 'file' | 'directory'; limit?: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'query', key: 'query' }, { in: 'query', key: 'dirs' }, { in: 'query', key: 'type' }, { in: 'query', key: 'limit' } ] }]); return (options?.client ?? client).get({ url: '/find/file', ...options, ...params }); }; /** * Find symbols * * Search for workspace symbols like functions, classes, and variables using LSP. */ export const findSymbols = (parameters: { directory?: string; query: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'query' }] }]); return (options?.client ?? client).get({ url: '/find/symbol', ...options, ...params }); }; /** * List files * * List files and directories in a specified path. */ export const fileList = (parameters: { directory?: string; path: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'path' }] }]); return (options?.client ?? client).get({ url: '/file', ...options, ...params }); }; /** * Read file * * Read the content of a specified file. */ export const fileRead = (parameters: { directory?: string; path: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'query', key: 'path' }] }]); return (options?.client ?? client).get({ url: '/file/content', ...options, ...params }); }; /** * Get file status * * Get the git status of all files in the project. */ export const fileStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/file/status', ...options, ...params }); }; /** * Write log * * Write a log entry to the server logs with specified level and metadata. */ export const appLog = (parameters: { directory?: string; service: string; level: 'debug' | 'info' | 'error' | 'warn'; message: string; extra?: { [key: string]: unknown; }; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'service' }, { in: 'body', key: 'level' }, { in: 'body', key: 'message' }, { in: 'body', key: 'extra' } ] }]); return (options?.client ?? client).post({ url: '/log', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * List agents * * Get a list of all available AI agents in the OpenCode system. */ export const appAgents = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/agent', ...options, ...params }); }; /** * Get MCP status * * Get the status of all Model Context Protocol (MCP) servers. */ export const mcpStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/mcp', ...options, ...params }); }; /** * Add MCP server * * Dynamically add a new Model Context Protocol (MCP) server to the system. */ export const mcpAdd = (parameters: { directory?: string; name: string; config: McpLocalConfig | McpRemoteConfig; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'name' }, { in: 'body', key: 'config' } ] }]); return (options?.client ?? client).post({ url: '/mcp', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Remove MCP OAuth * * Remove OAuth credentials for an MCP server */ export const mcpAuthRemove = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).delete({ url: '/mcp/{name}/auth', ...options, ...params }); }; /** * Start MCP OAuth * * Start OAuth authentication flow for a Model Context Protocol (MCP) server. */ export const mcpAuthStart = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/auth', ...options, ...params }); }; /** * Complete MCP OAuth * * Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code. */ export const mcpAuthCallback = (parameters: { name: string; directory?: string; code: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'name' }, { in: 'query', key: 'directory' }, { in: 'body', key: 'code' } ] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/auth/callback', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Authenticate MCP OAuth * * Start OAuth flow and wait for callback (opens browser) */ export const mcpAuthAuthenticate = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/auth/authenticate', ...options, ...params }); }; /** * Connect an MCP server */ export const mcpConnect = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/connect', ...options, ...params }); }; /** * Disconnect an MCP server */ export const mcpDisconnect = (parameters: { name: string; directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'name' }, { in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/mcp/{name}/disconnect', ...options, ...params }); }; /** * Get LSP status * * Get LSP server status */ export const lspStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/lsp', ...options, ...params }); }; /** * Get formatter status * * Get formatter status */ export const formatterStatus = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/formatter', ...options, ...params }); }; /** * Append TUI prompt * * Append prompt to the TUI */ export const tuiAppendPrompt = (parameters: { directory?: string; text: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'body', key: 'text' }] }]); return (options?.client ?? client).post({ url: '/tui/append-prompt', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Open help dialog * * Open the help dialog in the TUI to display user assistance information. */ export const tuiOpenHelp = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-help', ...options, ...params }); }; /** * Open sessions dialog * * Open the session dialog */ export const tuiOpenSessions = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-sessions', ...options, ...params }); }; /** * Open themes dialog * * Open the theme dialog */ export const tuiOpenThemes = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-themes', ...options, ...params }); }; /** * Open models dialog * * Open the model dialog */ export const tuiOpenModels = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/open-models', ...options, ...params }); }; /** * Submit TUI prompt * * Submit the prompt */ export const tuiSubmitPrompt = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/submit-prompt', ...options, ...params }); }; /** * Clear TUI prompt * * Clear the prompt */ export const tuiClearPrompt = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).post({ url: '/tui/clear-prompt', ...options, ...params }); }; /** * Execute TUI command * * Execute a TUI command (e.g. agent_cycle) */ export const tuiExecuteCommand = (parameters: { directory?: string; command: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { in: 'body', key: 'command' }] }]); return (options?.client ?? client).post({ url: '/tui/execute-command', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Show TUI toast * * Show a toast notification in the TUI */ export const tuiShowToast = (parameters: { directory?: string; title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; duration?: number; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'query', key: 'directory' }, { in: 'body', key: 'title' }, { in: 'body', key: 'message' }, { in: 'body', key: 'variant' }, { in: 'body', key: 'duration' } ] }]); return (options?.client ?? client).post({ url: '/tui/show-toast', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Publish TUI event * * Publish a TUI event */ export const tuiPublish = (parameters?: { directory?: string; body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { key: 'body', map: 'body' }] }]); return (options?.client ?? client).post({ url: '/tui/publish', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Get next TUI request * * Retrieve the next TUI (Terminal User Interface) request from the queue for processing. */ export const tuiControlNext = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).get({ url: '/tui/control/next', ...options, ...params }); }; /** * Submit TUI response * * Submit a response to the TUI request queue to complete a pending request. */ export const tuiControlResponse = (parameters?: { directory?: string; body?: unknown; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }, { key: 'body', map: 'body' }] }]); return (options?.client ?? client).post({ url: '/tui/control/response', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Set auth credentials * * Set authentication credentials */ export const authSet = (parameters: { providerID: string; directory?: string; auth?: Auth; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [ { in: 'path', key: 'providerID' }, { in: 'query', key: 'directory' }, { key: 'auth', map: 'body' } ] }]); return (options?.client ?? client).put({ url: '/auth/{providerID}', ...options, ...params, headers: { 'Content-Type': 'application/json', ...options?.headers, ...params.headers } }); }; /** * Subscribe to events * * Get events */ export const eventSubscribe = (parameters?: { directory?: string; }, options?: Options) => { const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'directory' }] }]); return (options?.client ?? client).sse.get({ url: '/event', ...options, ...params }); }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/flat/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSource = FileSource | SymbolSource; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type GlobalEvent = { directory: string; payload: Event; }; export type BadRequestError = { data: unknown; errors: Array<{ [key: string]: unknown; }>; success: false; }; export type NotFoundError = { name: 'NotFoundError'; data: { message: string; }; }; /** * Custom keybind configurations */ export type KeybindsConfig = { /** * Leader key for keybind combinations */ leader?: string; /** * Exit the application */ app_exit?: string; /** * Open external editor */ editor_open?: string; /** * List available themes */ theme_list?: string; /** * Toggle sidebar */ sidebar_toggle?: string; /** * Toggle session scrollbar */ scrollbar_toggle?: string; /** * Toggle username visibility */ username_toggle?: string; /** * View status */ status_view?: string; /** * Export session to editor */ session_export?: string; /** * Create a new session */ session_new?: string; /** * List all sessions */ session_list?: string; /** * Show session timeline */ session_timeline?: string; /** * Fork session from message */ session_fork?: string; /** * Rename session */ session_rename?: string; /** * Share current session */ session_share?: string; /** * Unshare current session */ session_unshare?: string; /** * Interrupt current session */ session_interrupt?: string; /** * Compact the session */ session_compact?: string; /** * Scroll messages up by one page */ messages_page_up?: string; /** * Scroll messages down by one page */ messages_page_down?: string; /** * Scroll messages up by half page */ messages_half_page_up?: string; /** * Scroll messages down by half page */ messages_half_page_down?: string; /** * Navigate to first message */ messages_first?: string; /** * Navigate to last message */ messages_last?: string; /** * Navigate to next message */ messages_next?: string; /** * Navigate to previous message */ messages_previous?: string; /** * Navigate to last user message */ messages_last_user?: string; /** * Copy message */ messages_copy?: string; /** * Undo message */ messages_undo?: string; /** * Redo message */ messages_redo?: string; /** * Toggle code block concealment in messages */ messages_toggle_conceal?: string; /** * Toggle tool details visibility */ tool_details?: string; /** * List available models */ model_list?: string; /** * Next recently used model */ model_cycle_recent?: string; /** * Previous recently used model */ model_cycle_recent_reverse?: string; /** * Next favorite model */ model_cycle_favorite?: string; /** * Previous favorite model */ model_cycle_favorite_reverse?: string; /** * List available commands */ command_list?: string; /** * List agents */ agent_list?: string; /** * Next agent */ agent_cycle?: string; /** * Previous agent */ agent_cycle_reverse?: string; /** * Cycle model variants */ variant_cycle?: string; /** * Clear input field */ input_clear?: string; /** * Paste from clipboard */ input_paste?: string; /** * Submit input */ input_submit?: string; /** * Insert newline in input */ input_newline?: string; /** * Move cursor left in input */ input_move_left?: string; /** * Move cursor right in input */ input_move_right?: string; /** * Move cursor up in input */ input_move_up?: string; /** * Move cursor down in input */ input_move_down?: string; /** * Select left in input */ input_select_left?: string; /** * Select right in input */ input_select_right?: string; /** * Select up in input */ input_select_up?: string; /** * Select down in input */ input_select_down?: string; /** * Move to start of line in input */ input_line_home?: string; /** * Move to end of line in input */ input_line_end?: string; /** * Select to start of line in input */ input_select_line_home?: string; /** * Select to end of line in input */ input_select_line_end?: string; /** * Move to start of visual line in input */ input_visual_line_home?: string; /** * Move to end of visual line in input */ input_visual_line_end?: string; /** * Select to start of visual line in input */ input_select_visual_line_home?: string; /** * Select to end of visual line in input */ input_select_visual_line_end?: string; /** * Move to start of buffer in input */ input_buffer_home?: string; /** * Move to end of buffer in input */ input_buffer_end?: string; /** * Select to start of buffer in input */ input_select_buffer_home?: string; /** * Select to end of buffer in input */ input_select_buffer_end?: string; /** * Delete line in input */ input_delete_line?: string; /** * Delete to end of line in input */ input_delete_to_line_end?: string; /** * Delete to start of line in input */ input_delete_to_line_start?: string; /** * Backspace in input */ input_backspace?: string; /** * Delete character in input */ input_delete?: string; /** * Undo in input */ input_undo?: string; /** * Redo in input */ input_redo?: string; /** * Move word forward in input */ input_word_forward?: string; /** * Move word backward in input */ input_word_backward?: string; /** * Select word forward in input */ input_select_word_forward?: string; /** * Select word backward in input */ input_select_word_backward?: string; /** * Delete word forward in input */ input_delete_word_forward?: string; /** * Delete word backward in input */ input_delete_word_backward?: string; /** * Previous history item */ history_previous?: string; /** * Next history item */ history_next?: string; /** * Next child session */ session_child_cycle?: string; /** * Previous child session */ session_child_cycle_reverse?: string; /** * Go to parent session */ session_parent?: string; /** * Suspend terminal */ terminal_suspend?: string; /** * Toggle terminal title */ terminal_title_toggle?: string; /** * Toggle tips on home screen */ tips_toggle?: string; }; /** * Log level */ export type LogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'; /** * Server configuration for opencode serve and web commands */ export type ServerConfig = { /** * Port to listen on */ port?: number; /** * Hostname to listen on */ hostname?: string; /** * Enable mDNS service discovery */ mdns?: boolean; /** * Additional domains to allow for CORS */ cors?: Array; }; export type PermissionActionConfig = 'ask' | 'allow' | 'deny'; export type PermissionObjectConfig = { [key: string]: PermissionActionConfig; }; export type PermissionRuleConfig = PermissionActionConfig | PermissionObjectConfig; export type PermissionConfig = { read?: PermissionRuleConfig; edit?: PermissionRuleConfig; glob?: PermissionRuleConfig; grep?: PermissionRuleConfig; list?: PermissionRuleConfig; bash?: PermissionRuleConfig; task?: PermissionRuleConfig; external_directory?: PermissionRuleConfig; todowrite?: PermissionActionConfig; todoread?: PermissionActionConfig; webfetch?: PermissionActionConfig; websearch?: PermissionActionConfig; codesearch?: PermissionActionConfig; lsp?: PermissionRuleConfig; doom_loop?: PermissionActionConfig; [key: string]: PermissionRuleConfig | PermissionActionConfig | undefined; } | PermissionActionConfig; export type AgentConfig = { model?: string; temperature?: number; top_p?: number; prompt?: string; /** * @deprecated Use 'permission' field instead */ tools?: { [key: string]: boolean; }; disable?: boolean; /** * Description of when to use the agent */ description?: string; mode?: 'subagent' | 'primary' | 'all'; options?: { [key: string]: unknown; }; /** * Hex color code for the agent (e.g., #FF5733) */ color?: string; /** * Maximum number of agentic iterations before forcing text-only response */ steps?: number; /** * @deprecated Use 'steps' field instead. */ maxSteps?: number; permission?: PermissionConfig; [key: string]: unknown; }; export type ProviderConfig = { api?: string; name?: string; env?: Array; id?: string; npm?: string; models?: { [key: string]: { id?: string; name?: string; family?: string; release_date?: string; attachment?: boolean; reasoning?: boolean; temperature?: boolean; tool_call?: boolean; interleaved?: true | { field: 'reasoning_content' | 'reasoning_details'; }; cost?: { input: number; output: number; cache_read?: number; cache_write?: number; context_over_200k?: { input: number; output: number; cache_read?: number; cache_write?: number; }; }; limit?: { context: number; output: number; }; modalities?: { input: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; output: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; }; experimental?: boolean; status?: 'alpha' | 'beta' | 'deprecated'; options?: { [key: string]: unknown; }; headers?: { [key: string]: string; }; provider?: { npm: string; }; /** * Variant-specific configuration */ variants?: { [key: string]: { /** * Disable this variant for the model */ disabled?: boolean; [key: string]: unknown; }; }; }; }; whitelist?: Array; blacklist?: Array; options?: { apiKey?: string; baseURL?: string; /** * GitHub Enterprise URL for copilot authentication */ enterpriseUrl?: string; /** * Enable promptCacheKey for this provider (default false) */ setCacheKey?: boolean; /** * Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout. */ timeout?: number | false; [key: string]: unknown; }; }; export type McpLocalConfig = { /** * Type of MCP server connection */ type: 'local'; /** * Command and arguments to run the MCP server */ command: Array; /** * Environment variables to set when running the MCP server */ environment?: { [key: string]: string; }; /** * Enable or disable the MCP server on startup */ enabled?: boolean; /** * Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. */ timeout?: number; }; export type McpOAuthConfig = { /** * OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted. */ clientId?: string; /** * OAuth client secret (if required by the authorization server) */ clientSecret?: string; /** * OAuth scopes to request during authorization */ scope?: string; }; export type McpRemoteConfig = { /** * Type of MCP server connection */ type: 'remote'; /** * URL of the remote MCP server */ url: string; /** * Enable or disable the MCP server on startup */ enabled?: boolean; /** * Headers to send with the request */ headers?: { [key: string]: string; }; /** * OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection. */ oauth?: McpOAuthConfig | false; /** * Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. */ timeout?: number; }; /** * @deprecated Always uses stretch layout. */ export type LayoutConfig = 'auto' | 'stretch'; export type Config = { /** * JSON schema reference for configuration validation */ $schema?: string; /** * Theme name to use for the interface */ theme?: string; keybinds?: KeybindsConfig; logLevel?: LogLevel; /** * TUI specific settings */ tui?: { /** * TUI scroll speed */ scroll_speed?: number; /** * Scroll acceleration settings */ scroll_acceleration?: { /** * Enable scroll acceleration */ enabled: boolean; }; /** * Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column */ diff_style?: 'auto' | 'stacked'; }; server?: ServerConfig; /** * Command configuration, see https://opencode.ai/docs/commands */ command?: { [key: string]: { template: string; description?: string; agent?: string; model?: string; subtask?: boolean; }; }; watcher?: { ignore?: Array; }; plugin?: Array; snapshot?: boolean; /** * Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing */ share?: 'manual' | 'auto' | 'disabled'; /** * @deprecated Use 'share' field instead. Share newly created sessions automatically */ autoshare?: boolean; /** * Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications */ autoupdate?: boolean | 'notify'; /** * Disable providers that are loaded automatically */ disabled_providers?: Array; /** * When set, ONLY these providers will be enabled. All other providers will be ignored */ enabled_providers?: Array; /** * Model to use in the format of provider/model, eg anthropic/claude-2 */ model?: string; /** * Small model to use for tasks like title generation in the format of provider/model */ small_model?: string; /** * Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid. */ default_agent?: string; /** * Custom username to display in conversations instead of system username */ username?: string; /** * @deprecated Use `agent` field instead. */ mode?: { build?: AgentConfig; plan?: AgentConfig; [key: string]: AgentConfig | undefined; }; /** * Agent configuration, see https://opencode.ai/docs/agent */ agent?: { plan?: AgentConfig; build?: AgentConfig; general?: AgentConfig; explore?: AgentConfig; title?: AgentConfig; summary?: AgentConfig; compaction?: AgentConfig; [key: string]: AgentConfig | undefined; }; /** * Custom provider configurations and model overrides */ provider?: { [key: string]: ProviderConfig; }; /** * MCP (Model Context Protocol) server configurations */ mcp?: { [key: string]: McpLocalConfig | McpRemoteConfig; }; formatter?: false | { [key: string]: { disabled?: boolean; command?: Array; environment?: { [key: string]: string; }; extensions?: Array; }; }; lsp?: false | { [key: string]: { disabled: true; } | { command: Array; extensions?: Array; disabled?: boolean; env?: { [key: string]: string; }; initialization?: { [key: string]: unknown; }; }; }; /** * Additional instruction files or patterns to include */ instructions?: Array; layout?: LayoutConfig; permission?: PermissionConfig; tools?: { [key: string]: boolean; }; enterprise?: { /** * Enterprise URL */ url?: string; }; compaction?: { /** * Enable automatic compaction when context is full (default: true) */ auto?: boolean; /** * Enable pruning of old tool outputs (default: true) */ prune?: boolean; }; experimental?: { hook?: { file_edited?: { [key: string]: Array<{ command: Array; environment?: { [key: string]: string; }; }>; }; session_completed?: Array<{ command: Array; environment?: { [key: string]: string; }; }>; }; /** * Number of retries for chat completions on failure */ chatMaxRetries?: number; disable_paste_summary?: boolean; /** * Enable the batch tool */ batch_tool?: boolean; /** * Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag) */ openTelemetry?: boolean; /** * Tools that should only be available to primary agents. */ primary_tools?: Array; /** * Continue the agent loop when a tool call is denied */ continue_loop_on_deny?: boolean; /** * Timeout in milliseconds for model context protocol (MCP) requests */ mcp_timeout?: number; }; }; export type ToolIds = Array; export type ToolListItem = { id: string; description: string; parameters: unknown; }; export type ToolList = Array; export type Path = { home: string; state: string; config: string; worktree: string; directory: string; }; export type VcsInfo = { branch: string; }; export type TextPartInput = { id?: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type FilePartInput = { id?: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type AgentPartInput = { id?: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type SubtaskPartInput = { id?: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; }; export type Command = { name: string; description?: string; agent?: string; model?: string; mcp?: boolean; template: string; subtask?: boolean; hints: Array; }; export type Model = { id: string; providerID: string; api: { id: string; url: string; npm: string; }; name: string; family?: string; capabilities: { temperature: boolean; reasoning: boolean; attachment: boolean; toolcall: boolean; input: { text: boolean; audio: boolean; image: boolean; video: boolean; pdf: boolean; }; output: { text: boolean; audio: boolean; image: boolean; video: boolean; pdf: boolean; }; interleaved: boolean | { field: 'reasoning_content' | 'reasoning_details'; }; }; cost: { input: number; output: number; cache: { read: number; write: number; }; experimentalOver200K?: { input: number; output: number; cache: { read: number; write: number; }; }; }; limit: { context: number; output: number; }; status: 'alpha' | 'beta' | 'deprecated' | 'active'; options: { [key: string]: unknown; }; headers: { [key: string]: string; }; release_date: string; variants?: { [key: string]: { [key: string]: unknown; }; }; }; export type Provider = { id: string; name: string; source: 'env' | 'config' | 'custom' | 'api'; env: Array; key?: string; options: { [key: string]: unknown; }; models: { [key: string]: Model; }; }; export type ProviderAuthMethod = { type: 'oauth' | 'api'; label: string; }; export type ProviderAuthAuthorization = { url: string; method: 'auto' | 'code'; instructions: string; }; export type Symbol = { name: string; kind: number; location: { uri: string; range: Range; }; }; export type FileNode = { name: string; path: string; absolute: string; type: 'file' | 'directory'; ignored: boolean; }; export type FileContent = { type: 'text'; content: string; diff?: string; patch?: { oldFileName: string; newFileName: string; oldHeader?: string; newHeader?: string; hunks: Array<{ oldStart: number; oldLines: number; newStart: number; newLines: number; lines: Array; }>; index?: string; }; encoding?: 'base64'; mimeType?: string; }; export type File = { path: string; added: number; removed: number; status: 'added' | 'deleted' | 'modified'; }; export type Agent = { name: string; description?: string; mode: 'subagent' | 'primary' | 'all'; native?: boolean; hidden?: boolean; topP?: number; temperature?: number; color?: string; permission: PermissionRuleset; model?: { modelID: string; providerID: string; }; prompt?: string; options: { [key: string]: unknown; }; steps?: number; }; export type McpStatusConnected = { status: 'connected'; }; export type McpStatusDisabled = { status: 'disabled'; }; export type McpStatusFailed = { status: 'failed'; error: string; }; export type McpStatusNeedsAuth = { status: 'needs_auth'; }; export type McpStatusNeedsClientRegistration = { status: 'needs_client_registration'; error: string; }; export type McpStatus = McpStatusConnected | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth | McpStatusNeedsClientRegistration; export type LspStatus = { id: string; name: string; root: string; status: 'connected' | 'error'; }; export type FormatterStatus = { name: string; extensions: Array; enabled: boolean; }; export type OAuth = { type: 'oauth'; refresh: string; access: string; expires: number; enterpriseUrl?: string; }; export type ApiAuth = { type: 'api'; key: string; }; export type WellKnownAuth = { type: 'wellknown'; key: string; token: string; }; export type Auth = OAuth | ApiAuth | WellKnownAuth; export type GlobalHealthData = { body?: never; path?: never; query?: never; url: '/global/health'; }; export type GlobalHealthResponses = { /** * Health information */ 200: { healthy: true; version: string; }; }; export type GlobalHealthResponse = GlobalHealthResponses[keyof GlobalHealthResponses]; export type GlobalEventData = { body?: never; path?: never; query?: never; url: '/global/event'; }; export type GlobalEventResponses = { /** * Event stream */ 200: GlobalEvent; }; export type GlobalEventResponse = GlobalEventResponses[keyof GlobalEventResponses]; export type GlobalDisposeData = { body?: never; path?: never; query?: never; url: '/global/dispose'; }; export type GlobalDisposeResponses = { /** * Global disposed */ 200: boolean; }; export type GlobalDisposeResponse = GlobalDisposeResponses[keyof GlobalDisposeResponses]; export type ProjectListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/project'; }; export type ProjectListResponses = { /** * List of projects */ 200: Array; }; export type ProjectListResponse = ProjectListResponses[keyof ProjectListResponses]; export type ProjectCurrentData = { body?: never; path?: never; query?: { directory?: string; }; url: '/project/current'; }; export type ProjectCurrentResponses = { /** * Current project information */ 200: Project; }; export type ProjectCurrentResponse = ProjectCurrentResponses[keyof ProjectCurrentResponses]; export type ProjectUpdateData = { body?: { name?: string; icon?: { url?: string; color?: string; }; }; path: { projectID: string; }; query?: { directory?: string; }; url: '/project/{projectID}'; }; export type ProjectUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type ProjectUpdateError = ProjectUpdateErrors[keyof ProjectUpdateErrors]; export type ProjectUpdateResponses = { /** * Updated project information */ 200: Project; }; export type ProjectUpdateResponse = ProjectUpdateResponses[keyof ProjectUpdateResponses]; export type PtyListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/pty'; }; export type PtyListResponses = { /** * List of sessions */ 200: Array; }; export type PtyListResponse = PtyListResponses[keyof PtyListResponses]; export type PtyCreateData = { body?: { command?: string; args?: Array; cwd?: string; title?: string; env?: { [key: string]: string; }; }; path?: never; query?: { directory?: string; }; url: '/pty'; }; export type PtyCreateErrors = { /** * Bad request */ 400: BadRequestError; }; export type PtyCreateError = PtyCreateErrors[keyof PtyCreateErrors]; export type PtyCreateResponses = { /** * Created session */ 200: Pty; }; export type PtyCreateResponse = PtyCreateResponses[keyof PtyCreateResponses]; export type PtyRemoveData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyRemoveErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyRemoveError = PtyRemoveErrors[keyof PtyRemoveErrors]; export type PtyRemoveResponses = { /** * Session removed */ 200: boolean; }; export type PtyRemoveResponse = PtyRemoveResponses[keyof PtyRemoveResponses]; export type PtyGetData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyGetErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyGetError = PtyGetErrors[keyof PtyGetErrors]; export type PtyGetResponses = { /** * Session info */ 200: Pty; }; export type PtyGetResponse = PtyGetResponses[keyof PtyGetResponses]; export type PtyUpdateData = { body?: { title?: string; size?: { rows: number; cols: number; }; }; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyUpdateErrors = { /** * Bad request */ 400: BadRequestError; }; export type PtyUpdateError = PtyUpdateErrors[keyof PtyUpdateErrors]; export type PtyUpdateResponses = { /** * Updated session */ 200: Pty; }; export type PtyUpdateResponse = PtyUpdateResponses[keyof PtyUpdateResponses]; export type PtyConnectData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}/connect'; }; export type PtyConnectErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyConnectError = PtyConnectErrors[keyof PtyConnectErrors]; export type PtyConnectResponses = { /** * Connected session */ 200: boolean; }; export type PtyConnectResponse = PtyConnectResponses[keyof PtyConnectResponses]; export type ConfigGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/config'; }; export type ConfigGetResponses = { /** * Get config info */ 200: Config; }; export type ConfigGetResponse = ConfigGetResponses[keyof ConfigGetResponses]; export type ConfigUpdateData = { body?: Config; path?: never; query?: { directory?: string; }; url: '/config'; }; export type ConfigUpdateErrors = { /** * Bad request */ 400: BadRequestError; }; export type ConfigUpdateError = ConfigUpdateErrors[keyof ConfigUpdateErrors]; export type ConfigUpdateResponses = { /** * Successfully updated config */ 200: Config; }; export type ConfigUpdateResponse = ConfigUpdateResponses[keyof ConfigUpdateResponses]; export type ToolIdsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/experimental/tool/ids'; }; export type ToolIdsErrors = { /** * Bad request */ 400: BadRequestError; }; export type ToolIdsError = ToolIdsErrors[keyof ToolIdsErrors]; export type ToolIdsResponses = { /** * Tool IDs */ 200: ToolIds; }; export type ToolIdsResponse = ToolIdsResponses[keyof ToolIdsResponses]; export type ToolListData = { body?: never; path?: never; query: { directory?: string; provider: string; model: string; }; url: '/experimental/tool'; }; export type ToolListErrors = { /** * Bad request */ 400: BadRequestError; }; export type ToolListError = ToolListErrors[keyof ToolListErrors]; export type ToolListResponses = { /** * Tools */ 200: ToolList; }; export type ToolListResponse = ToolListResponses[keyof ToolListResponses]; export type InstanceDisposeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/instance/dispose'; }; export type InstanceDisposeResponses = { /** * Instance disposed */ 200: boolean; }; export type InstanceDisposeResponse = InstanceDisposeResponses[keyof InstanceDisposeResponses]; export type PathGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/path'; }; export type PathGetResponses = { /** * Path */ 200: Path; }; export type PathGetResponse = PathGetResponses[keyof PathGetResponses]; export type VcsGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/vcs'; }; export type VcsGetResponses = { /** * VCS info */ 200: VcsInfo; }; export type VcsGetResponse = VcsGetResponses[keyof VcsGetResponses]; export type SessionListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/session'; }; export type SessionListResponses = { /** * List of sessions */ 200: Array; }; export type SessionListResponse = SessionListResponses[keyof SessionListResponses]; export type SessionCreateData = { body?: { parentID?: string; title?: string; permission?: PermissionRuleset; }; path?: never; query?: { directory?: string; }; url: '/session'; }; export type SessionCreateErrors = { /** * Bad request */ 400: BadRequestError; }; export type SessionCreateError = SessionCreateErrors[keyof SessionCreateErrors]; export type SessionCreateResponses = { /** * Successfully created session */ 200: Session; }; export type SessionCreateResponse = SessionCreateResponses[keyof SessionCreateResponses]; export type SessionStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/session/status'; }; export type SessionStatusErrors = { /** * Bad request */ 400: BadRequestError; }; export type SessionStatusError = SessionStatusErrors[keyof SessionStatusErrors]; export type SessionStatusResponses = { /** * Get session status */ 200: { [key: string]: SessionStatus; }; }; export type SessionStatusResponse = SessionStatusResponses[keyof SessionStatusResponses]; export type SessionDeleteData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionDeleteErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionDeleteError = SessionDeleteErrors[keyof SessionDeleteErrors]; export type SessionDeleteResponses = { /** * Successfully deleted session */ 200: boolean; }; export type SessionDeleteResponse = SessionDeleteResponses[keyof SessionDeleteResponses]; export type SessionGetData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionGetErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionGetError = SessionGetErrors[keyof SessionGetErrors]; export type SessionGetResponses = { /** * Get session */ 200: Session; }; export type SessionGetResponse = SessionGetResponses[keyof SessionGetResponses]; export type SessionUpdateData = { body?: { title?: string; time?: { archived?: number; }; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUpdateError = SessionUpdateErrors[keyof SessionUpdateErrors]; export type SessionUpdateResponses = { /** * Successfully updated session */ 200: Session; }; export type SessionUpdateResponse = SessionUpdateResponses[keyof SessionUpdateResponses]; export type SessionChildrenData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/children'; }; export type SessionChildrenErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionChildrenError = SessionChildrenErrors[keyof SessionChildrenErrors]; export type SessionChildrenResponses = { /** * List of children */ 200: Array; }; export type SessionChildrenResponse = SessionChildrenResponses[keyof SessionChildrenResponses]; export type SessionTodoData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/todo'; }; export type SessionTodoErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionTodoError = SessionTodoErrors[keyof SessionTodoErrors]; export type SessionTodoResponses = { /** * Todo list */ 200: Array; }; export type SessionTodoResponse = SessionTodoResponses[keyof SessionTodoResponses]; export type SessionInitData = { body?: { modelID: string; providerID: string; messageID: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/init'; }; export type SessionInitErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionInitError = SessionInitErrors[keyof SessionInitErrors]; export type SessionInitResponses = { /** * 200 */ 200: boolean; }; export type SessionInitResponse = SessionInitResponses[keyof SessionInitResponses]; export type SessionForkData = { body?: { messageID?: string; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/fork'; }; export type SessionForkResponses = { /** * 200 */ 200: Session; }; export type SessionForkResponse = SessionForkResponses[keyof SessionForkResponses]; export type SessionAbortData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/abort'; }; export type SessionAbortErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionAbortError = SessionAbortErrors[keyof SessionAbortErrors]; export type SessionAbortResponses = { /** * Aborted session */ 200: boolean; }; export type SessionAbortResponse = SessionAbortResponses[keyof SessionAbortResponses]; export type SessionUnshareData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/share'; }; export type SessionUnshareErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUnshareError = SessionUnshareErrors[keyof SessionUnshareErrors]; export type SessionUnshareResponses = { /** * Successfully unshared session */ 200: Session; }; export type SessionUnshareResponse = SessionUnshareResponses[keyof SessionUnshareResponses]; export type SessionShareData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/share'; }; export type SessionShareErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionShareError = SessionShareErrors[keyof SessionShareErrors]; export type SessionShareResponses = { /** * Successfully shared session */ 200: Session; }; export type SessionShareResponse = SessionShareResponses[keyof SessionShareResponses]; export type SessionDiffData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; messageID?: string; }; url: '/session/{sessionID}/diff'; }; export type SessionDiffErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionDiffError = SessionDiffErrors[keyof SessionDiffErrors]; export type SessionDiffResponses = { /** * List of diffs */ 200: Array; }; export type SessionDiffResponse = SessionDiffResponses[keyof SessionDiffResponses]; export type SessionSummarizeData = { body?: { providerID: string; modelID: string; auto?: boolean; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/summarize'; }; export type SessionSummarizeErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionSummarizeError = SessionSummarizeErrors[keyof SessionSummarizeErrors]; export type SessionSummarizeResponses = { /** * Summarized session */ 200: boolean; }; export type SessionSummarizeResponse = SessionSummarizeResponses[keyof SessionSummarizeResponses]; export type SessionMessagesData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; limit?: number; }; url: '/session/{sessionID}/message'; }; export type SessionMessagesErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionMessagesError = SessionMessagesErrors[keyof SessionMessagesErrors]; export type SessionMessagesResponses = { /** * List of messages */ 200: Array<{ info: Message; parts: Array; }>; }; export type SessionMessagesResponse = SessionMessagesResponses[keyof SessionMessagesResponses]; export type SessionPromptData = { body?: { messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; /** * @deprecated tools and permissions have been merged, you can set permissions on the session itself now */ tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message'; }; export type SessionPromptErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionPromptError = SessionPromptErrors[keyof SessionPromptErrors]; export type SessionPromptResponses = { /** * Created message */ 200: { info: AssistantMessage; parts: Array; }; }; export type SessionPromptResponse = SessionPromptResponses[keyof SessionPromptResponses]; export type SessionMessageData = { body?: never; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}'; }; export type SessionMessageErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionMessageError = SessionMessageErrors[keyof SessionMessageErrors]; export type SessionMessageResponses = { /** * Message */ 200: { info: Message; parts: Array; }; }; export type SessionMessageResponse = SessionMessageResponses[keyof SessionMessageResponses]; export type PartDeleteData = { body?: never; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; /** * Part ID */ partID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}/part/{partID}'; }; export type PartDeleteErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PartDeleteError = PartDeleteErrors[keyof PartDeleteErrors]; export type PartDeleteResponses = { /** * Successfully deleted part */ 200: boolean; }; export type PartDeleteResponse = PartDeleteResponses[keyof PartDeleteResponses]; export type PartUpdateData = { body?: Part; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; /** * Part ID */ partID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}/part/{partID}'; }; export type PartUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PartUpdateError = PartUpdateErrors[keyof PartUpdateErrors]; export type PartUpdateResponses = { /** * Successfully updated part */ 200: Part; }; export type PartUpdateResponse = PartUpdateResponses[keyof PartUpdateResponses]; export type SessionPromptAsyncData = { body?: { messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; /** * @deprecated tools and permissions have been merged, you can set permissions on the session itself now */ tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/prompt_async'; }; export type SessionPromptAsyncErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionPromptAsyncError = SessionPromptAsyncErrors[keyof SessionPromptAsyncErrors]; export type SessionPromptAsyncResponses = { /** * Prompt accepted */ 204: void; }; export type SessionPromptAsyncResponse = SessionPromptAsyncResponses[keyof SessionPromptAsyncResponses]; export type SessionCommandData = { body?: { messageID?: string; agent?: string; model?: string; arguments: string; command: string; variant?: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/command'; }; export type SessionCommandErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionCommandError = SessionCommandErrors[keyof SessionCommandErrors]; export type SessionCommandResponses = { /** * Created message */ 200: { info: AssistantMessage; parts: Array; }; }; export type SessionCommandResponse = SessionCommandResponses[keyof SessionCommandResponses]; export type SessionShellData = { body?: { agent: string; model?: { providerID: string; modelID: string; }; command: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/shell'; }; export type SessionShellErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionShellError = SessionShellErrors[keyof SessionShellErrors]; export type SessionShellResponses = { /** * Created message */ 200: AssistantMessage; }; export type SessionShellResponse = SessionShellResponses[keyof SessionShellResponses]; export type SessionRevertData = { body?: { messageID: string; partID?: string; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/revert'; }; export type SessionRevertErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionRevertError = SessionRevertErrors[keyof SessionRevertErrors]; export type SessionRevertResponses = { /** * Updated session */ 200: Session; }; export type SessionRevertResponse = SessionRevertResponses[keyof SessionRevertResponses]; export type SessionUnrevertData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/unrevert'; }; export type SessionUnrevertErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUnrevertError = SessionUnrevertErrors[keyof SessionUnrevertErrors]; export type SessionUnrevertResponses = { /** * Updated session */ 200: Session; }; export type SessionUnrevertResponse = SessionUnrevertResponses[keyof SessionUnrevertResponses]; export type PermissionRespondData = { body?: { response: 'once' | 'always' | 'reject'; }; path: { sessionID: string; permissionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/permissions/{permissionID}'; }; export type PermissionRespondErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PermissionRespondError = PermissionRespondErrors[keyof PermissionRespondErrors]; export type PermissionRespondResponses = { /** * Permission processed successfully */ 200: boolean; }; export type PermissionRespondResponse = PermissionRespondResponses[keyof PermissionRespondResponses]; export type PermissionReplyData = { body?: { reply: 'once' | 'always' | 'reject'; }; path: { requestID: string; }; query?: { directory?: string; }; url: '/permission/{requestID}/reply'; }; export type PermissionReplyErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PermissionReplyError = PermissionReplyErrors[keyof PermissionReplyErrors]; export type PermissionReplyResponses = { /** * Permission processed successfully */ 200: boolean; }; export type PermissionReplyResponse = PermissionReplyResponses[keyof PermissionReplyResponses]; export type PermissionListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/permission'; }; export type PermissionListResponses = { /** * List of pending permissions */ 200: Array; }; export type PermissionListResponse = PermissionListResponses[keyof PermissionListResponses]; export type CommandListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/command'; }; export type CommandListResponses = { /** * List of commands */ 200: Array; }; export type CommandListResponse = CommandListResponses[keyof CommandListResponses]; export type ConfigProvidersData = { body?: never; path?: never; query?: { directory?: string; }; url: '/config/providers'; }; export type ConfigProvidersResponses = { /** * List of providers */ 200: { providers: Array; default: { [key: string]: string; }; }; }; export type ConfigProvidersResponse = ConfigProvidersResponses[keyof ConfigProvidersResponses]; export type ProviderListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/provider'; }; export type ProviderListResponses = { /** * List of providers */ 200: { all: Array<{ api?: string; name: string; env: Array; id: string; npm?: string; models: { [key: string]: { id: string; name: string; family?: string; release_date: string; attachment: boolean; reasoning: boolean; temperature: boolean; tool_call: boolean; interleaved?: true | { field: 'reasoning_content' | 'reasoning_details'; }; cost?: { input: number; output: number; cache_read?: number; cache_write?: number; context_over_200k?: { input: number; output: number; cache_read?: number; cache_write?: number; }; }; limit: { context: number; output: number; }; modalities?: { input: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; output: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; }; experimental?: boolean; status?: 'alpha' | 'beta' | 'deprecated'; options: { [key: string]: unknown; }; headers?: { [key: string]: string; }; provider?: { npm: string; }; variants?: { [key: string]: { [key: string]: unknown; }; }; }; }; }>; default: { [key: string]: string; }; connected: Array; }; }; export type ProviderListResponse = ProviderListResponses[keyof ProviderListResponses]; export type ProviderAuthData = { body?: never; path?: never; query?: { directory?: string; }; url: '/provider/auth'; }; export type ProviderAuthResponses = { /** * Provider auth methods */ 200: { [key: string]: Array; }; }; export type ProviderAuthResponse = ProviderAuthResponses[keyof ProviderAuthResponses]; export type ProviderOauthAuthorizeData = { body?: { /** * Auth method index */ method: number; }; path: { /** * Provider ID */ providerID: string; }; query?: { directory?: string; }; url: '/provider/{providerID}/oauth/authorize'; }; export type ProviderOauthAuthorizeErrors = { /** * Bad request */ 400: BadRequestError; }; export type ProviderOauthAuthorizeError = ProviderOauthAuthorizeErrors[keyof ProviderOauthAuthorizeErrors]; export type ProviderOauthAuthorizeResponses = { /** * Authorization URL and method */ 200: ProviderAuthAuthorization; }; export type ProviderOauthAuthorizeResponse = ProviderOauthAuthorizeResponses[keyof ProviderOauthAuthorizeResponses]; export type ProviderOauthCallbackData = { body?: { /** * Auth method index */ method: number; /** * OAuth authorization code */ code?: string; }; path: { /** * Provider ID */ providerID: string; }; query?: { directory?: string; }; url: '/provider/{providerID}/oauth/callback'; }; export type ProviderOauthCallbackErrors = { /** * Bad request */ 400: BadRequestError; }; export type ProviderOauthCallbackError = ProviderOauthCallbackErrors[keyof ProviderOauthCallbackErrors]; export type ProviderOauthCallbackResponses = { /** * OAuth callback processed successfully */ 200: boolean; }; export type ProviderOauthCallbackResponse = ProviderOauthCallbackResponses[keyof ProviderOauthCallbackResponses]; export type FindTextData = { body?: never; path?: never; query: { directory?: string; pattern: string; }; url: '/find'; }; export type FindTextResponses = { /** * Matches */ 200: Array<{ path: { text: string; }; lines: { text: string; }; line_number: number; absolute_offset: number; submatches: Array<{ match: { text: string; }; start: number; end: number; }>; }>; }; export type FindTextResponse = FindTextResponses[keyof FindTextResponses]; export type FindFilesData = { body?: never; path?: never; query: { directory?: string; query: string; dirs?: 'true' | 'false'; type?: 'file' | 'directory'; limit?: number; }; url: '/find/file'; }; export type FindFilesResponses = { /** * File paths */ 200: Array; }; export type FindFilesResponse = FindFilesResponses[keyof FindFilesResponses]; export type FindSymbolsData = { body?: never; path?: never; query: { directory?: string; query: string; }; url: '/find/symbol'; }; export type FindSymbolsResponses = { /** * Symbols */ 200: Array; }; export type FindSymbolsResponse = FindSymbolsResponses[keyof FindSymbolsResponses]; export type FileListData = { body?: never; path?: never; query: { directory?: string; path: string; }; url: '/file'; }; export type FileListResponses = { /** * Files and directories */ 200: Array; }; export type FileListResponse = FileListResponses[keyof FileListResponses]; export type FileReadData = { body?: never; path?: never; query: { directory?: string; path: string; }; url: '/file/content'; }; export type FileReadResponses = { /** * File content */ 200: FileContent; }; export type FileReadResponse = FileReadResponses[keyof FileReadResponses]; export type FileStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/file/status'; }; export type FileStatusResponses = { /** * File status */ 200: Array; }; export type FileStatusResponse = FileStatusResponses[keyof FileStatusResponses]; export type AppLogData = { body?: { /** * Service name for the log entry */ service: string; /** * Log level */ level: 'debug' | 'info' | 'error' | 'warn'; /** * Log message */ message: string; /** * Additional metadata for the log entry */ extra?: { [key: string]: unknown; }; }; path?: never; query?: { directory?: string; }; url: '/log'; }; export type AppLogErrors = { /** * Bad request */ 400: BadRequestError; }; export type AppLogError = AppLogErrors[keyof AppLogErrors]; export type AppLogResponses = { /** * Log entry written successfully */ 200: boolean; }; export type AppLogResponse = AppLogResponses[keyof AppLogResponses]; export type AppAgentsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/agent'; }; export type AppAgentsResponses = { /** * List of agents */ 200: Array; }; export type AppAgentsResponse = AppAgentsResponses[keyof AppAgentsResponses]; export type McpStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/mcp'; }; export type McpStatusResponses = { /** * MCP server status */ 200: { [key: string]: McpStatus; }; }; export type McpStatusResponse = McpStatusResponses[keyof McpStatusResponses]; export type McpAddData = { body?: { name: string; config: McpLocalConfig | McpRemoteConfig; }; path?: never; query?: { directory?: string; }; url: '/mcp'; }; export type McpAddErrors = { /** * Bad request */ 400: BadRequestError; }; export type McpAddError = McpAddErrors[keyof McpAddErrors]; export type McpAddResponses = { /** * MCP server added successfully */ 200: { [key: string]: McpStatus; }; }; export type McpAddResponse = McpAddResponses[keyof McpAddResponses]; export type McpAuthRemoveData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth'; }; export type McpAuthRemoveErrors = { /** * Not found */ 404: NotFoundError; }; export type McpAuthRemoveError = McpAuthRemoveErrors[keyof McpAuthRemoveErrors]; export type McpAuthRemoveResponses = { /** * OAuth credentials removed */ 200: { success: true; }; }; export type McpAuthRemoveResponse = McpAuthRemoveResponses[keyof McpAuthRemoveResponses]; export type McpAuthStartData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth'; }; export type McpAuthStartErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthStartError = McpAuthStartErrors[keyof McpAuthStartErrors]; export type McpAuthStartResponses = { /** * OAuth flow started */ 200: { /** * URL to open in browser for authorization */ authorizationUrl: string; }; }; export type McpAuthStartResponse = McpAuthStartResponses[keyof McpAuthStartResponses]; export type McpAuthCallbackData = { body?: { /** * Authorization code from OAuth callback */ code: string; }; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth/callback'; }; export type McpAuthCallbackErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthCallbackError = McpAuthCallbackErrors[keyof McpAuthCallbackErrors]; export type McpAuthCallbackResponses = { /** * OAuth authentication completed */ 200: McpStatus; }; export type McpAuthCallbackResponse = McpAuthCallbackResponses[keyof McpAuthCallbackResponses]; export type McpAuthAuthenticateData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth/authenticate'; }; export type McpAuthAuthenticateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthAuthenticateError = McpAuthAuthenticateErrors[keyof McpAuthAuthenticateErrors]; export type McpAuthAuthenticateResponses = { /** * OAuth authentication completed */ 200: McpStatus; }; export type McpAuthAuthenticateResponse = McpAuthAuthenticateResponses[keyof McpAuthAuthenticateResponses]; export type McpConnectData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/connect'; }; export type McpConnectResponses = { /** * MCP server connected successfully */ 200: boolean; }; export type McpConnectResponse = McpConnectResponses[keyof McpConnectResponses]; export type McpDisconnectData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/disconnect'; }; export type McpDisconnectResponses = { /** * MCP server disconnected successfully */ 200: boolean; }; export type McpDisconnectResponse = McpDisconnectResponses[keyof McpDisconnectResponses]; export type LspStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/lsp'; }; export type LspStatusResponses = { /** * LSP server status */ 200: Array; }; export type LspStatusResponse = LspStatusResponses[keyof LspStatusResponses]; export type FormatterStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/formatter'; }; export type FormatterStatusResponses = { /** * Formatter status */ 200: Array; }; export type FormatterStatusResponse = FormatterStatusResponses[keyof FormatterStatusResponses]; export type TuiAppendPromptData = { body?: { text: string; }; path?: never; query?: { directory?: string; }; url: '/tui/append-prompt'; }; export type TuiAppendPromptErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiAppendPromptError = TuiAppendPromptErrors[keyof TuiAppendPromptErrors]; export type TuiAppendPromptResponses = { /** * Prompt processed successfully */ 200: boolean; }; export type TuiAppendPromptResponse = TuiAppendPromptResponses[keyof TuiAppendPromptResponses]; export type TuiOpenHelpData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-help'; }; export type TuiOpenHelpResponses = { /** * Help dialog opened successfully */ 200: boolean; }; export type TuiOpenHelpResponse = TuiOpenHelpResponses[keyof TuiOpenHelpResponses]; export type TuiOpenSessionsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-sessions'; }; export type TuiOpenSessionsResponses = { /** * Session dialog opened successfully */ 200: boolean; }; export type TuiOpenSessionsResponse = TuiOpenSessionsResponses[keyof TuiOpenSessionsResponses]; export type TuiOpenThemesData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-themes'; }; export type TuiOpenThemesResponses = { /** * Theme dialog opened successfully */ 200: boolean; }; export type TuiOpenThemesResponse = TuiOpenThemesResponses[keyof TuiOpenThemesResponses]; export type TuiOpenModelsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-models'; }; export type TuiOpenModelsResponses = { /** * Model dialog opened successfully */ 200: boolean; }; export type TuiOpenModelsResponse = TuiOpenModelsResponses[keyof TuiOpenModelsResponses]; export type TuiSubmitPromptData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/submit-prompt'; }; export type TuiSubmitPromptResponses = { /** * Prompt submitted successfully */ 200: boolean; }; export type TuiSubmitPromptResponse = TuiSubmitPromptResponses[keyof TuiSubmitPromptResponses]; export type TuiClearPromptData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/clear-prompt'; }; export type TuiClearPromptResponses = { /** * Prompt cleared successfully */ 200: boolean; }; export type TuiClearPromptResponse = TuiClearPromptResponses[keyof TuiClearPromptResponses]; export type TuiExecuteCommandData = { body?: { command: string; }; path?: never; query?: { directory?: string; }; url: '/tui/execute-command'; }; export type TuiExecuteCommandErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiExecuteCommandError = TuiExecuteCommandErrors[keyof TuiExecuteCommandErrors]; export type TuiExecuteCommandResponses = { /** * Command executed successfully */ 200: boolean; }; export type TuiExecuteCommandResponse = TuiExecuteCommandResponses[keyof TuiExecuteCommandResponses]; export type TuiShowToastData = { body?: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; path?: never; query?: { directory?: string; }; url: '/tui/show-toast'; }; export type TuiShowToastResponses = { /** * Toast notification shown successfully */ 200: boolean; }; export type TuiShowToastResponse = TuiShowToastResponses[keyof TuiShowToastResponses]; export type TuiPublishData = { body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow; path?: never; query?: { directory?: string; }; url: '/tui/publish'; }; export type TuiPublishErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiPublishError = TuiPublishErrors[keyof TuiPublishErrors]; export type TuiPublishResponses = { /** * Event published successfully */ 200: boolean; }; export type TuiPublishResponse = TuiPublishResponses[keyof TuiPublishResponses]; export type TuiControlNextData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/control/next'; }; export type TuiControlNextResponses = { /** * Next TUI request */ 200: { path: string; body: unknown; }; }; export type TuiControlNextResponse = TuiControlNextResponses[keyof TuiControlNextResponses]; export type TuiControlResponseData = { body?: unknown; path?: never; query?: { directory?: string; }; url: '/tui/control/response'; }; export type TuiControlResponseResponses = { /** * Response submitted successfully */ 200: boolean; }; export type TuiControlResponseResponse = TuiControlResponseResponses[keyof TuiControlResponseResponses]; export type AuthSetData = { body?: Auth; path: { providerID: string; }; query?: { directory?: string; }; url: '/auth/{providerID}'; }; export type AuthSetErrors = { /** * Bad request */ 400: BadRequestError; }; export type AuthSetError = AuthSetErrors[keyof AuthSetErrors]; export type AuthSetResponses = { /** * Successfully set authentication credentials */ 200: boolean; }; export type AuthSetResponse = AuthSetResponses[keyof AuthSetResponses]; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { appAgents, appLog, authSet, commandList, configGet, configProviders, configUpdate, eventSubscribe, fileList, fileRead, fileStatus, findFiles, findSymbols, findText, formatterStatus, globalDispose, globalEvent, globalHealth, instanceDispose, lspStatus, mcpAdd, mcpAuthAuthenticate, mcpAuthCallback, mcpAuthRemove, mcpAuthStart, mcpConnect, mcpDisconnect, mcpStatus, type Options, partDelete, partUpdate, pathGet, permissionList, permissionReply, permissionRespond, projectCurrent, projectList, projectUpdate, providerAuth, providerList, providerOauthAuthorize, providerOauthCallback, ptyConnect, ptyCreate, ptyGet, ptyList, ptyRemove, ptyUpdate, sessionAbort, sessionChildren, sessionCommand, sessionCreate, sessionDelete, sessionDiff, sessionFork, sessionGet, sessionInit, sessionList, sessionMessage, sessionMessages, sessionPrompt, sessionPromptAsync, sessionRevert, sessionShare, sessionShell, sessionStatus, sessionSummarize, sessionTodo, sessionUnrevert, sessionUnshare, sessionUpdate, toolIds, toolList, tuiAppendPrompt, tuiClearPrompt, tuiControlNext, tuiControlResponse, tuiExecuteCommand, tuiOpenHelp, tuiOpenModels, tuiOpenSessions, tuiOpenThemes, tuiPublish, tuiShowToast, tuiSubmitPrompt, vcsGet } from './sdk.gen'; export type { Agent, AgentConfig, AgentPart, AgentPartInput, ApiAuth, ApiError, AppAgentsData, AppAgentsResponse, AppAgentsResponses, AppLogData, AppLogError, AppLogErrors, AppLogResponse, AppLogResponses, AssistantMessage, Auth, AuthSetData, AuthSetError, AuthSetErrors, AuthSetResponse, AuthSetResponses, BadRequestError, ClientOptions, Command, CommandListData, CommandListResponse, CommandListResponses, CompactionPart, Config, ConfigGetData, ConfigGetResponse, ConfigGetResponses, ConfigProvidersData, ConfigProvidersResponse, ConfigProvidersResponses, ConfigUpdateData, ConfigUpdateError, ConfigUpdateErrors, ConfigUpdateResponse, ConfigUpdateResponses, Event, EventCommandExecuted, EventFileEdited, EventFileWatcherUpdated, EventGlobalDisposed, EventInstallationUpdateAvailable, EventInstallationUpdated, EventLspClientDiagnostics, EventLspUpdated, EventMcpToolsChanged, EventMessagePartRemoved, EventMessagePartUpdated, EventMessageRemoved, EventMessageUpdated, EventPermissionAsked, EventPermissionReplied, EventProjectUpdated, EventPtyCreated, EventPtyDeleted, EventPtyExited, EventPtyUpdated, EventServerConnected, EventServerInstanceDisposed, EventSessionCompacted, EventSessionCreated, EventSessionDeleted, EventSessionDiff, EventSessionError, EventSessionIdle, EventSessionStatus, EventSessionUpdated, EventSubscribeData, EventSubscribeResponse, EventSubscribeResponses, EventTodoUpdated, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiToastShow, EventVcsBranchUpdated, File, FileContent, FileDiff, FileListData, FileListResponse, FileListResponses, FileNode, FilePart, FilePartInput, FilePartSource, FilePartSourceText, FileReadData, FileReadResponse, FileReadResponses, FileSource, FileStatusData, FileStatusResponse, FileStatusResponses, FindFilesData, FindFilesResponse, FindFilesResponses, FindSymbolsData, FindSymbolsResponse, FindSymbolsResponses, FindTextData, FindTextResponse, FindTextResponses, FormatterStatus, FormatterStatusData, FormatterStatusResponse, FormatterStatusResponses, GlobalDisposeData, GlobalDisposeResponse, GlobalDisposeResponses, GlobalEvent, GlobalEventData, GlobalEventResponse, GlobalEventResponses, GlobalHealthData, GlobalHealthResponse, GlobalHealthResponses, InstanceDisposeData, InstanceDisposeResponse, InstanceDisposeResponses, KeybindsConfig, LayoutConfig, LogLevel, LspStatus, LspStatusData, LspStatusResponse, LspStatusResponses, McpAddData, McpAddError, McpAddErrors, McpAddResponse, McpAddResponses, McpAuthAuthenticateData, McpAuthAuthenticateError, McpAuthAuthenticateErrors, McpAuthAuthenticateResponse, McpAuthAuthenticateResponses, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponse, McpAuthCallbackResponses, McpAuthRemoveData, McpAuthRemoveError, McpAuthRemoveErrors, McpAuthRemoveResponse, McpAuthRemoveResponses, McpAuthStartData, McpAuthStartError, McpAuthStartErrors, McpAuthStartResponse, McpAuthStartResponses, McpConnectData, McpConnectResponse, McpConnectResponses, McpDisconnectData, McpDisconnectResponse, McpDisconnectResponses, McpLocalConfig, McpOAuthConfig, McpRemoteConfig, McpStatus, McpStatusConnected, McpStatusData, McpStatusDisabled, McpStatusFailed, McpStatusNeedsAuth, McpStatusNeedsClientRegistration, McpStatusResponse, McpStatusResponses, Message, MessageAbortedError, MessageOutputLengthError, Model, NotFoundError, OAuth, Part, PartDeleteData, PartDeleteError, PartDeleteErrors, PartDeleteResponse, PartDeleteResponses, PartUpdateData, PartUpdateError, PartUpdateErrors, PartUpdateResponse, PartUpdateResponses, PatchPart, Path, PathGetData, PathGetResponse, PathGetResponses, PermissionAction, PermissionActionConfig, PermissionConfig, PermissionListData, PermissionListResponse, PermissionListResponses, PermissionObjectConfig, PermissionReplyData, PermissionReplyError, PermissionReplyErrors, PermissionReplyResponse, PermissionReplyResponses, PermissionRequest, PermissionRespondData, PermissionRespondError, PermissionRespondErrors, PermissionRespondResponse, PermissionRespondResponses, PermissionRule, PermissionRuleConfig, PermissionRuleset, Project, ProjectCurrentData, ProjectCurrentResponse, ProjectCurrentResponses, ProjectListData, ProjectListResponse, ProjectListResponses, ProjectUpdateData, ProjectUpdateError, ProjectUpdateErrors, ProjectUpdateResponse, ProjectUpdateResponses, Provider, ProviderAuthAuthorization, ProviderAuthData, ProviderAuthError, ProviderAuthMethod, ProviderAuthResponse, ProviderAuthResponses, ProviderConfig, ProviderListData, ProviderListResponse, ProviderListResponses, ProviderOauthAuthorizeData, ProviderOauthAuthorizeError, ProviderOauthAuthorizeErrors, ProviderOauthAuthorizeResponse, ProviderOauthAuthorizeResponses, ProviderOauthCallbackData, ProviderOauthCallbackError, ProviderOauthCallbackErrors, ProviderOauthCallbackResponse, ProviderOauthCallbackResponses, Pty, PtyConnectData, PtyConnectError, PtyConnectErrors, PtyConnectResponse, PtyConnectResponses, PtyCreateData, PtyCreateError, PtyCreateErrors, PtyCreateResponse, PtyCreateResponses, PtyGetData, PtyGetError, PtyGetErrors, PtyGetResponse, PtyGetResponses, PtyListData, PtyListResponse, PtyListResponses, PtyRemoveData, PtyRemoveError, PtyRemoveErrors, PtyRemoveResponse, PtyRemoveResponses, PtyUpdateData, PtyUpdateError, PtyUpdateErrors, PtyUpdateResponse, PtyUpdateResponses, Range, ReasoningPart, RetryPart, ServerConfig, Session, SessionAbortData, SessionAbortError, SessionAbortErrors, SessionAbortResponse, SessionAbortResponses, SessionChildrenData, SessionChildrenError, SessionChildrenErrors, SessionChildrenResponse, SessionChildrenResponses, SessionCommandData, SessionCommandError, SessionCommandErrors, SessionCommandResponse, SessionCommandResponses, SessionCreateData, SessionCreateError, SessionCreateErrors, SessionCreateResponse, SessionCreateResponses, SessionDeleteData, SessionDeleteError, SessionDeleteErrors, SessionDeleteResponse, SessionDeleteResponses, SessionDiffData, SessionDiffError, SessionDiffErrors, SessionDiffResponse, SessionDiffResponses, SessionForkData, SessionForkResponse, SessionForkResponses, SessionGetData, SessionGetError, SessionGetErrors, SessionGetResponse, SessionGetResponses, SessionInitData, SessionInitError, SessionInitErrors, SessionInitResponse, SessionInitResponses, SessionListData, SessionListResponse, SessionListResponses, SessionMessageData, SessionMessageError, SessionMessageErrors, SessionMessageResponse, SessionMessageResponses, SessionMessagesData, SessionMessagesError, SessionMessagesErrors, SessionMessagesResponse, SessionMessagesResponses, SessionPromptAsyncData, SessionPromptAsyncError, SessionPromptAsyncErrors, SessionPromptAsyncResponse, SessionPromptAsyncResponses, SessionPromptData, SessionPromptError, SessionPromptErrors, SessionPromptResponse, SessionPromptResponses, SessionRevertData, SessionRevertError, SessionRevertErrors, SessionRevertResponse, SessionRevertResponses, SessionShareData, SessionShareError, SessionShareErrors, SessionShareResponse, SessionShareResponses, SessionShellData, SessionShellError, SessionShellErrors, SessionShellResponse, SessionShellResponses, SessionStatus, SessionStatusData, SessionStatusError, SessionStatusErrors, SessionStatusResponse, SessionStatusResponses, SessionSummarizeData, SessionSummarizeError, SessionSummarizeErrors, SessionSummarizeResponse, SessionSummarizeResponses, SessionTodoData, SessionTodoError, SessionTodoErrors, SessionTodoResponse, SessionTodoResponses, SessionUnrevertData, SessionUnrevertError, SessionUnrevertErrors, SessionUnrevertResponse, SessionUnrevertResponses, SessionUnshareData, SessionUnshareError, SessionUnshareErrors, SessionUnshareResponse, SessionUnshareResponses, SessionUpdateData, SessionUpdateError, SessionUpdateErrors, SessionUpdateResponse, SessionUpdateResponses, SnapshotPart, StepFinishPart, StepStartPart, SubtaskPartInput, Symbol, SymbolSource, TextPart, TextPartInput, Todo, ToolIds, ToolIdsData, ToolIdsError, ToolIdsErrors, ToolIdsResponse, ToolIdsResponses, ToolList, ToolListData, ToolListError, ToolListErrors, ToolListItem, ToolListResponse, ToolListResponses, ToolPart, ToolState, ToolStateCompleted, ToolStateError, ToolStatePending, ToolStateRunning, TuiAppendPromptData, TuiAppendPromptError, TuiAppendPromptErrors, TuiAppendPromptResponse, TuiAppendPromptResponses, TuiClearPromptData, TuiClearPromptResponse, TuiClearPromptResponses, TuiControlNextData, TuiControlNextResponse, TuiControlNextResponses, TuiControlResponseData, TuiControlResponseResponse, TuiControlResponseResponses, TuiExecuteCommandData, TuiExecuteCommandError, TuiExecuteCommandErrors, TuiExecuteCommandResponse, TuiExecuteCommandResponses, TuiOpenHelpData, TuiOpenHelpResponse, TuiOpenHelpResponses, TuiOpenModelsData, TuiOpenModelsResponse, TuiOpenModelsResponses, TuiOpenSessionsData, TuiOpenSessionsResponse, TuiOpenSessionsResponses, TuiOpenThemesData, TuiOpenThemesResponse, TuiOpenThemesResponses, TuiPublishData, TuiPublishError, TuiPublishErrors, TuiPublishResponse, TuiPublishResponses, TuiShowToastData, TuiShowToastResponse, TuiShowToastResponses, TuiSubmitPromptData, TuiSubmitPromptResponse, TuiSubmitPromptResponses, UnknownError, UserMessage, VcsGetData, VcsGetResponse, VcsGetResponses, VcsInfo, WellKnownAuth } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import type { AppAgentsData, AppAgentsResponses, AppLogData, AppLogErrors, AppLogResponses, AuthSetData, AuthSetErrors, AuthSetResponses, CommandListData, CommandListResponses, ConfigGetData, ConfigGetResponses, ConfigProvidersData, ConfigProvidersResponses, ConfigUpdateData, ConfigUpdateErrors, ConfigUpdateResponses, EventSubscribeData, EventSubscribeResponses, FileListData, FileListResponses, FileReadData, FileReadResponses, FileStatusData, FileStatusResponses, FindFilesData, FindFilesResponses, FindSymbolsData, FindSymbolsResponses, FindTextData, FindTextResponses, FormatterStatusData, FormatterStatusResponses, GlobalDisposeData, GlobalDisposeResponses, GlobalEventData, GlobalEventResponses, GlobalHealthData, GlobalHealthResponses, InstanceDisposeData, InstanceDisposeResponses, LspStatusData, LspStatusResponses, McpAddData, McpAddErrors, McpAddResponses, McpAuthAuthenticateData, McpAuthAuthenticateErrors, McpAuthAuthenticateResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpAuthRemoveData, McpAuthRemoveErrors, McpAuthRemoveResponses, McpAuthStartData, McpAuthStartErrors, McpAuthStartResponses, McpConnectData, McpConnectResponses, McpDisconnectData, McpDisconnectResponses, McpStatusData, McpStatusResponses, PartDeleteData, PartDeleteErrors, PartDeleteResponses, PartUpdateData, PartUpdateErrors, PartUpdateResponses, PathGetData, PathGetResponses, PermissionListData, PermissionListResponses, PermissionReplyData, PermissionReplyErrors, PermissionReplyResponses, PermissionRespondData, PermissionRespondErrors, PermissionRespondResponses, ProjectCurrentData, ProjectCurrentResponses, ProjectListData, ProjectListResponses, ProjectUpdateData, ProjectUpdateErrors, ProjectUpdateResponses, ProviderAuthData, ProviderAuthResponses, ProviderListData, ProviderListResponses, ProviderOauthAuthorizeData, ProviderOauthAuthorizeErrors, ProviderOauthAuthorizeResponses, ProviderOauthCallbackData, ProviderOauthCallbackErrors, ProviderOauthCallbackResponses, PtyConnectData, PtyConnectErrors, PtyConnectResponses, PtyCreateData, PtyCreateErrors, PtyCreateResponses, PtyGetData, PtyGetErrors, PtyGetResponses, PtyListData, PtyListResponses, PtyRemoveData, PtyRemoveErrors, PtyRemoveResponses, PtyUpdateData, PtyUpdateErrors, PtyUpdateResponses, SessionAbortData, SessionAbortErrors, SessionAbortResponses, SessionChildrenData, SessionChildrenErrors, SessionChildrenResponses, SessionCommandData, SessionCommandErrors, SessionCommandResponses, SessionCreateData, SessionCreateErrors, SessionCreateResponses, SessionDeleteData, SessionDeleteErrors, SessionDeleteResponses, SessionDiffData, SessionDiffErrors, SessionDiffResponses, SessionForkData, SessionForkResponses, SessionGetData, SessionGetErrors, SessionGetResponses, SessionInitData, SessionInitErrors, SessionInitResponses, SessionListData, SessionListResponses, SessionMessageData, SessionMessageErrors, SessionMessageResponses, SessionMessagesData, SessionMessagesErrors, SessionMessagesResponses, SessionPromptAsyncData, SessionPromptAsyncErrors, SessionPromptAsyncResponses, SessionPromptData, SessionPromptErrors, SessionPromptResponses, SessionRevertData, SessionRevertErrors, SessionRevertResponses, SessionShareData, SessionShareErrors, SessionShareResponses, SessionShellData, SessionShellErrors, SessionShellResponses, SessionStatusData, SessionStatusErrors, SessionStatusResponses, SessionSummarizeData, SessionSummarizeErrors, SessionSummarizeResponses, SessionTodoData, SessionTodoErrors, SessionTodoResponses, SessionUnrevertData, SessionUnrevertErrors, SessionUnrevertResponses, SessionUnshareData, SessionUnshareErrors, SessionUnshareResponses, SessionUpdateData, SessionUpdateErrors, SessionUpdateResponses, ToolIdsData, ToolIdsErrors, ToolIdsResponses, ToolListData, ToolListErrors, ToolListResponses, TuiAppendPromptData, TuiAppendPromptErrors, TuiAppendPromptResponses, TuiClearPromptData, TuiClearPromptResponses, TuiControlNextData, TuiControlNextResponses, TuiControlResponseData, TuiControlResponseResponses, TuiExecuteCommandData, TuiExecuteCommandErrors, TuiExecuteCommandResponses, TuiOpenHelpData, TuiOpenHelpResponses, TuiOpenModelsData, TuiOpenModelsResponses, TuiOpenSessionsData, TuiOpenSessionsResponses, TuiOpenThemesData, TuiOpenThemesResponses, TuiPublishData, TuiPublishErrors, TuiPublishResponses, TuiShowToastData, TuiShowToastResponses, TuiSubmitPromptData, TuiSubmitPromptResponses, VcsGetData, VcsGetResponses } from './types.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; /** * Get health * * Get health information about the OpenCode server. */ export const globalHealth = (options?: Options) => (options?.client ?? client).get({ url: '/global/health', ...options }); /** * Get global events * * Subscribe to global events from the OpenCode system using server-sent events. */ export const globalEvent = (options?: Options) => (options?.client ?? client).sse.get({ url: '/global/event', ...options }); /** * Dispose instance * * Clean up and dispose all OpenCode instances, releasing all resources. */ export const globalDispose = (options?: Options) => (options?.client ?? client).post({ url: '/global/dispose', ...options }); /** * List all projects * * Get a list of projects that have been opened with OpenCode. */ export const projectList = (options?: Options) => (options?.client ?? client).get({ url: '/project', ...options }); /** * Get current project * * Retrieve the currently active project that OpenCode is working with. */ export const projectCurrent = (options?: Options) => (options?.client ?? client).get({ url: '/project/current', ...options }); /** * Update project * * Update project properties such as name, icon and color. */ export const projectUpdate = (options: Options) => (options.client ?? client).patch({ url: '/project/{projectID}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * List PTY sessions * * Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode. */ export const ptyList = (options?: Options) => (options?.client ?? client).get({ url: '/pty', ...options }); /** * Create PTY session * * Create a new pseudo-terminal (PTY) session for running shell commands and processes. */ export const ptyCreate = (options?: Options) => (options?.client ?? client).post({ url: '/pty', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Remove PTY session * * Remove and terminate a specific pseudo-terminal (PTY) session. */ export const ptyRemove = (options: Options) => (options.client ?? client).delete({ url: '/pty/{ptyID}', ...options }); /** * Get PTY session * * Retrieve detailed information about a specific pseudo-terminal (PTY) session. */ export const ptyGet = (options: Options) => (options.client ?? client).get({ url: '/pty/{ptyID}', ...options }); /** * Update PTY session * * Update properties of an existing pseudo-terminal (PTY) session. */ export const ptyUpdate = (options: Options) => (options.client ?? client).put({ url: '/pty/{ptyID}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Connect to PTY session * * Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time. */ export const ptyConnect = (options: Options) => (options.client ?? client).get({ url: '/pty/{ptyID}/connect', ...options }); /** * Get configuration * * Retrieve the current OpenCode configuration settings and preferences. */ export const configGet = (options?: Options) => (options?.client ?? client).get({ url: '/config', ...options }); /** * Update configuration * * Update OpenCode configuration settings and preferences. */ export const configUpdate = (options?: Options) => (options?.client ?? client).patch({ url: '/config', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * List tool IDs * * Get a list of all available tool IDs, including both built-in tools and dynamically registered tools. */ export const toolIds = (options?: Options) => (options?.client ?? client).get({ url: '/experimental/tool/ids', ...options }); /** * List tools * * Get a list of available tools with their JSON schema parameters for a specific provider and model combination. */ export const toolList = (options: Options) => (options.client ?? client).get({ url: '/experimental/tool', ...options }); /** * Dispose instance * * Clean up and dispose the current OpenCode instance, releasing all resources. */ export const instanceDispose = (options?: Options) => (options?.client ?? client).post({ url: '/instance/dispose', ...options }); /** * Get paths * * Retrieve the current working directory and related path information for the OpenCode instance. */ export const pathGet = (options?: Options) => (options?.client ?? client).get({ url: '/path', ...options }); /** * Get VCS info * * Retrieve version control system (VCS) information for the current project, such as git branch. */ export const vcsGet = (options?: Options) => (options?.client ?? client).get({ url: '/vcs', ...options }); /** * List sessions * * Get a list of all OpenCode sessions, sorted by most recently updated. */ export const sessionList = (options?: Options) => (options?.client ?? client).get({ url: '/session', ...options }); /** * Create session * * Create a new OpenCode session for interacting with AI assistants and managing conversations. */ export const sessionCreate = (options?: Options) => (options?.client ?? client).post({ url: '/session', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Get session status * * Retrieve the current status of all sessions, including active, idle, and completed states. */ export const sessionStatus = (options?: Options) => (options?.client ?? client).get({ url: '/session/status', ...options }); /** * Delete session * * Delete a session and permanently remove all associated data, including messages and history. */ export const sessionDelete = (options: Options) => (options.client ?? client).delete({ url: '/session/{sessionID}', ...options }); /** * Get session * * Retrieve detailed information about a specific OpenCode session. */ export const sessionGet = (options: Options) => (options.client ?? client).get({ url: '/session/{sessionID}', ...options }); /** * Update session * * Update properties of an existing session, such as title or other metadata. */ export const sessionUpdate = (options: Options) => (options.client ?? client).patch({ url: '/session/{sessionID}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Get session children * * Retrieve all child sessions that were forked from the specified parent session. */ export const sessionChildren = (options: Options) => (options.client ?? client).get({ url: '/session/{sessionID}/children', ...options }); /** * Get session todos * * Retrieve the todo list associated with a specific session, showing tasks and action items. */ export const sessionTodo = (options: Options) => (options.client ?? client).get({ url: '/session/{sessionID}/todo', ...options }); /** * Initialize session * * Analyze the current application and create an AGENTS.md file with project-specific agent configurations. */ export const sessionInit = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/init', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Fork session * * Create a new session by forking an existing session at a specific message point. */ export const sessionFork = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/fork', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Abort session * * Abort an active session and stop any ongoing AI processing or command execution. */ export const sessionAbort = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/abort', ...options }); /** * Unshare session * * Remove the shareable link for a session, making it private again. */ export const sessionUnshare = (options: Options) => (options.client ?? client).delete({ url: '/session/{sessionID}/share', ...options }); /** * Share session * * Create a shareable link for a session, allowing others to view the conversation. */ export const sessionShare = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/share', ...options }); /** * Get session diff * * Get all file changes (diffs) made during this session. */ export const sessionDiff = (options: Options) => (options.client ?? client).get({ url: '/session/{sessionID}/diff', ...options }); /** * Summarize session * * Generate a concise summary of the session using AI compaction to preserve key information. */ export const sessionSummarize = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/summarize', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Get session messages * * Retrieve all messages in a session, including user prompts and AI responses. */ export const sessionMessages = (options: Options) => (options.client ?? client).get({ url: '/session/{sessionID}/message', ...options }); /** * Send message * * Create and send a new message to a session, streaming the AI response. */ export const sessionPrompt = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/message', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Get message * * Retrieve a specific message from a session by its message ID. */ export const sessionMessage = (options: Options) => (options.client ?? client).get({ url: '/session/{sessionID}/message/{messageID}', ...options }); /** * Delete a part from a message */ export const partDelete = (options: Options) => (options.client ?? client).delete({ url: '/session/{sessionID}/message/{messageID}/part/{partID}', ...options }); /** * Update a part in a message */ export const partUpdate = (options: Options) => (options.client ?? client).patch({ url: '/session/{sessionID}/message/{messageID}/part/{partID}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Send async message * * Create and send a new message to a session asynchronously, starting the session if needed and returning immediately. */ export const sessionPromptAsync = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/prompt_async', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Send command * * Send a new command to a session for execution by the AI assistant. */ export const sessionCommand = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/command', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Run shell command * * Execute a shell command within the session context and return the AI's response. */ export const sessionShell = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/shell', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Revert message * * Revert a specific message in a session, undoing its effects and restoring the previous state. */ export const sessionRevert = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/revert', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Restore reverted messages * * Restore all previously reverted messages in a session. */ export const sessionUnrevert = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/unrevert', ...options }); /** * Respond to permission * * Approve or deny a permission request from the AI assistant. * * @deprecated */ export const permissionRespond = (options: Options) => (options.client ?? client).post({ url: '/session/{sessionID}/permissions/{permissionID}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Respond to permission request * * Approve or deny a permission request from the AI assistant. */ export const permissionReply = (options: Options) => (options.client ?? client).post({ url: '/permission/{requestID}/reply', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * List pending permissions * * Get all pending permission requests across all sessions. */ export const permissionList = (options?: Options) => (options?.client ?? client).get({ url: '/permission', ...options }); /** * List commands * * Get a list of all available commands in the OpenCode system. */ export const commandList = (options?: Options) => (options?.client ?? client).get({ url: '/command', ...options }); /** * List config providers * * Get a list of all configured AI providers and their default models. */ export const configProviders = (options?: Options) => (options?.client ?? client).get({ url: '/config/providers', ...options }); /** * List providers * * Get a list of all available AI providers, including both available and connected ones. */ export const providerList = (options?: Options) => (options?.client ?? client).get({ url: '/provider', ...options }); /** * Get provider auth methods * * Retrieve available authentication methods for all AI providers. */ export const providerAuth = (options?: Options) => (options?.client ?? client).get({ url: '/provider/auth', ...options }); /** * OAuth authorize * * Initiate OAuth authorization for a specific AI provider to get an authorization URL. */ export const providerOauthAuthorize = (options: Options) => (options.client ?? client).post({ url: '/provider/{providerID}/oauth/authorize', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * OAuth callback * * Handle the OAuth callback from a provider after user authorization. */ export const providerOauthCallback = (options: Options) => (options.client ?? client).post({ url: '/provider/{providerID}/oauth/callback', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Find text * * Search for text patterns across files in the project using ripgrep. */ export const findText = (options: Options) => (options.client ?? client).get({ url: '/find', ...options }); /** * Find files * * Search for files or directories by name or pattern in the project directory. */ export const findFiles = (options: Options) => (options.client ?? client).get({ url: '/find/file', ...options }); /** * Find symbols * * Search for workspace symbols like functions, classes, and variables using LSP. */ export const findSymbols = (options: Options) => (options.client ?? client).get({ url: '/find/symbol', ...options }); /** * List files * * List files and directories in a specified path. */ export const fileList = (options: Options) => (options.client ?? client).get({ url: '/file', ...options }); /** * Read file * * Read the content of a specified file. */ export const fileRead = (options: Options) => (options.client ?? client).get({ url: '/file/content', ...options }); /** * Get file status * * Get the git status of all files in the project. */ export const fileStatus = (options?: Options) => (options?.client ?? client).get({ url: '/file/status', ...options }); /** * Write log * * Write a log entry to the server logs with specified level and metadata. */ export const appLog = (options?: Options) => (options?.client ?? client).post({ url: '/log', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * List agents * * Get a list of all available AI agents in the OpenCode system. */ export const appAgents = (options?: Options) => (options?.client ?? client).get({ url: '/agent', ...options }); /** * Get MCP status * * Get the status of all Model Context Protocol (MCP) servers. */ export const mcpStatus = (options?: Options) => (options?.client ?? client).get({ url: '/mcp', ...options }); /** * Add MCP server * * Dynamically add a new Model Context Protocol (MCP) server to the system. */ export const mcpAdd = (options?: Options) => (options?.client ?? client).post({ url: '/mcp', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Remove MCP OAuth * * Remove OAuth credentials for an MCP server */ export const mcpAuthRemove = (options: Options) => (options.client ?? client).delete({ url: '/mcp/{name}/auth', ...options }); /** * Start MCP OAuth * * Start OAuth authentication flow for a Model Context Protocol (MCP) server. */ export const mcpAuthStart = (options: Options) => (options.client ?? client).post({ url: '/mcp/{name}/auth', ...options }); /** * Complete MCP OAuth * * Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code. */ export const mcpAuthCallback = (options: Options) => (options.client ?? client).post({ url: '/mcp/{name}/auth/callback', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Authenticate MCP OAuth * * Start OAuth flow and wait for callback (opens browser) */ export const mcpAuthAuthenticate = (options: Options) => (options.client ?? client).post({ url: '/mcp/{name}/auth/authenticate', ...options }); /** * Connect an MCP server */ export const mcpConnect = (options: Options) => (options.client ?? client).post({ url: '/mcp/{name}/connect', ...options }); /** * Disconnect an MCP server */ export const mcpDisconnect = (options: Options) => (options.client ?? client).post({ url: '/mcp/{name}/disconnect', ...options }); /** * Get LSP status * * Get LSP server status */ export const lspStatus = (options?: Options) => (options?.client ?? client).get({ url: '/lsp', ...options }); /** * Get formatter status * * Get formatter status */ export const formatterStatus = (options?: Options) => (options?.client ?? client).get({ url: '/formatter', ...options }); /** * Append TUI prompt * * Append prompt to the TUI */ export const tuiAppendPrompt = (options?: Options) => (options?.client ?? client).post({ url: '/tui/append-prompt', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Open help dialog * * Open the help dialog in the TUI to display user assistance information. */ export const tuiOpenHelp = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-help', ...options }); /** * Open sessions dialog * * Open the session dialog */ export const tuiOpenSessions = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-sessions', ...options }); /** * Open themes dialog * * Open the theme dialog */ export const tuiOpenThemes = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-themes', ...options }); /** * Open models dialog * * Open the model dialog */ export const tuiOpenModels = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-models', ...options }); /** * Submit TUI prompt * * Submit the prompt */ export const tuiSubmitPrompt = (options?: Options) => (options?.client ?? client).post({ url: '/tui/submit-prompt', ...options }); /** * Clear TUI prompt * * Clear the prompt */ export const tuiClearPrompt = (options?: Options) => (options?.client ?? client).post({ url: '/tui/clear-prompt', ...options }); /** * Execute TUI command * * Execute a TUI command (e.g. agent_cycle) */ export const tuiExecuteCommand = (options?: Options) => (options?.client ?? client).post({ url: '/tui/execute-command', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Show TUI toast * * Show a toast notification in the TUI */ export const tuiShowToast = (options?: Options) => (options?.client ?? client).post({ url: '/tui/show-toast', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Publish TUI event * * Publish a TUI event */ export const tuiPublish = (options?: Options) => (options?.client ?? client).post({ url: '/tui/publish', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Get next TUI request * * Retrieve the next TUI (Terminal User Interface) request from the queue for processing. */ export const tuiControlNext = (options?: Options) => (options?.client ?? client).get({ url: '/tui/control/next', ...options }); /** * Submit TUI response * * Submit a response to the TUI request queue to complete a pending request. */ export const tuiControlResponse = (options?: Options) => (options?.client ?? client).post({ url: '/tui/control/response', ...options, headers: { 'Content-Type': 'application/json', ...options?.headers } }); /** * Set auth credentials * * Set authentication credentials */ export const authSet = (options: Options) => (options.client ?? client).put({ url: '/auth/{providerID}', ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); /** * Subscribe to events * * Get events */ export const eventSubscribe = (options?: Options) => (options?.client ?? client).sse.get({ url: '/event', ...options }); ================================================ FILE: packages/openapi-ts-tests/sdks/__snapshots__/opencode/grouped/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type EventInstallationUpdated = { type: 'installation.updated'; properties: { version: string; }; }; export type EventInstallationUpdateAvailable = { type: 'installation.update-available'; properties: { version: string; }; }; export type Project = { id: string; worktree: string; vcs?: 'git'; name?: string; icon?: { url?: string; color?: string; }; time: { created: number; updated: number; initialized?: number; }; }; export type EventProjectUpdated = { type: 'project.updated'; properties: Project; }; export type EventServerInstanceDisposed = { type: 'server.instance.disposed'; properties: { directory: string; }; }; export type EventLspClientDiagnostics = { type: 'lsp.client.diagnostics'; properties: { serverID: string; path: string; }; }; export type EventLspUpdated = { type: 'lsp.updated'; properties: { [key: string]: unknown; }; }; export type FileDiff = { file: string; before: string; after: string; additions: number; deletions: number; }; export type UserMessage = { id: string; sessionID: string; role: 'user'; time: { created: number; }; summary?: { title?: string; body?: string; diffs: Array; }; agent: string; model: { providerID: string; modelID: string; }; system?: string; tools?: { [key: string]: boolean; }; variant?: string; }; export type ProviderAuthError = { name: 'ProviderAuthError'; data: { providerID: string; message: string; }; }; export type UnknownError = { name: 'UnknownError'; data: { message: string; }; }; export type MessageOutputLengthError = { name: 'MessageOutputLengthError'; data: { [key: string]: unknown; }; }; export type MessageAbortedError = { name: 'MessageAbortedError'; data: { message: string; }; }; export type ApiError = { name: 'APIError'; data: { message: string; statusCode?: number; isRetryable: boolean; responseHeaders?: { [key: string]: string; }; responseBody?: string; metadata?: { [key: string]: string; }; }; }; export type AssistantMessage = { id: string; sessionID: string; role: 'assistant'; time: { created: number; completed?: number; }; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; parentID: string; modelID: string; providerID: string; mode: string; agent: string; path: { cwd: string; root: string; }; summary?: boolean; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; finish?: string; }; export type Message = UserMessage | AssistantMessage; export type EventMessageUpdated = { type: 'message.updated'; properties: { info: Message; }; }; export type EventMessageRemoved = { type: 'message.removed'; properties: { sessionID: string; messageID: string; }; }; export type TextPart = { id: string; sessionID: string; messageID: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type ReasoningPart = { id: string; sessionID: string; messageID: string; type: 'reasoning'; text: string; metadata?: { [key: string]: unknown; }; time: { start: number; end?: number; }; }; export type FilePartSourceText = { value: string; start: number; end: number; }; export type FileSource = { text: FilePartSourceText; type: 'file'; path: string; }; export type Range = { start: { line: number; character: number; }; end: { line: number; character: number; }; }; export type SymbolSource = { text: FilePartSourceText; type: 'symbol'; path: string; range: Range; name: string; kind: number; }; export type FilePartSource = FileSource | SymbolSource; export type FilePart = { id: string; sessionID: string; messageID: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type ToolStatePending = { status: 'pending'; input: { [key: string]: unknown; }; raw: string; }; export type ToolStateRunning = { status: 'running'; input: { [key: string]: unknown; }; title?: string; metadata?: { [key: string]: unknown; }; time: { start: number; }; }; export type ToolStateCompleted = { status: 'completed'; input: { [key: string]: unknown; }; output: string; title: string; metadata: { [key: string]: unknown; }; time: { start: number; end: number; compacted?: number; }; attachments?: Array; }; export type ToolStateError = { status: 'error'; input: { [key: string]: unknown; }; error: string; metadata?: { [key: string]: unknown; }; time: { start: number; end: number; }; }; export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError; export type ToolPart = { id: string; sessionID: string; messageID: string; type: 'tool'; callID: string; tool: string; state: ToolState; metadata?: { [key: string]: unknown; }; }; export type StepStartPart = { id: string; sessionID: string; messageID: string; type: 'step-start'; snapshot?: string; }; export type StepFinishPart = { id: string; sessionID: string; messageID: string; type: 'step-finish'; reason: string; snapshot?: string; cost: number; tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number; }; }; }; export type SnapshotPart = { id: string; sessionID: string; messageID: string; type: 'snapshot'; snapshot: string; }; export type PatchPart = { id: string; sessionID: string; messageID: string; type: 'patch'; hash: string; files: Array; }; export type AgentPart = { id: string; sessionID: string; messageID: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type RetryPart = { id: string; sessionID: string; messageID: string; type: 'retry'; attempt: number; error: ApiError; time: { created: number; }; }; export type CompactionPart = { id: string; sessionID: string; messageID: string; type: 'compaction'; auto: boolean; }; export type Part = TextPart | { id: string; sessionID: string; messageID: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; } | ReasoningPart | FilePart | ToolPart | StepStartPart | StepFinishPart | SnapshotPart | PatchPart | AgentPart | RetryPart | CompactionPart; export type EventMessagePartUpdated = { type: 'message.part.updated'; properties: { part: Part; delta?: string; }; }; export type EventMessagePartRemoved = { type: 'message.part.removed'; properties: { sessionID: string; messageID: string; partID: string; }; }; export type PermissionRequest = { id: string; sessionID: string; permission: string; patterns: Array; metadata: { [key: string]: unknown; }; always: Array; tool?: { messageID: string; callID: string; }; }; export type EventPermissionAsked = { type: 'permission.asked'; properties: PermissionRequest; }; export type EventPermissionReplied = { type: 'permission.replied'; properties: { sessionID: string; requestID: string; reply: 'once' | 'always' | 'reject'; }; }; export type SessionStatus = { type: 'idle'; } | { type: 'retry'; attempt: number; message: string; next: number; } | { type: 'busy'; }; export type EventSessionStatus = { type: 'session.status'; properties: { sessionID: string; status: SessionStatus; }; }; export type EventSessionIdle = { type: 'session.idle'; properties: { sessionID: string; }; }; export type EventSessionCompacted = { type: 'session.compacted'; properties: { sessionID: string; }; }; export type EventFileEdited = { type: 'file.edited'; properties: { file: string; }; }; export type Todo = { /** * Brief description of the task */ content: string; /** * Current status of the task: pending, in_progress, completed, cancelled */ status: string; /** * Priority level of the task: high, medium, low */ priority: string; /** * Unique identifier for the todo item */ id: string; }; export type EventTodoUpdated = { type: 'todo.updated'; properties: { sessionID: string; todos: Array; }; }; export type EventTuiPromptAppend = { type: 'tui.prompt.append'; properties: { text: string; }; }; export type EventTuiCommandExecute = { type: 'tui.command.execute'; properties: { command: 'session.list' | 'session.new' | 'session.share' | 'session.interrupt' | 'session.compact' | 'session.page.up' | 'session.page.down' | 'session.half.page.up' | 'session.half.page.down' | 'session.first' | 'session.last' | 'prompt.clear' | 'prompt.submit' | 'agent.cycle' | string; }; }; export type EventTuiToastShow = { type: 'tui.toast.show'; properties: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; }; export type EventMcpToolsChanged = { type: 'mcp.tools.changed'; properties: { server: string; }; }; export type EventCommandExecuted = { type: 'command.executed'; properties: { name: string; sessionID: string; arguments: string; messageID: string; }; }; export type PermissionAction = 'allow' | 'deny' | 'ask'; export type PermissionRule = { permission: string; pattern: string; action: PermissionAction; }; export type PermissionRuleset = Array; export type Session = { id: string; projectID: string; directory: string; parentID?: string; summary?: { additions: number; deletions: number; files: number; diffs?: Array; }; share?: { url: string; }; title: string; version: string; time: { created: number; updated: number; compacting?: number; archived?: number; }; permission?: PermissionRuleset; revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string; }; }; export type EventSessionCreated = { type: 'session.created'; properties: { info: Session; }; }; export type EventSessionUpdated = { type: 'session.updated'; properties: { info: Session; }; }; export type EventSessionDeleted = { type: 'session.deleted'; properties: { info: Session; }; }; export type EventSessionDiff = { type: 'session.diff'; properties: { sessionID: string; diff: Array; }; }; export type EventSessionError = { type: 'session.error'; properties: { sessionID?: string; error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError; }; }; export type EventFileWatcherUpdated = { type: 'file.watcher.updated'; properties: { file: string; event: 'add' | 'change' | 'unlink'; }; }; export type EventVcsBranchUpdated = { type: 'vcs.branch.updated'; properties: { branch?: string; }; }; export type Pty = { id: string; title: string; command: string; args: Array; cwd: string; status: 'running' | 'exited'; pid: number; }; export type EventPtyCreated = { type: 'pty.created'; properties: { info: Pty; }; }; export type EventPtyUpdated = { type: 'pty.updated'; properties: { info: Pty; }; }; export type EventPtyExited = { type: 'pty.exited'; properties: { id: string; exitCode: number; }; }; export type EventPtyDeleted = { type: 'pty.deleted'; properties: { id: string; }; }; export type EventServerConnected = { type: 'server.connected'; properties: { [key: string]: unknown; }; }; export type EventGlobalDisposed = { type: 'global.disposed'; properties: { [key: string]: unknown; }; }; export type Event = EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventServerInstanceDisposed | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventSessionStatus | EventSessionIdle | EventSessionCompacted | EventFileEdited | EventTodoUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventMcpToolsChanged | EventCommandExecuted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventFileWatcherUpdated | EventVcsBranchUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventGlobalDisposed; export type GlobalEvent = { directory: string; payload: Event; }; export type BadRequestError = { data: unknown; errors: Array<{ [key: string]: unknown; }>; success: false; }; export type NotFoundError = { name: 'NotFoundError'; data: { message: string; }; }; /** * Custom keybind configurations */ export type KeybindsConfig = { /** * Leader key for keybind combinations */ leader?: string; /** * Exit the application */ app_exit?: string; /** * Open external editor */ editor_open?: string; /** * List available themes */ theme_list?: string; /** * Toggle sidebar */ sidebar_toggle?: string; /** * Toggle session scrollbar */ scrollbar_toggle?: string; /** * Toggle username visibility */ username_toggle?: string; /** * View status */ status_view?: string; /** * Export session to editor */ session_export?: string; /** * Create a new session */ session_new?: string; /** * List all sessions */ session_list?: string; /** * Show session timeline */ session_timeline?: string; /** * Fork session from message */ session_fork?: string; /** * Rename session */ session_rename?: string; /** * Share current session */ session_share?: string; /** * Unshare current session */ session_unshare?: string; /** * Interrupt current session */ session_interrupt?: string; /** * Compact the session */ session_compact?: string; /** * Scroll messages up by one page */ messages_page_up?: string; /** * Scroll messages down by one page */ messages_page_down?: string; /** * Scroll messages up by half page */ messages_half_page_up?: string; /** * Scroll messages down by half page */ messages_half_page_down?: string; /** * Navigate to first message */ messages_first?: string; /** * Navigate to last message */ messages_last?: string; /** * Navigate to next message */ messages_next?: string; /** * Navigate to previous message */ messages_previous?: string; /** * Navigate to last user message */ messages_last_user?: string; /** * Copy message */ messages_copy?: string; /** * Undo message */ messages_undo?: string; /** * Redo message */ messages_redo?: string; /** * Toggle code block concealment in messages */ messages_toggle_conceal?: string; /** * Toggle tool details visibility */ tool_details?: string; /** * List available models */ model_list?: string; /** * Next recently used model */ model_cycle_recent?: string; /** * Previous recently used model */ model_cycle_recent_reverse?: string; /** * Next favorite model */ model_cycle_favorite?: string; /** * Previous favorite model */ model_cycle_favorite_reverse?: string; /** * List available commands */ command_list?: string; /** * List agents */ agent_list?: string; /** * Next agent */ agent_cycle?: string; /** * Previous agent */ agent_cycle_reverse?: string; /** * Cycle model variants */ variant_cycle?: string; /** * Clear input field */ input_clear?: string; /** * Paste from clipboard */ input_paste?: string; /** * Submit input */ input_submit?: string; /** * Insert newline in input */ input_newline?: string; /** * Move cursor left in input */ input_move_left?: string; /** * Move cursor right in input */ input_move_right?: string; /** * Move cursor up in input */ input_move_up?: string; /** * Move cursor down in input */ input_move_down?: string; /** * Select left in input */ input_select_left?: string; /** * Select right in input */ input_select_right?: string; /** * Select up in input */ input_select_up?: string; /** * Select down in input */ input_select_down?: string; /** * Move to start of line in input */ input_line_home?: string; /** * Move to end of line in input */ input_line_end?: string; /** * Select to start of line in input */ input_select_line_home?: string; /** * Select to end of line in input */ input_select_line_end?: string; /** * Move to start of visual line in input */ input_visual_line_home?: string; /** * Move to end of visual line in input */ input_visual_line_end?: string; /** * Select to start of visual line in input */ input_select_visual_line_home?: string; /** * Select to end of visual line in input */ input_select_visual_line_end?: string; /** * Move to start of buffer in input */ input_buffer_home?: string; /** * Move to end of buffer in input */ input_buffer_end?: string; /** * Select to start of buffer in input */ input_select_buffer_home?: string; /** * Select to end of buffer in input */ input_select_buffer_end?: string; /** * Delete line in input */ input_delete_line?: string; /** * Delete to end of line in input */ input_delete_to_line_end?: string; /** * Delete to start of line in input */ input_delete_to_line_start?: string; /** * Backspace in input */ input_backspace?: string; /** * Delete character in input */ input_delete?: string; /** * Undo in input */ input_undo?: string; /** * Redo in input */ input_redo?: string; /** * Move word forward in input */ input_word_forward?: string; /** * Move word backward in input */ input_word_backward?: string; /** * Select word forward in input */ input_select_word_forward?: string; /** * Select word backward in input */ input_select_word_backward?: string; /** * Delete word forward in input */ input_delete_word_forward?: string; /** * Delete word backward in input */ input_delete_word_backward?: string; /** * Previous history item */ history_previous?: string; /** * Next history item */ history_next?: string; /** * Next child session */ session_child_cycle?: string; /** * Previous child session */ session_child_cycle_reverse?: string; /** * Go to parent session */ session_parent?: string; /** * Suspend terminal */ terminal_suspend?: string; /** * Toggle terminal title */ terminal_title_toggle?: string; /** * Toggle tips on home screen */ tips_toggle?: string; }; /** * Log level */ export type LogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'; /** * Server configuration for opencode serve and web commands */ export type ServerConfig = { /** * Port to listen on */ port?: number; /** * Hostname to listen on */ hostname?: string; /** * Enable mDNS service discovery */ mdns?: boolean; /** * Additional domains to allow for CORS */ cors?: Array; }; export type PermissionActionConfig = 'ask' | 'allow' | 'deny'; export type PermissionObjectConfig = { [key: string]: PermissionActionConfig; }; export type PermissionRuleConfig = PermissionActionConfig | PermissionObjectConfig; export type PermissionConfig = { read?: PermissionRuleConfig; edit?: PermissionRuleConfig; glob?: PermissionRuleConfig; grep?: PermissionRuleConfig; list?: PermissionRuleConfig; bash?: PermissionRuleConfig; task?: PermissionRuleConfig; external_directory?: PermissionRuleConfig; todowrite?: PermissionActionConfig; todoread?: PermissionActionConfig; webfetch?: PermissionActionConfig; websearch?: PermissionActionConfig; codesearch?: PermissionActionConfig; lsp?: PermissionRuleConfig; doom_loop?: PermissionActionConfig; [key: string]: PermissionRuleConfig | PermissionActionConfig | undefined; } | PermissionActionConfig; export type AgentConfig = { model?: string; temperature?: number; top_p?: number; prompt?: string; /** * @deprecated Use 'permission' field instead */ tools?: { [key: string]: boolean; }; disable?: boolean; /** * Description of when to use the agent */ description?: string; mode?: 'subagent' | 'primary' | 'all'; options?: { [key: string]: unknown; }; /** * Hex color code for the agent (e.g., #FF5733) */ color?: string; /** * Maximum number of agentic iterations before forcing text-only response */ steps?: number; /** * @deprecated Use 'steps' field instead. */ maxSteps?: number; permission?: PermissionConfig; [key: string]: unknown; }; export type ProviderConfig = { api?: string; name?: string; env?: Array; id?: string; npm?: string; models?: { [key: string]: { id?: string; name?: string; family?: string; release_date?: string; attachment?: boolean; reasoning?: boolean; temperature?: boolean; tool_call?: boolean; interleaved?: true | { field: 'reasoning_content' | 'reasoning_details'; }; cost?: { input: number; output: number; cache_read?: number; cache_write?: number; context_over_200k?: { input: number; output: number; cache_read?: number; cache_write?: number; }; }; limit?: { context: number; output: number; }; modalities?: { input: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; output: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; }; experimental?: boolean; status?: 'alpha' | 'beta' | 'deprecated'; options?: { [key: string]: unknown; }; headers?: { [key: string]: string; }; provider?: { npm: string; }; /** * Variant-specific configuration */ variants?: { [key: string]: { /** * Disable this variant for the model */ disabled?: boolean; [key: string]: unknown; }; }; }; }; whitelist?: Array; blacklist?: Array; options?: { apiKey?: string; baseURL?: string; /** * GitHub Enterprise URL for copilot authentication */ enterpriseUrl?: string; /** * Enable promptCacheKey for this provider (default false) */ setCacheKey?: boolean; /** * Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout. */ timeout?: number | false; [key: string]: unknown; }; }; export type McpLocalConfig = { /** * Type of MCP server connection */ type: 'local'; /** * Command and arguments to run the MCP server */ command: Array; /** * Environment variables to set when running the MCP server */ environment?: { [key: string]: string; }; /** * Enable or disable the MCP server on startup */ enabled?: boolean; /** * Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. */ timeout?: number; }; export type McpOAuthConfig = { /** * OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted. */ clientId?: string; /** * OAuth client secret (if required by the authorization server) */ clientSecret?: string; /** * OAuth scopes to request during authorization */ scope?: string; }; export type McpRemoteConfig = { /** * Type of MCP server connection */ type: 'remote'; /** * URL of the remote MCP server */ url: string; /** * Enable or disable the MCP server on startup */ enabled?: boolean; /** * Headers to send with the request */ headers?: { [key: string]: string; }; /** * OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection. */ oauth?: McpOAuthConfig | false; /** * Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. */ timeout?: number; }; /** * @deprecated Always uses stretch layout. */ export type LayoutConfig = 'auto' | 'stretch'; export type Config = { /** * JSON schema reference for configuration validation */ $schema?: string; /** * Theme name to use for the interface */ theme?: string; keybinds?: KeybindsConfig; logLevel?: LogLevel; /** * TUI specific settings */ tui?: { /** * TUI scroll speed */ scroll_speed?: number; /** * Scroll acceleration settings */ scroll_acceleration?: { /** * Enable scroll acceleration */ enabled: boolean; }; /** * Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column */ diff_style?: 'auto' | 'stacked'; }; server?: ServerConfig; /** * Command configuration, see https://opencode.ai/docs/commands */ command?: { [key: string]: { template: string; description?: string; agent?: string; model?: string; subtask?: boolean; }; }; watcher?: { ignore?: Array; }; plugin?: Array; snapshot?: boolean; /** * Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing */ share?: 'manual' | 'auto' | 'disabled'; /** * @deprecated Use 'share' field instead. Share newly created sessions automatically */ autoshare?: boolean; /** * Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications */ autoupdate?: boolean | 'notify'; /** * Disable providers that are loaded automatically */ disabled_providers?: Array; /** * When set, ONLY these providers will be enabled. All other providers will be ignored */ enabled_providers?: Array; /** * Model to use in the format of provider/model, eg anthropic/claude-2 */ model?: string; /** * Small model to use for tasks like title generation in the format of provider/model */ small_model?: string; /** * Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid. */ default_agent?: string; /** * Custom username to display in conversations instead of system username */ username?: string; /** * @deprecated Use `agent` field instead. */ mode?: { build?: AgentConfig; plan?: AgentConfig; [key: string]: AgentConfig | undefined; }; /** * Agent configuration, see https://opencode.ai/docs/agent */ agent?: { plan?: AgentConfig; build?: AgentConfig; general?: AgentConfig; explore?: AgentConfig; title?: AgentConfig; summary?: AgentConfig; compaction?: AgentConfig; [key: string]: AgentConfig | undefined; }; /** * Custom provider configurations and model overrides */ provider?: { [key: string]: ProviderConfig; }; /** * MCP (Model Context Protocol) server configurations */ mcp?: { [key: string]: McpLocalConfig | McpRemoteConfig; }; formatter?: false | { [key: string]: { disabled?: boolean; command?: Array; environment?: { [key: string]: string; }; extensions?: Array; }; }; lsp?: false | { [key: string]: { disabled: true; } | { command: Array; extensions?: Array; disabled?: boolean; env?: { [key: string]: string; }; initialization?: { [key: string]: unknown; }; }; }; /** * Additional instruction files or patterns to include */ instructions?: Array; layout?: LayoutConfig; permission?: PermissionConfig; tools?: { [key: string]: boolean; }; enterprise?: { /** * Enterprise URL */ url?: string; }; compaction?: { /** * Enable automatic compaction when context is full (default: true) */ auto?: boolean; /** * Enable pruning of old tool outputs (default: true) */ prune?: boolean; }; experimental?: { hook?: { file_edited?: { [key: string]: Array<{ command: Array; environment?: { [key: string]: string; }; }>; }; session_completed?: Array<{ command: Array; environment?: { [key: string]: string; }; }>; }; /** * Number of retries for chat completions on failure */ chatMaxRetries?: number; disable_paste_summary?: boolean; /** * Enable the batch tool */ batch_tool?: boolean; /** * Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag) */ openTelemetry?: boolean; /** * Tools that should only be available to primary agents. */ primary_tools?: Array; /** * Continue the agent loop when a tool call is denied */ continue_loop_on_deny?: boolean; /** * Timeout in milliseconds for model context protocol (MCP) requests */ mcp_timeout?: number; }; }; export type ToolIds = Array; export type ToolListItem = { id: string; description: string; parameters: unknown; }; export type ToolList = Array; export type Path = { home: string; state: string; config: string; worktree: string; directory: string; }; export type VcsInfo = { branch: string; }; export type TextPartInput = { id?: string; type: 'text'; text: string; synthetic?: boolean; ignored?: boolean; time?: { start: number; end?: number; }; metadata?: { [key: string]: unknown; }; }; export type FilePartInput = { id?: string; type: 'file'; mime: string; filename?: string; url: string; source?: FilePartSource; }; export type AgentPartInput = { id?: string; type: 'agent'; name: string; source?: { value: string; start: number; end: number; }; }; export type SubtaskPartInput = { id?: string; type: 'subtask'; prompt: string; description: string; agent: string; command?: string; }; export type Command = { name: string; description?: string; agent?: string; model?: string; mcp?: boolean; template: string; subtask?: boolean; hints: Array; }; export type Model = { id: string; providerID: string; api: { id: string; url: string; npm: string; }; name: string; family?: string; capabilities: { temperature: boolean; reasoning: boolean; attachment: boolean; toolcall: boolean; input: { text: boolean; audio: boolean; image: boolean; video: boolean; pdf: boolean; }; output: { text: boolean; audio: boolean; image: boolean; video: boolean; pdf: boolean; }; interleaved: boolean | { field: 'reasoning_content' | 'reasoning_details'; }; }; cost: { input: number; output: number; cache: { read: number; write: number; }; experimentalOver200K?: { input: number; output: number; cache: { read: number; write: number; }; }; }; limit: { context: number; output: number; }; status: 'alpha' | 'beta' | 'deprecated' | 'active'; options: { [key: string]: unknown; }; headers: { [key: string]: string; }; release_date: string; variants?: { [key: string]: { [key: string]: unknown; }; }; }; export type Provider = { id: string; name: string; source: 'env' | 'config' | 'custom' | 'api'; env: Array; key?: string; options: { [key: string]: unknown; }; models: { [key: string]: Model; }; }; export type ProviderAuthMethod = { type: 'oauth' | 'api'; label: string; }; export type ProviderAuthAuthorization = { url: string; method: 'auto' | 'code'; instructions: string; }; export type Symbol = { name: string; kind: number; location: { uri: string; range: Range; }; }; export type FileNode = { name: string; path: string; absolute: string; type: 'file' | 'directory'; ignored: boolean; }; export type FileContent = { type: 'text'; content: string; diff?: string; patch?: { oldFileName: string; newFileName: string; oldHeader?: string; newHeader?: string; hunks: Array<{ oldStart: number; oldLines: number; newStart: number; newLines: number; lines: Array; }>; index?: string; }; encoding?: 'base64'; mimeType?: string; }; export type File = { path: string; added: number; removed: number; status: 'added' | 'deleted' | 'modified'; }; export type Agent = { name: string; description?: string; mode: 'subagent' | 'primary' | 'all'; native?: boolean; hidden?: boolean; topP?: number; temperature?: number; color?: string; permission: PermissionRuleset; model?: { modelID: string; providerID: string; }; prompt?: string; options: { [key: string]: unknown; }; steps?: number; }; export type McpStatusConnected = { status: 'connected'; }; export type McpStatusDisabled = { status: 'disabled'; }; export type McpStatusFailed = { status: 'failed'; error: string; }; export type McpStatusNeedsAuth = { status: 'needs_auth'; }; export type McpStatusNeedsClientRegistration = { status: 'needs_client_registration'; error: string; }; export type McpStatus = McpStatusConnected | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth | McpStatusNeedsClientRegistration; export type LspStatus = { id: string; name: string; root: string; status: 'connected' | 'error'; }; export type FormatterStatus = { name: string; extensions: Array; enabled: boolean; }; export type OAuth = { type: 'oauth'; refresh: string; access: string; expires: number; enterpriseUrl?: string; }; export type ApiAuth = { type: 'api'; key: string; }; export type WellKnownAuth = { type: 'wellknown'; key: string; token: string; }; export type Auth = OAuth | ApiAuth | WellKnownAuth; export type GlobalHealthData = { body?: never; path?: never; query?: never; url: '/global/health'; }; export type GlobalHealthResponses = { /** * Health information */ 200: { healthy: true; version: string; }; }; export type GlobalHealthResponse = GlobalHealthResponses[keyof GlobalHealthResponses]; export type GlobalEventData = { body?: never; path?: never; query?: never; url: '/global/event'; }; export type GlobalEventResponses = { /** * Event stream */ 200: GlobalEvent; }; export type GlobalEventResponse = GlobalEventResponses[keyof GlobalEventResponses]; export type GlobalDisposeData = { body?: never; path?: never; query?: never; url: '/global/dispose'; }; export type GlobalDisposeResponses = { /** * Global disposed */ 200: boolean; }; export type GlobalDisposeResponse = GlobalDisposeResponses[keyof GlobalDisposeResponses]; export type ProjectListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/project'; }; export type ProjectListResponses = { /** * List of projects */ 200: Array; }; export type ProjectListResponse = ProjectListResponses[keyof ProjectListResponses]; export type ProjectCurrentData = { body?: never; path?: never; query?: { directory?: string; }; url: '/project/current'; }; export type ProjectCurrentResponses = { /** * Current project information */ 200: Project; }; export type ProjectCurrentResponse = ProjectCurrentResponses[keyof ProjectCurrentResponses]; export type ProjectUpdateData = { body?: { name?: string; icon?: { url?: string; color?: string; }; }; path: { projectID: string; }; query?: { directory?: string; }; url: '/project/{projectID}'; }; export type ProjectUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type ProjectUpdateError = ProjectUpdateErrors[keyof ProjectUpdateErrors]; export type ProjectUpdateResponses = { /** * Updated project information */ 200: Project; }; export type ProjectUpdateResponse = ProjectUpdateResponses[keyof ProjectUpdateResponses]; export type PtyListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/pty'; }; export type PtyListResponses = { /** * List of sessions */ 200: Array; }; export type PtyListResponse = PtyListResponses[keyof PtyListResponses]; export type PtyCreateData = { body?: { command?: string; args?: Array; cwd?: string; title?: string; env?: { [key: string]: string; }; }; path?: never; query?: { directory?: string; }; url: '/pty'; }; export type PtyCreateErrors = { /** * Bad request */ 400: BadRequestError; }; export type PtyCreateError = PtyCreateErrors[keyof PtyCreateErrors]; export type PtyCreateResponses = { /** * Created session */ 200: Pty; }; export type PtyCreateResponse = PtyCreateResponses[keyof PtyCreateResponses]; export type PtyRemoveData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyRemoveErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyRemoveError = PtyRemoveErrors[keyof PtyRemoveErrors]; export type PtyRemoveResponses = { /** * Session removed */ 200: boolean; }; export type PtyRemoveResponse = PtyRemoveResponses[keyof PtyRemoveResponses]; export type PtyGetData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyGetErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyGetError = PtyGetErrors[keyof PtyGetErrors]; export type PtyGetResponses = { /** * Session info */ 200: Pty; }; export type PtyGetResponse = PtyGetResponses[keyof PtyGetResponses]; export type PtyUpdateData = { body?: { title?: string; size?: { rows: number; cols: number; }; }; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}'; }; export type PtyUpdateErrors = { /** * Bad request */ 400: BadRequestError; }; export type PtyUpdateError = PtyUpdateErrors[keyof PtyUpdateErrors]; export type PtyUpdateResponses = { /** * Updated session */ 200: Pty; }; export type PtyUpdateResponse = PtyUpdateResponses[keyof PtyUpdateResponses]; export type PtyConnectData = { body?: never; path: { ptyID: string; }; query?: { directory?: string; }; url: '/pty/{ptyID}/connect'; }; export type PtyConnectErrors = { /** * Not found */ 404: NotFoundError; }; export type PtyConnectError = PtyConnectErrors[keyof PtyConnectErrors]; export type PtyConnectResponses = { /** * Connected session */ 200: boolean; }; export type PtyConnectResponse = PtyConnectResponses[keyof PtyConnectResponses]; export type ConfigGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/config'; }; export type ConfigGetResponses = { /** * Get config info */ 200: Config; }; export type ConfigGetResponse = ConfigGetResponses[keyof ConfigGetResponses]; export type ConfigUpdateData = { body?: Config; path?: never; query?: { directory?: string; }; url: '/config'; }; export type ConfigUpdateErrors = { /** * Bad request */ 400: BadRequestError; }; export type ConfigUpdateError = ConfigUpdateErrors[keyof ConfigUpdateErrors]; export type ConfigUpdateResponses = { /** * Successfully updated config */ 200: Config; }; export type ConfigUpdateResponse = ConfigUpdateResponses[keyof ConfigUpdateResponses]; export type ToolIdsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/experimental/tool/ids'; }; export type ToolIdsErrors = { /** * Bad request */ 400: BadRequestError; }; export type ToolIdsError = ToolIdsErrors[keyof ToolIdsErrors]; export type ToolIdsResponses = { /** * Tool IDs */ 200: ToolIds; }; export type ToolIdsResponse = ToolIdsResponses[keyof ToolIdsResponses]; export type ToolListData = { body?: never; path?: never; query: { directory?: string; provider: string; model: string; }; url: '/experimental/tool'; }; export type ToolListErrors = { /** * Bad request */ 400: BadRequestError; }; export type ToolListError = ToolListErrors[keyof ToolListErrors]; export type ToolListResponses = { /** * Tools */ 200: ToolList; }; export type ToolListResponse = ToolListResponses[keyof ToolListResponses]; export type InstanceDisposeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/instance/dispose'; }; export type InstanceDisposeResponses = { /** * Instance disposed */ 200: boolean; }; export type InstanceDisposeResponse = InstanceDisposeResponses[keyof InstanceDisposeResponses]; export type PathGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/path'; }; export type PathGetResponses = { /** * Path */ 200: Path; }; export type PathGetResponse = PathGetResponses[keyof PathGetResponses]; export type VcsGetData = { body?: never; path?: never; query?: { directory?: string; }; url: '/vcs'; }; export type VcsGetResponses = { /** * VCS info */ 200: VcsInfo; }; export type VcsGetResponse = VcsGetResponses[keyof VcsGetResponses]; export type SessionListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/session'; }; export type SessionListResponses = { /** * List of sessions */ 200: Array; }; export type SessionListResponse = SessionListResponses[keyof SessionListResponses]; export type SessionCreateData = { body?: { parentID?: string; title?: string; permission?: PermissionRuleset; }; path?: never; query?: { directory?: string; }; url: '/session'; }; export type SessionCreateErrors = { /** * Bad request */ 400: BadRequestError; }; export type SessionCreateError = SessionCreateErrors[keyof SessionCreateErrors]; export type SessionCreateResponses = { /** * Successfully created session */ 200: Session; }; export type SessionCreateResponse = SessionCreateResponses[keyof SessionCreateResponses]; export type SessionStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/session/status'; }; export type SessionStatusErrors = { /** * Bad request */ 400: BadRequestError; }; export type SessionStatusError = SessionStatusErrors[keyof SessionStatusErrors]; export type SessionStatusResponses = { /** * Get session status */ 200: { [key: string]: SessionStatus; }; }; export type SessionStatusResponse = SessionStatusResponses[keyof SessionStatusResponses]; export type SessionDeleteData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionDeleteErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionDeleteError = SessionDeleteErrors[keyof SessionDeleteErrors]; export type SessionDeleteResponses = { /** * Successfully deleted session */ 200: boolean; }; export type SessionDeleteResponse = SessionDeleteResponses[keyof SessionDeleteResponses]; export type SessionGetData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionGetErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionGetError = SessionGetErrors[keyof SessionGetErrors]; export type SessionGetResponses = { /** * Get session */ 200: Session; }; export type SessionGetResponse = SessionGetResponses[keyof SessionGetResponses]; export type SessionUpdateData = { body?: { title?: string; time?: { archived?: number; }; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}'; }; export type SessionUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUpdateError = SessionUpdateErrors[keyof SessionUpdateErrors]; export type SessionUpdateResponses = { /** * Successfully updated session */ 200: Session; }; export type SessionUpdateResponse = SessionUpdateResponses[keyof SessionUpdateResponses]; export type SessionChildrenData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/children'; }; export type SessionChildrenErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionChildrenError = SessionChildrenErrors[keyof SessionChildrenErrors]; export type SessionChildrenResponses = { /** * List of children */ 200: Array; }; export type SessionChildrenResponse = SessionChildrenResponses[keyof SessionChildrenResponses]; export type SessionTodoData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/todo'; }; export type SessionTodoErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionTodoError = SessionTodoErrors[keyof SessionTodoErrors]; export type SessionTodoResponses = { /** * Todo list */ 200: Array; }; export type SessionTodoResponse = SessionTodoResponses[keyof SessionTodoResponses]; export type SessionInitData = { body?: { modelID: string; providerID: string; messageID: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/init'; }; export type SessionInitErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionInitError = SessionInitErrors[keyof SessionInitErrors]; export type SessionInitResponses = { /** * 200 */ 200: boolean; }; export type SessionInitResponse = SessionInitResponses[keyof SessionInitResponses]; export type SessionForkData = { body?: { messageID?: string; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/fork'; }; export type SessionForkResponses = { /** * 200 */ 200: Session; }; export type SessionForkResponse = SessionForkResponses[keyof SessionForkResponses]; export type SessionAbortData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/abort'; }; export type SessionAbortErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionAbortError = SessionAbortErrors[keyof SessionAbortErrors]; export type SessionAbortResponses = { /** * Aborted session */ 200: boolean; }; export type SessionAbortResponse = SessionAbortResponses[keyof SessionAbortResponses]; export type SessionUnshareData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/share'; }; export type SessionUnshareErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUnshareError = SessionUnshareErrors[keyof SessionUnshareErrors]; export type SessionUnshareResponses = { /** * Successfully unshared session */ 200: Session; }; export type SessionUnshareResponse = SessionUnshareResponses[keyof SessionUnshareResponses]; export type SessionShareData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/share'; }; export type SessionShareErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionShareError = SessionShareErrors[keyof SessionShareErrors]; export type SessionShareResponses = { /** * Successfully shared session */ 200: Session; }; export type SessionShareResponse = SessionShareResponses[keyof SessionShareResponses]; export type SessionDiffData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; messageID?: string; }; url: '/session/{sessionID}/diff'; }; export type SessionDiffErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionDiffError = SessionDiffErrors[keyof SessionDiffErrors]; export type SessionDiffResponses = { /** * List of diffs */ 200: Array; }; export type SessionDiffResponse = SessionDiffResponses[keyof SessionDiffResponses]; export type SessionSummarizeData = { body?: { providerID: string; modelID: string; auto?: boolean; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/summarize'; }; export type SessionSummarizeErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionSummarizeError = SessionSummarizeErrors[keyof SessionSummarizeErrors]; export type SessionSummarizeResponses = { /** * Summarized session */ 200: boolean; }; export type SessionSummarizeResponse = SessionSummarizeResponses[keyof SessionSummarizeResponses]; export type SessionMessagesData = { body?: never; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; limit?: number; }; url: '/session/{sessionID}/message'; }; export type SessionMessagesErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionMessagesError = SessionMessagesErrors[keyof SessionMessagesErrors]; export type SessionMessagesResponses = { /** * List of messages */ 200: Array<{ info: Message; parts: Array; }>; }; export type SessionMessagesResponse = SessionMessagesResponses[keyof SessionMessagesResponses]; export type SessionPromptData = { body?: { messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; /** * @deprecated tools and permissions have been merged, you can set permissions on the session itself now */ tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message'; }; export type SessionPromptErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionPromptError = SessionPromptErrors[keyof SessionPromptErrors]; export type SessionPromptResponses = { /** * Created message */ 200: { info: AssistantMessage; parts: Array; }; }; export type SessionPromptResponse = SessionPromptResponses[keyof SessionPromptResponses]; export type SessionMessageData = { body?: never; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}'; }; export type SessionMessageErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionMessageError = SessionMessageErrors[keyof SessionMessageErrors]; export type SessionMessageResponses = { /** * Message */ 200: { info: Message; parts: Array; }; }; export type SessionMessageResponse = SessionMessageResponses[keyof SessionMessageResponses]; export type PartDeleteData = { body?: never; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; /** * Part ID */ partID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}/part/{partID}'; }; export type PartDeleteErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PartDeleteError = PartDeleteErrors[keyof PartDeleteErrors]; export type PartDeleteResponses = { /** * Successfully deleted part */ 200: boolean; }; export type PartDeleteResponse = PartDeleteResponses[keyof PartDeleteResponses]; export type PartUpdateData = { body?: Part; path: { /** * Session ID */ sessionID: string; /** * Message ID */ messageID: string; /** * Part ID */ partID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/message/{messageID}/part/{partID}'; }; export type PartUpdateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PartUpdateError = PartUpdateErrors[keyof PartUpdateErrors]; export type PartUpdateResponses = { /** * Successfully updated part */ 200: Part; }; export type PartUpdateResponse = PartUpdateResponses[keyof PartUpdateResponses]; export type SessionPromptAsyncData = { body?: { messageID?: string; model?: { providerID: string; modelID: string; }; agent?: string; noReply?: boolean; /** * @deprecated tools and permissions have been merged, you can set permissions on the session itself now */ tools?: { [key: string]: boolean; }; system?: string; variant?: string; parts: Array; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/prompt_async'; }; export type SessionPromptAsyncErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionPromptAsyncError = SessionPromptAsyncErrors[keyof SessionPromptAsyncErrors]; export type SessionPromptAsyncResponses = { /** * Prompt accepted */ 204: void; }; export type SessionPromptAsyncResponse = SessionPromptAsyncResponses[keyof SessionPromptAsyncResponses]; export type SessionCommandData = { body?: { messageID?: string; agent?: string; model?: string; arguments: string; command: string; variant?: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/command'; }; export type SessionCommandErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionCommandError = SessionCommandErrors[keyof SessionCommandErrors]; export type SessionCommandResponses = { /** * Created message */ 200: { info: AssistantMessage; parts: Array; }; }; export type SessionCommandResponse = SessionCommandResponses[keyof SessionCommandResponses]; export type SessionShellData = { body?: { agent: string; model?: { providerID: string; modelID: string; }; command: string; }; path: { /** * Session ID */ sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/shell'; }; export type SessionShellErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionShellError = SessionShellErrors[keyof SessionShellErrors]; export type SessionShellResponses = { /** * Created message */ 200: AssistantMessage; }; export type SessionShellResponse = SessionShellResponses[keyof SessionShellResponses]; export type SessionRevertData = { body?: { messageID: string; partID?: string; }; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/revert'; }; export type SessionRevertErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionRevertError = SessionRevertErrors[keyof SessionRevertErrors]; export type SessionRevertResponses = { /** * Updated session */ 200: Session; }; export type SessionRevertResponse = SessionRevertResponses[keyof SessionRevertResponses]; export type SessionUnrevertData = { body?: never; path: { sessionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/unrevert'; }; export type SessionUnrevertErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type SessionUnrevertError = SessionUnrevertErrors[keyof SessionUnrevertErrors]; export type SessionUnrevertResponses = { /** * Updated session */ 200: Session; }; export type SessionUnrevertResponse = SessionUnrevertResponses[keyof SessionUnrevertResponses]; export type PermissionRespondData = { body?: { response: 'once' | 'always' | 'reject'; }; path: { sessionID: string; permissionID: string; }; query?: { directory?: string; }; url: '/session/{sessionID}/permissions/{permissionID}'; }; export type PermissionRespondErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PermissionRespondError = PermissionRespondErrors[keyof PermissionRespondErrors]; export type PermissionRespondResponses = { /** * Permission processed successfully */ 200: boolean; }; export type PermissionRespondResponse = PermissionRespondResponses[keyof PermissionRespondResponses]; export type PermissionReplyData = { body?: { reply: 'once' | 'always' | 'reject'; }; path: { requestID: string; }; query?: { directory?: string; }; url: '/permission/{requestID}/reply'; }; export type PermissionReplyErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type PermissionReplyError = PermissionReplyErrors[keyof PermissionReplyErrors]; export type PermissionReplyResponses = { /** * Permission processed successfully */ 200: boolean; }; export type PermissionReplyResponse = PermissionReplyResponses[keyof PermissionReplyResponses]; export type PermissionListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/permission'; }; export type PermissionListResponses = { /** * List of pending permissions */ 200: Array; }; export type PermissionListResponse = PermissionListResponses[keyof PermissionListResponses]; export type CommandListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/command'; }; export type CommandListResponses = { /** * List of commands */ 200: Array; }; export type CommandListResponse = CommandListResponses[keyof CommandListResponses]; export type ConfigProvidersData = { body?: never; path?: never; query?: { directory?: string; }; url: '/config/providers'; }; export type ConfigProvidersResponses = { /** * List of providers */ 200: { providers: Array; default: { [key: string]: string; }; }; }; export type ConfigProvidersResponse = ConfigProvidersResponses[keyof ConfigProvidersResponses]; export type ProviderListData = { body?: never; path?: never; query?: { directory?: string; }; url: '/provider'; }; export type ProviderListResponses = { /** * List of providers */ 200: { all: Array<{ api?: string; name: string; env: Array; id: string; npm?: string; models: { [key: string]: { id: string; name: string; family?: string; release_date: string; attachment: boolean; reasoning: boolean; temperature: boolean; tool_call: boolean; interleaved?: true | { field: 'reasoning_content' | 'reasoning_details'; }; cost?: { input: number; output: number; cache_read?: number; cache_write?: number; context_over_200k?: { input: number; output: number; cache_read?: number; cache_write?: number; }; }; limit: { context: number; output: number; }; modalities?: { input: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; output: Array<'text' | 'audio' | 'image' | 'video' | 'pdf'>; }; experimental?: boolean; status?: 'alpha' | 'beta' | 'deprecated'; options: { [key: string]: unknown; }; headers?: { [key: string]: string; }; provider?: { npm: string; }; variants?: { [key: string]: { [key: string]: unknown; }; }; }; }; }>; default: { [key: string]: string; }; connected: Array; }; }; export type ProviderListResponse = ProviderListResponses[keyof ProviderListResponses]; export type ProviderAuthData = { body?: never; path?: never; query?: { directory?: string; }; url: '/provider/auth'; }; export type ProviderAuthResponses = { /** * Provider auth methods */ 200: { [key: string]: Array; }; }; export type ProviderAuthResponse = ProviderAuthResponses[keyof ProviderAuthResponses]; export type ProviderOauthAuthorizeData = { body?: { /** * Auth method index */ method: number; }; path: { /** * Provider ID */ providerID: string; }; query?: { directory?: string; }; url: '/provider/{providerID}/oauth/authorize'; }; export type ProviderOauthAuthorizeErrors = { /** * Bad request */ 400: BadRequestError; }; export type ProviderOauthAuthorizeError = ProviderOauthAuthorizeErrors[keyof ProviderOauthAuthorizeErrors]; export type ProviderOauthAuthorizeResponses = { /** * Authorization URL and method */ 200: ProviderAuthAuthorization; }; export type ProviderOauthAuthorizeResponse = ProviderOauthAuthorizeResponses[keyof ProviderOauthAuthorizeResponses]; export type ProviderOauthCallbackData = { body?: { /** * Auth method index */ method: number; /** * OAuth authorization code */ code?: string; }; path: { /** * Provider ID */ providerID: string; }; query?: { directory?: string; }; url: '/provider/{providerID}/oauth/callback'; }; export type ProviderOauthCallbackErrors = { /** * Bad request */ 400: BadRequestError; }; export type ProviderOauthCallbackError = ProviderOauthCallbackErrors[keyof ProviderOauthCallbackErrors]; export type ProviderOauthCallbackResponses = { /** * OAuth callback processed successfully */ 200: boolean; }; export type ProviderOauthCallbackResponse = ProviderOauthCallbackResponses[keyof ProviderOauthCallbackResponses]; export type FindTextData = { body?: never; path?: never; query: { directory?: string; pattern: string; }; url: '/find'; }; export type FindTextResponses = { /** * Matches */ 200: Array<{ path: { text: string; }; lines: { text: string; }; line_number: number; absolute_offset: number; submatches: Array<{ match: { text: string; }; start: number; end: number; }>; }>; }; export type FindTextResponse = FindTextResponses[keyof FindTextResponses]; export type FindFilesData = { body?: never; path?: never; query: { directory?: string; query: string; dirs?: 'true' | 'false'; type?: 'file' | 'directory'; limit?: number; }; url: '/find/file'; }; export type FindFilesResponses = { /** * File paths */ 200: Array; }; export type FindFilesResponse = FindFilesResponses[keyof FindFilesResponses]; export type FindSymbolsData = { body?: never; path?: never; query: { directory?: string; query: string; }; url: '/find/symbol'; }; export type FindSymbolsResponses = { /** * Symbols */ 200: Array; }; export type FindSymbolsResponse = FindSymbolsResponses[keyof FindSymbolsResponses]; export type FileListData = { body?: never; path?: never; query: { directory?: string; path: string; }; url: '/file'; }; export type FileListResponses = { /** * Files and directories */ 200: Array; }; export type FileListResponse = FileListResponses[keyof FileListResponses]; export type FileReadData = { body?: never; path?: never; query: { directory?: string; path: string; }; url: '/file/content'; }; export type FileReadResponses = { /** * File content */ 200: FileContent; }; export type FileReadResponse = FileReadResponses[keyof FileReadResponses]; export type FileStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/file/status'; }; export type FileStatusResponses = { /** * File status */ 200: Array; }; export type FileStatusResponse = FileStatusResponses[keyof FileStatusResponses]; export type AppLogData = { body?: { /** * Service name for the log entry */ service: string; /** * Log level */ level: 'debug' | 'info' | 'error' | 'warn'; /** * Log message */ message: string; /** * Additional metadata for the log entry */ extra?: { [key: string]: unknown; }; }; path?: never; query?: { directory?: string; }; url: '/log'; }; export type AppLogErrors = { /** * Bad request */ 400: BadRequestError; }; export type AppLogError = AppLogErrors[keyof AppLogErrors]; export type AppLogResponses = { /** * Log entry written successfully */ 200: boolean; }; export type AppLogResponse = AppLogResponses[keyof AppLogResponses]; export type AppAgentsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/agent'; }; export type AppAgentsResponses = { /** * List of agents */ 200: Array; }; export type AppAgentsResponse = AppAgentsResponses[keyof AppAgentsResponses]; export type McpStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/mcp'; }; export type McpStatusResponses = { /** * MCP server status */ 200: { [key: string]: McpStatus; }; }; export type McpStatusResponse = McpStatusResponses[keyof McpStatusResponses]; export type McpAddData = { body?: { name: string; config: McpLocalConfig | McpRemoteConfig; }; path?: never; query?: { directory?: string; }; url: '/mcp'; }; export type McpAddErrors = { /** * Bad request */ 400: BadRequestError; }; export type McpAddError = McpAddErrors[keyof McpAddErrors]; export type McpAddResponses = { /** * MCP server added successfully */ 200: { [key: string]: McpStatus; }; }; export type McpAddResponse = McpAddResponses[keyof McpAddResponses]; export type McpAuthRemoveData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth'; }; export type McpAuthRemoveErrors = { /** * Not found */ 404: NotFoundError; }; export type McpAuthRemoveError = McpAuthRemoveErrors[keyof McpAuthRemoveErrors]; export type McpAuthRemoveResponses = { /** * OAuth credentials removed */ 200: { success: true; }; }; export type McpAuthRemoveResponse = McpAuthRemoveResponses[keyof McpAuthRemoveResponses]; export type McpAuthStartData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth'; }; export type McpAuthStartErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthStartError = McpAuthStartErrors[keyof McpAuthStartErrors]; export type McpAuthStartResponses = { /** * OAuth flow started */ 200: { /** * URL to open in browser for authorization */ authorizationUrl: string; }; }; export type McpAuthStartResponse = McpAuthStartResponses[keyof McpAuthStartResponses]; export type McpAuthCallbackData = { body?: { /** * Authorization code from OAuth callback */ code: string; }; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth/callback'; }; export type McpAuthCallbackErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthCallbackError = McpAuthCallbackErrors[keyof McpAuthCallbackErrors]; export type McpAuthCallbackResponses = { /** * OAuth authentication completed */ 200: McpStatus; }; export type McpAuthCallbackResponse = McpAuthCallbackResponses[keyof McpAuthCallbackResponses]; export type McpAuthAuthenticateData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/auth/authenticate'; }; export type McpAuthAuthenticateErrors = { /** * Bad request */ 400: BadRequestError; /** * Not found */ 404: NotFoundError; }; export type McpAuthAuthenticateError = McpAuthAuthenticateErrors[keyof McpAuthAuthenticateErrors]; export type McpAuthAuthenticateResponses = { /** * OAuth authentication completed */ 200: McpStatus; }; export type McpAuthAuthenticateResponse = McpAuthAuthenticateResponses[keyof McpAuthAuthenticateResponses]; export type McpConnectData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/connect'; }; export type McpConnectResponses = { /** * MCP server connected successfully */ 200: boolean; }; export type McpConnectResponse = McpConnectResponses[keyof McpConnectResponses]; export type McpDisconnectData = { body?: never; path: { name: string; }; query?: { directory?: string; }; url: '/mcp/{name}/disconnect'; }; export type McpDisconnectResponses = { /** * MCP server disconnected successfully */ 200: boolean; }; export type McpDisconnectResponse = McpDisconnectResponses[keyof McpDisconnectResponses]; export type LspStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/lsp'; }; export type LspStatusResponses = { /** * LSP server status */ 200: Array; }; export type LspStatusResponse = LspStatusResponses[keyof LspStatusResponses]; export type FormatterStatusData = { body?: never; path?: never; query?: { directory?: string; }; url: '/formatter'; }; export type FormatterStatusResponses = { /** * Formatter status */ 200: Array; }; export type FormatterStatusResponse = FormatterStatusResponses[keyof FormatterStatusResponses]; export type TuiAppendPromptData = { body?: { text: string; }; path?: never; query?: { directory?: string; }; url: '/tui/append-prompt'; }; export type TuiAppendPromptErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiAppendPromptError = TuiAppendPromptErrors[keyof TuiAppendPromptErrors]; export type TuiAppendPromptResponses = { /** * Prompt processed successfully */ 200: boolean; }; export type TuiAppendPromptResponse = TuiAppendPromptResponses[keyof TuiAppendPromptResponses]; export type TuiOpenHelpData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-help'; }; export type TuiOpenHelpResponses = { /** * Help dialog opened successfully */ 200: boolean; }; export type TuiOpenHelpResponse = TuiOpenHelpResponses[keyof TuiOpenHelpResponses]; export type TuiOpenSessionsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-sessions'; }; export type TuiOpenSessionsResponses = { /** * Session dialog opened successfully */ 200: boolean; }; export type TuiOpenSessionsResponse = TuiOpenSessionsResponses[keyof TuiOpenSessionsResponses]; export type TuiOpenThemesData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-themes'; }; export type TuiOpenThemesResponses = { /** * Theme dialog opened successfully */ 200: boolean; }; export type TuiOpenThemesResponse = TuiOpenThemesResponses[keyof TuiOpenThemesResponses]; export type TuiOpenModelsData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/open-models'; }; export type TuiOpenModelsResponses = { /** * Model dialog opened successfully */ 200: boolean; }; export type TuiOpenModelsResponse = TuiOpenModelsResponses[keyof TuiOpenModelsResponses]; export type TuiSubmitPromptData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/submit-prompt'; }; export type TuiSubmitPromptResponses = { /** * Prompt submitted successfully */ 200: boolean; }; export type TuiSubmitPromptResponse = TuiSubmitPromptResponses[keyof TuiSubmitPromptResponses]; export type TuiClearPromptData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/clear-prompt'; }; export type TuiClearPromptResponses = { /** * Prompt cleared successfully */ 200: boolean; }; export type TuiClearPromptResponse = TuiClearPromptResponses[keyof TuiClearPromptResponses]; export type TuiExecuteCommandData = { body?: { command: string; }; path?: never; query?: { directory?: string; }; url: '/tui/execute-command'; }; export type TuiExecuteCommandErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiExecuteCommandError = TuiExecuteCommandErrors[keyof TuiExecuteCommandErrors]; export type TuiExecuteCommandResponses = { /** * Command executed successfully */ 200: boolean; }; export type TuiExecuteCommandResponse = TuiExecuteCommandResponses[keyof TuiExecuteCommandResponses]; export type TuiShowToastData = { body?: { title?: string; message: string; variant: 'info' | 'success' | 'warning' | 'error'; /** * Duration in milliseconds */ duration?: number; }; path?: never; query?: { directory?: string; }; url: '/tui/show-toast'; }; export type TuiShowToastResponses = { /** * Toast notification shown successfully */ 200: boolean; }; export type TuiShowToastResponse = TuiShowToastResponses[keyof TuiShowToastResponses]; export type TuiPublishData = { body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow; path?: never; query?: { directory?: string; }; url: '/tui/publish'; }; export type TuiPublishErrors = { /** * Bad request */ 400: BadRequestError; }; export type TuiPublishError = TuiPublishErrors[keyof TuiPublishErrors]; export type TuiPublishResponses = { /** * Event published successfully */ 200: boolean; }; export type TuiPublishResponse = TuiPublishResponses[keyof TuiPublishResponses]; export type TuiControlNextData = { body?: never; path?: never; query?: { directory?: string; }; url: '/tui/control/next'; }; export type TuiControlNextResponses = { /** * Next TUI request */ 200: { path: string; body: unknown; }; }; export type TuiControlNextResponse = TuiControlNextResponses[keyof TuiControlNextResponses]; export type TuiControlResponseData = { body?: unknown; path?: never; query?: { directory?: string; }; url: '/tui/control/response'; }; export type TuiControlResponseResponses = { /** * Response submitted successfully */ 200: boolean; }; export type TuiControlResponseResponse = TuiControlResponseResponses[keyof TuiControlResponseResponses]; export type AuthSetData = { body?: Auth; path: { providerID: string; }; query?: { directory?: string; }; url: '/auth/{providerID}'; }; export type AuthSetErrors = { /** * Bad request */ 400: BadRequestError; }; export type AuthSetError = AuthSetErrors[keyof AuthSetErrors]; export type AuthSetResponses = { /** * Successfully set authentication credentials */ 200: boolean; }; export type AuthSetResponse = AuthSetResponses[keyof AuthSetResponses]; export type EventSubscribeData = { body?: never; path?: never; query?: { directory?: string; }; url: '/event'; }; export type EventSubscribeResponses = { /** * Event stream */ 200: Event; }; export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; ================================================ FILE: packages/openapi-ts-tests/sdks/package.json ================================================ { "name": "@test/openapi-ts-sdks", "version": "0.0.0", "private": true, "type": "module", "scripts": { "typecheck": "tsgo --noEmit" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "typescript": "5.9.3" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts-tests/sdks/test/method-class-conflict.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; import { createSdkConfig, getSnapshotsPath, getTempSnapshotsPath } from './utils'; const namespace = 'method-class-conflict'; const outputDir = path.join(getTempSnapshotsPath(), namespace); const snapshotsDir = path.join(getSnapshotsPath(), namespace); const specPath = path.join(getSpecsPath(), '3.0.x', 'sdk-method-class-conflict.yaml'); describe(`SDK: ${namespace}`, () => { const createConfig = createSdkConfig({ outputDir, }); const scenarios = [ { config: createConfig({ input: specPath, output: { entryFile: false, path: 'class', }, plugins: [ { asClass: true, instance: false, name: '@hey-api/sdk', }, ], }), description: 'class', }, { config: createConfig({ input: specPath, output: { entryFile: false, path: 'flat', }, plugins: [ { asClass: false, instance: false, name: '@hey-api/sdk', }, ], }), description: 'flat', }, { config: createConfig({ input: specPath, output: { entryFile: false, path: 'instance', }, plugins: [ { instance: true, name: '@hey-api/sdk', }, ], }), description: 'instance', }, ]; it.each(scenarios)( '$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths( typeof config.output === 'string' ? config.output : config.output.path, ); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }, 15_000, ); }); ================================================ FILE: packages/openapi-ts-tests/sdks/test/opencode.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths, getSpecsPath } from '../../utils'; import { createSdkConfig, getSnapshotsPath, getTempSnapshotsPath } from './utils'; const namespace = 'opencode'; const outputDir = path.join(getTempSnapshotsPath(), namespace); const snapshotsDir = path.join(getSnapshotsPath(), namespace); const specPath = path.join(getSpecsPath(), '3.1.x', 'opencode.yaml'); describe(`SDK: ${namespace}`, () => { const createConfig = createSdkConfig({ outputDir, }); const scenarios = [ { config: createConfig({ input: specPath, output: { path: 'export-all', preferExportAll: true, }, plugins: [ { name: '@hey-api/sdk', paramsStructure: 'flat', }, ], }), description: 'export all', }, { config: createConfig({ input: specPath, output: 'flat', plugins: [ { name: '@hey-api/sdk', paramsStructure: 'flat', }, ], }), description: 'flat', }, { config: createConfig({ input: specPath, output: 'grouped', plugins: [ { name: '@hey-api/sdk', paramsStructure: 'grouped', }, ], }), description: 'grouped', }, ]; it.each(scenarios)( '$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths( typeof config.output === 'string' ? config.output : config.output.path, ); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }, 15_000, ); }); ================================================ FILE: packages/openapi-ts-tests/sdks/test/utils.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { type UserConfig } from '@hey-api/openapi-ts'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export const createSdkConfig = ({ outputDir }: { outputDir: string }) => (userConfig: UserConfig) => ({ ...userConfig, logs: { level: 'silent', path: './logs', }, output: typeof userConfig.output === 'string' ? path.join(outputDir, userConfig.output) : { ...userConfig.output, path: path.join( outputDir, userConfig.output instanceof Array ? '' : userConfig.output.path, ), }, }) as const satisfies UserConfig; export const getSnapshotsPath = (): string => path.join(__dirname, '..', '__snapshots__'); export const getTempSnapshotsPath = (): string => path.join(__dirname, '..', '.gen', 'snapshots'); ================================================ FILE: packages/openapi-ts-tests/sdks/tsconfig.json ================================================ { "extends": "../tsconfig.base.json", "include": ["test/**/*", "__snapshots__/**/*"], "exclude": [".gen/**/*"], "references": [{ "path": "../../openapi-ts" }] } ================================================ FILE: packages/openapi-ts-tests/sdks/turbo.json ================================================ { "$schema": "../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts-tests/sdks/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-ts-tests/tsconfig.base.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "declaration": false, "declarationMap": false, "noEmit": true, "noImplicitOverride": true, "noImplicitReturns": true, "noUnusedLocals": true, "noUnusedParameters": true, "types": ["vitest/globals"], "useUnknownInCatchVariables": false } } ================================================ FILE: packages/openapi-ts-tests/utils.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; export const getFilePaths = (dirPath: string): Array => { let filePaths: Array = []; const files = fs.readdirSync(dirPath); for (const file of files) { const filePath = path.join(dirPath, file); const stat = fs.statSync(filePath); if (stat.isDirectory()) { filePaths = filePaths.concat(getFilePaths(filePath)); } else { filePaths.push(filePath); } } return filePaths; }; export const getSpecsPath = (): string => path.join(__dirname, '..', '..', 'specs'); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.0.x/array-items-one-of-length-1/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBar = v.string(); export const vFoo = v.object({ foo: v.optional(v.pipe(v.array(vBar), v.minLength(1), v.maxLength(2147483647))) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.0.x/enum-null/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vFoo = v.nullable(v.picklist(['foo', 'bar'])); export const vBar = v.picklist(['foo', 'bar']); export const vBaz = v.picklist(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.0.x/validators/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBaz = v.optional(v.pipe(v.pipe(v.string(), v.regex(/foo\nbar/)), v.readonly()), 'baz'); export const vFoo: v.GenericSchema = v.nullish(v.object({ foo: v.optional(v.pipe(v.string(), v.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: v.optional(v.lazy(() => vBar)), baz: v.optional(v.array(v.lazy(() => vFoo))), qux: v.optional(v.pipe(v.number(), v.integer(), v.gtValue(0)), 0) }), null); export const vBar = v.object({ foo: v.optional(vFoo) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/array-items-one-of-length-1/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBar = v.string(); export const vFoo = v.object({ foo: v.optional(v.pipe(v.array(vBar), v.minLength(1), v.maxLength(2147483647))) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/enum-null/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vFoo = v.nullable(v.picklist(['foo', 'bar'])); export const vBar = v.picklist(['foo', 'bar']); export const vBaz = v.picklist(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/integer-formats/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vIntegerFormats = v.object({ numberNoFormat: v.optional(v.number()), numberInt8: v.optional(v.pipe(v.number(), v.minValue(-128, 'Invalid value: Expected int8 to be >= -128'), v.maxValue(127, 'Invalid value: Expected int8 to be <= 127'))), numberInt16: v.optional(v.pipe(v.number(), v.minValue(-32768, 'Invalid value: Expected int16 to be >= -32768'), v.maxValue(32767, 'Invalid value: Expected int16 to be <= 32767'))), numberInt32: v.optional(v.pipe(v.number(), v.minValue(-2147483648, 'Invalid value: Expected int32 to be >= -2147483648'), v.maxValue(2147483647, 'Invalid value: Expected int32 to be <= 2147483647'))), numberInt64: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), numberUint8: v.optional(v.pipe(v.number(), v.minValue(0, 'Invalid value: Expected uint8 to be >= 0'), v.maxValue(255, 'Invalid value: Expected uint8 to be <= 255'))), numberUint16: v.optional(v.pipe(v.number(), v.minValue(0, 'Invalid value: Expected uint16 to be >= 0'), v.maxValue(65535, 'Invalid value: Expected uint16 to be <= 65535'))), numberUint32: v.optional(v.pipe(v.number(), v.minValue(0, 'Invalid value: Expected uint32 to be >= 0'), v.maxValue(4294967295, 'Invalid value: Expected uint32 to be <= 4294967295'))), numberUint64: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('0'), 'Invalid value: Expected uint64 to be >= 0'), v.maxValue(BigInt('18446744073709551615'), 'Invalid value: Expected uint64 to be <= 18446744073709551615'))), integerNoFormat: v.optional(v.pipe(v.number(), v.integer())), integerInt8: v.optional(v.pipe(v.number(), v.integer(), v.minValue(-128, 'Invalid value: Expected int8 to be >= -128'), v.maxValue(127, 'Invalid value: Expected int8 to be <= 127'))), integerInt16: v.optional(v.pipe(v.number(), v.integer(), v.minValue(-32768, 'Invalid value: Expected int16 to be >= -32768'), v.maxValue(32767, 'Invalid value: Expected int16 to be <= 32767'))), integerInt32: v.optional(v.pipe(v.number(), v.integer(), v.minValue(-2147483648, 'Invalid value: Expected int32 to be >= -2147483648'), v.maxValue(2147483647, 'Invalid value: Expected int32 to be <= 2147483647'))), integerInt64: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), integerUint8: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0, 'Invalid value: Expected uint8 to be >= 0'), v.maxValue(255, 'Invalid value: Expected uint8 to be <= 255'))), integerUint16: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0, 'Invalid value: Expected uint16 to be >= 0'), v.maxValue(65535, 'Invalid value: Expected uint16 to be <= 65535'))), integerUint32: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0, 'Invalid value: Expected uint32 to be >= 0'), v.maxValue(4294967295, 'Invalid value: Expected uint32 to be <= 4294967295'))), integerUint64: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('0'), 'Invalid value: Expected uint64 to be >= 0'), v.maxValue(BigInt('18446744073709551615'), 'Invalid value: Expected uint64 to be <= 18446744073709551615'))), stringInt64: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), stringUint64: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('0'), 'Invalid value: Expected uint64 to be >= 0'), v.maxValue(BigInt('18446744073709551615'), 'Invalid value: Expected uint64 to be <= 18446744073709551615'))) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/schema-const/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vFoo = v.object({ foo: v.optional(v.literal('foo')), bar: v.optional(v.literal(3.2)), baz: v.optional(v.literal(-1)), qux: v.optional(v.literal(true)), quux: v.optional(v.tuple([ v.literal(1), v.literal(2), v.literal(3), v.literal('foo'), v.literal(true) ])), corge: v.optional(v.record(v.string(), v.unknown())), garply: v.optional(v.literal(BigInt('10'))), numberInt8: v.optional(v.literal(100)), numberInt16: v.optional(v.literal(1000)), numberInt32: v.optional(v.literal(100000)), numberInt64: v.optional(v.literal(BigInt(1000000000000))), numberUint8: v.optional(v.literal(200)), numberUint16: v.optional(v.literal(50000)), numberUint32: v.optional(v.literal(3000000000)), numberUint64: v.optional(v.literal(BigInt(18000000000000000000))), integerInt8: v.optional(v.literal(-100)), integerInt16: v.optional(v.literal(-1000)), integerInt32: v.optional(v.literal(-100000)), integerInt64: v.optional(v.literal(BigInt(-1000000000000))), integerUint8: v.optional(v.literal(255)), integerUint16: v.optional(v.literal(65535)), integerUint32: v.optional(v.literal(4294967295)), integerUint64: v.optional(v.literal(BigInt('18446744073709551615'))), stringInt64: v.optional(v.literal(BigInt('-9223372036854775808'))), stringUint64: v.optional(v.literal(BigInt('18446744073709551615'))) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/string-with-format/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vFoo = v.object({ foo: v.optional(v.array(v.unknown())) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/time-format/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vGetSearchData = v.object({ body: v.optional(v.never()), path: v.optional(v.never()), query: v.object({ start_time: v.optional(v.pipe(v.string(), v.isoTimeSecond())), end_time: v.pipe(v.string(), v.isoTimeSecond()) }) }); /** * Success */ export const vGetSearchResponse = v.object({ result: v.optional(v.string()), scheduled_time: v.optional(v.pipe(v.string(), v.isoTimeSecond())) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { vPostFooData, vPostFooResponse } from './valibot.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await v.parseAsync(vPostFooData, data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await v.parseAsync(vPostFooResponse, data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/type-format/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vFoo = v.object({ bar: v.optional(v.pipe(v.number(), v.integer())), foo: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), BigInt(0)), id: v.string() }); export const vBar = v.objectWithRest({ foo: v.pipe(v.number(), v.integer()) }, v.pipe(v.number(), v.integer())); export const vPostFooData = v.object({ body: v.optional(v.never()), path: v.optional(v.never()), query: v.optional(v.never()) }); /** * OK */ export const vPostFooResponse = vFoo; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBaz = v.optional(v.pipe(v.pipe(v.string(), v.regex(/foo\nbar/)), v.readonly()), 'baz'); export const vQux = v.record(v.string(), v.object({ qux: v.optional(v.string()) })); /** * This is Foo schema. */ export const vFoo: v.GenericSchema = v.nullish(v.object({ foo: v.optional(v.pipe(v.string(), v.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: v.optional(v.lazy(() => vBar)), baz: v.optional(v.array(v.lazy(() => vFoo))), qux: v.optional(v.pipe(v.number(), v.integer(), v.gtValue(0)), 0) }), null); /** * This is Bar schema. */ export const vBar = v.object({ foo: v.optional(vFoo) }); /** * This is Foo parameter. */ export const vFoo2 = v.string(); export const vFoo3 = v.object({ foo: v.optional(vBar) }); export const vPatchFooData = v.object({ body: v.object({ foo: v.optional(v.string()) }), path: v.optional(v.never()), query: v.optional(v.object({ foo: v.optional(v.string()), bar: v.optional(vBar), baz: v.optional(v.object({ baz: v.optional(v.string()) })), qux: v.optional(v.pipe(v.string(), v.isoDate())), quux: v.optional(v.pipe(v.string(), v.isoTimestamp())) })) }); export const vPostFooData = v.object({ body: vFoo3, path: v.optional(v.never()), query: v.optional(v.never()) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators-bigint-min-max/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vFoo = v.object({ foo: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt(0)), v.maxValue(BigInt(100)))) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators-circular-ref/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBar: v.GenericSchema = v.object({ bar: v.optional(v.array(v.lazy(() => vBar))) }); export const vFoo = v.object({ foo: v.optional(vBar) }); export const vBaz: v.GenericSchema = v.lazy(() => vQux); /** * description caused circular reference error */ export const vQux = vBaz; ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators-circular-ref-2/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBar: v.GenericSchema = v.strictObject({ bar: v.nullable(v.array(v.lazy(() => vBar))) }); export const vFoo = v.strictObject({ foo: vBar }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators-metadata/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBaz = v.optional(v.pipe(v.pipe(v.string(), v.regex(/foo\nbar/)), v.readonly()), 'baz'); export const vQux = v.record(v.string(), v.object({ qux: v.optional(v.string()) })); /** * This is Foo schema. */ export const vFoo: v.GenericSchema = v.nullish(v.object({ foo: v.optional(v.pipe(v.pipe(v.string(), v.regex(/^\d{3}-\d{2}-\d{4}$/)), v.metadata({ description: 'This is foo property.' }))), bar: v.optional(v.lazy(() => vBar)), baz: v.optional(v.pipe(v.array(v.lazy(() => vFoo)), v.metadata({ description: 'This is baz property.' }))), qux: v.optional(v.pipe(v.pipe(v.number(), v.integer(), v.gtValue(0)), v.metadata({ description: 'This is qux property.' })), 0) }), null); /** * This is Bar schema. */ export const vBar = v.pipe(v.object({ foo: v.optional(vFoo) }), v.metadata({ description: 'This is Bar schema.' })); /** * This is Foo parameter. */ export const vFoo2 = v.pipe(v.string(), v.metadata({ description: 'This is Foo parameter.' })); export const vFoo3 = v.object({ foo: v.optional(vBar) }); export const vPatchFooData = v.object({ body: v.object({ foo: v.optional(v.string()) }), path: v.optional(v.never()), query: v.optional(v.object({ foo: v.optional(v.pipe(v.string(), v.metadata({ description: 'This is Foo parameter.' }))), bar: v.optional(vBar), baz: v.optional(v.object({ baz: v.optional(v.string()) })), qux: v.optional(v.pipe(v.string(), v.isoDate())), quux: v.optional(v.pipe(v.string(), v.isoTimestamp())) })) }); export const vPostFooData = v.object({ body: vFoo3, path: v.optional(v.never()), query: v.optional(v.never()) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators-metadata-fn/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBaz = v.optional(v.pipe(v.pipe(v.string(), v.regex(/foo\nbar/)), v.metadata({ custom: 'value', title: 'string' }), v.readonly()), 'baz'); export const vQux = v.pipe(v.record(v.string(), v.pipe(v.object({ qux: v.optional(v.pipe(v.string(), v.metadata({ custom: 'value', title: 'string' }))) }), v.metadata({ custom: 'value', title: 'object' }))), v.metadata({ custom: 'value', title: 'object' })); /** * This is Foo schema. */ export const vFoo: v.GenericSchema = v.nullish(v.pipe(v.object({ foo: v.optional(v.pipe(v.pipe(v.string(), v.regex(/^\d{3}-\d{2}-\d{4}$/)), v.metadata({ custom: 'value', title: 'This is foo property.' }))), bar: v.optional(v.lazy(() => vBar)), baz: v.optional(v.pipe(v.array(v.lazy(() => vFoo)), v.metadata({ custom: 'value', title: 'This is baz property.' }))), qux: v.optional(v.pipe(v.pipe(v.number(), v.integer(), v.gtValue(0)), v.metadata({ custom: 'value', title: 'This is qux property.' })), 0) }), v.metadata({ custom: 'value', title: 'object' })), null); /** * This is Bar schema. */ export const vBar = v.pipe(v.object({ foo: v.optional(vFoo) }), v.metadata({ custom: 'value', title: 'This is Bar schema.' })); /** * This is Foo parameter. */ export const vFoo2 = v.pipe(v.string(), v.metadata({ custom: 'value', title: 'This is Foo parameter.' })); export const vFoo3 = v.pipe(v.object({ foo: v.optional(vBar) }), v.metadata({ custom: 'value', title: 'object' })); export const vPatchFooData = v.pipe(v.object({ body: v.pipe(v.object({ foo: v.optional(v.pipe(v.string(), v.metadata({ custom: 'value', title: 'string' }))) }), v.metadata({ custom: 'value', title: 'object' })), path: v.optional(v.pipe(v.never(), v.metadata({ custom: 'value', title: 'never' }))), query: v.optional(v.pipe(v.object({ foo: v.optional(v.pipe(v.string(), v.metadata({ custom: 'value', title: 'This is Foo parameter.' }))), bar: v.optional(vBar), baz: v.optional(v.pipe(v.object({ baz: v.optional(v.pipe(v.string(), v.metadata({ custom: 'value', title: 'string' }))) }), v.metadata({ custom: 'value', title: 'object' }))), qux: v.optional(v.pipe(v.pipe(v.string(), v.isoDate()), v.metadata({ custom: 'value', title: 'string' }))), quux: v.optional(v.pipe(v.pipe(v.string(), v.isoTimestamp()), v.metadata({ custom: 'value', title: 'string' }))) }), v.metadata({ custom: 'value', title: 'object' }))) }), v.metadata({ custom: 'value', title: 'object' })); export const vPostFooData = v.pipe(v.object({ body: vFoo3, path: v.optional(v.pipe(v.never(), v.metadata({ custom: 'value', title: 'never' }))), query: v.optional(v.pipe(v.never(), v.metadata({ custom: 'value', title: 'never' }))) }), v.metadata({ custom: 'value', title: 'object' })); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators-types/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vBaz = v.optional(v.pipe(v.pipe(v.string(), v.regex(/foo\nbar/)), v.readonly()), 'baz'); export const vQux = v.record(v.string(), v.object({ qux: v.optional(v.string()) })); /** * This is Foo schema. */ export const vFoo: v.GenericSchema = v.nullish(v.object({ foo: v.optional(v.pipe(v.string(), v.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: v.optional(v.lazy(() => vBar)), baz: v.optional(v.array(v.lazy(() => vFoo))), qux: v.optional(v.pipe(v.number(), v.integer(), v.gtValue(0)), 0) }), null); /** * This is Bar schema. */ export const vBar = v.object({ foo: v.optional(vFoo) }); /** * This is Foo parameter. */ export const vFoo2 = v.string(); export const vFoo3 = v.object({ foo: v.optional(vBar) }); export const vPatchFooData = v.object({ body: v.object({ foo: v.optional(v.string()) }), path: v.optional(v.never()), query: v.optional(v.object({ foo: v.optional(v.string()), bar: v.optional(vBar), baz: v.optional(v.object({ baz: v.optional(v.string()) })), qux: v.optional(v.pipe(v.string(), v.isoDate())), quux: v.optional(v.pipe(v.string(), v.isoTimestamp())) })) }); export const vPostFooData = v.object({ body: vFoo3, path: v.optional(v.never()), query: v.optional(v.never()) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/validators-union-merge/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vContact = v.union([v.object({ email: v.string() }), v.object({ phone: v.string() })]); export const vUser = v.intersect([vContact, v.object({ username: v.string() })]); export const vDogDetails = v.object({ breed: v.string(), barkVolume: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(10)) }); export const vCatDetails = v.object({ furLength: v.picklist([ 'short', 'medium', 'long' ]), purrs: v.boolean() }); export const vPetStore = v.object({ animals: v.array(v.object({ name: v.string(), type: v.optional(v.picklist(['dog', 'cat'])), details: v.union([vDogDetails, vCatDetails]) })) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/__snapshots__/3.1.x/webhooks/valibot.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as v from 'valibot'; export const vSessionUserPhoneCalloutRingingWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), session_key: v.string(), user_key: v.string(), host_id: v.string(), participant: v.strictObject({ invitee_name: v.string(), phone_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), from_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserRoomSystemCalloutRingingWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), host_id: v.string(), message_id: v.string(), inviter_name: v.string(), participant: v.objectWithRest({ call_type: v.string(), device_ip: v.string() }, v.unknown()) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingStartedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_started']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string(), recording_file: v.object({ recording_start: v.optional(v.string()), recording_end: v.optional(v.string()) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingResumedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_resumed']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string(), recording_file: v.object({ recording_start: v.optional(v.string()), recording_end: v.optional(v.string()) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionLiveStreamingStoppedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.live_streaming_stopped']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), start_time: v.pipe(v.string(), v.isoTimestamp()), live_streaming: v.object({ service: v.picklist([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: v.object({ stream_url: v.string(), stream_key: v.string(), page_url: v.string(), resolution: v.optional(v.string()) }), date_time: v.pipe(v.string(), v.isoTimestamp()) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionStreamIngestionStoppedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.stream_ingestion_stopped']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), stream_ingestion: v.object({ stream_id: v.string(), stream_name: v.string(), stream_description: v.optional(v.string()), stream_key: v.string(), stream_url: v.string(), backup_stream_url: v.string() }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserRoomSystemCalloutRejectedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), host_id: v.string(), message_id: v.string(), inviter_name: v.string(), participant: v.objectWithRest({ call_type: v.string(), device_ip: v.string() }, v.unknown()) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionAlertWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.alert']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), issues: v.array(v.picklist([ 'Unstable audio quality', 'Unstable video quality', 'Unstable screen share quality', 'High CPU occupation', 'Call Reconnection' ])) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionSharingEndedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.sharing_ended']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), user: v.strictObject({ id: v.string(), name: v.string(), user_key: v.optional(v.string()), sharing_details: v.strictObject({ content: v.picklist([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: v.pipe(v.string(), v.isoTimestamp()) }) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingPausedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_paused']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string(), recording_file: v.object({ recording_start: v.optional(v.string()), recording_end: v.optional(v.string()) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionEndedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.ended']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), start_time: v.pipe(v.string(), v.isoTimestamp()), end_time: v.pipe(v.string(), v.isoTimestamp()) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionStartedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.started']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), start_time: v.pipe(v.string(), v.isoTimestamp()) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionStreamIngestionUnbindWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.stream_ingestion_unbind']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), stream_ingestion: v.object({ stream_id: v.string(), stream_name: v.string(), stream_description: v.optional(v.string()), stream_key: v.string(), stream_url: v.string(), backup_stream_url: v.string() }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionLiveStreamingStartedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.live_streaming_started']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), start_time: v.pipe(v.string(), v.isoTimestamp()), live_streaming: v.object({ service: v.picklist([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: v.object({ stream_url: v.string(), stream_key: v.string(), page_url: v.string(), resolution: v.optional(v.string()) }), date_time: v.pipe(v.string(), v.isoTimestamp()) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserRoomSystemCalloutMissedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), host_id: v.string(), message_id: v.string(), inviter_name: v.string(), participant: v.objectWithRest({ call_type: v.string(), device_ip: v.string() }, v.unknown()) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserPhoneCalloutAcceptedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), session_key: v.string(), user_key: v.string(), host_id: v.string(), participant: v.strictObject({ invitee_name: v.string(), phone_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), from_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserLeftWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.user_left']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), user: v.strictObject({ id: v.string(), name: v.string(), leave_time: v.pipe(v.string(), v.isoTimestamp()), leave_reason: v.optional(v.string()), user_key: v.optional(v.string()), phone_number: v.optional(v.string()), participant_uuid: v.string() }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionSharingStartedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.sharing_started']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), user: v.strictObject({ id: v.string(), name: v.string(), user_key: v.optional(v.string()), sharing_details: v.strictObject({ content: v.picklist([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: v.pipe(v.string(), v.isoTimestamp()) }) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserPhoneCalloutCanceledWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), user_key: v.string(), participant: v.strictObject({ invitee_name: v.string(), phone_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), from_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingTranscriptCompletedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_transcript_completed']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), download_token: v.string(), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string(), recording_files: v.array(v.object({ id: v.optional(v.string()), recording_start: v.optional(v.string()), recording_end: v.optional(v.string()), file_name: v.optional(v.string()), file_path: v.optional(v.string()), file_type: v.optional(v.picklist([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE', 'TIMELINE' ])), file_size: v.optional(v.number()), file_extension: v.optional(v.picklist([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ])), download_url: v.optional(v.string()), status: v.optional(v.picklist(['completed'])), recording_type: v.optional(v.picklist([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ])) })) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingDeletedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_deleted']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), operator: v.pipe(v.string(), v.email()), operator_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string() }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserRoomSystemCalloutFailedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), host_id: v.string(), message_id: v.string(), inviter_name: v.string(), reason_type: v.unknown(), participant: v.objectWithRest({ call_type: v.string(), device_ip: v.string() }, v.unknown()) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingCompletedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_completed']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), download_token: v.string(), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string(), recording_files: v.array(v.object({ id: v.optional(v.string()), recording_start: v.optional(v.string()), recording_end: v.optional(v.string()), file_name: v.optional(v.string()), file_path: v.optional(v.string()), file_type: v.optional(v.picklist([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ])), file_size: v.optional(v.number()), file_extension: v.optional(v.picklist([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ])), download_url: v.optional(v.string()), status: v.optional(v.picklist(['completed'])), recording_type: v.optional(v.picklist([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ])) })), participant_audio_files: v.optional(v.array(v.object({ id: v.optional(v.string()), recording_start: v.optional(v.string()), recording_end: v.optional(v.string()), file_name: v.optional(v.string()), file_path: v.optional(v.string()), file_type: v.optional(v.picklist([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ])), file_size: v.optional(v.number()), file_extension: v.optional(v.picklist([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ])), download_url: v.optional(v.string()), status: v.optional(v.picklist(['completed'])), recording_type: v.optional(v.picklist([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ])), user_id: v.optional(v.string()), user_key: v.optional(v.string()) }))), participant_video_files: v.optional(v.array(v.object({ id: v.optional(v.string()), recording_start: v.optional(v.string()), recording_end: v.optional(v.string()), file_name: v.optional(v.string()), file_path: v.optional(v.string()), file_type: v.optional(v.picklist(['MP4'])), file_size: v.optional(v.number()), file_extension: v.optional(v.picklist(['MP4'])), download_url: v.optional(v.string()), status: v.optional(v.picklist(['completed'])), recording_type: v.optional(v.picklist(['individual_user', 'individual_shared_screen'])), user_id: v.optional(v.string()), user_key: v.optional(v.string()) }))) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingTranscriptFailedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_transcript_failed']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string() }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingTrashedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_trashed']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), operator: v.pipe(v.string(), v.email()), operator_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string() }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserJoinedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.user_joined']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.string(), session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), user: v.strictObject({ id: v.string(), name: v.string(), join_time: v.pipe(v.string(), v.isoTimestamp()), user_key: v.optional(v.string()), phone_number: v.optional(v.string()), participant_uuid: v.string() }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionStreamIngestionStartedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.stream_ingestion_started']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), stream_ingestion: v.object({ stream_id: v.string(), stream_name: v.string(), stream_description: v.optional(v.string()), stream_key: v.string(), stream_url: v.string(), backup_stream_url: v.string() }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionStreamIngestionConnectedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.stream_ingestion_connected']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), stream_ingestion: v.object({ stream_id: v.string(), stream_name: v.string(), stream_description: v.optional(v.string()), stream_key: v.string(), stream_url: v.string(), backup_stream_url: v.string() }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionStreamIngestionDisconnectedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.stream_ingestion_disconnected']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.optional(v.string()), stream_ingestion: v.object({ stream_id: v.string(), stream_name: v.string(), stream_description: v.optional(v.string()), stream_key: v.string(), stream_url: v.string(), backup_stream_url: v.string() }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingRecoveredWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_recovered']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), operator: v.pipe(v.string(), v.email()), operator_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string() }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserPhoneCalloutMissedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), session_key: v.string(), user_key: v.string(), host_id: v.string(), participant: v.strictObject({ invitee_name: v.string(), phone_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), from_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserPhoneCalloutRejectedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), session_key: v.string(), user_key: v.string(), host_id: v.string(), participant: v.strictObject({ invitee_name: v.string(), phone_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), from_number: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionUserRoomSystemCalloutAcceptedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.string(), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ id: v.optional(v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807'))), uuid: v.optional(v.string()), session_id: v.string(), session_name: v.string(), host_id: v.string(), message_id: v.string(), inviter_name: v.string(), participant: v.objectWithRest({ call_type: v.string(), device_ip: v.string() }, v.unknown()) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); export const vSessionRecordingStoppedWebhookRequest = v.object({ body: v.optional(v.strictObject({ event: v.picklist(['session.recording_stopped']), event_ts: v.pipe(v.union([ v.number(), v.string(), v.bigint() ]), v.transform(x => BigInt(x)), v.minValue(BigInt('-9223372036854775808'), 'Invalid value: Expected int64 to be >= -9223372036854775808'), v.maxValue(BigInt('9223372036854775807'), 'Invalid value: Expected int64 to be <= 9223372036854775807')), payload: v.strictObject({ account_id: v.string(), object: v.strictObject({ session_id: v.string(), session_name: v.string(), session_key: v.string(), start_time: v.pipe(v.string(), v.isoTimestamp()), timezone: v.string(), recording_file: v.object({ recording_start: v.optional(v.string()), recording_end: v.optional(v.string()) }) }) }) })), path: v.optional(v.never()), query: v.optional(v.never()) }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/package.json ================================================ { "name": "@test/openapi-ts-valibot-v1", "version": "0.0.0", "private": true, "type": "module", "scripts": { "typecheck": "tsgo --noEmit" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "typescript": "5.9.3", "valibot": "1.2.0" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts-tests/valibot/v1/test/3.0.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createValibotConfig, getSnapshotsPath, getTempSnapshotsPath } from './utils'; const version = '3.0.x'; const outputDir = path.join(getTempSnapshotsPath(), version); const snapshotsDir = path.join(getSnapshotsPath(), version); describe(`OpenAPI ${version}`, () => { const createConfig = createValibotConfig({ openApiVersion: version, outputDir }); const scenarios = [ { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'validators.json', output: 'validators', }), description: 'generates validator schemas', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const outputString = config.output as string; const filePaths = getFilePaths(outputString); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/test/3.1.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createValibotConfig, getSnapshotsPath, getTempSnapshotsPath } from './utils'; const version = '3.1.x'; const outputDir = path.join(getTempSnapshotsPath(), version); const snapshotsDir = path.join(getSnapshotsPath(), version); describe(`OpenAPI ${version}`, () => { const createConfig = createValibotConfig({ openApiVersion: version, outputDir }); const scenarios = [ { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'schema-const.yaml', output: 'schema-const', }), description: 'handles various constants', }, { config: createConfig({ input: 'validators.yaml', output: 'validators', }), description: 'generates validator schemas', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-metadata', plugins: [ { metadata: true, name: 'valibot', }, ], }), description: 'generates validator schemas with metadata', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-metadata-fn', plugins: [ { metadata: ({ $, node, schema }) => { node .prop('custom', $.literal('value')) .prop('title', $.literal(schema.description ?? schema.type ?? '')); }, name: 'valibot', }, ], }), description: 'generates validator schemas with metadata function', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-types', }), description: 'generates validator schemas with types', }, { config: createConfig({ input: 'validators-bigint-min-max.json', output: 'validators-bigint-min-max', }), description: 'validator schemas with BigInt and min/max constraints', }, { config: createConfig({ input: 'validators-circular-ref.json', output: 'validators-circular-ref', }), description: 'validator schemas with circular reference', }, { config: createConfig({ input: 'validators-circular-ref-2.yaml', output: 'validators-circular-ref-2', }), description: 'validator schemas with circular reference 2', }, { config: createConfig({ input: 'validators-union-merge.json', output: 'validators-union-merge', }), description: "validator schemas with merged unions (can't use .merge())", }, { config: createConfig({ input: 'integer-formats.yaml', output: 'integer-formats', }), description: 'generates validator schemas for all integer format combinations (number/integer/string types with int8, int16, int32, int64, uint8, uint16, uint32, uint64 formats)', }, { config: createConfig({ input: 'zoom-video-sdk.json', output: 'webhooks', }), description: 'webhook schemas', }, { config: createConfig({ input: 'string-with-format.yaml', output: 'string-with-format', }), description: 'anyOf string and binary string', }, { config: createConfig({ input: 'time-format.yaml', output: 'time-format', }), description: 'generates correct valibot schema for time format', }, { config: createConfig({ input: 'type-format.yaml', output: 'type-format', plugins: [ '@hey-api/transformers', '@hey-api/client-fetch', 'valibot', { name: '@hey-api/sdk', transformer: true, validator: true, }, ], }), description: 'handles various schema types and formats', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const outputString = config.output as string; const filePaths = getFilePaths(outputString); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/test/additional-properties.test.ts ================================================ import * as v from 'valibot'; import { setupValibotTest } from './utils'; // TODO: further clean up describe('Object Additional Properties Tests', () => { let generatedSchemas: any; beforeAll(async () => { generatedSchemas = await setupValibotTest( 'additional-properties.yaml', 'additional-properties', ); }); describe('ObjectWithAdditionalPropertiesString', () => { it('should preserve string additional properties in nested headers object', () => { const input = { headers: { Authorization: 'Bearer token', 'Content-Type': 'application/json', }, }; const result = v.safeParse(generatedSchemas.vObjectWithAdditionalPropertiesString, input); expect(result.success).toBe(true); if (result.success) { expect(result.output.headers).toEqual({ Authorization: 'Bearer token', 'Content-Type': 'application/json', }); } }); it('should reject non-string values in additional properties', () => { const input = { headers: { Authorization: 'Bearer token', Count: 123, // Invalid: should be string }, }; const result = v.safeParse(generatedSchemas.vObjectWithAdditionalPropertiesString, input); expect(result.success).toBe(false); }); it('should accept empty headers object', () => { const input = { headers: {}, }; const result = v.safeParse(generatedSchemas.vObjectWithAdditionalPropertiesString, input); expect(result.success).toBe(true); }); }); describe('ObjectOnlyAdditionalPropertiesString', () => { it('should preserve string additional properties', () => { const input = { key1: 'value1', key2: 'value2', key3: 'value3', }; const result = v.safeParse(generatedSchemas.vObjectOnlyAdditionalPropertiesString, input); expect(result.success).toBe(true); if (result.success) { expect(result.output).toEqual(input); } }); it('should reject non-string values', () => { const input = { key1: 'value1', key2: 123, // Invalid: should be string }; const result = v.safeParse(generatedSchemas.vObjectOnlyAdditionalPropertiesString, input); expect(result.success).toBe(false); }); }); describe('ObjectOnlyAdditionalPropertiesNumber', () => { it('should preserve number additional properties', () => { const input = { score1: 100, score2: 95.5, score3: 0, }; const result = v.safeParse(generatedSchemas.vObjectOnlyAdditionalPropertiesNumber, input); expect(result.success).toBe(true); if (result.success) { expect(result.output).toEqual(input); } }); it('should reject non-number values', () => { const input = { score1: 100, score2: 'invalid', // Invalid: should be number }; const result = v.safeParse(generatedSchemas.vObjectOnlyAdditionalPropertiesNumber, input); expect(result.success).toBe(false); }); }); describe('ObjectOnlyAdditionalPropertiesBoolean', () => { it('should preserve boolean additional properties', () => { const input = { flag1: true, flag2: false, flag3: true, }; const result = v.safeParse(generatedSchemas.vObjectOnlyAdditionalPropertiesBoolean, input); expect(result.success).toBe(true); if (result.success) { expect(result.output).toEqual(input); } }); it('should reject non-boolean values', () => { const input = { flag1: true, flag2: 'true', // Invalid: should be boolean }; const result = v.safeParse(generatedSchemas.vObjectOnlyAdditionalPropertiesBoolean, input); expect(result.success).toBe(false); }); }); describe('ObjectWithPropertiesAndAdditionalPropertiesNumber', () => { it('should preserve both named properties and additional properties', () => { const input = { count: 42, extra1: 1.5, extra2: 2.5, id: 'abc123', }; const result = v.safeParse( generatedSchemas.vObjectWithPropertiesAndAdditionalPropertiesNumber, input, ); if (!result.success) { console.log('Validation failed:', result.issues); } expect(result.success).toBe(true); if (result.success) { expect(result.output).toEqual(input); } }); it('should validate types of both named and additional properties', () => { const input = { count: 42, extra1: 'invalid', id: 'abc123', // Invalid: should be number }; const result = v.safeParse( generatedSchemas.vObjectWithPropertiesAndAdditionalPropertiesNumber, input, ); expect(result.success).toBe(false); }); it('should require named properties but allow empty additional properties', () => { const input = { count: 42, id: 'abc123', }; const result = v.safeParse( generatedSchemas.vObjectWithPropertiesAndAdditionalPropertiesNumber, input, ); expect(result.success).toBe(true); }); }); describe('ObjectWithAdditionalPropertiesObject', () => { it('should preserve nested object additional properties', () => { const input = { metadata: { field1: { value: 'test1' }, field2: { value: 'test2' }, }, }; const result = v.safeParse(generatedSchemas.vObjectWithAdditionalPropertiesObject, input); expect(result.success).toBe(true); if (result.success) { expect(result.output.metadata).toEqual({ field1: { value: 'test1' }, field2: { value: 'test2' }, }); } }); it('should validate nested object structure', () => { const input = { metadata: { field1: { value: 'test1' }, field2: { invalidKey: 'test2' }, // Object without required structure }, }; const result = v.safeParse(generatedSchemas.vObjectWithAdditionalPropertiesObject, input); // Should succeed as the nested object properties are optional expect(result.success).toBe(true); }); }); describe('ObjectOnlyAdditionalPropertiesObject', () => { it('should preserve object additional properties', () => { const input = { item1: { name: 'Item 1' }, item2: { name: 'Item 2' }, }; const result = v.safeParse(generatedSchemas.vObjectOnlyAdditionalPropertiesObject, input); expect(result.success).toBe(true); if (result.success) { expect(result.output).toEqual(input); } }); }); describe('ObjectWithAdditionalPropertiesFalse', () => { it('should accept object with only defined properties', () => { const input = { count: 42, id: 'abc123', }; const result = v.safeParse(generatedSchemas.vObjectWithAdditionalPropertiesFalse, input); expect(result.success).toBe(true); if (result.success) { expect(result.output).toEqual(input); } }); it('should reject object with additional properties', () => { const input = { count: 42, extra: 'not allowed', id: 'abc123', }; const result = v.safeParse(generatedSchemas.vObjectWithAdditionalPropertiesFalse, input); expect(result.success).toBe(false); }); }); describe('ObjectWithNestedAdditionalPropertiesFalse', () => { it('should accept object with correct nested properties', () => { const input = { membership: { calendar_membership_tier_id: 'tier_id', status: 'approved', }, }; const result = v.safeParse( generatedSchemas.vObjectWithNestedAdditionalPropertiesFalse, input, ); expect(result.success).toBe(true); if (result.success) { expect(result.output).toEqual(input); } }); it('should reject object with additional properties in nested object', () => { const input = { membership: { calendar_membership_tier_id: 'tier_id', extra: 'not allowed', status: 'approved', }, }; const result = v.safeParse( generatedSchemas.vObjectWithNestedAdditionalPropertiesFalse, input, ); expect(result.success).toBe(false); }); }); }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/test/const-values.test.ts ================================================ import * as v from 'valibot'; import { setupValibotTest } from './utils'; // TODO: further clean up describe('Number Type Const Values Tests', () => { let generatedSchemas: any; beforeAll(async () => { generatedSchemas = await setupValibotTest('const-values.yaml', 'const-values'); }); describe('Number Type Const Validation', () => { it('should accept exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberNoFormat, 42.5); expect(result.success).toBe(true); }); it('should reject non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberNoFormat, 42.6); expect(result.success).toBe(false); }); }); describe('Number Type Format Const Validation', () => { it('should accept NumberInt8 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberInt8, 100); expect(result.success).toBe(true); }); it('should reject NumberInt8 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberInt8, 101); expect(result.success).toBe(false); }); it('should accept NumberInt16 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberInt16, 1000); expect(result.success).toBe(true); }); it('should reject NumberInt16 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberInt16, 1001); expect(result.success).toBe(false); }); it('should accept NumberInt32 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberInt32, 100000); expect(result.success).toBe(true); }); it('should reject NumberInt32 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberInt32, 100001); expect(result.success).toBe(false); }); it('should accept NumberInt64 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberInt64, BigInt('1000000000000')); expect(result.success).toBe(true); }); it('should reject NumberInt64 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberInt64, BigInt('1000000000001')); expect(result.success).toBe(false); }); it('should accept NumberUint8 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberUint8, 200); expect(result.success).toBe(true); }); it('should reject NumberUint8 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberUint8, 201); expect(result.success).toBe(false); }); it('should accept NumberUint16 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberUint16, 50000); expect(result.success).toBe(true); }); it('should reject NumberUint16 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberUint16, 50001); expect(result.success).toBe(false); }); it('should accept NumberUint32 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberUint32, 3000000000); expect(result.success).toBe(true); }); it('should reject NumberUint32 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberUint32, 3000000001); expect(result.success).toBe(false); }); it('should accept NumberUint64 exact const value', () => { const result = v.safeParse(generatedSchemas.vNumberUint64, BigInt('18000000000000000000')); expect(result.success).toBe(true); }); it('should reject NumberUint64 non-matching values', () => { const result = v.safeParse(generatedSchemas.vNumberUint64, BigInt('18000000000000000001')); expect(result.success).toBe(false); }); }); describe('Integer Type Const Validation', () => { it('should accept exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerNoFormat, -1); expect(result.success).toBe(true); }); it('should reject non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerNoFormat, 0); expect(result.success).toBe(false); }); }); describe('Integer Type Format Const Validation', () => { it('should accept IntegerInt8 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerInt8, -100); expect(result.success).toBe(true); }); it('should reject IntegerInt8 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerInt8, -99); expect(result.success).toBe(false); }); it('should accept IntegerInt16 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerInt16, -1000); expect(result.success).toBe(true); }); it('should reject IntegerInt16 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerInt16, -999); expect(result.success).toBe(false); }); it('should accept IntegerInt32 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerInt32, -100000); expect(result.success).toBe(true); }); it('should reject IntegerInt32 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerInt32, -99999); expect(result.success).toBe(false); }); it('should accept IntegerInt64 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerInt64, BigInt('-1000000000000')); expect(result.success).toBe(true); }); it('should reject IntegerInt64 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerInt64, BigInt('-999999999999')); expect(result.success).toBe(false); }); it('should accept IntegerUint8 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerUint8, 255); expect(result.success).toBe(true); }); it('should reject IntegerUint8 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint8, 254); expect(result.success).toBe(false); }); it('should accept IntegerUint16 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerUint16, 65535); expect(result.success).toBe(true); }); it('should reject IntegerUint16 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint16, 65534); expect(result.success).toBe(false); }); it('should accept IntegerUint32 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerUint32, 4294967295); expect(result.success).toBe(true); }); it('should reject IntegerUint32 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint32, 4294967294); expect(result.success).toBe(false); }); it('should accept IntegerUint64 exact const value', () => { const result = v.safeParse(generatedSchemas.vIntegerUint64, BigInt('1000000000000')); expect(result.success).toBe(true); }); it('should reject IntegerUint64 non-matching values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint64, BigInt('1000000000001')); expect(result.success).toBe(false); }); }); describe('String Type Format Const Validation', () => { it('should accept StringInt64 exact const value', () => { const result = v.safeParse(generatedSchemas.vStringInt64, BigInt('-9223372036854775808')); expect(result.success).toBe(true); }); it('should reject StringInt64 non-matching values', () => { const result = v.safeParse(generatedSchemas.vStringInt64, BigInt('-9223372036854775807')); expect(result.success).toBe(false); }); it('should accept StringUint64 exact const value', () => { const result = v.safeParse(generatedSchemas.vStringUint64, BigInt('18446744073709551615')); expect(result.success).toBe(true); }); it('should reject StringUint64 non-matching values', () => { const result = v.safeParse(generatedSchemas.vStringUint64, BigInt('18446744073709551614')); expect(result.success).toBe(false); }); }); describe('String Type Format Const Validation (BigInt Literal)', () => { it('should accept StringInt64n exact const value', () => { const result = v.safeParse(generatedSchemas.vStringInt64n, BigInt('-9223372036854775808')); expect(result.success).toBe(true); }); it('should reject StringInt64n non-matching values', () => { const result = v.safeParse(generatedSchemas.vStringInt64n, BigInt('-9223372036854775807')); expect(result.success).toBe(false); }); it('should accept StringUint64n exact const value', () => { const result = v.safeParse(generatedSchemas.vStringUint64n, BigInt('18446744073709551615')); expect(result.success).toBe(true); }); it('should reject StringUint64n non-matching values', () => { const result = v.safeParse(generatedSchemas.vStringUint64n, BigInt('18446744073709551614')); expect(result.success).toBe(false); }); }); }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/test/formats.test.ts ================================================ import * as v from 'valibot'; import { setupValibotTest } from './utils'; // TODO: further clean up describe('Number Type Formats Tests', () => { let generatedSchemas: any; beforeAll(async () => { generatedSchemas = await setupValibotTest('formats.yaml', 'formats'); }); // Format bounds and error messages from INTEGER_FORMATS const FORMAT_BOUNDS = { int16: { max: 32767, maxError: 'Invalid value: Expected int16 to be <= 32767', min: -32768, minError: 'Invalid value: Expected int16 to be >= -32768', }, int32: { max: 2147483647, maxError: 'Invalid value: Expected int32 to be <= 2147483647', min: -2147483648, minError: 'Invalid value: Expected int32 to be >= -2147483648', }, int64: { max: '9223372036854775807', maxError: 'Invalid value: Expected int64 to be <= 9223372036854775807', min: '-9223372036854775808', minError: 'Invalid value: Expected int64 to be >= -9223372036854775808', }, int8: { max: 127, maxError: 'Invalid value: Expected int8 to be <= 127', min: -128, minError: 'Invalid value: Expected int8 to be >= -128', }, uint16: { max: 65535, maxError: 'Invalid value: Expected uint16 to be <= 65535', min: 0, minError: 'Invalid value: Expected uint16 to be >= 0', }, uint32: { max: 4294967295, maxError: 'Invalid value: Expected uint32 to be <= 4294967295', min: 0, minError: 'Invalid value: Expected uint32 to be >= 0', }, uint64: { max: '18446744073709551615', maxError: 'Invalid value: Expected uint64 to be <= 18446744073709551615', min: '0', minError: 'Invalid value: Expected uint64 to be >= 0', }, uint8: { max: 255, maxError: 'Invalid value: Expected uint8 to be <= 255', min: 0, minError: 'Invalid value: Expected uint8 to be >= 0', }, }; describe('Number Type Format Validation', () => { describe('numberNoFormat', () => { it('should validate any number value', () => { const result = v.safeParse(generatedSchemas.vNumberNoFormat, 123.456); expect(result.success).toBe(true); }); }); describe('numberInt8', () => { it('should validate values within int8 range', () => { const result = v.safeParse(generatedSchemas.vNumberInt8, 100); expect(result.success).toBe(true); }); it('should reject values below int8 minimum', () => { const result = v.safeParse(generatedSchemas.vNumberInt8, -129); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int8.minError); }); it('should reject values above int8 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberInt8, 128); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int8.maxError); }); }); describe('numberInt16', () => { it('should validate values within int16 range', () => { const result = v.safeParse(generatedSchemas.vNumberInt16, 30000); expect(result.success).toBe(true); }); it('should reject values below int16 minimum', () => { const result = v.safeParse(generatedSchemas.vNumberInt16, -32769); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int16.minError); }); it('should reject values above int16 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberInt16, 32768); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int16.maxError); }); }); describe('numberInt32', () => { it('should validate values within int32 range', () => { const result = v.safeParse(generatedSchemas.vNumberInt32, 2000000000); expect(result.success).toBe(true); }); it('should reject values below int32 minimum', () => { const result = v.safeParse(generatedSchemas.vNumberInt32, -2147483649); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int32.minError); }); it('should reject values above int32 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberInt32, 2147483648); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int32.maxError); }); }); describe('numberInt64', () => { it('should validate values within int64 range and convert to BigInt', () => { const result = v.safeParse(generatedSchemas.vNumberInt64, 1000000000000); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should validate string values within int64 range', () => { const result = v.safeParse(generatedSchemas.vNumberInt64, '1000000000000'); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should reject values above int64 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberInt64, '9223372036854775808'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int64.maxError); }); }); describe('numberUint8', () => { it('should validate values within uint8 range', () => { const result = v.safeParse(generatedSchemas.vNumberUint8, 200); expect(result.success).toBe(true); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vNumberUint8, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint8.minError); }); it('should reject values above uint8 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberUint8, 256); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint8.maxError); }); }); describe('numberUint16', () => { it('should validate values within uint16 range', () => { const result = v.safeParse(generatedSchemas.vNumberUint16, 60000); expect(result.success).toBe(true); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vNumberUint16, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint16.minError); }); it('should reject values above uint16 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberUint16, 65536); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint16.maxError); }); }); describe('numberUint32', () => { it('should validate values within uint32 range', () => { const result = v.safeParse(generatedSchemas.vNumberUint32, 4000000000); expect(result.success).toBe(true); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vNumberUint32, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint32.minError); }); it('should reject values above uint32 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberUint32, 4294967296); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint32.maxError); }); }); describe('numberUint64', () => { it('should validate values within uint64 range and convert to BigInt', () => { const result = v.safeParse(generatedSchemas.vNumberUint64, 1000000000000); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vNumberUint64, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint64.minError); }); it('should reject values above uint64 maximum', () => { const result = v.safeParse(generatedSchemas.vNumberUint64, '18446744073709551616'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint64.maxError); }); }); }); describe('Integer Type Format Validation', () => { describe('integerNoFormat', () => { it('should validate any integer value', () => { const result = v.safeParse(generatedSchemas.vIntegerNoFormat, 123); expect(result.success).toBe(true); }); it('should reject non-integer values', () => { const result = v.safeParse(generatedSchemas.vIntegerNoFormat, 123.456); expect(result.success).toBe(false); }); }); describe('integerInt8', () => { it('should validate values within int8 range', () => { const result = v.safeParse(generatedSchemas.vIntegerInt8, 100); expect(result.success).toBe(true); }); it('should reject values below int8 minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerInt8, -129); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int8.minError); }); it('should reject values above int8 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerInt8, 128); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int8.maxError); }); }); describe('integerInt16', () => { it('should validate values within int16 range', () => { const result = v.safeParse(generatedSchemas.vIntegerInt16, 30000); expect(result.success).toBe(true); }); it('should reject values below int16 minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerInt16, -32769); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int16.minError); }); it('should reject values above int16 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerInt16, 32768); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int16.maxError); }); }); describe('integerInt32', () => { it('should validate values within int32 range', () => { const result = v.safeParse(generatedSchemas.vIntegerInt32, 2000000000); expect(result.success).toBe(true); }); it('should reject values below int32 minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerInt32, -2147483649); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int32.minError); }); it('should reject values above int32 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerInt32, 2147483648); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int32.maxError); }); }); describe('integerInt64', () => { it('should validate values within int64 range and convert to BigInt', () => { const result = v.safeParse(generatedSchemas.vIntegerInt64, 1000000000000); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should validate string values within int64 range', () => { const result = v.safeParse(generatedSchemas.vIntegerInt64, '1000000000000'); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should reject values above int64 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerInt64, '9223372036854775808'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int64.maxError); }); }); describe('integerUint8', () => { it('should validate values within uint8 range', () => { const result = v.safeParse(generatedSchemas.vIntegerUint8, 200); expect(result.success).toBe(true); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint8, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint8.minError); }); it('should reject values above uint8 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerUint8, 256); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint8.maxError); }); }); describe('integerUint16', () => { it('should validate values within uint16 range', () => { const result = v.safeParse(generatedSchemas.vIntegerUint16, 60000); expect(result.success).toBe(true); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint16, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint16.minError); }); it('should reject values above uint16 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerUint16, 65536); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint16.maxError); }); }); describe('integerUint32', () => { it('should validate values within uint32 range', () => { const result = v.safeParse(generatedSchemas.vIntegerUint32, 4000000000); expect(result.success).toBe(true); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint32, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint32.minError); }); it('should reject values above uint32 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerUint32, 4294967296); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint32.maxError); }); }); describe('integerUint64', () => { it('should validate values within uint64 range and convert to BigInt', () => { const result = v.safeParse(generatedSchemas.vIntegerUint64, 1000000000000); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vIntegerUint64, -1); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint64.minError); }); it('should reject values above uint64 maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerUint64, '18446744073709551616'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint64.maxError); }); }); }); describe('String Type Format Validation', () => { describe('stringInt64', () => { it('should validate string values within int64 range and convert to BigInt', () => { const result = v.safeParse(generatedSchemas.vStringInt64, '1000000000000'); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should reject values below int64 minimum', () => { const result = v.safeParse(generatedSchemas.vStringInt64, '-9223372036854775809'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int64.minError); }); it('should reject values above int64 maximum', () => { const result = v.safeParse(generatedSchemas.vStringInt64, '9223372036854775808'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.int64.maxError); }); }); describe('stringUint64', () => { it('should validate string values within uint64 range and convert to BigInt', () => { const result = v.safeParse(generatedSchemas.vStringUint64, '1000000000000'); expect(result.success).toBe(true); expect(typeof result.output).toBe('bigint'); }); it('should reject negative values', () => { const result = v.safeParse(generatedSchemas.vStringUint64, '-1'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint64.minError); }); it('should reject values above uint64 maximum', () => { const result = v.safeParse(generatedSchemas.vStringUint64, '18446744073709551616'); expect(result.success).toBe(false); expect(result.issues![0].message).toContain(FORMAT_BOUNDS.uint64.maxError); }); }); }); }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/test/min-max-constraints.test.ts ================================================ import * as v from 'valibot'; import { setupValibotTest } from './utils'; // TODO: further clean up describe('Number Type Min/Max Constraints Tests', () => { let generatedSchemas: any; beforeAll(async () => { generatedSchemas = await setupValibotTest('min-max-constraints.yaml', 'min-max-constraints'); }); describe('Basic Number Constraints', () => { describe('NumberWithMinimum', () => { it('should accept values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinimum, 10); expect(result.success).toBe(true); }); it('should accept values above minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinimum, 15); expect(result.success).toBe(true); }); it('should reject values below minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinimum, 9); expect(result.success).toBe(false); }); }); describe('NumberWithMaximum', () => { it('should accept values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vNumberWithMaximum, 100); expect(result.success).toBe(true); }); it('should accept values below maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithMaximum, 50); expect(result.success).toBe(true); }); it('should reject values above maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithMaximum, 101); expect(result.success).toBe(false); }); }); describe('NumberWithMinMax', () => { it('should accept values within range', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinMax, 50); expect(result.success).toBe(true); }); it('should accept values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinMax, 0); expect(result.success).toBe(true); }); it('should accept values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinMax, 100); expect(result.success).toBe(true); }); it('should reject values below minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinMax, -1); expect(result.success).toBe(false); }); it('should reject values above maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithMinMax, 101); expect(result.success).toBe(false); }); }); }); describe('Basic Integer Constraints', () => { describe('IntegerWithMinimum', () => { it('should accept values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinimum, 5); expect(result.success).toBe(true); }); it('should accept values above minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinimum, 10); expect(result.success).toBe(true); }); it('should reject values below minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinimum, 4); expect(result.success).toBe(false); }); }); describe('IntegerWithMaximum', () => { it('should accept values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMaximum, 999); expect(result.success).toBe(true); }); it('should accept values below maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMaximum, 500); expect(result.success).toBe(true); }); it('should reject values above maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMaximum, 1000); expect(result.success).toBe(false); }); }); describe('IntegerWithMinMax', () => { it('should accept values within range', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinMax, 500); expect(result.success).toBe(true); }); it('should accept values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinMax, 1); expect(result.success).toBe(true); }); it('should accept values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinMax, 999); expect(result.success).toBe(true); }); it('should reject values below minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinMax, 0); expect(result.success).toBe(false); }); it('should reject values above maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithMinMax, 1000); expect(result.success).toBe(false); }); }); }); describe('Exclusive Constraints', () => { describe('NumberWithExclusiveMin', () => { it('should accept values above exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMin, 0.1); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMin, 0); expect(result.success).toBe(false); }); it('should reject values below exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMin, -1); expect(result.success).toBe(false); }); }); describe('NumberWithExclusiveMax', () => { it('should accept values below exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMax, 99.9); expect(result.success).toBe(true); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMax, 100); expect(result.success).toBe(false); }); it('should reject values above exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMax, 101); expect(result.success).toBe(false); }); }); describe('NumberWithExclusiveMinMax', () => { it('should accept values within exclusive range', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMinMax, 0.5); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMinMax, 0); expect(result.success).toBe(false); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMinMax, 1); expect(result.success).toBe(false); }); }); describe('IntegerWithExclusiveMin', () => { it('should accept values above exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMin, 11); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMin, 10); expect(result.success).toBe(false); }); it('should reject values below exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMin, 9); expect(result.success).toBe(false); }); }); describe('IntegerWithExclusiveMax', () => { it('should accept values below exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMax, 49); expect(result.success).toBe(true); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMax, 50); expect(result.success).toBe(false); }); it('should reject values above exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMax, 51); expect(result.success).toBe(false); }); }); describe('IntegerWithExclusiveMinMax', () => { it('should accept values within exclusive range', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMinMax, 10); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMinMax, 5); expect(result.success).toBe(false); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMinMax, 15); expect(result.success).toBe(false); }); }); }); describe('Mixed Constraints', () => { describe('NumberWithExclusiveMinInclusiveMax', () => { it('should accept values above exclusive minimum and at inclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMinInclusiveMax, 90); expect(result.success).toBe(true); }); it('should accept values above exclusive minimum and below inclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMinInclusiveMax, 50); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMinInclusiveMax, 10); expect(result.success).toBe(false); }); it('should reject values above inclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithExclusiveMinInclusiveMax, 91); expect(result.success).toBe(false); }); }); describe('NumberWithInclusiveMinExclusiveMax', () => { it('should accept values at inclusive minimum and below exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithInclusiveMinExclusiveMax, 20); expect(result.success).toBe(true); }); it('should accept values above inclusive minimum and below exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithInclusiveMinExclusiveMax, 50); expect(result.success).toBe(true); }); it('should reject values below inclusive minimum', () => { const result = v.safeParse(generatedSchemas.vNumberWithInclusiveMinExclusiveMax, 19); expect(result.success).toBe(false); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vNumberWithInclusiveMinExclusiveMax, 80); expect(result.success).toBe(false); }); }); describe('IntegerWithExclusiveMinInclusiveMax', () => { it('should accept values above exclusive minimum and at inclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMinInclusiveMax, 50); expect(result.success).toBe(true); }); it('should accept values above exclusive minimum and below inclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMinInclusiveMax, 25); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMinInclusiveMax, 5); expect(result.success).toBe(false); }); it('should reject values above inclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithExclusiveMinInclusiveMax, 51); expect(result.success).toBe(false); }); }); describe('IntegerWithInclusiveMinExclusiveMax', () => { it('should accept values at inclusive minimum and below exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithInclusiveMinExclusiveMax, 10); expect(result.success).toBe(true); }); it('should accept values above inclusive minimum and below exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithInclusiveMinExclusiveMax, 55); expect(result.success).toBe(true); }); it('should reject values below inclusive minimum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithInclusiveMinExclusiveMax, 9); expect(result.success).toBe(false); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse(generatedSchemas.vIntegerWithInclusiveMinExclusiveMax, 100); expect(result.success).toBe(false); }); }); }); describe('Format-Specific Constraints (Int64)', () => { describe('Int64WithMinimum', () => { it('should accept BigInt values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinimum, BigInt('-5000000000000')); expect(result.success).toBe(true); }); it('should accept BigInt values above minimum', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinimum, BigInt('0')); expect(result.success).toBe(true); }); it('should reject BigInt values below minimum', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinimum, BigInt('-5000000000001')); expect(result.success).toBe(false); }); }); describe('Int64WithMaximum', () => { it('should accept BigInt values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vInt64WithMaximum, BigInt('5000000000000')); expect(result.success).toBe(true); }); it('should accept BigInt values below maximum', () => { const result = v.safeParse(generatedSchemas.vInt64WithMaximum, BigInt('1000000000000')); expect(result.success).toBe(true); }); it('should reject BigInt values above maximum', () => { const result = v.safeParse(generatedSchemas.vInt64WithMaximum, BigInt('5000000000001')); expect(result.success).toBe(false); }); }); describe('Int64WithMinMax', () => { it('should accept BigInt values within range', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinMax, BigInt('0')); expect(result.success).toBe(true); }); it('should accept BigInt values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinMax, BigInt('-4000000000000')); expect(result.success).toBe(true); }); it('should accept BigInt values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinMax, BigInt('4000000000000')); expect(result.success).toBe(true); }); it('should reject BigInt values below minimum', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinMax, BigInt('-4000000000001')); expect(result.success).toBe(false); }); it('should reject BigInt values above maximum', () => { const result = v.safeParse(generatedSchemas.vInt64WithMinMax, BigInt('4000000000001')); expect(result.success).toBe(false); }); }); describe('Int64WithExclusiveMin', () => { it('should accept BigInt values above exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMin, BigInt('-2999999999999'), ); expect(result.success).toBe(true); }); it('should reject BigInt values at exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMin, BigInt('-3000000000000'), ); expect(result.success).toBe(false); }); }); describe('Int64WithExclusiveMax', () => { it('should accept BigInt values below exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMax, BigInt('2999999999999'), ); expect(result.success).toBe(true); }); it('should reject BigInt values at exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMax, BigInt('3000000000000'), ); expect(result.success).toBe(false); }); }); describe('Int64WithExclusiveMinMax', () => { it('should accept BigInt values within exclusive range', () => { const result = v.safeParse(generatedSchemas.vInt64WithExclusiveMinMax, BigInt('0')); expect(result.success).toBe(true); }); it('should reject BigInt values at exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMinMax, BigInt('-2000000000000'), ); expect(result.success).toBe(false); }); it('should reject BigInt values at exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMinMax, BigInt('2000000000000'), ); expect(result.success).toBe(false); }); }); describe('Int64WithExclusiveMinInclusiveMax', () => { it('should accept values above exclusive minimum and at inclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMinInclusiveMax, BigInt('6000000000000'), ); expect(result.success).toBe(true); }); it('should accept values above exclusive minimum and below inclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMinInclusiveMax, BigInt('0'), ); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMinInclusiveMax, BigInt('-6000000000000'), ); expect(result.success).toBe(false); }); it('should reject values above inclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithExclusiveMinInclusiveMax, BigInt('6000000000001'), ); expect(result.success).toBe(false); }); }); describe('Int64WithInclusiveMinExclusiveMax', () => { it('should accept values at inclusive minimum and below exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithInclusiveMinExclusiveMax, BigInt('-7000000000000'), ); expect(result.success).toBe(true); }); it('should accept values above inclusive minimum and below exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithInclusiveMinExclusiveMax, BigInt('0'), ); expect(result.success).toBe(true); }); it('should reject values below inclusive minimum', () => { const result = v.safeParse( generatedSchemas.vInt64WithInclusiveMinExclusiveMax, BigInt('-7000000000001'), ); expect(result.success).toBe(false); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vInt64WithInclusiveMinExclusiveMax, BigInt('7000000000000'), ); expect(result.success).toBe(false); }); }); }); describe('Format-Specific Constraints (UInt64)', () => { describe('UInt64WithMinimum', () => { it('should accept BigInt values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinimum, BigInt('5000000000000')); expect(result.success).toBe(true); }); it('should accept BigInt values above minimum', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinimum, BigInt('8000000000000')); expect(result.success).toBe(true); }); it('should reject BigInt values below minimum', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinimum, BigInt('4999999999999')); expect(result.success).toBe(false); }); }); describe('UInt64WithMaximum', () => { it('should accept BigInt values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMaximum, BigInt('15000000000000')); expect(result.success).toBe(true); }); it('should accept BigInt values below maximum', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMaximum, BigInt('10000000000000')); expect(result.success).toBe(true); }); it('should reject BigInt values above maximum', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMaximum, BigInt('15000000000001')); expect(result.success).toBe(false); }); }); describe('UInt64WithMinMax', () => { it('should accept BigInt values within range', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinMax, BigInt('5000000000000')); expect(result.success).toBe(true); }); it('should accept BigInt values at minimum boundary', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinMax, BigInt('1000000000000')); expect(result.success).toBe(true); }); it('should accept BigInt values at maximum boundary', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinMax, BigInt('10000000000000')); expect(result.success).toBe(true); }); it('should reject BigInt values below minimum', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinMax, BigInt('999999999999')); expect(result.success).toBe(false); }); it('should reject BigInt values above maximum', () => { const result = v.safeParse(generatedSchemas.vUInt64WithMinMax, BigInt('10000000000001')); expect(result.success).toBe(false); }); }); describe('UInt64WithExclusiveMin', () => { it('should accept BigInt values above exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMin, BigInt('8000000000001'), ); expect(result.success).toBe(true); }); it('should reject BigInt values at exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMin, BigInt('8000000000000'), ); expect(result.success).toBe(false); }); }); describe('UInt64WithExclusiveMax', () => { it('should accept BigInt values below exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMax, BigInt('11999999999999'), ); expect(result.success).toBe(true); }); it('should reject BigInt values at exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMax, BigInt('12000000000000'), ); expect(result.success).toBe(false); }); }); describe('UInt64WithExclusiveMinMax', () => { it('should accept BigInt values within exclusive range', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMinMax, BigInt('5000000000000'), ); expect(result.success).toBe(true); }); it('should reject BigInt values at exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMinMax, BigInt('2000000000000'), ); expect(result.success).toBe(false); }); it('should reject BigInt values at exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMinMax, BigInt('8000000000000'), ); expect(result.success).toBe(false); }); }); describe('UInt64WithExclusiveMinInclusiveMax', () => { it('should accept values above exclusive minimum and at inclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMinInclusiveMax, BigInt('13000000000000'), ); expect(result.success).toBe(true); }); it('should accept values above exclusive minimum and below inclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMinInclusiveMax, BigInt('8000000000000'), ); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMinInclusiveMax, BigInt('3000000000000'), ); expect(result.success).toBe(false); }); it('should reject values above inclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithExclusiveMinInclusiveMax, BigInt('13000000000001'), ); expect(result.success).toBe(false); }); }); describe('UInt64WithInclusiveMinExclusiveMax', () => { it('should accept values at inclusive minimum and below exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithInclusiveMinExclusiveMax, BigInt('4000000000000'), ); expect(result.success).toBe(true); }); it('should accept values above inclusive minimum and below exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithInclusiveMinExclusiveMax, BigInt('9000000000000'), ); expect(result.success).toBe(true); }); it('should reject values below inclusive minimum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithInclusiveMinExclusiveMax, BigInt('3999999999999'), ); expect(result.success).toBe(false); }); it('should reject values at exclusive maximum', () => { const result = v.safeParse( generatedSchemas.vUInt64WithInclusiveMinExclusiveMax, BigInt('14000000000000'), ); expect(result.success).toBe(false); }); }); }); describe('Special Cases', () => { describe('PrecedenceTest', () => { it('should use exclusive constraints over inclusive (exclusive minimum takes precedence)', () => { // exclusiveMinimum: 5, minimum: 10 - exclusive should take precedence const result = v.safeParse(generatedSchemas.vPrecedenceTest, 6); expect(result.success).toBe(true); }); it('should use exclusive constraints over inclusive (exclusive maximum takes precedence)', () => { // exclusiveMaximum: 95, maximum: 90 - exclusive should take precedence const result = v.safeParse(generatedSchemas.vPrecedenceTest, 94); expect(result.success).toBe(true); }); it('should reject values at exclusive minimum boundary', () => { const result = v.safeParse(generatedSchemas.vPrecedenceTest, 5); expect(result.success).toBe(false); }); it('should reject values at exclusive maximum boundary', () => { const result = v.safeParse(generatedSchemas.vPrecedenceTest, 95); expect(result.success).toBe(false); }); }); }); }); ================================================ FILE: packages/openapi-ts-tests/valibot/v1/test/utils.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createClient, type UserConfig } from '@hey-api/openapi-ts'; import * as v from 'valibot'; import { getSpecsPath } from '../../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export const getSnapshotsPath = (): string => path.join(__dirname, '..', '__snapshots__'); export const getTempSnapshotsPath = (): string => path.join(__dirname, '..', '.gen', 'snapshots'); export const createValibotConfig = ({ openApiVersion, outputDir }: { openApiVersion: string; outputDir: string }) => (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0]! : userConfig.input; const inputPath = path.join( getSpecsPath(), openApiVersion, typeof input === 'string' ? input : (input.path as string), ); const output = userConfig.output instanceof Array ? userConfig.output[0]! : userConfig.output; const outputPath = typeof output === 'string' ? output : (output?.path ?? ''); return { plugins: ['valibot'], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', path: './logs' }, output: path.join(outputDir, outputPath), } as UserConfig; }; function loadGeneratedSchemas(generatedPath: string): any { if (!fs.existsSync(generatedPath)) { throw new Error( `Generated schema file not found: ${generatedPath}\n` + `Schema generation may have failed. Check the input schema file for errors.`, ); } try { const generatedCode = fs.readFileSync(generatedPath, 'utf-8'); const exportMatches = generatedCode.match(/export const (\w+)/g); if (!exportMatches) { throw new Error('No exported schemas found in generated code'); } const schemaNames = exportMatches.map((match: string) => match.replace('export const ', '')); const evalCode = generatedCode .replace(/import \* as v from 'valibot';/, '') .replace(/export const/g, 'const') .replace(/v\./g, 'vModule.') + `\n\nreturn { ${schemaNames.join(', ')} };`; const schemaFunction = new Function('vModule', evalCode); return schemaFunction(v); } catch (error) { throw new Error( `Failed to load generated schemas from ${generatedPath}: ${error instanceof Error ? error.message : String(error)}\n` + `The generated file may contain syntax errors or be malformed.`, ); } } export async function setupValibotTest( input: string, output: string, version = '3.1.x', ): Promise { const inputPath = path.join(getSpecsPath(), version, input); const outputPath = path.join(__dirname, '.gen', version, output); fs.mkdirSync(outputPath, { recursive: true }); await createClient({ input: inputPath, logs: { level: 'silent' }, output: outputPath, plugins: ['valibot'], }); const generatedPath = path.join(outputPath, 'valibot.gen.ts'); return loadGeneratedSchemas(generatedPath); } ================================================ FILE: packages/openapi-ts-tests/valibot/v1/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["test/**/*", "__snapshots__/**/*"], "exclude": [".gen/**/*"], "references": [{ "path": "../../../openapi-ts" }] } ================================================ FILE: packages/openapi-ts-tests/valibot/v1/turbo.json ================================================ { "$schema": "../../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts-tests/valibot/v1/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/mini/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zArrayWithAllOfObjects = z.array(z.intersection(z.object({ id: z.optional(z.int()) }), z.object({ name: z.optional(z.string()) }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.optional(z.int()), createdAt: z.optional(z.iso.datetime()) }); export const zArrayWithAllOfRefs = z.array(z.intersection(zBaseModel, z.object({ extra: z.optional(z.string()) }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/mini/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a type-only model that defines Date as a string */ export const zDate = z.string(); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.optional(z.int()) }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.optional(z.boolean()) }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.optional(z.string()) }); export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.optional(z.string()) }); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp: z.nullish(z.string()), nullableRequiredProp: z.nullable(z.string()) }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ test: z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])), statusCode: z.optional(z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ])), bool: z.optional(z.literal(true)) }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.optional(z.int()) }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.optional(z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ]))), dictionaryWithEnumFromDescription: z.optional(z.record(z.string(), z.int())), arrayWithEnum: z.optional(z.array(z.enum([ 'Success', 'Warning', 'Error' ]))), arrayWithDescription: z.optional(z.array(z.int())) }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.optional(z.array(zModelWithString)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.optional(z.record(z.string(), z.string())) }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.optional(z.lazy((): any => zModelWithCircularReference)) }); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.readonly(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()), '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())) }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: z.optional(zModelWithProperties) }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.readonly(z.object({ second: z.readonly(z.object({ third: z.readonly(z.string()) })) })) }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: z.optional(zModelWithString) }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.optional(z.string()), apple: z.optional(z.string()), hawaii: z.optional(z.string()) }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: z.optional(zModelWithString), propB: z.optional(zModelWithString), propC: z.optional(zModelWithString) }); /** * This is a model that extends another model */ export const zModelThatExtends = z.intersection(zModelWithString, z.object({ propExtendsA: z.optional(z.string()), propExtendsB: z.optional(zModelWithString) })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = z.intersection(z.intersection(zModelWithString, zModelThatExtends), z.object({ propExtendsC: z.optional(z.string()), propExtendsD: z.optional(zModelWithString) })); export const zDefault = z.object({ name: z.optional(z.string()) }); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), enabled: z.optional(z.readonly(z.boolean())), modified: z.optional(z.readonly(z.iso.datetime())), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zParameterActivityParams = z.object({ description: z.optional(z.string()), graduate_id: z.optional(z.int()), organization_id: z.optional(z.int()), parent_activity: z.optional(z.int()), post_id: z.optional(z.int()) }); export const zResponsePostActivityResponse = z.object({ description: z.optional(z.string()), graduate_id: z.optional(z.int()), organization_id: z.optional(z.int()), parent_activity_id: z.optional(z.int()), post_id: z.optional(z.int()) }); export const zFailureFailure = z.object({ error: z.optional(z.string()), message: z.optional(z.string()), reference_code: z.optional(z.string()) }); export const zExternalSharedModel = z.object({ id: z.string(), name: z.optional(z.string()) }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()) }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: z.optional(zModelWithPropertiesWritable) }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zServiceWithEmptyTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zFooWowData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithDescriptionsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterWithBreaks: z.optional(z.string()), parameterWithBackticks: z.optional(z.string()), parameterWithSlashes: z.optional(z.string()), parameterWithExpressionPlaceholders: z.optional(z.string()), parameterWithQuotes: z.optional(z.string()), parameterWithReservedCharacters: z.optional(z.string()) })) }); export const zCallWithParametersData = z.object({ body: z.optional(z.never()), path: z.object({ parameterPath: z.string(), 'api-version': z.string() }), query: z.object({ parameterQuery: z.string() }), headers: z.object({ parameterHeader: z.string() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.string(), path: z.object({ 'parameter.path.1': z.optional(z.string()), 'parameter-path-2': z.optional(z.string()), 'PARAMETER-PATH-3': z.optional(z.string()), 'api-version': z.string() }), query: z.object({ default: z.optional(z.string()), 'parameter-query': z.string() }), headers: z.object({ 'parameter.header': z.string() }) }); export const zCallWithDefaultParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterString: z._default(z.string(), 'Hello World!'), parameterNumber: z._default(z.number(), 123), parameterBoolean: z._default(z.boolean(), true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]), parameterModel: z._default(z.object({ prop: z.optional(z.string()) }), { prop: 'Hello World!' }) }) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.optional(z.string()), 'Hello World!'), parameterNumber: z._default(z.optional(z.number()), 123), parameterBoolean: z._default(z.optional(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])) })) }); export const zCallToTestOrderOfParamsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterOptionalStringWithDefault: z._default(z.optional(z.string()), 'Hello World!'), parameterOptionalStringWithEmptyDefault: z._default(z.optional(z.string()), ''), parameterOptionalStringWithNoDefault: z.optional(z.string()), parameterStringWithDefault: z._default(z.string(), 'Hello World!'), parameterStringWithEmptyDefault: z._default(z.string(), ''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.nullish(z.string()), parameterStringNullableWithDefault: z._default(z.nullish(z.string()), null) }) }); export const zDuplicateNameData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName2Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName3Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName4Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.unknown() ]); export const zDummyAData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDummyBData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Message for default response */ export const zCallWithResponseResponse = zModelWithString; export const zCallWithDuplicateResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Message for 201 response */ export const zCallWithDuplicateResponsesResponse = zModelWithString; export const zCallWithResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())), value: z.optional(z.readonly(z.array(zModelWithString))) }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterArrayCSV: z.array(z.string()), parameterArraySSV: z.array(z.string()), parameterArrayTSV: z.array(z.string()), parameterArrayPipes: z.array(z.string()), parameterArrayMulti: z.array(z.string()) }) }); export const zTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.object({ id: z.optional(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))) })), query: z.object({ parameterNumber: z._default(z.number(), 123), parameterString: z._default(z.string(), 'default'), parameterBoolean: z._default(z.boolean(), true), parameterArray: z.array(z.string()), parameterDictionary: z.record(z.string(), z.unknown()), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zComplexTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterObject: z.object({ first: z.optional(z.object({ second: z.optional(z.object({ third: z.optional(z.string()) })) })) }), parameterReference: z.object({ prop: z.optional(z.string()) }) }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zCallWithResultFromHeaderData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zTestErrorCodeData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ status: z.string() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = zNonAsciiStringæøåÆøÅöôêÊ字符串; export const zPostApiVbyApiVersionBodyData = z.object({ body: zParameterActivityParams, path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostApiVbyApiVersionBodyResponse = zResponsePostActivityResponse; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/mini/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.object({ bar: z.optional(z.int()), foo: z._default(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/v3/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.number().int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.number().int().optional(), createdAt: z.string().datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/v3/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.number().int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.number().int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.number().int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.number().int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.number().int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.number().int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.number().int(); /** * This is a simple number */ export const zSimpleInteger = z.number().int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.number().int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string()); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.record(z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a type-only model that defines Date as a string */ export const zDate = z.string(); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.number().int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp: z.string().nullish(), nullableRequiredProp: z.string().nullable() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ test: z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.number().int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.number().int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.number().int()).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string()).optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference: z.AnyZodObject = z.object({ prop: z.lazy(() => zModelWithCircularReference).optional() }); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly() }).readonly() }).readonly() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); export const zDefault = z.object({ name: z.string().optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.string().datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zParameterActivityParams = z.object({ description: z.string().optional(), graduate_id: z.number().int().optional(), organization_id: z.number().int().optional(), parent_activity: z.number().int().optional(), post_id: z.number().int().optional() }); export const zResponsePostActivityResponse = z.object({ description: z.string().optional(), graduate_id: z.number().int().optional(), organization_id: z.number().int().optional(), parent_activity_id: z.number().int().optional(), post_id: z.number().int().optional() }); export const zFailureFailure = z.object({ error: z.string().optional(), message: z.string().optional(), reference_code: z.string().optional() }); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zServiceWithEmptyTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zCallWithParametersData = z.object({ body: z.never().optional(), path: z.object({ parameterPath: z.string(), 'api-version': z.string() }), query: z.object({ parameterQuery: z.string() }), headers: z.object({ parameterHeader: z.string() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.string(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string() }), headers: z.object({ 'parameter.header': z.string() }) }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().default('Hello World!'), parameterNumber: z.number().default(123), parameterBoolean: z.boolean().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]), parameterModel: z.object({ prop: z.string().optional() }).default({ prop: 'Hello World!' }) }) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.unknown() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for default response */ export const zCallWithResponseResponse = zModelWithString; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for 201 response */ export const zCallWithDuplicateResponsesResponse = zModelWithString; export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()), parameterArraySSV: z.array(z.string()), parameterArrayTSV: z.array(z.string()), parameterArrayPipes: z.array(z.string()), parameterArrayMulti: z.array(z.string()) }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().default('default'), parameterBoolean: z.boolean().default(true), parameterArray: z.array(z.string()), parameterDictionary: z.record(z.unknown()), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.unknown()) ]); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: z.object({ prop: z.string().optional() }) }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.string() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.number().int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = zNonAsciiStringæøåÆøÅöôêÊ字符串; export const zPostApiVbyApiVersionBodyData = z.object({ body: zParameterActivityParams, path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostApiVbyApiVersionBodyResponse = zResponsePostActivityResponse; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/v3/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.object({ bar: z.number().int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.number().int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/v4/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.int().optional(), createdAt: z.iso.datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/v4/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a type-only model that defines Date as a string */ export const zDate = z.string(); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp: z.string().nullish(), nullableRequiredProp: z.string().nullable() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ test: z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.string(), z.int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.int()).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string(), z.string()).optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.lazy((): any => zModelWithCircularReference).optional() }); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly() }).readonly() }).readonly() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); export const zDefault = z.object({ name: z.string().optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.iso.datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zParameterActivityParams = z.object({ description: z.string().optional(), graduate_id: z.int().optional(), organization_id: z.int().optional(), parent_activity: z.int().optional(), post_id: z.int().optional() }); export const zResponsePostActivityResponse = z.object({ description: z.string().optional(), graduate_id: z.int().optional(), organization_id: z.int().optional(), parent_activity_id: z.int().optional(), post_id: z.int().optional() }); export const zFailureFailure = z.object({ error: z.string().optional(), message: z.string().optional(), reference_code: z.string().optional() }); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zServiceWithEmptyTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zCallWithParametersData = z.object({ body: z.never().optional(), path: z.object({ parameterPath: z.string(), 'api-version': z.string() }), query: z.object({ parameterQuery: z.string() }), headers: z.object({ parameterHeader: z.string() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.string(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string() }), headers: z.object({ 'parameter.header': z.string() }) }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().default('Hello World!'), parameterNumber: z.number().default(123), parameterBoolean: z.boolean().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]), parameterModel: z.object({ prop: z.string().optional() }).default({ prop: 'Hello World!' }) }) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.unknown() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for default response */ export const zCallWithResponseResponse = zModelWithString; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for 201 response */ export const zCallWithDuplicateResponsesResponse = zModelWithString; export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()), parameterArraySSV: z.array(z.string()), parameterArrayTSV: z.array(z.string()), parameterArrayPipes: z.array(z.string()), parameterArrayMulti: z.array(z.string()) }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().default('default'), parameterBoolean: z.boolean().default(true), parameterArray: z.array(z.string()), parameterDictionary: z.record(z.string(), z.unknown()), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: z.object({ prop: z.string().optional() }) }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.string() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = zNonAsciiStringæøåÆøÅöôêÊ字符串; export const zPostApiVbyApiVersionBodyData = z.object({ body: zParameterActivityParams, path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostApiVbyApiVersionBodyResponse = zResponsePostActivityResponse; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/2.0.x/v4/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.object({ bar: z.int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/mini/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zArrayWithAllOfObjects = z.array(z.intersection(z.object({ id: z.optional(z.int()) }), z.object({ name: z.optional(z.string()) }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.optional(z.int()), createdAt: z.optional(z.iso.datetime()) }); export const zArrayWithAllOfRefs = z.array(z.intersection(zBaseModel, z.object({ extra: z.optional(z.string()) }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/mini/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.optional(z.array(zBar).check(z.minLength(1), z.maxLength(2147483647))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/mini/circular/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.object({ quux: z.optional(z.lazy((): any => zQuux)) }); export const zBar = z.object({ bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.lazy((): any => zBaz)) }); export const zBaz = z.object({ quux: z.optional(z.lazy((): any => zQuux)) }); export const zQux = z.union([ z.intersection(z.object({ type: z.literal('struct') }), z.lazy(() => z.lazy((): any => zCorge))), z.intersection(z.object({ type: z.literal('array') }), zFoo) ]); export const zQuux = z.object({ qux: z.optional(zQux) }); export const zCorge = z.object({ baz: z.optional(z.array(zBaz)) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/mini/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.nullable(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/))); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z._default(z.array(z.string()), ['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': z.optional(zCamelCaseCommentWithBreaks), bar: z.optional(z.string()) })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z._default(z.optional(z.string()), 'test') }), z.object({ bar: z.optional(z.string()) })])); export const zAnyOfAnyAndNull = z.object({ data: z.optional(z.unknown()) }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.optional(z.array(z.union([z.object({ foo: z.optional(z.string()) }), z.object({ bar: z.optional(z.string()) })]))) }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.optional(z.number()), bar: z.optional(z.boolean()) }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.optional(z.int()) }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.optional(z.boolean()) }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.optional(z.string()) }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.optional(z.string()) }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.nullish(z.string()), nullableRequiredProp1: z.nullable(z.string()), nullableProp2: z.nullish(z.string()), nullableRequiredProp2: z.nullable(z.string()), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])), statusCode: z.optional(z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ])), bool: z.optional(z.literal(true)) }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.optional(z.enum(['3.0'])) }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.optional(z.int()) }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.optional(z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ]))), dictionaryWithEnumFromDescription: z.optional(z.record(z.string(), z.int())), arrayWithEnum: z.optional(z.array(z.enum([ 'Success', 'Warning', 'Error' ]))), arrayWithDescription: z.optional(z.array(z.int())), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.optional(z.array(zModelWithString)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.optional(z.record(z.string(), z.string())) }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.optional(z.string()) }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.optional(z.lazy((): any => zModelWithCircularReference)) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.optional(z.number()) }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.optional(z.number()) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.intersection(z.object({ kind: z.literal('circle') }), zModelCircle), z.intersection(z.object({ kind: z.literal('square') }), zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.optional(z.union([ z.array(z.nullable(zModelWithDictionary)), z.array(z.nullable(zModelWithArray)) ])) }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.enum(['ConstValue']); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.nullish(z.array(z.union([z3eNum1Период, zConstValue]))) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.number()) ])) }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ])) }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ])) }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.nullish(z.intersection(z.intersection(z.intersection(z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum), zModelWithArray), zModelWithDictionary)) }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.optional(z.string()), lastname: z.optional(z.string()) }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = z.intersection(zCompositionBaseModel, z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.readonly(z.string()), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()), '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())) }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: z.optional(zModelWithProperties) }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.nullable(z.readonly(z.object({ second: z.nullable(z.readonly(z.object({ third: z.nullable(z.readonly(z.string())) }))) }))) }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: z.optional(zModelWithString) }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.optional(z.string()), apple: z.optional(z.string()), hawaii: z.optional(z.string()) }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: z.optional(zModelWithString), propB: z.optional(zModelWithString), propC: z.optional(zModelWithString) }); /** * This is a model that extends another model */ export const zModelThatExtends = z.intersection(zModelWithString, z.object({ propExtendsA: z.optional(z.string()), propExtendsB: z.optional(zModelWithString) })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = z.intersection(z.intersection(zModelWithString, zModelThatExtends), z.object({ propExtendsC: z.optional(z.string()), propExtendsD: z.optional(zModelWithString) })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), enabled: z.optional(z.readonly(z.boolean())), modified: z.optional(z.readonly(z.iso.datetime())), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFile = z.object({ id: z.optional(z.readonly(z.string().check(z.minLength(1)))), updated_at: z.optional(z.readonly(z.iso.datetime())), created_at: z.optional(z.readonly(z.iso.datetime())), mime: z.string().check(z.minLength(1), z.maxLength(24)), file: z.optional(z.readonly(z.url())) }); export const zDefault = z.object({ name: z.optional(z.string()) }); export const zPageable = z.object({ page: z._default(z.optional(z.int().check(z.gte(0), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), 0), size: z.optional(z.int().check(z.gte(1), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), sort: z.optional(z.array(z.string())) }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.optional(z.enum(['String'])), number: z.optional(z.literal(0)), null: z.optional(z.unknown()), withType: z.optional(z.enum(['Some string'])) }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.optional(z.string()) }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.nullish(z.array(z.union([z.string(), z.boolean()]))) }); /** * An object that can be null */ export const zNullableObject = z._default(z.nullable(z.object({ foo: z.optional(z.string()) })), null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: z.optional(zNullableObject) }); /** * An object with additional properties that can be null */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), z.nullable(zNullableObject)); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.iso.datetime()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.optional(z.array(zModelWithNestedArrayEnumsDataFoo)), bar: z.optional(z.array(zModelWithNestedArrayEnumsDataBar)) }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.optional(z.array(z.string())), data: z.optional(zModelWithNestedArrayEnumsData) }); export const zModelWithNestedCompositionEnums = z.object({ foo: z.optional(zModelWithNestedArrayEnumsDataFoo) }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.readonly(z.string()) }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnly)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.array(z.union([ zModelWithInteger, z.number(), z.string() ])); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])) ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.optional(z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ])) }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.optional(z.string()) }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()), object: z.optional(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) })), array: z.optional(z.array(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) }))) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.optional(z.string()), uid: z.optional(z.string()) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: z.optional(zIoK8sApimachineryPkgApisMetaV1Preconditions) }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())) }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.optional(z.string()) }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()) }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: z.optional(zModelWithPropertiesWritable) }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFileWritable = z.object({ mime: z.string().check(z.minLength(1), z.maxLength(24)) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnlyWritable)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()) }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; export const zSimpleRequestBody = zModelWithString; export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zApiVVersionODataControllerCountData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.string() }), query: z.optional(z.never()) }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDeleteFooData3 = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.optional(z.never()), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterWithBreaks: z.optional(z.string()), parameterWithBackticks: z.optional(z.string()), parameterWithSlashes: z.optional(z.string()), parameterWithExpressionPlaceholders: z.optional(z.string()), parameterWithQuotes: z.optional(z.string()), parameterWithReservedCharacters: z.optional(z.string()) })) }); export const zDeprecatedCallData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()), headers: z.object({ parameter: z.nullable(zDeprecatedModel) }) }); export const zCallWithParametersData = z.object({ body: z.nullable(z.record(z.string(), z.unknown())), path: z.object({ parameterPath: z.nullable(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ foo_ref_enum: z.optional(zModelWithNestedArrayEnumsDataFoo), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.nullable(z.string()) }), headers: z.object({ parameterHeader: z.nullable(z.string()) }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.nullable(zModelWithString), path: z.object({ 'parameter.path.1': z.optional(z.string()), 'parameter-path-2': z.optional(z.string()), 'PARAMETER-PATH-3': z.optional(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ default: z.optional(z.string()), 'parameter-query': z.nullable(z.string()) }), headers: z.object({ 'parameter.header': z.nullable(z.string()) }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.optional(z.never()), query: z.optional(z.object({ page: z.optional(z.number()) })) }); export const zPostCallWithOptionalParamData = z.object({ body: z.optional(z.object({ offset: z.nullish(z.number()) })), path: z.optional(z.never()), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: z.optional(zSimpleRequestBody), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: z.optional(zSimpleFormData), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zCallWithDefaultParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.nullish(z.string()), 'Hello World!'), parameterNumber: z._default(z.nullish(z.number()), 123), parameterBoolean: z._default(z.nullish(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z.nullish(zModelWithString) })) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.optional(z.string()), 'Hello World!'), parameterNumber: z._default(z.optional(z.number()), 123), parameterBoolean: z._default(z.optional(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z.optional(zModelWithString) })) }); export const zCallToTestOrderOfParamsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterOptionalStringWithDefault: z._default(z.optional(z.string()), 'Hello World!'), parameterOptionalStringWithEmptyDefault: z._default(z.optional(z.string()), ''), parameterOptionalStringWithNoDefault: z.optional(z.string()), parameterStringWithDefault: z._default(z.string(), 'Hello World!'), parameterStringWithEmptyDefault: z._default(z.string(), ''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.nullish(z.string()), parameterStringNullableWithDefault: z._default(z.nullish(z.string()), null) }) }); export const zDuplicateNameData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName2Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName3Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName4Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithDuplicateResponsesResponse = z.union([ z.intersection(zModelWithBoolean, zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())), value: z.optional(z.readonly(z.array(zModelWithString))) }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterArrayCSV: z.nullable(z.array(z.string())), parameterArraySSV: z.nullable(z.array(z.string())), parameterArrayTSV: z.nullable(z.array(z.string())), parameterArrayPipes: z.nullable(z.array(z.string())), parameterArrayMulti: z.nullable(z.array(z.string())) }) }); export const zTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.object({ id: z.optional(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))) })), query: z.object({ parameterNumber: z._default(z.number(), 123), parameterString: z._default(z.nullable(z.string()), 'default'), parameterBoolean: z._default(z.nullable(z.boolean()), true), parameterObject: z._default(z.nullable(z.record(z.string(), z.unknown())), null), parameterArray: z.nullable(z.array(z.string())), parameterDictionary: z.nullable(z.record(z.string(), z.unknown())), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.nullable(z.string()) }), query: z.optional(z.never()) }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.optional(z.never()), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterObject: z.object({ first: z.optional(z.object({ second: z.optional(z.object({ third: z.optional(z.string()) })) })) }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.optional(z.string()), metadata: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })) }); export const zMultipartRequestData = z.object({ body: z.optional(z.object({ content: z.optional(z.string()), data: z.nullish(zModelWithString) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zComplexParamsData = z.object({ body: z.optional(z.object({ key: z.nullable(z.readonly(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)))), name: z.nullable(z.string().check(z.maxLength(255))), enabled: z._default(z.optional(z.boolean()), true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.nullish(z.array(zModelWithString)), listOfStrings: z.nullish(z.array(z.string())), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.optional(z.readonly(z.object({ id: z.optional(z.readonly(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })))), name: z.nullish(z.readonly(z.string())) }))) })), path: z.object({ id: z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zTestErrorCodeData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/mini/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.nullable(z.enum(['foo', 'bar'])); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/mini/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.object({ bar: z.optional(z.int()), foo: z._default(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/mini/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); export const zBar = z.object({ foo: z.optional(zFoo) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v3/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.number().int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.number().int().optional(), createdAt: z.string().datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v3/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v3/circular/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo: z.AnyZodObject = z.object({ quux: z.lazy(() => zQuux).optional() }); export const zBar: z.AnyZodObject = z.object({ bar: z.lazy(() => zBar).optional(), baz: z.lazy(() => zBaz).optional() }); export const zBaz: z.AnyZodObject = z.object({ quux: z.lazy(() => zQuux).optional() }); export const zQux: z.ZodTypeAny = z.union([ z.object({ type: z.literal('struct') }).and(z.lazy(() => zCorge)), z.object({ type: z.literal('array') }).and(zFoo) ]); export const zQuux = z.object({ qux: zQux.optional() }); export const zCorge = z.object({ baz: z.array(zBaz).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v3/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.number().int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.number().int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.number().int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.number().int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.number().int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.number().int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.number().int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.number().int(); /** * This is a simple number */ export const zSimpleInteger = z.number().int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.number().int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().optional() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.record(z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.number().int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.number().int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.number().int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.number().int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference: z.AnyZodObject = z.object({ prop: z.lazy(() => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(zModelWithDictionary.nullable()), z.array(zModelWithArray.nullable()) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.enum(['ConstValue']); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.string().datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.string().datetime().readonly().optional(), created_at: z.string().datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.string().url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.number().int().gte(0).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.number().int().gte(1).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.unknown()); export const zModelWithConst = z.object({ String: z.enum(['String']).optional(), number: z.literal(0).optional(), null: z.unknown().optional(), withType: z.enum(['Some string']).optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null */ export const zModelWithAdditionalPropertiesRef = z.record(zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.string().datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.string().datetime(), z.string().datetime()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.array(z.union([ zModelWithInteger, z.number(), z.string() ])); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.number().int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; export const zSimpleRequestBody = zModelWithString; export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string() }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.unknown()).nullable(), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.number().int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.number().int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v3/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v3/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.object({ bar: z.number().int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.number().int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v3/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); export const zBar = z.object({ foo: zFoo.optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v4/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.int().optional(), createdAt: z.iso.datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v4/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v4/circular/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.object({ quux: z.lazy((): any => zQuux).optional() }); export const zBar = z.object({ bar: z.lazy((): any => zBar).optional(), baz: z.lazy((): any => zBaz).optional() }); export const zBaz = z.object({ quux: z.lazy((): any => zQuux).optional() }); export const zQux = z.union([ z.object({ type: z.literal('struct') }).and(z.lazy(() => z.lazy((): any => zCorge))), z.object({ type: z.literal('array') }).and(zFoo) ]); export const zQuux = z.object({ qux: zQux.optional() }); export const zCorge = z.object({ baz: z.array(zBaz).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v4/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().optional() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.string(), z.int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string(), z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.lazy((): any => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(zModelWithDictionary.nullable()), z.array(zModelWithArray.nullable()) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.enum(['ConstValue']); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.iso.datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.iso.datetime().readonly().optional(), created_at: z.iso.datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.int().gte(0).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.int().gte(1).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.enum(['String']).optional(), number: z.literal(0).optional(), null: z.unknown().optional(), withType: z.enum(['Some string']).optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.iso.datetime()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.array(z.union([ zModelWithInteger, z.number(), z.string() ])); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; export const zSimpleRequestBody = zModelWithString; export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string() }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.string(), z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.string(), z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.string(), z.unknown()).nullable(), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v4/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v4/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.object({ bar: z.int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.0.x/v4/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); export const zBar = z.object({ foo: zFoo.optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zArrayWithAllOfObjects = z.array(z.intersection(z.object({ id: z.optional(z.int()) }), z.object({ name: z.optional(z.string()) }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.optional(z.int()), createdAt: z.optional(z.iso.datetime()) }); export const zArrayWithAllOfRefs = z.array(z.intersection(zBaseModel, z.object({ extra: z.optional(z.string()) }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.optional(z.array(zBar).check(z.minLength(1), z.maxLength(2147483647))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.nullable(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/))); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z._default(z.array(z.string()), ['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': z.optional(zCamelCaseCommentWithBreaks), bar: z.optional(z.string()) })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z._default(z.optional(z.string()), 'test') }), z.object({ bar: z.optional(z.string()) })])); export const zAnyOfAnyAndNull = z.object({ data: z.nullish(z.unknown()) }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.optional(z.array(z.union([z.object({ foo: z.optional(z.string()) }), z.object({ bar: z.optional(z.string()) })]))) }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.optional(z.number()), bar: z.optional(z.boolean()) }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.optional(z.int()) }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.optional(z.boolean()) }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.optional(z.string()) }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.optional(z.string()) }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.nullish(z.string()), nullableRequiredProp1: z.nullable(z.string()), nullableProp2: z.nullish(z.string()), nullableRequiredProp2: z.nullable(z.string()), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])), statusCode: z.optional(z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ])), bool: z.optional(z.literal(true)) }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.optional(z.enum(['3.0'])) }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.optional(z.int()) }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.optional(z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ]))), dictionaryWithEnumFromDescription: z.optional(z.record(z.string(), z.int())), arrayWithEnum: z.optional(z.array(z.enum([ 'Success', 'Warning', 'Error' ]))), arrayWithDescription: z.optional(z.array(z.int())), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.optional(z.array(zModelWithString)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.optional(z.record(z.string(), z.string())) }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.optional(z.string()) }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.optional(z.lazy((): any => zModelWithCircularReference)) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.optional(z.number()) }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.optional(z.number()) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.intersection(z.object({ kind: z.literal('circle') }), zModelCircle), z.intersection(z.object({ kind: z.literal('square') }), zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.optional(z.union([ z.array(z.union([zModelWithDictionary, z.null()])), z.array(z.union([zModelWithArray, z.null()])) ])) }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.literal('ConstValue'); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.nullish(z.array(z.union([z3eNum1Период, zConstValue]))) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.number()) ])) }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ])) }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ])) }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.nullish(z.intersection(z.intersection(z.intersection(z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum), zModelWithArray), zModelWithDictionary)) }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.optional(z.string()), lastname: z.optional(z.string()) }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = z.intersection(zCompositionBaseModel, z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.readonly(z.string()), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()), '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())) }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: z.optional(zModelWithProperties) }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.nullable(z.readonly(z.object({ second: z.nullable(z.readonly(z.object({ third: z.nullable(z.readonly(z.string())) }))) }))) }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: z.optional(zModelWithString) }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.optional(z.string()), apple: z.optional(z.string()), hawaii: z.optional(z.string()) }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: z.optional(zModelWithString), propB: z.optional(zModelWithString), propC: z.optional(zModelWithString) }); /** * This is a model that extends another model */ export const zModelThatExtends = z.intersection(zModelWithString, z.object({ propExtendsA: z.optional(z.string()), propExtendsB: z.optional(zModelWithString) })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = z.intersection(z.intersection(zModelWithString, zModelThatExtends), z.object({ propExtendsC: z.optional(z.string()), propExtendsD: z.optional(zModelWithString) })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), enabled: z.optional(z.readonly(z.boolean())), modified: z.optional(z.readonly(z.iso.datetime())), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFile = z.object({ id: z.optional(z.readonly(z.string().check(z.minLength(1)))), updated_at: z.optional(z.readonly(z.iso.datetime())), created_at: z.optional(z.readonly(z.iso.datetime())), mime: z.string().check(z.minLength(1), z.maxLength(24)), file: z.optional(z.readonly(z.url())) }); export const zDefault = z.object({ name: z.optional(z.string()) }); export const zPageable = z.object({ page: z._default(z.optional(z.int().check(z.gte(0), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), 0), size: z.optional(z.int().check(z.gte(1), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), sort: z.optional(z.array(z.string())) }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.optional(z.literal('String')), number: z.optional(z.literal(0)), null: z.optional(z.null()), withType: z.optional(z.literal('Some string')) }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.optional(z.string()) }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.nullish(z.array(z.union([z.string(), z.boolean()]))) }); /** * An object that can be null */ export const zNullableObject = z._default(z.nullable(z.object({ foo: z.optional(z.string()) })), null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: z.optional(zNullableObject) }); /** * An object with additional properties that can be null (anyOf ref + null) */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), z.nullable(zNullableObject)); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.string()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.optional(z.array(zModelWithNestedArrayEnumsDataFoo)), bar: z.optional(z.array(zModelWithNestedArrayEnumsDataBar)) }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.optional(z.array(z.string())), data: z.optional(zModelWithNestedArrayEnumsData) }); export const zModelWithNestedCompositionEnums = z.object({ foo: z.optional(zModelWithNestedArrayEnumsDataFoo) }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.readonly(z.string()) }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnly)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.tuple([ zModelWithInteger, z.union([ z.number(), z.string() ]), z.string() ]); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])) ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.optional(z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ])) }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.optional(z.string()) }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()), object: z.optional(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) })), array: z.optional(z.array(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) }))) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.optional(z.string()), uid: z.optional(z.string()) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: z.optional(zIoK8sApimachineryPkgApisMetaV1Preconditions) }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())) }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.optional(z.string()) }); /** * External ref to shared model (A) */ export const zExternalRefA = zExternalSharedModel; /** * External ref to shared model (B) */ export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()) }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: z.optional(zModelWithPropertiesWritable) }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFileWritable = z.object({ mime: z.string().check(z.minLength(1), z.maxLength(24)) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnlyWritable)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()) }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; /** * A reusable request body */ export const zSimpleRequestBody = zModelWithString; /** * A reusable request body */ export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zApiVVersionODataControllerCountData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.union([ z.string(), z.uuid() ]) }), query: z.optional(z.never()) }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDeleteFooData3 = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.optional(z.never()), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterWithBreaks: z.optional(z.string()), parameterWithBackticks: z.optional(z.string()), parameterWithSlashes: z.optional(z.string()), parameterWithExpressionPlaceholders: z.optional(z.string()), parameterWithQuotes: z.optional(z.string()), parameterWithReservedCharacters: z.optional(z.string()) })) }); export const zDeprecatedCallData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()), headers: z.object({ parameter: z.nullable(zDeprecatedModel) }) }); export const zCallWithParametersData = z.object({ body: z.nullable(z.record(z.string(), z.unknown())), path: z.object({ parameterPath: z.nullable(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ foo_ref_enum: z.optional(zModelWithNestedArrayEnumsDataFoo), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.nullable(z.string()) }), headers: z.object({ parameterHeader: z.nullable(z.string()) }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.nullable(zModelWithString), path: z.object({ 'parameter.path.1': z.optional(z.string()), 'parameter-path-2': z.optional(z.string()), 'PARAMETER-PATH-3': z.optional(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ default: z.optional(z.string()), 'parameter-query': z.nullable(z.string()) }), headers: z.object({ 'parameter.header': z.nullable(z.string()) }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.optional(z.never()), query: z.optional(z.object({ page: z.optional(z.number()) })) }); export const zPostCallWithOptionalParamData = z.object({ body: z.optional(z.object({ offset: z.nullish(z.number()) })), path: z.optional(z.never()), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: z.optional(zSimpleRequestBody), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: z.optional(zSimpleFormData), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zCallWithDefaultParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.nullish(z.string()), 'Hello World!'), parameterNumber: z._default(z.nullish(z.number()), 123), parameterBoolean: z._default(z.nullish(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z.nullish(zModelWithString) })) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.optional(z.string()), 'Hello World!'), parameterNumber: z._default(z.optional(z.number()), 123), parameterBoolean: z._default(z.optional(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z._default(z.optional(zModelWithString), { prop: 'Hello World!' }) })) }); export const zCallToTestOrderOfParamsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterOptionalStringWithDefault: z._default(z.optional(z.string()), 'Hello World!'), parameterOptionalStringWithEmptyDefault: z._default(z.optional(z.string()), ''), parameterOptionalStringWithNoDefault: z.optional(z.string()), parameterStringWithDefault: z._default(z.string(), 'Hello World!'), parameterStringWithEmptyDefault: z._default(z.string(), ''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.nullish(z.string()), parameterStringNullableWithDefault: z._default(z.nullish(z.string()), null) }) }); export const zDuplicateNameData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName2Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName3Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName4Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithDuplicateResponsesResponse = z.union([ z.intersection(zModelWithBoolean, zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())), value: z.optional(z.readonly(z.array(zModelWithString))) }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterArrayCSV: z.nullable(z.array(z.string())), parameterArraySSV: z.nullable(z.array(z.string())), parameterArrayTSV: z.nullable(z.array(z.string())), parameterArrayPipes: z.nullable(z.array(z.string())), parameterArrayMulti: z.nullable(z.array(z.string())) }) }); export const zTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.object({ id: z.optional(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))) })), query: z.object({ parameterNumber: z._default(z.number(), 123), parameterString: z._default(z.nullable(z.string()), 'default'), parameterBoolean: z._default(z.nullable(z.boolean()), true), parameterObject: z._default(z.nullable(z.record(z.string(), z.unknown())), null), parameterArray: z.nullable(z.array(z.string())), parameterDictionary: z.nullable(z.record(z.string(), z.unknown())), parameterEnum: z.nullable(z.union([ z.literal('Success'), z.literal('Warning'), z.literal('Error') ])) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.nullable(z.string()) }), query: z.optional(z.never()) }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.optional(z.never()), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterObject: z.object({ first: z.optional(z.object({ second: z.optional(z.object({ third: z.optional(z.string()) })) })) }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.optional(z.string()), metadata: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })) }); export const zMultipartRequestData = z.object({ body: z.optional(z.object({ content: z.optional(z.string()), data: z.nullish(zModelWithString) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zComplexParamsData = z.object({ body: z.optional(z.object({ key: z.nullable(z.readonly(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)))), name: z.nullable(z.string().check(z.maxLength(255))), enabled: z._default(z.optional(z.boolean()), true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.nullish(z.array(zModelWithString)), listOfStrings: z.nullish(z.array(z.string())), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.optional(z.readonly(z.object({ id: z.optional(z.readonly(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })))), name: z.nullish(z.readonly(z.string())) }))) })), path: z.object({ id: z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zTestErrorCodeData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.nullable(z.enum(['foo', 'bar'])); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/enum-resolver-permissive/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.nullable(z.union([z.enum(['foo', 'bar']), z.string()])); export const zBar = z.union([z.enum(['foo', 'bar']), z.string()]); export const zBaz = z.union([z.enum(['foo', 'bar']), z.string()]); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/schema-const/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.object({ foo: z.optional(z.literal('foo')), bar: z.optional(z.literal(3.2)), baz: z.optional(z.literal(-1)), qux: z.optional(z.literal(true)), quux: z.optional(z.tuple([ z.literal(1), z.literal(2), z.literal(3), z.literal('foo'), z.literal(true) ])), corge: z.optional(z.record(z.string(), z.unknown())), garply: z.optional(z.literal(BigInt('10'))), numberInt8: z.optional(z.literal(100)), numberInt16: z.optional(z.literal(1000)), numberInt32: z.optional(z.literal(100000)), numberInt64: z.optional(z.literal(BigInt(1000000000000))), numberUint8: z.optional(z.literal(200)), numberUint16: z.optional(z.literal(50000)), numberUint32: z.optional(z.literal(3000000000)), numberUint64: z.optional(z.literal(BigInt(18000000000000000000))), integerInt8: z.optional(z.literal(-100)), integerInt16: z.optional(z.literal(-1000)), integerInt32: z.optional(z.literal(-100000)), integerInt64: z.optional(z.literal(BigInt(-1000000000000))), integerUint8: z.optional(z.literal(255)), integerUint16: z.optional(z.literal(65535)), integerUint32: z.optional(z.literal(4294967295)), integerUint64: z.optional(z.literal(BigInt('18446744073709551615'))), stringInt64: z.optional(z.literal(BigInt('-9223372036854775808'))), stringUint64: z.optional(z.literal(BigInt('18446744073709551615'))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.object({ bar: z.optional(z.int()), foo: z._default(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: z.optional(zBar) }); export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime()) })) }); export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-bigint-min-max/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zFoo = z.object({ foo: z.optional(z.coerce.bigint().check(z.gte(BigInt(0)), z.lte(BigInt(100)))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-circular-ref/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBar = z.object({ bar: z.optional(z.array(z.lazy((): any => zBar))) }); export const zFoo = z.object({ foo: z.optional(zBar) }); export const zBaz = z.lazy((): any => zQux); /** * description caused circular reference error */ export const zQux = zBaz; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-circular-ref-2/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBar = z.object({ bar: z.nullable(z.array(z.lazy((): any => zBar))) }); export const zFoo = z.object({ foo: zBar }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-dates/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: z.optional(zBar) }); export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime({ offset: true })) })) }); export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-metadata/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/)).register(z.globalRegistry, { description: 'This is foo property.' })), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo)).register(z.globalRegistry, { description: 'This is baz property.' })), qux: z._default(z.optional(z.int().check(z.gt(0)).register(z.globalRegistry, { description: 'This is qux property.' })), 0) })), null); /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }).register(z.globalRegistry, { description: 'This is Bar schema.' }); /** * This is Foo parameter. */ export const zFoo2 = z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' }); export const zFoo3 = z.object({ foo: z.optional(zBar) }); export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' })), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime()) })) }); export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-string-constraints-union/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zLocaleOrLanguage = z.union([ z.string().check(z.length(5)), z.string().check(z.length(2)) ]); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-types/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export type BazZodType = z.infer; export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); export type QuxZodType = z.infer; /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); export type FooZodType = z.infer; /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }); export type BarZodType = z.infer; /** * This is Foo parameter. */ export const zFoo2 = z.string(); export type FooZodType2 = z.infer; export const zFoo3 = z.object({ foo: z.optional(zBar) }); export type FooZodType3 = z.infer; export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime()) })) }); export type PatchFooDataZodType = z.infer; export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); export type PostFooDataZodType = z.infer; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/mini/validators-union-merge/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4-mini'; export const zContact = z.union([ z.object({ email: z.string() }), z.object({ phone: z.string() }) ]); export const zUser = z.intersection(zContact, z.object({ username: z.string() })); export const zDogDetails = z.object({ breed: z.string(), barkVolume: z.int().check(z.gte(1), z.lte(10)) }); export const zCatDetails = z.object({ furLength: z.enum([ 'short', 'medium', 'long' ]), purrs: z.boolean() }); export const zPetStore = z.object({ animals: z.array(z.object({ name: z.string(), type: z.optional(z.enum(['dog', 'cat'])), details: z.union([ zDogDetails, zCatDetails ]) })) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.number().int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.number().int().optional(), createdAt: z.string().datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.number().int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.number().int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.number().int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.number().int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.number().int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.number().int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.number().int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.number().int(); /** * This is a simple number */ export const zSimpleInteger = z.number().int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.number().int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().nullish() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.record(z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.number().int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.number().int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.number().int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.number().int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference: z.AnyZodObject = z.object({ prop: z.lazy(() => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(z.union([zModelWithDictionary, z.null()])), z.array(z.union([zModelWithArray, z.null()])) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.literal('ConstValue'); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.string().datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.string().datetime().readonly().optional(), created_at: z.string().datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.string().url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.number().int().gte(0).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.number().int().gte(1).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.unknown()); export const zModelWithConst = z.object({ String: z.literal('String').optional(), number: z.literal(0).optional(), null: z.null().optional(), withType: z.literal('Some string').optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null (anyOf ref + null) */ export const zModelWithAdditionalPropertiesRef = z.record(zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.string().datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.string().datetime(), z.string()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.tuple([ zModelWithInteger, z.union([ z.number(), z.string() ]), z.string() ]); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.number().int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); /** * External ref to shared model (A) */ export const zExternalRefA = zExternalSharedModel; /** * External ref to shared model (B) */ export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; /** * A reusable request body */ export const zSimpleRequestBody = zModelWithString; /** * A reusable request body */ export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.union([ z.string(), z.string().uuid() ]) }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional().default({ prop: 'Hello World!' }) }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.unknown()).nullable(), parameterEnum: z.union([ z.literal('Success'), z.literal('Warning'), z.literal('Error') ]).nullable() }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.number().int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.number().int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/enum-resolver-permissive/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.union([z.enum(['foo', 'bar']), z.string()]).nullable(); export const zBar = z.union([z.enum(['foo', 'bar']), z.string()]); export const zBaz = z.union([z.enum(['foo', 'bar']), z.string()]); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/schema-const/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.object({ foo: z.literal('foo').optional(), bar: z.literal(3.2).optional(), baz: z.literal(-1).optional(), qux: z.literal(true).optional(), quux: z.tuple([ z.literal(1), z.literal(2), z.literal(3), z.literal('foo'), z.literal(true) ]).optional(), corge: z.record(z.unknown()).optional(), garply: z.literal(BigInt('10')).optional(), numberInt8: z.literal(100).optional(), numberInt16: z.literal(1000).optional(), numberInt32: z.literal(100000).optional(), numberInt64: z.literal(BigInt(1000000000000)).optional(), numberUint8: z.literal(200).optional(), numberUint16: z.literal(50000).optional(), numberUint32: z.literal(3000000000).optional(), numberUint64: z.literal(BigInt(18000000000000000000)).optional(), integerInt8: z.literal(-100).optional(), integerInt16: z.literal(-1000).optional(), integerInt32: z.literal(-100000).optional(), integerInt64: z.literal(BigInt(-1000000000000)).optional(), integerUint8: z.literal(255).optional(), integerUint16: z.literal(65535).optional(), integerUint32: z.literal(4294967295).optional(), integerUint64: z.literal(BigInt('18446744073709551615')).optional(), stringInt64: z.literal(BigInt('-9223372036854775808')).optional(), stringUint64: z.literal(BigInt('18446744073709551615')).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.object({ bar: z.number().int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.number().int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-bigint-min-max/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zFoo = z.object({ foo: z.coerce.bigint().gte(BigInt(0)).lte(BigInt(100)).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-circular-ref/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBar: z.AnyZodObject = z.object({ bar: z.array(z.lazy(() => zBar)).optional() }); export const zFoo = z.object({ foo: zBar.optional() }); export const zBaz: z.ZodTypeAny = z.lazy(() => zQux); /** * description caused circular reference error */ export const zQux = zBaz; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-circular-ref-2/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBar: z.AnyZodObject = z.object({ bar: z.array(z.lazy(() => zBar)).nullable() }); export const zFoo = z.object({ foo: zBar }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-dates/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime({ offset: true }).optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-metadata/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).describe('This is foo property.').optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).describe('This is baz property.').optional(), qux: z.number().int().gt(0).describe('This is qux property.').optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }).describe('This is Bar schema.'); /** * This is Foo parameter. */ export const zFoo2 = z.string().describe('This is Foo parameter.'); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().describe('This is Foo parameter.').optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-string-constraints-union/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zLocaleOrLanguage = z.union([ z.string().length(5), z.string().length(2) ]); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-types/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export type BazZodType = z.infer; export const zQux = z.record(z.object({ qux: z.string().optional() })); export type QuxZodType = z.infer; /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); export type FooZodType = z.infer; /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); export type BarZodType = z.infer; /** * This is Foo parameter. */ export const zFoo2 = z.string(); export type FooZodType2 = z.infer; export const zFoo3 = z.object({ foo: zBar.optional() }); export type FooZodType3 = z.infer; export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime().optional() }).optional() }); export type PatchFooDataZodType = z.infer; export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); export type PostFooDataZodType = z.infer; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v3/validators-union-merge/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod'; export const zContact = z.union([ z.object({ email: z.string() }), z.object({ phone: z.string() }) ]); export const zUser = zContact.and(z.object({ username: z.string() })); export const zDogDetails = z.object({ breed: z.string(), barkVolume: z.number().int().gte(1).lte(10) }); export const zCatDetails = z.object({ furLength: z.enum([ 'short', 'medium', 'long' ]), purrs: z.boolean() }); export const zPetStore = z.object({ animals: z.array(z.object({ name: z.string(), type: z.enum(['dog', 'cat']).optional(), details: z.union([ zDogDetails, zCatDetails ]) })) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.int().optional(), createdAt: z.iso.datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().nullish() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.string(), z.int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string(), z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.lazy((): any => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(z.union([zModelWithDictionary, z.null()])), z.array(z.union([zModelWithArray, z.null()])) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.literal('ConstValue'); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.iso.datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.iso.datetime().readonly().optional(), created_at: z.iso.datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.int().gte(0).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.int().gte(1).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.literal('String').optional(), number: z.literal(0).optional(), null: z.null().optional(), withType: z.literal('Some string').optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null (anyOf ref + null) */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.string()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.tuple([ zModelWithInteger, z.union([ z.number(), z.string() ]), z.string() ]); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); /** * External ref to shared model (A) */ export const zExternalRefA = zExternalSharedModel; /** * External ref to shared model (B) */ export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; /** * A reusable request body */ export const zSimpleRequestBody = zModelWithString; /** * A reusable request body */ export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.union([ z.string(), z.uuid() ]) }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.string(), z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional().default({ prop: 'Hello World!' }) }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.string(), z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.string(), z.unknown()).nullable(), parameterEnum: z.union([ z.literal('Success'), z.literal('Warning'), z.literal('Error') ]).nullable() }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/enum-resolver-permissive/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.union([z.enum(['foo', 'bar']), z.string()]).nullable(); export const zBar = z.union([z.enum(['foo', 'bar']), z.string()]); export const zBaz = z.union([z.enum(['foo', 'bar']), z.string()]); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/schema-const/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.object({ foo: z.literal('foo').optional(), bar: z.literal(3.2).optional(), baz: z.literal(-1).optional(), qux: z.literal(true).optional(), quux: z.tuple([ z.literal(1), z.literal(2), z.literal(3), z.literal('foo'), z.literal(true) ]).optional(), corge: z.record(z.string(), z.unknown()).optional(), garply: z.literal(BigInt('10')).optional(), numberInt8: z.literal(100).optional(), numberInt16: z.literal(1000).optional(), numberInt32: z.literal(100000).optional(), numberInt64: z.literal(BigInt(1000000000000)).optional(), numberUint8: z.literal(200).optional(), numberUint16: z.literal(50000).optional(), numberUint32: z.literal(3000000000).optional(), numberUint64: z.literal(BigInt(18000000000000000000)).optional(), integerInt8: z.literal(-100).optional(), integerInt16: z.literal(-1000).optional(), integerInt32: z.literal(-100000).optional(), integerInt64: z.literal(BigInt(-1000000000000)).optional(), integerUint8: z.literal(255).optional(), integerUint16: z.literal(65535).optional(), integerUint32: z.literal(4294967295).optional(), integerUint64: z.literal(BigInt('18446744073709551615')).optional(), stringInt64: z.literal(BigInt('-9223372036854775808')).optional(), stringUint64: z.literal(BigInt('18446744073709551615')).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.object({ bar: z.int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-bigint-min-max/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zFoo = z.object({ foo: z.coerce.bigint().gte(BigInt(0)).lte(BigInt(100)).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-circular-ref/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBar = z.object({ bar: z.array(z.lazy((): any => zBar)).optional() }); export const zFoo = z.object({ foo: zBar.optional() }); export const zBaz = z.lazy((): any => zQux); /** * description caused circular reference error */ export const zQux = zBaz; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-circular-ref-2/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBar = z.object({ bar: z.array(z.lazy((): any => zBar)).nullable() }); export const zFoo = z.object({ foo: zBar }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-dates/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime({ offset: true }).optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-metadata/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).register(z.globalRegistry, { description: 'This is foo property.' }).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).register(z.globalRegistry, { description: 'This is baz property.' }).optional(), qux: z.int().gt(0).register(z.globalRegistry, { description: 'This is qux property.' }).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }).register(z.globalRegistry, { description: 'This is Bar schema.' }); /** * This is Foo parameter. */ export const zFoo2 = z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' }); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' }).optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-string-constraints-union/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zLocaleOrLanguage = z.union([ z.string().length(5), z.string().length(2) ]); ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-types/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export type BazZodType = z.infer; export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); export type QuxZodType = z.infer; /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); export type FooZodType = z.infer; /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); export type BarZodType = z.infer; /** * This is Foo parameter. */ export const zFoo2 = z.string(); export type FooZodType2 = z.infer; export const zFoo3 = z.object({ foo: zBar.optional() }); export type FooZodType3 = z.infer; export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime().optional() }).optional() }); export type PatchFooDataZodType = z.infer; export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); export type PostFooDataZodType = z.infer; ================================================ FILE: packages/openapi-ts-tests/zod/v3/__snapshots__/3.1.x/v4/validators-union-merge/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/v4'; export const zContact = z.union([ z.object({ email: z.string() }), z.object({ phone: z.string() }) ]); export const zUser = zContact.and(z.object({ username: z.string() })); export const zDogDetails = z.object({ breed: z.string(), barkVolume: z.int().gte(1).lte(10) }); export const zCatDetails = z.object({ furLength: z.enum([ 'short', 'medium', 'long' ]), purrs: z.boolean() }); export const zPetStore = z.object({ animals: z.array(z.object({ name: z.string(), type: z.enum(['dog', 'cat']).optional(), details: z.union([ zDogDetails, zCatDetails ]) })) }); ================================================ FILE: packages/openapi-ts-tests/zod/v3/package.json ================================================ { "name": "@test/openapi-ts-zod-v3", "version": "0.0.0", "private": true, "type": "module", "scripts": { "typecheck": "tsgo --noEmit" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "typescript": "5.9.3", "zod": "^3.25.0" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts-tests/zod/v3/test/3.0.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createZodConfig, getSnapshotsPath, getTempSnapshotsPath, zodVersions } from './utils'; const version = '3.0.x'; for (const zodVersion of zodVersions) { const outputDir = path.join(getTempSnapshotsPath(), version, zodVersion.folder); const snapshotsDir = path.join(getSnapshotsPath(), version, zodVersion.folder); describe(`OpenAPI ${version}`, () => { const createConfig = createZodConfig({ openApiVersion: version, outputDir, zodVersion, }); const scenarios = [ { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'circular.yaml', output: 'circular', }), description: 'generates circular schemas', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'validators.json', output: 'validators', }), description: 'generates validator schemas', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } ================================================ FILE: packages/openapi-ts-tests/zod/v3/test/3.1.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createZodConfig, getSnapshotsPath, getTempSnapshotsPath, zodVersions } from './utils'; const version = '3.1.x'; for (const zodVersion of zodVersions) { const outputDir = path.join(getTempSnapshotsPath(), version, zodVersion.folder); const snapshotsDir = path.join(getSnapshotsPath(), version, zodVersion.folder); describe(`OpenAPI ${version}`, () => { const createConfig = createZodConfig({ openApiVersion: version, outputDir, zodVersion, }); const scenarios = [ { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'schema-const.yaml', output: 'schema-const', }), description: 'handles various constants', }, { config: createConfig({ input: 'validators.yaml', output: 'validators', }), description: 'generates validator schemas', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-dates', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, dates: { offset: true, }, name: 'zod', }, ], }), description: 'generates validator schemas with any offset', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-metadata', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, metadata: true, name: 'zod', }, ], }), description: 'generates validator schemas with metadata', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-types', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', types: { infer: true, }, }, ], }), description: 'generates validator schemas with types', }, { config: createConfig({ input: 'validators-bigint-min-max.json', output: 'validators-bigint-min-max', }), description: 'validator schemas with BigInt and min/max constraints', }, { config: createConfig({ input: 'validators-circular-ref.json', output: 'validators-circular-ref', }), description: 'validator schemas with circular reference', }, { config: createConfig({ input: 'validators-circular-ref-2.yaml', output: 'validators-circular-ref-2', }), description: 'validator schemas with circular reference 2', }, { config: createConfig({ input: 'validators-union-merge.json', output: 'validators-union-merge', }), description: "validator schemas with merged unions (can't use .merge())", }, { config: createConfig({ input: 'validators-string-constraints-union.json', output: 'validators-string-constraints-union', }), description: 'validator schemas with string constraints union', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-resolver-permissive', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', '~resolvers': { enum(ctx) { const { $, symbols } = ctx; const { z } = symbols; const { allStrings, enumMembers } = ctx.nodes.items(ctx); if (!allStrings || !enumMembers.length) { return; } const enumSchema = $(z) .attr('enum') .call($.array(...enumMembers)); return $(z) .attr('union') .call($.array(enumSchema, $(z).attr('string').call())); }, }, }, ], }), description: 'generates permissive enums with enum resolver', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } ================================================ FILE: packages/openapi-ts-tests/zod/v3/test/openapi.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createZodConfig, getSnapshotsPath, getTempSnapshotsPath, zodVersions } from './utils'; const versions = ['2.0.x', '3.0.x', '3.1.x']; for (const version of versions) { for (const zodVersion of zodVersions) { const outputDir = path.join(getTempSnapshotsPath(), version, zodVersion.folder); const snapshotsDir = path.join(getSnapshotsPath(), version, zodVersion.folder); describe(`OpenAPI ${version}`, () => { const createConfig = createZodConfig({ openApiVersion: version, outputDir, zodVersion, }); const scenarios = [ { config: createConfig({ input: 'array-items-all-of.yaml', output: 'array-items-all-of', }), description: 'generates correct array when items use allOf (intersection)', }, { config: createConfig({ input: 'full.yaml', output: 'default', }), description: 'generate Zod schemas with Zod plugin', }, { config: createConfig({ input: 'type-format.yaml', output: 'type-format', }), description: 'handles various schema types and formats', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } } ================================================ FILE: packages/openapi-ts-tests/zod/v3/test/utils.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { type UserConfig } from '@hey-api/openapi-ts'; import { getSpecsPath } from '../../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export const createZodConfig = ({ openApiVersion, outputDir, zodVersion, }: { openApiVersion: string; outputDir: string; zodVersion: (typeof zodVersions)[number]; }) => (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0]! : userConfig.input; const inputPath = path.join( getSpecsPath(), openApiVersion, typeof input === 'string' ? input : (input.path as string), ); return { plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', }, ], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', path: './logs', }, output: path.join(outputDir, typeof userConfig.output === 'string' ? userConfig.output : ''), } as const satisfies UserConfig; }; export const getSnapshotsPath = (): string => path.join(__dirname, '..', '__snapshots__'); export const getTempSnapshotsPath = (): string => path.join(__dirname, '..', '.gen', 'snapshots'); export const zodVersions = [ { compatibilityVersion: 3, folder: 'v3', }, { compatibilityVersion: 4, folder: 'v4', }, { compatibilityVersion: 'mini', folder: 'mini', }, ] as const; ================================================ FILE: packages/openapi-ts-tests/zod/v3/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["test/**/*", "__snapshots__/**/*"], "exclude": [".gen/**/*"], "references": [{ "path": "../../../openapi-ts" }] } ================================================ FILE: packages/openapi-ts-tests/zod/v3/turbo.json ================================================ { "$schema": "../../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts-tests/zod/v3/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zArrayWithAllOfObjects = z.array(z.intersection(z.object({ id: z.optional(z.int()) }), z.object({ name: z.optional(z.string()) }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.optional(z.int()), createdAt: z.optional(z.iso.datetime()) }); export const zArrayWithAllOfRefs = z.array(z.intersection(zBaseModel, z.object({ extra: z.optional(z.string()) }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a type-only model that defines Date as a string */ export const zDate = z.string(); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.optional(z.int()) }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.optional(z.boolean()) }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.optional(z.string()) }); export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.optional(z.string()) }); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp: z.nullish(z.string()), nullableRequiredProp: z.nullable(z.string()) }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ test: z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])), statusCode: z.optional(z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ])), bool: z.optional(z.literal(true)) }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.optional(z.int()) }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.optional(z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ]))), dictionaryWithEnumFromDescription: z.optional(z.record(z.string(), z.int())), arrayWithEnum: z.optional(z.array(z.enum([ 'Success', 'Warning', 'Error' ]))), arrayWithDescription: z.optional(z.array(z.int())) }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.optional(z.array(zModelWithString)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.optional(z.record(z.string(), z.string())) }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.optional(z.lazy((): any => zModelWithCircularReference)) }); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.readonly(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()), '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())) }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: z.optional(zModelWithProperties) }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.readonly(z.object({ second: z.readonly(z.object({ third: z.readonly(z.string()) })) })) }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: z.optional(zModelWithString) }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.optional(z.string()), apple: z.optional(z.string()), hawaii: z.optional(z.string()) }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: z.optional(zModelWithString), propB: z.optional(zModelWithString), propC: z.optional(zModelWithString) }); /** * This is a model that extends another model */ export const zModelThatExtends = z.intersection(zModelWithString, z.object({ propExtendsA: z.optional(z.string()), propExtendsB: z.optional(zModelWithString) })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = z.intersection(z.intersection(zModelWithString, zModelThatExtends), z.object({ propExtendsC: z.optional(z.string()), propExtendsD: z.optional(zModelWithString) })); export const zDefault = z.object({ name: z.optional(z.string()) }); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), enabled: z.optional(z.readonly(z.boolean())), modified: z.optional(z.readonly(z.iso.datetime())), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zParameterActivityParams = z.object({ description: z.optional(z.string()), graduate_id: z.optional(z.int()), organization_id: z.optional(z.int()), parent_activity: z.optional(z.int()), post_id: z.optional(z.int()) }); export const zResponsePostActivityResponse = z.object({ description: z.optional(z.string()), graduate_id: z.optional(z.int()), organization_id: z.optional(z.int()), parent_activity_id: z.optional(z.int()), post_id: z.optional(z.int()) }); export const zFailureFailure = z.object({ error: z.optional(z.string()), message: z.optional(z.string()), reference_code: z.optional(z.string()) }); export const zExternalSharedModel = z.object({ id: z.string(), name: z.optional(z.string()) }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()) }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: z.optional(zModelWithPropertiesWritable) }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zServiceWithEmptyTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zFooWowData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithDescriptionsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterWithBreaks: z.optional(z.string()), parameterWithBackticks: z.optional(z.string()), parameterWithSlashes: z.optional(z.string()), parameterWithExpressionPlaceholders: z.optional(z.string()), parameterWithQuotes: z.optional(z.string()), parameterWithReservedCharacters: z.optional(z.string()) })) }); export const zCallWithParametersData = z.object({ body: z.optional(z.never()), path: z.object({ parameterPath: z.string(), 'api-version': z.string() }), query: z.object({ parameterQuery: z.string() }), headers: z.object({ parameterHeader: z.string() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.string(), path: z.object({ 'parameter.path.1': z.optional(z.string()), 'parameter-path-2': z.optional(z.string()), 'PARAMETER-PATH-3': z.optional(z.string()), 'api-version': z.string() }), query: z.object({ default: z.optional(z.string()), 'parameter-query': z.string() }), headers: z.object({ 'parameter.header': z.string() }) }); export const zCallWithDefaultParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterString: z._default(z.string(), 'Hello World!'), parameterNumber: z._default(z.number(), 123), parameterBoolean: z._default(z.boolean(), true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]), parameterModel: z._default(z.object({ prop: z.optional(z.string()) }), { prop: 'Hello World!' }) }) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.optional(z.string()), 'Hello World!'), parameterNumber: z._default(z.optional(z.number()), 123), parameterBoolean: z._default(z.optional(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])) })) }); export const zCallToTestOrderOfParamsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterOptionalStringWithDefault: z._default(z.optional(z.string()), 'Hello World!'), parameterOptionalStringWithEmptyDefault: z._default(z.optional(z.string()), ''), parameterOptionalStringWithNoDefault: z.optional(z.string()), parameterStringWithDefault: z._default(z.string(), 'Hello World!'), parameterStringWithEmptyDefault: z._default(z.string(), ''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.nullish(z.string()), parameterStringNullableWithDefault: z._default(z.nullish(z.string()), null) }) }); export const zDuplicateNameData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName2Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName3Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName4Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.unknown() ]); export const zDummyAData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDummyBData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Message for default response */ export const zCallWithResponseResponse = zModelWithString; export const zCallWithDuplicateResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Message for 201 response */ export const zCallWithDuplicateResponsesResponse = zModelWithString; export const zCallWithResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())), value: z.optional(z.readonly(z.array(zModelWithString))) }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterArrayCSV: z.array(z.string()), parameterArraySSV: z.array(z.string()), parameterArrayTSV: z.array(z.string()), parameterArrayPipes: z.array(z.string()), parameterArrayMulti: z.array(z.string()) }) }); export const zTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.object({ id: z.optional(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))) })), query: z.object({ parameterNumber: z._default(z.number(), 123), parameterString: z._default(z.string(), 'default'), parameterBoolean: z._default(z.boolean(), true), parameterArray: z.array(z.string()), parameterDictionary: z.record(z.string(), z.unknown()), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zComplexTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterObject: z.object({ first: z.optional(z.object({ second: z.optional(z.object({ third: z.optional(z.string()) })) })) }), parameterReference: z.object({ prop: z.optional(z.string()) }) }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zCallWithResultFromHeaderData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zTestErrorCodeData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ status: z.string() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = zNonAsciiStringæøåÆøÅöôêÊ字符串; export const zPostApiVbyApiVersionBodyData = z.object({ body: zParameterActivityParams, path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostApiVbyApiVersionBodyResponse = zResponsePostActivityResponse; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/mini/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.object({ bar: z.optional(z.int()), foo: z._default(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.number().int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.number().int().optional(), createdAt: z.string().datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.number().int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.number().int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.number().int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.number().int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.number().int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.number().int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.number().int(); /** * This is a simple number */ export const zSimpleInteger = z.number().int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.number().int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string()); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.record(z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a type-only model that defines Date as a string */ export const zDate = z.string(); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.number().int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp: z.string().nullish(), nullableRequiredProp: z.string().nullable() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ test: z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.number().int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.number().int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.number().int()).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string()).optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference: z.AnyZodObject = z.object({ prop: z.lazy(() => zModelWithCircularReference).optional() }); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly() }).readonly() }).readonly() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); export const zDefault = z.object({ name: z.string().optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.string().datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zParameterActivityParams = z.object({ description: z.string().optional(), graduate_id: z.number().int().optional(), organization_id: z.number().int().optional(), parent_activity: z.number().int().optional(), post_id: z.number().int().optional() }); export const zResponsePostActivityResponse = z.object({ description: z.string().optional(), graduate_id: z.number().int().optional(), organization_id: z.number().int().optional(), parent_activity_id: z.number().int().optional(), post_id: z.number().int().optional() }); export const zFailureFailure = z.object({ error: z.string().optional(), message: z.string().optional(), reference_code: z.string().optional() }); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zServiceWithEmptyTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zCallWithParametersData = z.object({ body: z.never().optional(), path: z.object({ parameterPath: z.string(), 'api-version': z.string() }), query: z.object({ parameterQuery: z.string() }), headers: z.object({ parameterHeader: z.string() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.string(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string() }), headers: z.object({ 'parameter.header': z.string() }) }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().default('Hello World!'), parameterNumber: z.number().default(123), parameterBoolean: z.boolean().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]), parameterModel: z.object({ prop: z.string().optional() }).default({ prop: 'Hello World!' }) }) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.unknown() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for default response */ export const zCallWithResponseResponse = zModelWithString; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for 201 response */ export const zCallWithDuplicateResponsesResponse = zModelWithString; export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()), parameterArraySSV: z.array(z.string()), parameterArrayTSV: z.array(z.string()), parameterArrayPipes: z.array(z.string()), parameterArrayMulti: z.array(z.string()) }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().default('default'), parameterBoolean: z.boolean().default(true), parameterArray: z.array(z.string()), parameterDictionary: z.record(z.unknown()), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.unknown()) ]); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: z.object({ prop: z.string().optional() }) }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.string() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.number().int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = zNonAsciiStringæøåÆøÅöôêÊ字符串; export const zPostApiVbyApiVersionBodyData = z.object({ body: zParameterActivityParams, path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostApiVbyApiVersionBodyResponse = zResponsePostActivityResponse; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v3/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.object({ bar: z.number().int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.number().int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.int().optional(), createdAt: z.iso.datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a type-only model that defines Date as a string */ export const zDate = z.string(); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp: z.string().nullish(), nullableRequiredProp: z.string().nullable() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ test: z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.string(), z.int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.int()).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string(), z.string()).optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.lazy((): any => zModelWithCircularReference).optional() }); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly() }).readonly() }).readonly() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); export const zDefault = z.object({ name: z.string().optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.iso.datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zParameterActivityParams = z.object({ description: z.string().optional(), graduate_id: z.int().optional(), organization_id: z.int().optional(), parent_activity: z.int().optional(), post_id: z.int().optional() }); export const zResponsePostActivityResponse = z.object({ description: z.string().optional(), graduate_id: z.int().optional(), organization_id: z.int().optional(), parent_activity_id: z.int().optional(), post_id: z.int().optional() }); export const zFailureFailure = z.object({ error: z.string().optional(), message: z.string().optional(), reference_code: z.string().optional() }); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zServiceWithEmptyTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zCallWithParametersData = z.object({ body: z.never().optional(), path: z.object({ parameterPath: z.string(), 'api-version': z.string() }), query: z.object({ parameterQuery: z.string() }), headers: z.object({ parameterHeader: z.string() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.string(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string() }), headers: z.object({ 'parameter.header': z.string() }) }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().default('Hello World!'), parameterNumber: z.number().default(123), parameterBoolean: z.boolean().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]), parameterModel: z.object({ prop: z.string().optional() }).default({ prop: 'Hello World!' }) }) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.unknown() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for default response */ export const zCallWithResponseResponse = zModelWithString; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Message for 201 response */ export const zCallWithDuplicateResponsesResponse = zModelWithString; export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()), parameterArraySSV: z.array(z.string()), parameterArrayTSV: z.array(z.string()), parameterArrayPipes: z.array(z.string()), parameterArrayMulti: z.array(z.string()) }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().default('default'), parameterBoolean: z.boolean().default(true), parameterArray: z.array(z.string()), parameterDictionary: z.record(z.string(), z.unknown()), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: z.object({ prop: z.string().optional() }) }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.string() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = zNonAsciiStringæøåÆøÅöôêÊ字符串; export const zPostApiVbyApiVersionBodyData = z.object({ body: zParameterActivityParams, path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostApiVbyApiVersionBodyResponse = zResponsePostActivityResponse; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: string; }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/2.0.x/v4/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.object({ bar: z.int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zArrayWithAllOfObjects = z.array(z.intersection(z.object({ id: z.optional(z.int()) }), z.object({ name: z.optional(z.string()) }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.optional(z.int()), createdAt: z.optional(z.iso.datetime()) }); export const zArrayWithAllOfRefs = z.array(z.intersection(zBaseModel, z.object({ extra: z.optional(z.string()) }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.optional(z.array(zBar).check(z.minLength(1), z.maxLength(2147483647))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/circular/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.object({ quux: z.optional(z.lazy((): any => zQuux)) }); export const zBar = z.object({ bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.lazy((): any => zBaz)) }); export const zBaz = z.object({ quux: z.optional(z.lazy((): any => zQuux)) }); export const zQux = z.union([ z.intersection(z.object({ type: z.literal('struct') }), z.lazy(() => z.lazy((): any => zCorge))), z.intersection(z.object({ type: z.literal('array') }), zFoo) ]); export const zQuux = z.object({ qux: z.optional(zQux) }); export const zCorge = z.object({ baz: z.optional(z.array(zBaz)) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.nullable(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/))); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z._default(z.array(z.string()), ['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': z.optional(zCamelCaseCommentWithBreaks), bar: z.optional(z.string()) })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z._default(z.optional(z.string()), 'test') }), z.object({ bar: z.optional(z.string()) })])); export const zAnyOfAnyAndNull = z.object({ data: z.optional(z.unknown()) }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.optional(z.array(z.union([z.object({ foo: z.optional(z.string()) }), z.object({ bar: z.optional(z.string()) })]))) }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.optional(z.number()), bar: z.optional(z.boolean()) }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.optional(z.int()) }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.optional(z.boolean()) }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.optional(z.string()) }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.optional(z.string()) }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.nullish(z.string()), nullableRequiredProp1: z.nullable(z.string()), nullableProp2: z.nullish(z.string()), nullableRequiredProp2: z.nullable(z.string()), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])), statusCode: z.optional(z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ])), bool: z.optional(z.literal(true)) }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.optional(z.enum(['3.0'])) }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.optional(z.int()) }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.optional(z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ]))), dictionaryWithEnumFromDescription: z.optional(z.record(z.string(), z.int())), arrayWithEnum: z.optional(z.array(z.enum([ 'Success', 'Warning', 'Error' ]))), arrayWithDescription: z.optional(z.array(z.int())), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.optional(z.array(zModelWithString)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.optional(z.record(z.string(), z.string())) }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.optional(z.string()) }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.optional(z.lazy((): any => zModelWithCircularReference)) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.optional(z.number()) }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.optional(z.number()) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.intersection(z.object({ kind: z.literal('circle') }), zModelCircle), z.intersection(z.object({ kind: z.literal('square') }), zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.optional(z.union([ z.array(z.nullable(zModelWithDictionary)), z.array(z.nullable(zModelWithArray)) ])) }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.enum(['ConstValue']); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.nullish(z.array(z.union([z3eNum1Период, zConstValue]))) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.number()) ])) }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ])) }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ])) }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.nullish(z.intersection(z.intersection(z.intersection(z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum), zModelWithArray), zModelWithDictionary)) }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.optional(z.string()), lastname: z.optional(z.string()) }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = z.intersection(zCompositionBaseModel, z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.readonly(z.string()), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()), '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())) }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: z.optional(zModelWithProperties) }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.nullable(z.readonly(z.object({ second: z.nullable(z.readonly(z.object({ third: z.nullable(z.readonly(z.string())) }))) }))) }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: z.optional(zModelWithString) }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.optional(z.string()), apple: z.optional(z.string()), hawaii: z.optional(z.string()) }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: z.optional(zModelWithString), propB: z.optional(zModelWithString), propC: z.optional(zModelWithString) }); /** * This is a model that extends another model */ export const zModelThatExtends = z.intersection(zModelWithString, z.object({ propExtendsA: z.optional(z.string()), propExtendsB: z.optional(zModelWithString) })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = z.intersection(z.intersection(zModelWithString, zModelThatExtends), z.object({ propExtendsC: z.optional(z.string()), propExtendsD: z.optional(zModelWithString) })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), enabled: z.optional(z.readonly(z.boolean())), modified: z.optional(z.readonly(z.iso.datetime())), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFile = z.object({ id: z.optional(z.readonly(z.string().check(z.minLength(1)))), updated_at: z.optional(z.readonly(z.iso.datetime())), created_at: z.optional(z.readonly(z.iso.datetime())), mime: z.string().check(z.minLength(1), z.maxLength(24)), file: z.optional(z.readonly(z.url())) }); export const zDefault = z.object({ name: z.optional(z.string()) }); export const zPageable = z.object({ page: z._default(z.optional(z.int().check(z.gte(0), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), 0), size: z.optional(z.int().check(z.gte(1), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), sort: z.optional(z.array(z.string())) }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.optional(z.enum(['String'])), number: z.optional(z.literal(0)), null: z.optional(z.unknown()), withType: z.optional(z.enum(['Some string'])) }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.optional(z.string()) }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.nullish(z.array(z.union([z.string(), z.boolean()]))) }); /** * An object that can be null */ export const zNullableObject = z._default(z.nullable(z.object({ foo: z.optional(z.string()) })), null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: z.optional(zNullableObject) }); /** * An object with additional properties that can be null */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), z.nullable(zNullableObject)); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.iso.datetime()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.optional(z.array(zModelWithNestedArrayEnumsDataFoo)), bar: z.optional(z.array(zModelWithNestedArrayEnumsDataBar)) }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.optional(z.array(z.string())), data: z.optional(zModelWithNestedArrayEnumsData) }); export const zModelWithNestedCompositionEnums = z.object({ foo: z.optional(zModelWithNestedArrayEnumsDataFoo) }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.readonly(z.string()) }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnly)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.array(z.union([ zModelWithInteger, z.number(), z.string() ])); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])) ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.optional(z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ])) }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.optional(z.string()) }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()), object: z.optional(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) })), array: z.optional(z.array(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) }))) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.optional(z.string()), uid: z.optional(z.string()) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: z.optional(zIoK8sApimachineryPkgApisMetaV1Preconditions) }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())) }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.optional(z.string()) }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()) }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: z.optional(zModelWithPropertiesWritable) }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFileWritable = z.object({ mime: z.string().check(z.minLength(1), z.maxLength(24)) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnlyWritable)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()) }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; export const zSimpleRequestBody = zModelWithString; export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zApiVVersionODataControllerCountData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.string() }), query: z.optional(z.never()) }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDeleteFooData3 = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.optional(z.never()), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterWithBreaks: z.optional(z.string()), parameterWithBackticks: z.optional(z.string()), parameterWithSlashes: z.optional(z.string()), parameterWithExpressionPlaceholders: z.optional(z.string()), parameterWithQuotes: z.optional(z.string()), parameterWithReservedCharacters: z.optional(z.string()) })) }); export const zDeprecatedCallData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()), headers: z.object({ parameter: z.nullable(zDeprecatedModel) }) }); export const zCallWithParametersData = z.object({ body: z.nullable(z.record(z.string(), z.unknown())), path: z.object({ parameterPath: z.nullable(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ foo_ref_enum: z.optional(zModelWithNestedArrayEnumsDataFoo), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.nullable(z.string()) }), headers: z.object({ parameterHeader: z.nullable(z.string()) }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.nullable(zModelWithString), path: z.object({ 'parameter.path.1': z.optional(z.string()), 'parameter-path-2': z.optional(z.string()), 'PARAMETER-PATH-3': z.optional(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ default: z.optional(z.string()), 'parameter-query': z.nullable(z.string()) }), headers: z.object({ 'parameter.header': z.nullable(z.string()) }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.optional(z.never()), query: z.optional(z.object({ page: z.optional(z.number()) })) }); export const zPostCallWithOptionalParamData = z.object({ body: z.optional(z.object({ offset: z.nullish(z.number()) })), path: z.optional(z.never()), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: z.optional(zSimpleRequestBody), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: z.optional(zSimpleFormData), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zCallWithDefaultParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.nullish(z.string()), 'Hello World!'), parameterNumber: z._default(z.nullish(z.number()), 123), parameterBoolean: z._default(z.nullish(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z.nullish(zModelWithString) })) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.optional(z.string()), 'Hello World!'), parameterNumber: z._default(z.optional(z.number()), 123), parameterBoolean: z._default(z.optional(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z.optional(zModelWithString) })) }); export const zCallToTestOrderOfParamsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterOptionalStringWithDefault: z._default(z.optional(z.string()), 'Hello World!'), parameterOptionalStringWithEmptyDefault: z._default(z.optional(z.string()), ''), parameterOptionalStringWithNoDefault: z.optional(z.string()), parameterStringWithDefault: z._default(z.string(), 'Hello World!'), parameterStringWithEmptyDefault: z._default(z.string(), ''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.nullish(z.string()), parameterStringNullableWithDefault: z._default(z.nullish(z.string()), null) }) }); export const zDuplicateNameData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName2Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName3Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName4Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithDuplicateResponsesResponse = z.union([ z.intersection(zModelWithBoolean, zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())), value: z.optional(z.readonly(z.array(zModelWithString))) }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterArrayCSV: z.nullable(z.array(z.string())), parameterArraySSV: z.nullable(z.array(z.string())), parameterArrayTSV: z.nullable(z.array(z.string())), parameterArrayPipes: z.nullable(z.array(z.string())), parameterArrayMulti: z.nullable(z.array(z.string())) }) }); export const zTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.object({ id: z.optional(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))) })), query: z.object({ parameterNumber: z._default(z.number(), 123), parameterString: z._default(z.nullable(z.string()), 'default'), parameterBoolean: z._default(z.nullable(z.boolean()), true), parameterObject: z._default(z.nullable(z.record(z.string(), z.unknown())), null), parameterArray: z.nullable(z.array(z.string())), parameterDictionary: z.nullable(z.record(z.string(), z.unknown())), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.nullable(z.string()) }), query: z.optional(z.never()) }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.optional(z.never()), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterObject: z.object({ first: z.optional(z.object({ second: z.optional(z.object({ third: z.optional(z.string()) })) })) }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.optional(z.string()), metadata: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })) }); export const zMultipartRequestData = z.object({ body: z.optional(z.object({ content: z.optional(z.string()), data: z.nullish(zModelWithString) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zComplexParamsData = z.object({ body: z.optional(z.object({ key: z.nullable(z.readonly(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)))), name: z.nullable(z.string().check(z.maxLength(255))), enabled: z._default(z.optional(z.boolean()), true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.nullish(z.array(zModelWithString)), listOfStrings: z.nullish(z.array(z.string())), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.optional(z.readonly(z.object({ id: z.optional(z.readonly(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })))), name: z.nullish(z.readonly(z.string())) }))) })), path: z.object({ id: z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zTestErrorCodeData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.nullable(z.enum(['foo', 'bar'])); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.object({ bar: z.optional(z.int()), foo: z._default(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/mini/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); export const zBar = z.object({ foo: z.optional(zFoo) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.number().int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.number().int().optional(), createdAt: z.string().datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/circular/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo: z.AnyZodObject = z.object({ quux: z.lazy(() => zQuux).optional() }); export const zBar: z.AnyZodObject = z.object({ bar: z.lazy(() => zBar).optional(), baz: z.lazy(() => zBaz).optional() }); export const zBaz: z.AnyZodObject = z.object({ quux: z.lazy(() => zQuux).optional() }); export const zQux: z.ZodTypeAny = z.union([ z.object({ type: z.literal('struct') }).and(z.lazy(() => zCorge)), z.object({ type: z.literal('array') }).and(zFoo) ]); export const zQuux = z.object({ qux: zQux.optional() }); export const zCorge = z.object({ baz: z.array(zBaz).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.number().int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.number().int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.number().int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.number().int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.number().int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.number().int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.number().int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.number().int(); /** * This is a simple number */ export const zSimpleInteger = z.number().int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.number().int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().optional() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.record(z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.number().int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.number().int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.number().int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.number().int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference: z.AnyZodObject = z.object({ prop: z.lazy(() => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(zModelWithDictionary.nullable()), z.array(zModelWithArray.nullable()) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.enum(['ConstValue']); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.string().datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.string().datetime().readonly().optional(), created_at: z.string().datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.string().url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.number().int().gte(0).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.number().int().gte(1).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.unknown()); export const zModelWithConst = z.object({ String: z.enum(['String']).optional(), number: z.literal(0).optional(), null: z.unknown().optional(), withType: z.enum(['Some string']).optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null */ export const zModelWithAdditionalPropertiesRef = z.record(zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.string().datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.string().datetime(), z.string().datetime()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.array(z.union([ zModelWithInteger, z.number(), z.string() ])); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.number().int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; export const zSimpleRequestBody = zModelWithString; export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string() }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.unknown()).nullable(), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.number().int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.number().int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.object({ bar: z.number().int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.number().int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v3/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); export const zBar = z.object({ foo: zFoo.optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.int().optional(), createdAt: z.iso.datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/circular/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.object({ quux: z.lazy((): any => zQuux).optional() }); export const zBar = z.object({ bar: z.lazy((): any => zBar).optional(), baz: z.lazy((): any => zBaz).optional() }); export const zBaz = z.object({ quux: z.lazy((): any => zQuux).optional() }); export const zQux = z.union([ z.object({ type: z.literal('struct') }).and(z.lazy(() => z.lazy((): any => zCorge))), z.object({ type: z.literal('array') }).and(zFoo) ]); export const zQuux = z.object({ qux: zQux.optional() }); export const zCorge = z.object({ baz: z.array(zBaz).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().optional() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.string(), z.int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string(), z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.lazy((): any => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(zModelWithDictionary.nullable()), z.array(zModelWithArray.nullable()) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.enum(['ConstValue']); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.iso.datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.iso.datetime().readonly().optional(), created_at: z.iso.datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.int().gte(0).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.int().gte(1).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.enum(['String']).optional(), number: z.literal(0).optional(), null: z.unknown().optional(), withType: z.enum(['Some string']).optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.iso.datetime()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.array(z.union([ zModelWithInteger, z.number(), z.string() ])); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); export const zExternalRefA = zExternalSharedModel; export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; export const zSimpleRequestBody = zModelWithString; export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string() }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.string(), z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional() }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.string(), z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.string(), z.unknown()).nullable(), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.object({ bar: z.int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.0.x/v4/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); export const zBar = z.object({ foo: zFoo.optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zArrayWithAllOfObjects = z.array(z.intersection(z.object({ id: z.optional(z.int()) }), z.object({ name: z.optional(z.string()) }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.optional(z.int()), createdAt: z.optional(z.iso.datetime()) }); export const zArrayWithAllOfRefs = z.array(z.intersection(zBaseModel, z.object({ extra: z.optional(z.string()) }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.optional(z.array(zBar).check(z.minLength(1), z.maxLength(2147483647))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.nullable(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/))); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z._default(z.array(z.string()), ['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': z.optional(zCamelCaseCommentWithBreaks), bar: z.optional(z.string()) })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z._default(z.optional(z.string()), 'test') }), z.object({ bar: z.optional(z.string()) })])); export const zAnyOfAnyAndNull = z.object({ data: z.nullish(z.unknown()) }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.optional(z.array(z.union([z.object({ foo: z.optional(z.string()) }), z.object({ bar: z.optional(z.string()) })]))) }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.optional(z.number()), bar: z.optional(z.boolean()) }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.optional(z.int()) }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.optional(z.boolean()) }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.optional(z.string()) }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.optional(z.string()) }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.nullish(z.string()), nullableRequiredProp1: z.nullable(z.string()), nullableProp2: z.nullish(z.string()), nullableRequiredProp2: z.nullable(z.string()), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])), statusCode: z.optional(z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ])), bool: z.optional(z.literal(true)) }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.optional(z.enum(['3.0'])) }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.optional(z.int()) }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.optional(z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ]))), dictionaryWithEnumFromDescription: z.optional(z.record(z.string(), z.int())), arrayWithEnum: z.optional(z.array(z.enum([ 'Success', 'Warning', 'Error' ]))), arrayWithDescription: z.optional(z.array(z.int())), 'foo_bar-enum': z.optional(z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ])) }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.optional(z.array(zModelWithString)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.optional(z.record(z.string(), z.string())) }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.optional(z.string()) }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.optional(z.lazy((): any => zModelWithCircularReference)) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.optional(z.number()) }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.optional(z.number()) }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.intersection(z.object({ kind: z.literal('circle') }), zModelCircle), z.intersection(z.object({ kind: z.literal('square') }), zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.optional(z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.optional(z.union([ z.object({ propA: z.optional(z.string()) }), z.string(), z.int() ])) }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.optional(z.union([ z.array(z.union([zModelWithDictionary, z.null()])), z.array(z.union([zModelWithArray, z.null()])) ])) }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.literal('ConstValue'); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.nullish(z.array(z.union([z3eNum1Период, zConstValue]))) }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.number()) ])) }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ])) }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.optional(z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ])) }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.nullish(z.intersection(z.intersection(z.intersection(z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum), zModelWithArray), zModelWithDictionary)) }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.nullish(z.union([ z.object({ boolean: z.optional(z.boolean()) }), zModelWithEnum, zModelWithArray, zModelWithDictionary ])) }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.optional(z.string()), lastname: z.optional(z.string()) }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = z.intersection(zCompositionBaseModel, z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.readonly(z.string()), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()), '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())) }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: z.optional(zModelWithProperties) }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.nullable(z.readonly(z.object({ second: z.nullable(z.readonly(z.object({ third: z.nullable(z.readonly(z.string())) }))) }))) }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: z.optional(zModelWithString) }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.optional(z.string()), apple: z.optional(z.string()), hawaii: z.optional(z.string()) }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: z.optional(zModelWithString), propB: z.optional(zModelWithString), propC: z.optional(zModelWithString) }); /** * This is a model that extends another model */ export const zModelThatExtends = z.intersection(zModelWithString, z.object({ propExtendsA: z.optional(z.string()), propExtendsB: z.optional(zModelWithString) })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = z.intersection(z.intersection(zModelWithString, zModelThatExtends), z.object({ propExtendsC: z.optional(z.string()), propExtendsD: z.optional(zModelWithString) })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), enabled: z.optional(z.readonly(z.boolean())), modified: z.optional(z.readonly(z.iso.datetime())), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFile = z.object({ id: z.optional(z.readonly(z.string().check(z.minLength(1)))), updated_at: z.optional(z.readonly(z.iso.datetime())), created_at: z.optional(z.readonly(z.iso.datetime())), mime: z.string().check(z.minLength(1), z.maxLength(24)), file: z.optional(z.readonly(z.url())) }); export const zDefault = z.object({ name: z.optional(z.string()) }); export const zPageable = z.object({ page: z._default(z.optional(z.int().check(z.gte(0), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), 0), size: z.optional(z.int().check(z.gte(1), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))), sort: z.optional(z.array(z.string())) }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.optional(z.literal('String')), number: z.optional(z.literal(0)), null: z.optional(z.null()), withType: z.optional(z.literal('Some string')) }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.optional(z.string()) }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.nullish(z.array(z.union([z.string(), z.boolean()]))) }); /** * An object that can be null */ export const zNullableObject = z._default(z.nullable(z.object({ foo: z.optional(z.string()) })), null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: z.optional(zNullableObject) }); /** * An object with additional properties that can be null (anyOf ref + null) */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), z.nullable(zNullableObject)); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.string()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.optional(z.array(zModelWithNestedArrayEnumsDataFoo)), bar: z.optional(z.array(zModelWithNestedArrayEnumsDataBar)) }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.optional(z.array(z.string())), data: z.optional(zModelWithNestedArrayEnumsData) }); export const zModelWithNestedCompositionEnums = z.object({ foo: z.optional(zModelWithNestedArrayEnumsDataFoo) }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.readonly(z.string()) }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnly)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.tuple([ zModelWithInteger, z.union([ z.number(), z.string() ]), z.string() ]); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])), z.nullable(z.union([ z.number(), z.string() ])) ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.optional(z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ])) }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.optional(z.string()) }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()), object: z.optional(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) })), array: z.optional(z.array(z.object({ description: z.optional(z.string()), 'x-enum-descriptions': z.optional(z.string()), 'x-enum-varnames': z.optional(z.string()), 'x-enumNames': z.optional(z.string()), title: z.optional(z.string()) }))) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.optional(z.string()), uid: z.optional(z.string()) }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: z.optional(zIoK8sApimachineryPkgApisMetaV1Preconditions) }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()), hasError: z.optional(z.readonly(z.boolean())) }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.optional(z.string()) }); /** * External ref to shared model (A) */ export const zExternalRefA = zExternalSharedModel; /** * External ref to shared model (B) */ export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.nullable(z.string()), string: z.optional(z.string()), number: z.optional(z.number()), boolean: z.optional(z.boolean()), reference: z.optional(zModelWithString), 'property with space': z.optional(z.string()), default: z.optional(z.string()), try: z.optional(z.string()) }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: z.optional(zModelWithPropertiesWritable) }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)), name: z.string().check(z.maxLength(255)), id: z.optional(z.string().check(z.regex(/^\d{2}-\d{3}-\d{4}$/))), text: z.optional(z.string().check(z.regex(/^\w+$/))), patternWithSingleQuotes: z.optional(z.string().check(z.regex(/^[a-zA-Z0-9']*$/))), patternWithNewline: z.optional(z.string().check(z.regex(/aaa\nbbb/))), patternWithBacktick: z.optional(z.string().check(z.regex(/aaa`bbb/))), patternWithUnicode: z.optional(z.string().check(z.regex(/^\p{L}+$/u))) }); export const zFileWritable = z.object({ mime: z.string().check(z.minLength(1), z.maxLength(24)) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.optional(z.array(zModelWithReadOnlyAndWriteOnlyWritable)), propWithFile: z.optional(z.array(z.string())), propWithNumber: z.optional(z.array(z.number())) }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.optional(z.boolean()), error: z.nullish(z.string()), data: z.optional(z.record(z.string(), z.never())) }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.nullish(z.string()), error: z.nullish(z.string()) }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.nullable(z.int().check(z.gte(0), z.maximum(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }))), qux: z.int().check(z.gte(0), z.maximum(255, { error: 'Invalid value: Expected uint8 to be <= 255' })) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; /** * A reusable request body */ export const zSimpleRequestBody = zModelWithString; /** * A reusable request body */ export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zApiVVersionODataControllerCountData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.union([ z.string(), z.uuid() ]) }), query: z.optional(z.never()) }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDeleteFooData3 = z.object({ body: z.optional(z.never()), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.optional(z.never()), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterWithBreaks: z.optional(z.string()), parameterWithBackticks: z.optional(z.string()), parameterWithSlashes: z.optional(z.string()), parameterWithExpressionPlaceholders: z.optional(z.string()), parameterWithQuotes: z.optional(z.string()), parameterWithReservedCharacters: z.optional(z.string()) })) }); export const zDeprecatedCallData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()), headers: z.object({ parameter: z.nullable(zDeprecatedModel) }) }); export const zCallWithParametersData = z.object({ body: z.nullable(z.record(z.string(), z.unknown())), path: z.object({ parameterPath: z.nullable(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ foo_ref_enum: z.optional(zModelWithNestedArrayEnumsDataFoo), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.nullable(z.string()) }), headers: z.object({ parameterHeader: z.nullable(z.string()) }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: z.nullable(zModelWithString), path: z.object({ 'parameter.path.1': z.optional(z.string()), 'parameter-path-2': z.optional(z.string()), 'PARAMETER-PATH-3': z.optional(z.string()), 'api-version': z.nullable(z.string()) }), query: z.object({ default: z.optional(z.string()), 'parameter-query': z.nullable(z.string()) }), headers: z.object({ 'parameter.header': z.nullable(z.string()) }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.optional(z.never()), query: z.optional(z.object({ page: z.optional(z.number()) })) }); export const zPostCallWithOptionalParamData = z.object({ body: z.optional(z.object({ offset: z.nullish(z.number()) })), path: z.optional(z.never()), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: z.optional(zSimpleRequestBody), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: z.optional(zSimpleFormData), path: z.optional(z.never()), query: z.optional(z.object({ parameter: z.optional(z.string()) })) }); export const zCallWithDefaultParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.nullish(z.string()), 'Hello World!'), parameterNumber: z._default(z.nullish(z.number()), 123), parameterBoolean: z._default(z.nullish(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z.nullish(zModelWithString) })) }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.object({ parameterString: z._default(z.optional(z.string()), 'Hello World!'), parameterNumber: z._default(z.optional(z.number()), 123), parameterBoolean: z._default(z.optional(z.boolean()), true), parameterEnum: z.optional(z.enum([ 'Success', 'Warning', 'Error' ])), parameterModel: z._default(z.optional(zModelWithString), { prop: 'Hello World!' }) })) }); export const zCallToTestOrderOfParamsData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterOptionalStringWithDefault: z._default(z.optional(z.string()), 'Hello World!'), parameterOptionalStringWithEmptyDefault: z._default(z.optional(z.string()), ''), parameterOptionalStringWithNoDefault: z.optional(z.string()), parameterStringWithDefault: z._default(z.string(), 'Hello World!'), parameterStringWithEmptyDefault: z._default(z.string(), ''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.nullish(z.string()), parameterStringNullableWithDefault: z._default(z.nullish(z.string()), null) }) }); export const zDuplicateNameData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName2Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName3Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDuplicateName4Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithDuplicateResponsesResponse = z.union([ z.intersection(zModelWithBoolean, zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.optional(z.readonly(z.string())), '@namespace.integer': z.optional(z.readonly(z.int())), value: z.optional(z.readonly(z.array(zModelWithString))) }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterArrayCSV: z.nullable(z.array(z.string())), parameterArraySSV: z.nullable(z.array(z.string())), parameterArrayTSV: z.nullable(z.array(z.string())), parameterArrayPipes: z.nullable(z.array(z.string())), parameterArrayMulti: z.nullable(z.array(z.string())) }) }); export const zTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.object({ id: z.optional(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }))) })), query: z.object({ parameterNumber: z._default(z.number(), 123), parameterString: z._default(z.nullable(z.string()), 'default'), parameterBoolean: z._default(z.nullable(z.boolean()), true), parameterObject: z._default(z.nullable(z.record(z.string(), z.unknown())), null), parameterArray: z.nullable(z.array(z.string())), parameterDictionary: z.nullable(z.record(z.string(), z.unknown())), parameterEnum: z.nullable(z.union([ z.literal('Success'), z.literal('Warning'), z.literal('Error') ])) }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.nullable(z.string()) }), query: z.optional(z.never()) }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.optional(z.never()), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ parameterObject: z.object({ first: z.optional(z.object({ second: z.optional(z.object({ third: z.optional(z.string()) })) })) }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.optional(z.string()), metadata: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(z.string()) })) }); export const zMultipartRequestData = z.object({ body: z.optional(z.object({ content: z.optional(z.string()), data: z.nullish(zModelWithString) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zComplexParamsData = z.object({ body: z.optional(z.object({ key: z.nullable(z.readonly(z.string().check(z.maxLength(64), z.regex(/^[a-zA-Z0-9_]*$/)))), name: z.nullable(z.string().check(z.maxLength(255))), enabled: z._default(z.optional(z.boolean()), true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.nullish(z.array(zModelWithString)), listOfStrings: z.nullish(z.array(z.string())), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.optional(z.readonly(z.object({ id: z.optional(z.readonly(z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })))), name: z.nullish(z.readonly(z.string())) }))) })), path: z.object({ id: z.int().check(z.minimum(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }), z.maximum(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })), 'api-version': z.string() }), query: z.optional(z.never()) }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zTestErrorCodeData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/defaults-with-ref-and-anyof/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zAudioFormat = z.enum(['pcm_16bit_44.1khz', 'pcm_16bit_24khz']); export const zLanguage = z.enum([ 'en', 'es', 'fr' ]); export const zNestedConfig = z.object({ model: z._default(z.string(), 'gpt-4'), temperature: z._default(z.number(), 1) }); export const zTestSchema = z.object({ primitiveDefault: z._default(z.number(), 42), refWithPrimitiveDefault: z._default(zAudioFormat, 'pcm_16bit_44.1khz'), refWithObjectDefault: z._default(zNestedConfig, { model: 'gpt-4', temperature: 1 }), anyOfWithNullDefault: z._default(z.nullable(z.number()), null), anyOfWithRefAndNullDefault: z._default(z.nullable(zLanguage), null), optionalAnyOfWithDefault: z._default(z.nullish(z.string()), null) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.nullable(z.enum(['foo', 'bar'])); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/enum-resolver-permissive/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.nullable(z.union([z.enum(['foo', 'bar']), z.string()])); export const zBar = z.union([z.enum(['foo', 'bar']), z.string()]); export const zBaz = z.union([z.enum(['foo', 'bar']), z.string()]); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/schema-const/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.object({ foo: z.optional(z.literal('foo')), bar: z.optional(z.literal(3.2)), baz: z.optional(z.literal(-1)), qux: z.optional(z.literal(true)), quux: z.optional(z.tuple([ z.literal(1), z.literal(2), z.literal(3), z.literal('foo'), z.literal(true) ])), corge: z.optional(z.record(z.string(), z.unknown())), garply: z.optional(z.literal(BigInt('10'))), numberInt8: z.optional(z.literal(100)), numberInt16: z.optional(z.literal(1000)), numberInt32: z.optional(z.literal(100000)), numberInt64: z.optional(z.literal(BigInt(1000000000000))), numberUint8: z.optional(z.literal(200)), numberUint16: z.optional(z.literal(50000)), numberUint32: z.optional(z.literal(3000000000)), numberUint64: z.optional(z.literal(BigInt(18000000000000000000))), integerInt8: z.optional(z.literal(-100)), integerInt16: z.optional(z.literal(-1000)), integerInt32: z.optional(z.literal(-100000)), integerInt64: z.optional(z.literal(BigInt(-1000000000000))), integerUint8: z.optional(z.literal(255)), integerUint16: z.optional(z.literal(65535)), integerUint32: z.optional(z.literal(4294967295)), integerUint64: z.optional(z.literal(BigInt('18446744073709551615'))), stringInt64: z.optional(z.literal(BigInt('-9223372036854775808'))), stringUint64: z.optional(z.literal(BigInt('18446744073709551615'))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/string-with-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.object({ foo: z.optional(z.array(z.union([z.string(), z.string()]))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/string-with-guid-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zGetFooData = z.object({ body: z.optional(z.never()), path: z.object({ guidId: z.guid() }), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.object({ bar: z.optional(z.int()), foo: z._default(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.optional(z.never()), path: z.optional(z.never()), query: z.optional(z.never()) }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: z.optional(zBar) }); export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime()) })) }); export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-bigint-min-max/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zFoo = z.object({ foo: z.optional(z.coerce.bigint().check(z.gte(BigInt(0)), z.lte(BigInt(100)))) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-circular-ref/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBar = z.object({ bar: z.optional(z.array(z.lazy((): any => zBar))) }); export const zFoo = z.object({ foo: z.optional(zBar) }); export const zBaz = z.lazy((): any => zQux); /** * description caused circular reference error */ export const zQux = zBaz; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-circular-ref-2/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBar = z.object({ bar: z.nullable(z.array(z.lazy((): any => zBar))) }); export const zFoo = z.object({ foo: zBar }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-dates/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: z.optional(zBar) }); export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime({ offset: true })) })) }); export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-metadata/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/)).register(z.globalRegistry, { description: 'This is foo property.' })), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo)).register(z.globalRegistry, { description: 'This is baz property.' })), qux: z._default(z.optional(z.int().check(z.gt(0)).register(z.globalRegistry, { description: 'This is qux property.' })), 0) })), null); /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }).register(z.globalRegistry, { description: 'This is Bar schema.' }); /** * This is Foo parameter. */ export const zFoo2 = z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' }); export const zFoo3 = z.object({ foo: z.optional(zBar) }); export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' })), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime()) })) }); export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-metadata-fn/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/)).register(z.globalRegistry, { custom: 'value', title: 'string' })), 'baz'); export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string().register(z.globalRegistry, { custom: 'value', title: 'string' })) }).register(z.globalRegistry, { custom: 'value', title: 'object' })).register(z.globalRegistry, { custom: 'value', title: 'object' }); /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/)).register(z.globalRegistry, { custom: 'value', title: 'This is foo property.' })), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo)).register(z.globalRegistry, { custom: 'value', title: 'This is baz property.' })), qux: z._default(z.optional(z.int().check(z.gt(0)).register(z.globalRegistry, { custom: 'value', title: 'This is qux property.' })), 0) }).register(z.globalRegistry, { custom: 'value', title: 'object' })), null); /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }).register(z.globalRegistry, { custom: 'value', title: 'This is Bar schema.' }); /** * This is Foo parameter. */ export const zFoo2 = z.string().register(z.globalRegistry, { custom: 'value', title: 'This is Foo parameter.' }); export const zFoo3 = z.object({ foo: z.optional(zBar) }).register(z.globalRegistry, { custom: 'value', title: 'object' }); export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string().register(z.globalRegistry, { custom: 'value', title: 'string' })) }).register(z.globalRegistry, { custom: 'value', title: 'object' }), path: z.optional(z.never().register(z.globalRegistry, { custom: 'value', title: 'never' })), query: z.optional(z.object({ foo: z.optional(z.string().register(z.globalRegistry, { custom: 'value', title: 'This is Foo parameter.' })), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string().register(z.globalRegistry, { custom: 'value', title: 'string' })) }).register(z.globalRegistry, { custom: 'value', title: 'object' })), qux: z.optional(z.iso.date().register(z.globalRegistry, { custom: 'value', title: 'string' })), quux: z.optional(z.iso.datetime().register(z.globalRegistry, { custom: 'value', title: 'string' })) }).register(z.globalRegistry, { custom: 'value', title: 'object' })) }).register(z.globalRegistry, { custom: 'value', title: 'object' }); export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never().register(z.globalRegistry, { custom: 'value', title: 'never' })), query: z.optional(z.never().register(z.globalRegistry, { custom: 'value', title: 'never' })) }).register(z.globalRegistry, { custom: 'value', title: 'object' }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-string-constraints-union/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zLocaleOrLanguage = z.union([ z.string().check(z.length(5)), z.string().check(z.length(2)) ]); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-types/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zBaz = z._default(z.readonly(z.string().check(z.regex(/foo\nbar/))), 'baz'); export type BazZodType = z.infer; export const zQux = z.record(z.string(), z.object({ qux: z.optional(z.string()) })); export type QuxZodType = z.infer; /** * This is Foo schema. */ export const zFoo = z._default(z.nullable(z.object({ foo: z.optional(z.string().check(z.regex(/^\d{3}-\d{2}-\d{4}$/))), bar: z.optional(z.lazy((): any => zBar)), baz: z.optional(z.array(z.lazy((): any => zFoo))), qux: z._default(z.optional(z.int().check(z.gt(0))), 0) })), null); export type FooZodType = z.infer; /** * This is Bar schema. */ export const zBar = z.object({ foo: z.optional(zFoo) }); export type BarZodType = z.infer; /** * This is Foo parameter. */ export const zFoo2 = z.string(); export type FooZodType2 = z.infer; export const zFoo3 = z.object({ foo: z.optional(zBar) }); export type FooZodType3 = z.infer; export const zPatchFooData = z.object({ body: z.object({ foo: z.optional(z.string()) }), path: z.optional(z.never()), query: z.optional(z.object({ foo: z.optional(z.string()), bar: z.optional(zBar), baz: z.optional(z.object({ baz: z.optional(z.string()) })), qux: z.optional(z.iso.date()), quux: z.optional(z.iso.datetime()) })) }); export type PatchFooDataZodType = z.infer; export const zPostFooData = z.object({ body: zFoo3, path: z.optional(z.never()), query: z.optional(z.never()) }); export type PostFooDataZodType = z.infer; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/validators-union-merge/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zContact = z.union([ z.object({ email: z.string() }), z.object({ phone: z.string() }) ]); export const zUser = z.intersection(zContact, z.object({ username: z.string() })); export const zDogDetails = z.object({ breed: z.string(), barkVolume: z.int().check(z.gte(1), z.lte(10)) }); export const zCatDetails = z.object({ furLength: z.enum([ 'short', 'medium', 'long' ]), purrs: z.boolean() }); export const zPetStore = z.object({ animals: z.array(z.object({ name: z.string(), type: z.optional(z.enum(['dog', 'cat'])), details: z.union([ zDogDetails, zCatDetails ]) })) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/mini/webhooks/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod/mini'; export const zSessionUserPhoneCalloutRingingWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), from_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserRoomSystemCalloutRingingWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingStartedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_started']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.optional(z.string()), recording_end: z.optional(z.string()) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingResumedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_resumed']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.optional(z.string()), recording_end: z.optional(z.string()) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionLiveStreamingStoppedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.live_streaming_stopped']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), start_time: z.iso.datetime(), live_streaming: z.object({ service: z.enum([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: z.object({ stream_url: z.string(), stream_key: z.string(), page_url: z.string(), resolution: z.optional(z.string()) }), date_time: z.iso.datetime() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionStreamIngestionStoppedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.stream_ingestion_stopped']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.optional(z.string()), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserRoomSystemCalloutRejectedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionAlertWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.alert']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), issues: z.array(z.enum([ 'Unstable audio quality', 'Unstable video quality', 'Unstable screen share quality', 'High CPU occupation', 'Call Reconnection' ])) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionSharingEndedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.sharing_ended']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), user: z.object({ id: z.string(), name: z.string(), user_key: z.optional(z.string()), sharing_details: z.object({ content: z.enum([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: z.iso.datetime() }) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingPausedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_paused']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.optional(z.string()), recording_end: z.optional(z.string()) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionEndedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.ended']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), start_time: z.iso.datetime(), end_time: z.iso.datetime() }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionStartedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.started']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), start_time: z.iso.datetime() }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionStreamIngestionUnbindWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.stream_ingestion_unbind']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.optional(z.string()), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionLiveStreamingStartedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.live_streaming_started']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), start_time: z.iso.datetime(), live_streaming: z.object({ service: z.enum([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: z.object({ stream_url: z.string(), stream_key: z.string(), page_url: z.string(), resolution: z.optional(z.string()) }), date_time: z.iso.datetime() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserRoomSystemCalloutMissedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserPhoneCalloutAcceptedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), from_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserLeftWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.user_left']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), user: z.object({ id: z.string(), name: z.string(), leave_time: z.iso.datetime(), leave_reason: z.optional(z.string()), user_key: z.optional(z.string()), phone_number: z.optional(z.string()), participant_uuid: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionSharingStartedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.sharing_started']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), user: z.object({ id: z.string(), name: z.string(), user_key: z.optional(z.string()), sharing_details: z.object({ content: z.enum([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: z.iso.datetime() }) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserPhoneCalloutCanceledWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), from_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingTranscriptCompletedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_transcript_completed']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), download_token: z.string(), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_files: z.array(z.object({ id: z.optional(z.string()), recording_start: z.optional(z.string()), recording_end: z.optional(z.string()), file_name: z.optional(z.string()), file_path: z.optional(z.string()), file_type: z.optional(z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE', 'TIMELINE' ])), file_size: z.optional(z.number()), file_extension: z.optional(z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ])), download_url: z.optional(z.string()), status: z.optional(z.enum(['completed'])), recording_type: z.optional(z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ])) })) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingDeletedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_deleted']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), operator: z.email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserRoomSystemCalloutFailedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), reason_type: z.union([ z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(7), z.literal(8), z.literal(9), z.literal(10), z.literal(11), z.literal(12), z.literal(13), z.literal(14) ]), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingCompletedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_completed']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), download_token: z.string(), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_files: z.array(z.object({ id: z.optional(z.string()), recording_start: z.optional(z.string()), recording_end: z.optional(z.string()), file_name: z.optional(z.string()), file_path: z.optional(z.string()), file_type: z.optional(z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ])), file_size: z.optional(z.number()), file_extension: z.optional(z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ])), download_url: z.optional(z.string()), status: z.optional(z.enum(['completed'])), recording_type: z.optional(z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ])) })), participant_audio_files: z.optional(z.array(z.object({ id: z.optional(z.string()), recording_start: z.optional(z.string()), recording_end: z.optional(z.string()), file_name: z.optional(z.string()), file_path: z.optional(z.string()), file_type: z.optional(z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ])), file_size: z.optional(z.number()), file_extension: z.optional(z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ])), download_url: z.optional(z.string()), status: z.optional(z.enum(['completed'])), recording_type: z.optional(z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ])), user_id: z.optional(z.string()), user_key: z.optional(z.string()) }))), participant_video_files: z.optional(z.array(z.object({ id: z.optional(z.string()), recording_start: z.optional(z.string()), recording_end: z.optional(z.string()), file_name: z.optional(z.string()), file_path: z.optional(z.string()), file_type: z.optional(z.enum(['MP4'])), file_size: z.optional(z.number()), file_extension: z.optional(z.enum(['MP4'])), download_url: z.optional(z.string()), status: z.optional(z.enum(['completed'])), recording_type: z.optional(z.enum(['individual_user', 'individual_shared_screen'])), user_id: z.optional(z.string()), user_key: z.optional(z.string()) }))) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingTranscriptFailedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_transcript_failed']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingTrashedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_trashed']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), operator: z.email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserJoinedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.user_joined']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), user: z.object({ id: z.string(), name: z.string(), join_time: z.iso.datetime(), user_key: z.optional(z.string()), phone_number: z.optional(z.string()), participant_uuid: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionStreamIngestionStartedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.stream_ingestion_started']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.optional(z.string()), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionStreamIngestionConnectedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.stream_ingestion_connected']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.optional(z.string()), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionStreamIngestionDisconnectedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.stream_ingestion_disconnected']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.optional(z.string()), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.optional(z.string()), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingRecoveredWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_recovered']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), operator: z.email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserPhoneCalloutMissedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), from_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserPhoneCalloutRejectedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), from_number: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionUserRoomSystemCalloutAcceptedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.string(), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ id: z.optional(z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }))), uuid: z.optional(z.string()), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); export const zSessionRecordingStoppedWebhookRequest = z.object({ body: z.optional(z.object({ event: z.enum(['session.recording_stopped']), event_ts: z.coerce.bigint().check(z.minimum(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }), z.maximum(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' })), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.optional(z.string()), recording_end: z.optional(z.string()) }) }) }) })), path: z.optional(z.never()), query: z.optional(z.never()) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.number().int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.number().int().optional(), createdAt: z.string().datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.number().int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.number().int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.number().int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.number().int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.number().int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.number().int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.number().int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.number().int(); /** * This is a simple number */ export const zSimpleInteger = z.number().int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.number().int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().nullish() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.record(z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.number().int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.number().int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.number().int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.number().int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference: z.AnyZodObject = z.object({ prop: z.lazy(() => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.number().int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(z.union([zModelWithDictionary, z.null()])), z.array(z.union([zModelWithArray, z.null()])) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.literal('ConstValue'); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.string().datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.string().datetime().readonly().optional(), created_at: z.string().datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.string().url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.number().int().gte(0).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.number().int().gte(1).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.unknown()); export const zModelWithConst = z.object({ String: z.literal('String').optional(), number: z.literal(0).optional(), null: z.null().optional(), withType: z.literal('Some string').optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null (anyOf ref + null) */ export const zModelWithAdditionalPropertiesRef = z.record(zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.string().datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.string().datetime(), z.string()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.tuple([ zModelWithInteger, z.union([ z.number(), z.string() ]), z.string() ]); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.number().int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); /** * External ref to shared model (A) */ export const zExternalRefA = zExternalSharedModel; /** * External ref to shared model (B) */ export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.number().int().gte(0).max(65535, { message: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.number().int().gte(0).max(255, { message: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; /** * A reusable request body */ export const zSimpleRequestBody = zModelWithString; /** * A reusable request body */ export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.union([ z.string(), z.string().uuid() ]) }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional().default({ prop: 'Hello World!' }) }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.number().int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.unknown()).nullable(), parameterEnum: z.union([ z.literal('Success'), z.literal('Warning'), z.literal('Error') ]).nullable() }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.number().int().min(-2147483648, { message: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { message: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.number().int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.number().int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/defaults-with-ref-and-anyof/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zAudioFormat = z.enum(['pcm_16bit_44.1khz', 'pcm_16bit_24khz']); export const zLanguage = z.enum([ 'en', 'es', 'fr' ]); export const zNestedConfig = z.object({ model: z.string().default('gpt-4'), temperature: z.number().default(1) }); export const zTestSchema = z.object({ primitiveDefault: z.number().default(42), refWithPrimitiveDefault: zAudioFormat.default('pcm_16bit_44.1khz'), refWithObjectDefault: zNestedConfig.default({ model: 'gpt-4', temperature: 1 }), anyOfWithNullDefault: z.number().nullable().default(null), anyOfWithRefAndNullDefault: zLanguage.nullable().default(null), optionalAnyOfWithDefault: z.string().nullish().default(null) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/enum-resolver-permissive/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.union([z.enum(['foo', 'bar']), z.string()]).nullable(); export const zBar = z.union([z.enum(['foo', 'bar']), z.string()]); export const zBaz = z.union([z.enum(['foo', 'bar']), z.string()]); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/schema-const/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.object({ foo: z.literal('foo').optional(), bar: z.literal(3.2).optional(), baz: z.literal(-1).optional(), qux: z.literal(true).optional(), quux: z.tuple([ z.literal(1), z.literal(2), z.literal(3), z.literal('foo'), z.literal(true) ]).optional(), corge: z.record(z.unknown()).optional(), garply: z.literal(BigInt('10')).optional(), numberInt8: z.literal(100).optional(), numberInt16: z.literal(1000).optional(), numberInt32: z.literal(100000).optional(), numberInt64: z.literal(BigInt(1000000000000)).optional(), numberUint8: z.literal(200).optional(), numberUint16: z.literal(50000).optional(), numberUint32: z.literal(3000000000).optional(), numberUint64: z.literal(BigInt(18000000000000000000)).optional(), integerInt8: z.literal(-100).optional(), integerInt16: z.literal(-1000).optional(), integerInt32: z.literal(-100000).optional(), integerInt64: z.literal(BigInt(-1000000000000)).optional(), integerUint8: z.literal(255).optional(), integerUint16: z.literal(65535).optional(), integerUint32: z.literal(4294967295).optional(), integerUint64: z.literal(BigInt('18446744073709551615')).optional(), stringInt64: z.literal(BigInt('-9223372036854775808')).optional(), stringUint64: z.literal(BigInt('18446744073709551615')).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/string-with-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.object({ foo: z.array(z.union([z.string(), z.string()])).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/string-with-guid-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zGetFooData = z.object({ body: z.never().optional(), path: z.object({ guidId: z.string() }), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.object({ bar: z.number().int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.number().int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-bigint-min-max/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zFoo = z.object({ foo: z.coerce.bigint().gte(BigInt(0)).lte(BigInt(100)).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-circular-ref/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBar: z.AnyZodObject = z.object({ bar: z.array(z.lazy(() => zBar)).optional() }); export const zFoo = z.object({ foo: zBar.optional() }); export const zBaz: z.ZodTypeAny = z.lazy(() => zQux); /** * description caused circular reference error */ export const zQux = zBaz; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-circular-ref-2/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBar: z.AnyZodObject = z.object({ bar: z.array(z.lazy(() => zBar)).nullable() }); export const zFoo = z.object({ foo: zBar }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-dates/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime({ offset: true }).optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-metadata/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).describe('This is foo property.').optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).describe('This is baz property.').optional(), qux: z.number().int().gt(0).describe('This is qux property.').optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }).describe('This is Bar schema.'); /** * This is Foo parameter. */ export const zFoo2 = z.string().describe('This is Foo parameter.'); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().describe('This is Foo parameter.').optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-metadata-fn/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).describe('This is foo property.').optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).describe('This is baz property.').optional(), qux: z.number().int().gt(0).describe('This is qux property.').optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }).describe('This is Bar schema.'); /** * This is Foo parameter. */ export const zFoo2 = z.string().describe('This is Foo parameter.'); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().describe('This is Foo parameter.').optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-string-constraints-union/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zLocaleOrLanguage = z.union([ z.string().length(5), z.string().length(2) ]); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-types/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export type BazZodType = z.infer; export const zQux = z.record(z.object({ qux: z.string().optional() })); export type QuxZodType = z.infer; /** * This is Foo schema. */ export const zFoo: z.ZodTypeAny = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy(() => zBar).optional(), baz: z.array(z.lazy(() => zFoo)).optional(), qux: z.number().int().gt(0).optional().default(0) }).nullable().default(null); export type FooZodType = z.infer; /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); export type BarZodType = z.infer; /** * This is Foo parameter. */ export const zFoo2 = z.string(); export type FooZodType2 = z.infer; export const zFoo3 = z.object({ foo: zBar.optional() }); export type FooZodType3 = z.infer; export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.string().date().optional(), quux: z.string().datetime().optional() }).optional() }); export type PatchFooDataZodType = z.infer; export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); export type PostFooDataZodType = z.infer; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/validators-union-merge/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zContact = z.union([ z.object({ email: z.string() }), z.object({ phone: z.string() }) ]); export const zUser = zContact.and(z.object({ username: z.string() })); export const zDogDetails = z.object({ breed: z.string(), barkVolume: z.number().int().gte(1).lte(10) }); export const zCatDetails = z.object({ furLength: z.enum([ 'short', 'medium', 'long' ]), purrs: z.boolean() }); export const zPetStore = z.object({ animals: z.array(z.object({ name: z.string(), type: z.enum(['dog', 'cat']).optional(), details: z.union([ zDogDetails, zCatDetails ]) })) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v3/webhooks/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { z } from 'zod/v3'; export const zSessionUserPhoneCalloutRingingWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutRingingWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingResumedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_resumed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionLiveStreamingStoppedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.live_streaming_stopped']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.string().datetime(), live_streaming: z.object({ service: z.enum([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: z.object({ stream_url: z.string(), stream_key: z.string(), page_url: z.string(), resolution: z.string().optional() }), date_time: z.string().datetime() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionStoppedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_stopped']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutRejectedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionAlertWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.alert']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), issues: z.array(z.enum([ 'Unstable audio quality', 'Unstable video quality', 'Unstable screen share quality', 'High CPU occupation', 'Call Reconnection' ])) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionSharingEndedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.sharing_ended']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), user_key: z.string().optional(), sharing_details: z.object({ content: z.enum([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: z.string().datetime() }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingPausedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_paused']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionEndedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.ended']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.string().datetime(), end_time: z.string().datetime() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.string().datetime() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionUnbindWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_unbind']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionLiveStreamingStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.live_streaming_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.string().datetime(), live_streaming: z.object({ service: z.enum([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: z.object({ stream_url: z.string(), stream_key: z.string(), page_url: z.string(), resolution: z.string().optional() }), date_time: z.string().datetime() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutMissedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutAcceptedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserLeftWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.user_left']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), leave_time: z.string().datetime(), leave_reason: z.string().optional(), user_key: z.string().optional(), phone_number: z.string().optional(), participant_uuid: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionSharingStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.sharing_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), user_key: z.string().optional(), sharing_details: z.object({ content: z.enum([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: z.string().datetime() }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutCanceledWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingTranscriptCompletedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_transcript_completed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), download_token: z.string(), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string(), recording_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE', 'TIMELINE' ]).optional(), file_size: z.number().optional(), file_extension: z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ]).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ]).optional() })) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingDeletedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_deleted']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), operator: z.string().email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutFailedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), reason_type: z.union([ z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(7), z.literal(8), z.literal(9), z.literal(10), z.literal(11), z.literal(12), z.literal(13), z.literal(14) ]), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingCompletedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_completed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), download_token: z.string(), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string(), recording_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ]).optional(), file_size: z.number().optional(), file_extension: z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ]).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ]).optional() })), participant_audio_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ]).optional(), file_size: z.number().optional(), file_extension: z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ]).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ]).optional(), user_id: z.string().optional(), user_key: z.string().optional() })).optional(), participant_video_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum(['MP4']).optional(), file_size: z.number().optional(), file_extension: z.enum(['MP4']).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum(['individual_user', 'individual_shared_screen']).optional(), user_id: z.string().optional(), user_key: z.string().optional() })).optional() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingTranscriptFailedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_transcript_failed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingTrashedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_trashed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), operator: z.string().email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserJoinedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.user_joined']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), join_time: z.string().datetime(), user_key: z.string().optional(), phone_number: z.string().optional(), participant_uuid: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionConnectedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_connected']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionDisconnectedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_disconnected']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingRecoveredWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_recovered']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), operator: z.string().email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutMissedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutRejectedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutAcceptedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingStoppedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_stopped']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { message: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.string().datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/array-items-all-of/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zArrayWithAllOfObjects = z.array(z.object({ id: z.int().optional() }).and(z.object({ name: z.string().optional() }))); export const zArrayWithAllOfPrimitives = z.array(z.intersection(z.number(), z.string())); export const zBaseModel = z.object({ id: z.int().optional(), createdAt: z.iso.datetime().optional() }); export const zArrayWithAllOfRefs = z.array(zBaseModel.and(z.object({ extra: z.string().optional() }))); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/array-items-one-of-length-1/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBar = z.string(); export const zFoo = z.object({ foo: z.array(zBar).min(1).max(2147483647).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/default/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; /** * Model with number-only name */ export const z400 = z.string(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCamelCaseCommentWithBreaks = z.int(); /** * Testing multiline comments in string: First line * Second line * * Fourth line */ export const zCommentWithBreaks = z.int(); /** * Testing backticks in string: `backticks` and ```multiple backticks``` should work */ export const zCommentWithBackticks = z.int(); /** * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work */ export const zCommentWithBackticksAndQuotes = z.int(); /** * Testing slashes in string: \backwards\\\ and /forwards/// should work */ export const zCommentWithSlashes = z.int(); /** * Testing expression placeholders in string: ${expression} should work */ export const zCommentWithExpressionPlaceholders = z.int(); /** * Testing quotes in string: 'single quote''' and "double quotes""" should work */ export const zCommentWithQuotes = z.int(); /** * Testing reserved characters in string: * inline * and ** inline ** should work */ export const zCommentWithReservedCharacters = z.int(); /** * This is a simple number */ export const zSimpleInteger = z.int(); /** * This is a simple boolean */ export const zSimpleBoolean = z.boolean(); /** * This is a simple string */ export const zSimpleString = z.string(); /** * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) */ export const zNonAsciiStringæøåÆøÅöôêÊ字符串 = z.string(); /** * This is a simple file */ export const zSimpleFile = z.string(); /** * This is a simple string */ export const zSimpleStringWithPattern = z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).nullable(); /** * This is a simple enum with strings */ export const zEnumWithStrings = z.enum([ 'Success', 'Warning', 'Error', '\'Single Quote\'', '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串' ]); export const zEnumWithReplacedCharacters = z.union([ z.literal('\'Single Quote\''), z.literal('"Double Quotes"'), z.literal('øæåôöØÆÅÔÖ字符串'), z.literal(3.1), z.literal('') ]); /** * This is a simple enum with numbers */ export const zEnumWithNumbers = z.union([ z.literal(1), z.literal(2), z.literal(3), z.literal(1.1), z.literal(1.2), z.literal(1.3), z.literal(100), z.literal(200), z.literal(300), z.literal(-100), z.literal(-200), z.literal(-300), z.literal(-1.1), z.literal(-1.2), z.literal(-1.3) ]); /** * Success=1,Warning=2,Error=3 */ export const zEnumFromDescription = z.number(); /** * This is a simple enum with numbers */ export const zEnumWithExtensions = z.union([ z.literal(200), z.literal(400), z.literal(500) ]); export const zEnumWithXEnumNames = z.union([ z.literal(0), z.literal(1), z.literal(2) ]); /** * This is a simple array with numbers */ export const zArrayWithNumbers = z.array(z.int()); /** * This is a simple array with booleans */ export const zArrayWithBooleans = z.array(z.boolean()); /** * This is a simple array with strings */ export const zArrayWithStrings = z.array(z.string()).default(['test']); /** * This is a simple array with properties */ export const zArrayWithProperties = z.array(z.object({ '16x16': zCamelCaseCommentWithBreaks.optional(), bar: z.string().optional() })); /** * This is a simple array with any of properties */ export const zArrayWithAnyOfProperties = z.array(z.union([z.object({ foo: z.string().optional().default('test') }), z.object({ bar: z.string().optional() })])); export const zAnyOfAnyAndNull = z.object({ data: z.unknown().nullish() }); /** * This is a simple array with any of properties */ export const zAnyOfArrays = z.object({ results: z.array(z.union([z.object({ foo: z.string().optional() }), z.object({ bar: z.string().optional() })])).optional() }); /** * This is a string dictionary */ export const zDictionaryWithString = z.record(z.string(), z.string()); export const zDictionaryWithPropertiesAndAdditionalProperties = z.object({ foo: z.number().optional(), bar: z.boolean().optional() }); /** * This is a string dictionary */ export const zDictionaryWithDictionary = z.record(z.string(), z.record(z.string(), z.string())); /** * This is a complex dictionary */ export const zDictionaryWithProperties = z.record(z.string(), z.object({ foo: z.string().optional(), bar: z.string().optional() })); /** * This is a model with one number property */ export const zModelWithInteger = z.object({ prop: z.int().optional() }); /** * This is a model with one boolean property */ export const zModelWithBoolean = z.object({ prop: z.boolean().optional() }); /** * This is a model with one string property */ export const zModelWithString = z.object({ prop: z.string().optional() }); /** * This is a simple reference */ export const zSimpleReference = zModelWithString; /** * This is a simple array with references */ export const zArrayWithReferences = z.array(zModelWithString); /** * This is a simple array containing an array */ export const zArrayWithArray = z.array(z.array(zModelWithString)); /** * This is a string reference */ export const zDictionaryWithReference = z.record(z.string(), zModelWithString); /** * This is a complex dictionary */ export const zDictionaryWithArray = z.record(z.string(), z.array(zModelWithString)); /** * This is a model with one string property */ export const zModelWithStringError = z.object({ prop: z.string().optional() }); /** * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) */ export const zModelFromZendesk = z.string(); /** * This is a model with one string property */ export const zModelWithNullableString = z.object({ nullableProp1: z.string().nullish(), nullableRequiredProp1: z.string().nullable(), nullableProp2: z.string().nullish(), nullableRequiredProp2: z.string().nullable(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one enum */ export const zModelWithEnum = z.object({ 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional(), statusCode: z.enum([ '100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar' ]).optional(), bool: z.literal(true).optional() }); /** * This is a model with one enum with escaped name */ export const zModelWithEnumWithHyphen = z.object({ 'foo-bar-baz-qux': z.enum(['3.0']).optional() }); /** * This is a model with one enum */ export const zModelWithEnumFromDescription = z.object({ test: z.int().optional() }); /** * This is a model with nested enums */ export const zModelWithNestedEnums = z.object({ dictionaryWithEnum: z.record(z.string(), z.enum([ 'Success', 'Warning', 'Error' ])).optional(), dictionaryWithEnumFromDescription: z.record(z.string(), z.int()).optional(), arrayWithEnum: z.array(z.enum([ 'Success', 'Warning', 'Error' ])).optional(), arrayWithDescription: z.array(z.int()).optional(), 'foo_bar-enum': z.enum([ 'Success', 'Warning', 'Error', 'ØÆÅ字符串' ]).optional() }); /** * This is a model with one property containing an array */ export const zModelWithArray = z.object({ prop: z.array(zModelWithString).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); /** * This is a model with one property containing a dictionary */ export const zModelWithDictionary = z.object({ prop: z.record(z.string(), z.string()).optional() }); /** * This is a deprecated model with a deprecated property * * @deprecated */ export const zDeprecatedModel = z.object({ prop: z.string().optional() }); /** * This is a model with one property containing a circular reference */ export const zModelWithCircularReference = z.object({ prop: z.lazy((): any => zModelWithCircularReference).optional() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * Circle */ export const zModelCircle = z.object({ kind: z.string(), radius: z.number().optional() }); /** * Square */ export const zModelSquare = z.object({ kind: z.string(), sideLength: z.number().optional() }); /** * This is a model with one property with a 'one of' relationship where the options are not $ref */ export const zCompositionWithOneOfDiscriminator = z.union([ z.object({ kind: z.literal('circle') }).and(zModelCircle), z.object({ kind: z.literal('square') }).and(zModelSquare) ]); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOf = z.object({ propA: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]).optional() }); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithAnyOfAnonymous = z.object({ propA: z.union([ z.object({ propA: z.string().optional() }), z.string(), z.int() ]).optional() }); /** * This is a model with nested 'any of' property with a type null */ export const zCompositionWithNestedAnyAndTypeNull = z.object({ propA: z.union([ z.array(z.union([zModelWithDictionary, z.null()])), z.array(z.union([zModelWithArray, z.null()])) ]).optional() }); export const z3eNum1Период = z.enum(['Bird', 'Dog']); export const zConstValue = z.literal('ConstValue'); /** * This is a model with one property with a 'any of' relationship where the options are not $ref */ export const zCompositionWithNestedAnyOfAndNull = z.object({ propA: z.array(z.union([z3eNum1Период, zConstValue])).nullish() }); /** * This is a model with one property with a 'one of' relationship */ export const zCompositionWithOneOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a model that contains a simple dictionary within composition */ export const zCompositionWithOneOfAndSimpleDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.number()) ]).optional() }); /** * This is a model that contains a dictionary of simple arrays within composition */ export const zCompositionWithOneOfAndSimpleArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.boolean())) ]).optional() }); /** * This is a model that contains a dictionary of complex arrays (composited) within composition */ export const zCompositionWithOneOfAndComplexArrayDictionary = z.object({ propA: z.union([ z.boolean(), z.record(z.string(), z.array(z.union([z.number(), z.string()]))) ]).optional() }); /** * This is a model with one property with a 'all of' relationship */ export const zCompositionWithAllOfAndNullable = z.object({ propA: z.object({ boolean: z.boolean().optional() }).and(zModelWithEnum).and(zModelWithArray).and(zModelWithDictionary).nullish() }); /** * This is a model with one property with a 'any of' relationship */ export const zCompositionWithAnyOfAndNullable = z.object({ propA: z.union([ z.object({ boolean: z.boolean().optional() }), zModelWithEnum, zModelWithArray, zModelWithDictionary ]).nullish() }); /** * This is a base model with two simple optional properties */ export const zCompositionBaseModel = z.object({ firstName: z.string().optional(), lastname: z.string().optional() }); /** * This is a model that extends the base model */ export const zCompositionExtendedModel = zCompositionBaseModel.and(z.object({ age: z.number(), firstName: z.string(), lastname: z.string() })); /** * This is a model with one nested property */ export const zModelWithProperties = z.object({ required: z.string(), requiredAndReadOnly: z.string().readonly(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional(), '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReference = z.object({ prop: zModelWithProperties.optional() }); /** * This is a model with one nested property */ export const zModelWithNestedProperties = z.object({ first: z.object({ second: z.object({ third: z.string().readonly().nullable() }).readonly().nullable() }).readonly().nullable() }); /** * This is a model with duplicated properties */ export const zModelWithDuplicateProperties = z.object({ prop: zModelWithString.optional() }); /** * This is a model with ordered properties */ export const zModelWithOrderedProperties = z.object({ zebra: z.string().optional(), apple: z.string().optional(), hawaii: z.string().optional() }); /** * This is a model with duplicated imports */ export const zModelWithDuplicateImports = z.object({ propA: zModelWithString.optional(), propB: zModelWithString.optional(), propC: zModelWithString.optional() }); /** * This is a model that extends another model */ export const zModelThatExtends = zModelWithString.and(z.object({ propExtendsA: z.string().optional(), propExtendsB: zModelWithString.optional() })); /** * This is a model that extends another model */ export const zModelThatExtendsExtends = zModelWithString.and(zModelThatExtends).and(z.object({ propExtendsC: z.string().optional(), propExtendsD: zModelWithString.optional() })); /** * This is a model that contains a some patterns */ export const zModelWithPattern = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), enabled: z.boolean().readonly().optional(), modified: z.iso.datetime().readonly().optional(), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFile = z.object({ id: z.string().min(1).readonly().optional(), updated_at: z.iso.datetime().readonly().optional(), created_at: z.iso.datetime().readonly().optional(), mime: z.string().min(1).max(24), file: z.url().readonly().optional() }); export const zDefault = z.object({ name: z.string().optional() }); export const zPageable = z.object({ page: z.int().gte(0).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional().default(0), size: z.int().gte(1).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(), sort: z.array(z.string()).optional() }); /** * This is a free-form object without additionalProperties. */ export const zFreeFormObjectWithoutAdditionalProperties = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: true. */ export const zFreeFormObjectWithAdditionalPropertiesEqTrue = z.record(z.string(), z.unknown()); /** * This is a free-form object with additionalProperties: {}. */ export const zFreeFormObjectWithAdditionalPropertiesEqEmptyObject = z.record(z.string(), z.unknown()); export const zModelWithConst = z.object({ String: z.literal('String').optional(), number: z.literal(0).optional(), null: z.null().optional(), withType: z.literal('Some string').optional() }); /** * This is a model with one property and additionalProperties: true */ export const zModelWithAdditionalPropertiesEqTrue = z.object({ prop: z.string().optional() }); export const zNestedAnyOfArraysNullable = z.object({ nullableArray: z.array(z.union([z.string(), z.boolean()])).nullish() }); /** * An object that can be null */ export const zNullableObject = z.object({ foo: z.string().optional() }).nullable().default(null); /** * Some % character */ export const zCharactersInDescription = z.string(); export const zModelWithNullableObject = z.object({ data: zNullableObject.optional() }); /** * An object with additional properties that can be null (anyOf ref + null) */ export const zModelWithAdditionalPropertiesRef = z.record(z.string(), zNullableObject.nullable()); export const zModelWithOneOfEnum = z.union([ z.object({ foo: z.enum(['Bar']) }), z.object({ foo: z.enum(['Baz']) }), z.object({ foo: z.enum(['Qux']) }), z.object({ content: z.iso.datetime(), foo: z.enum(['Quux']) }), z.object({ content: z.tuple([z.iso.datetime(), z.string()]), foo: z.enum(['Corge']) }) ]); export const zModelWithNestedArrayEnumsDataFoo = z.enum(['foo', 'bar']); export const zModelWithNestedArrayEnumsDataBar = z.enum(['baz', 'qux']); export const zModelWithNestedArrayEnumsData = z.object({ foo: z.array(zModelWithNestedArrayEnumsDataFoo).optional(), bar: z.array(zModelWithNestedArrayEnumsDataBar).optional() }); export const zModelWithNestedArrayEnums = z.object({ array_strings: z.array(z.string()).optional(), data: zModelWithNestedArrayEnumsData.optional() }); export const zModelWithNestedCompositionEnums = z.object({ foo: zModelWithNestedArrayEnumsDataFoo.optional() }); export const zModelWithReadOnlyAndWriteOnly = z.object({ foo: z.string(), bar: z.string().readonly() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnly = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnly).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithConstantSizeArray = z.tuple([z.number(), z.number()]); export const zModelWithAnyOfConstantSizeArray = z.tuple([ z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]), z.union([ z.number(), z.string() ]) ]); export const zModelWithPrefixItemsConstantSizeArray = z.tuple([ zModelWithInteger, z.union([ z.number(), z.string() ]), z.string() ]); export const zModelWithAnyOfConstantSizeArrayNullable = z.tuple([ z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable(), z.union([ z.number(), z.string() ]).nullable() ]); export const zModelWithAnyOfConstantSizeArrayAndIntersect = z.tuple([z.intersection(z.number(), z.string()), z.intersection(z.number(), z.string())]); export const zModelWithNumericEnumUnion = z.object({ value: z.union([ z.literal(-10), z.literal(-1), z.literal(0), z.literal(1), z.literal(3), z.literal(6), z.literal(12) ]).optional() }); /** * Some description with `back ticks` */ export const zModelWithBackticksInDescription = z.object({ template: z.string().optional() }); /** * Model used to test deduplication strategy (unused) */ export const zParameterSimpleParameterUnused = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse = z.string(); /** * Model used to test deduplication strategy */ export const zPostServiceWithEmptyTagResponse2 = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData = z.string(); /** * Model used to test deduplication strategy */ export const zDeleteFooData2 = z.string(); /** * Model with restricted keyword name */ export const zImport = z.string(); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zSchemaWithFormRestrictedKeys = z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional(), object: z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() }).optional(), array: z.array(z.object({ description: z.string().optional(), 'x-enum-descriptions': z.string().optional(), 'x-enum-varnames': z.string().optional(), 'x-enumNames': z.string().optional(), title: z.string().optional() })).optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1Preconditions = z.object({ resourceVersion: z.string().optional(), uid: z.string().optional() }); /** * This schema was giving PascalCase transformations a hard time */ export const zIoK8sApimachineryPkgApisMetaV1DeleteOptions = z.object({ preconditions: zIoK8sApimachineryPkgApisMetaV1Preconditions.optional() }); export const zAdditionalPropertiesUnknownIssue = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue2 = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zAdditionalPropertiesUnknownIssue3 = z.intersection(z.string(), z.object({ entries: z.record(z.string(), zAdditionalPropertiesUnknownIssue) })); export const zAdditionalPropertiesIntegerIssue = z.object({ value: z.int() }); export const zGenericSchemaDuplicateIssue1SystemBoolean = z.object({ item: z.boolean().optional(), error: z.string().nullish(), hasError: z.boolean().readonly().optional(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemString = z.object({ item: z.string().nullish(), error: z.string().nullish(), hasError: z.boolean().readonly().optional() }); export const zOneOfAllOfIssue = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zExternalSharedModel = z.object({ id: z.string(), name: z.string().optional() }); /** * External ref to shared model (A) */ export const zExternalRefA = zExternalSharedModel; /** * External ref to shared model (B) */ export const zExternalRefB = zExternalSharedModel; /** * This is a model with one nested property */ export const zModelWithPropertiesWritable = z.object({ required: z.string(), requiredAndNullable: z.string().nullable(), string: z.string().optional(), number: z.number().optional(), boolean: z.boolean().optional(), reference: zModelWithString.optional(), 'property with space': z.string().optional(), default: z.string().optional(), try: z.string().optional() }); /** * This is a model with one property containing a reference */ export const zModelWithReferenceWritable = z.object({ prop: zModelWithPropertiesWritable.optional() }); /** * This is a model that contains a some patterns */ export const zModelWithPatternWritable = z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/), name: z.string().max(255), id: z.string().regex(/^\d{2}-\d{3}-\d{4}$/).optional(), text: z.string().regex(/^\w+$/).optional(), patternWithSingleQuotes: z.string().regex(/^[a-zA-Z0-9']*$/).optional(), patternWithNewline: z.string().regex(/aaa\nbbb/).optional(), patternWithBacktick: z.string().regex(/aaa`bbb/).optional(), patternWithUnicode: z.string().regex(/^\p{L}+$/u).optional() }); export const zFileWritable = z.object({ mime: z.string().min(1).max(24) }); export const zModelWithReadOnlyAndWriteOnlyWritable = z.object({ foo: z.string(), baz: z.string() }); /** * This is a model with one property containing an array */ export const zModelWithArrayReadOnlyAndWriteOnlyWritable = z.object({ prop: z.array(zModelWithReadOnlyAndWriteOnlyWritable).optional(), propWithFile: z.array(z.string()).optional(), propWithNumber: z.array(z.number()).optional() }); export const zModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = z.tuple([z.union([ z.number(), zImport ]), z.union([ z.number(), zImport ])]); export const zAdditionalPropertiesUnknownIssueWritable = z.record(z.string(), z.union([ z.string(), z.number() ])); export const zOneOfAllOfIssueWritable = z.union([ z.intersection(z.union([ zConstValue, zGenericSchemaDuplicateIssue1SystemBoolean ]), z3eNum1Период), zGenericSchemaDuplicateIssue1SystemString ]); export const zGenericSchemaDuplicateIssue1SystemBooleanWritable = z.object({ item: z.boolean().optional(), error: z.string().nullish(), data: z.record(z.string(), z.never()).optional() }); export const zGenericSchemaDuplicateIssue1SystemStringWritable = z.object({ item: z.string().nullish(), error: z.string().nullish() }); /** * This is a reusable parameter */ export const zSimpleParameter = z.string(); export const zCompositionWithOneOfAndProperties = z.intersection(z.union([ z.object({ foo: zSimpleParameter }), z.object({ bar: zNonAsciiStringæøåÆøÅöôêÊ字符串 }) ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); export const zModelWithOneOfAndProperties = z.intersection(z.union([ zSimpleParameter, zNonAsciiStringæøåÆøÅöôêÊ字符串 ]), z.object({ baz: z.int().gte(0).max(65535, { error: 'Invalid value: Expected uint16 to be <= 65535' }).nullable(), qux: z.int().gte(0).max(255, { error: 'Invalid value: Expected uint8 to be <= 255' }) })); /** * Parameter with illegal characters */ export const zXFooBar = zModelWithString; /** * A reusable request body */ export const zSimpleRequestBody = zModelWithString; /** * A reusable request body */ export const zSimpleFormData = zModelWithString; export const zExportData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchApiVbyApiVersionNoTagData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zImportData = z.object({ body: z.union([ zModelWithReadOnlyAndWriteOnlyWritable, zModelWithArrayReadOnlyAndWriteOnlyWritable ]), path: z.never().optional(), query: z.never().optional() }); export const zImportResponse = z.union([ zModelFromZendesk, zModelWithReadOnlyAndWriteOnly ]); export const zFooWowData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zApiVVersionODataControllerCountData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zApiVVersionODataControllerCountResponse = zModelFromZendesk; export const zGetApiVbyApiVersionSimpleOperationData = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.union([ z.string(), z.uuid() ]) }), query: z.never().optional() }); /** * Response is a simple number */ export const zGetApiVbyApiVersionSimpleOperationResponse = z.number(); export const zDeleteCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zGetCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zHeadCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zOptionsCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPatchCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPostCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zPutCallWithoutParametersAndResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDeleteFooData3 = z.object({ body: z.never().optional(), path: z.object({ foo_param: z.string(), BarParam: z.string() }), query: z.never().optional(), headers: z.object({ 'x-Foo-Bar': zModelWithString }) }); export const zCallWithDescriptionsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterWithBreaks: z.string().optional(), parameterWithBackticks: z.string().optional(), parameterWithSlashes: z.string().optional(), parameterWithExpressionPlaceholders: z.string().optional(), parameterWithQuotes: z.string().optional(), parameterWithReservedCharacters: z.string().optional() }).optional() }); export const zDeprecatedCallData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional(), headers: z.object({ parameter: zDeprecatedModel.nullable() }) }); export const zCallWithParametersData = z.object({ body: z.record(z.string(), z.unknown()).nullable(), path: z.object({ parameterPath: z.string().nullable(), 'api-version': z.string().nullable() }), query: z.object({ foo_ref_enum: zModelWithNestedArrayEnumsDataFoo.optional(), foo_all_of_enum: zModelWithNestedArrayEnumsDataFoo, cursor: z.string().nullable() }), headers: z.object({ parameterHeader: z.string().nullable() }) }); export const zCallWithWeirdParameterNamesData = z.object({ body: zModelWithString.nullable(), path: z.object({ 'parameter.path.1': z.string().optional(), 'parameter-path-2': z.string().optional(), 'PARAMETER-PATH-3': z.string().optional(), 'api-version': z.string().nullable() }), query: z.object({ default: z.string().optional(), 'parameter-query': z.string().nullable() }), headers: z.object({ 'parameter.header': z.string().nullable() }) }); export const zGetCallWithOptionalParamData = z.object({ body: zModelWithOneOfEnum, path: z.never().optional(), query: z.object({ page: z.number().optional() }).optional() }); export const zPostCallWithOptionalParamData = z.object({ body: z.object({ offset: z.number().nullish() }).optional(), path: z.never().optional(), query: z.object({ parameter: zPageable }) }); export const zPostCallWithOptionalParamResponse = z.union([ z.number(), z.void() ]); export const zPostApiVbyApiVersionRequestBodyData = z.object({ body: zSimpleRequestBody.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zPostApiVbyApiVersionFormDataData = z.object({ body: zSimpleFormData.optional(), path: z.never().optional(), query: z.object({ parameter: z.string().optional() }).optional() }); export const zCallWithDefaultParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().nullish().default('Hello World!'), parameterNumber: z.number().nullish().default(123), parameterBoolean: z.boolean().nullish().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.nullish() }).optional() }); export const zCallWithDefaultOptionalParametersData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterString: z.string().optional().default('Hello World!'), parameterNumber: z.number().optional().default(123), parameterBoolean: z.boolean().optional().default(true), parameterEnum: z.enum([ 'Success', 'Warning', 'Error' ]).optional(), parameterModel: zModelWithString.optional().default({ prop: 'Hello World!' }) }).optional() }); export const zCallToTestOrderOfParamsData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterOptionalStringWithDefault: z.string().optional().default('Hello World!'), parameterOptionalStringWithEmptyDefault: z.string().optional().default(''), parameterOptionalStringWithNoDefault: z.string().optional(), parameterStringWithDefault: z.string().default('Hello World!'), parameterStringWithEmptyDefault: z.string().default(''), parameterStringWithNoDefault: z.string(), parameterStringNullableWithNoDefault: z.string().nullish(), parameterStringNullableWithDefault: z.string().nullish().default(null) }) }); export const zDuplicateNameData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName2Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName3Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDuplicateName4Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zCallWithNoContentResponseResponse = z.void(); export const zCallWithResponseAndNoContentResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseAndNoContentResponseResponse = z.union([ z.number(), z.void() ]); export const zDummyAData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zDummyAResponse = z400; export const zDummyBData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * Success */ export const zDummyBResponse = z.void(); export const zCallWithResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponseResponse = zImport; export const zCallWithDuplicateResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithDuplicateResponsesResponse = z.union([ zModelWithBoolean.and(zModelWithInteger), zModelWithString ]); export const zCallWithResponsesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zCallWithResponsesResponse = z.union([ z.object({ '@namespace.string': z.string().readonly().optional(), '@namespace.integer': z.int().readonly().optional(), value: z.array(zModelWithString).readonly().optional() }), zModelThatExtends, zModelThatExtendsExtends ]); export const zCollectionFormatData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterArrayCSV: z.array(z.string()).nullable(), parameterArraySSV: z.array(z.string()).nullable(), parameterArrayTSV: z.array(z.string()).nullable(), parameterArrayPipes: z.array(z.string()).nullable(), parameterArrayMulti: z.array(z.string()).nullable() }) }); export const zTypesData = z.object({ body: z.never().optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional() }).optional(), query: z.object({ parameterNumber: z.number().default(123), parameterString: z.string().nullable().default('default'), parameterBoolean: z.boolean().nullable().default(true), parameterObject: z.record(z.string(), z.unknown()).nullable().default(null), parameterArray: z.array(z.string()).nullable(), parameterDictionary: z.record(z.string(), z.unknown()).nullable(), parameterEnum: z.union([ z.literal('Success'), z.literal('Warning'), z.literal('Error') ]).nullable() }) }); export const zTypesResponse = z.union([ z.number(), z.string(), z.boolean(), z.record(z.string(), z.unknown()) ]); export const zUploadFileData = z.object({ body: z.string(), path: z.object({ 'api-version': z.string().nullable() }), query: z.never().optional() }); export const zUploadFileResponse = z.boolean(); export const zFileResponseData = z.object({ body: z.never().optional(), path: z.object({ id: z.string(), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zFileResponseResponse = z.string(); export const zComplexTypesData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ parameterObject: z.object({ first: z.object({ second: z.object({ third: z.string().optional() }).optional() }).optional() }), parameterReference: zModelWithString }) }); /** * Successful response */ export const zComplexTypesResponse = z.array(zModelWithString); export const zMultipartResponseData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zMultipartResponseResponse = z.object({ file: z.string().optional(), metadata: z.object({ foo: z.string().optional(), bar: z.string().optional() }).optional() }); export const zMultipartRequestData = z.object({ body: z.object({ content: z.string().optional(), data: zModelWithString.nullish() }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zComplexParamsData = z.object({ body: z.object({ key: z.string().max(64).regex(/^[a-zA-Z0-9_]*$/).readonly().nullable(), name: z.string().max(255).nullable(), enabled: z.boolean().optional().default(true), type: z.enum([ 'Monkey', 'Horse', 'Bird' ]), listOfModels: z.array(zModelWithString).nullish(), listOfStrings: z.array(z.string()).nullish(), parameters: z.union([ zModelWithString, zModelWithEnum, zModelWithArray, zModelWithDictionary ]), user: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).readonly().optional(), name: z.string().readonly().nullish() }).readonly().optional() }).optional(), path: z.object({ id: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }), 'api-version': z.string() }), query: z.never().optional() }); /** * Success */ export const zComplexParamsResponse = zModelWithString; export const zCallWithResultFromHeaderData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); export const zTestErrorCodeData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ status: z.int() }) }); export const zNonAsciiæøåÆøÅöôêÊ字符串Data = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.object({ nonAsciiParamæøåÆØÅöôêÊ: z.int() }) }); /** * Successful response */ export const zNonAsciiæøåÆøÅöôêÊ字符串Response = z.array(zNonAsciiStringæøåÆøÅöôêÊ字符串); export const zPutWithFormUrlEncodedData = z.object({ body: zArrayWithStrings, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/defaults-with-ref-and-anyof/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zAudioFormat = z.enum(['pcm_16bit_44.1khz', 'pcm_16bit_24khz']); export const zLanguage = z.enum([ 'en', 'es', 'fr' ]); export const zNestedConfig = z.object({ model: z.string().default('gpt-4'), temperature: z.number().default(1) }); export const zTestSchema = z.object({ primitiveDefault: z.number().default(42), refWithPrimitiveDefault: zAudioFormat.default('pcm_16bit_44.1khz'), refWithObjectDefault: zNestedConfig.default({ model: 'gpt-4', temperature: 1 }), anyOfWithNullDefault: z.number().nullable().default(null), anyOfWithRefAndNullDefault: zLanguage.nullable().default(null), optionalAnyOfWithDefault: z.string().nullish().default(null) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/enum-null/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.enum(['foo', 'bar']).nullable(); export const zBar = z.enum(['foo', 'bar']); export const zBaz = z.enum(['foo', 'bar']); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/enum-resolver-permissive/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.union([z.enum(['foo', 'bar']), z.string()]).nullable(); export const zBar = z.union([z.enum(['foo', 'bar']), z.string()]); export const zBaz = z.union([z.enum(['foo', 'bar']), z.string()]); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/schema-const/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.object({ foo: z.literal('foo').optional(), bar: z.literal(3.2).optional(), baz: z.literal(-1).optional(), qux: z.literal(true).optional(), quux: z.tuple([ z.literal(1), z.literal(2), z.literal(3), z.literal('foo'), z.literal(true) ]).optional(), corge: z.record(z.string(), z.unknown()).optional(), garply: z.literal(BigInt('10')).optional(), numberInt8: z.literal(100).optional(), numberInt16: z.literal(1000).optional(), numberInt32: z.literal(100000).optional(), numberInt64: z.literal(BigInt(1000000000000)).optional(), numberUint8: z.literal(200).optional(), numberUint16: z.literal(50000).optional(), numberUint32: z.literal(3000000000).optional(), numberUint64: z.literal(BigInt(18000000000000000000)).optional(), integerInt8: z.literal(-100).optional(), integerInt16: z.literal(-1000).optional(), integerInt32: z.literal(-100000).optional(), integerInt64: z.literal(BigInt(-1000000000000)).optional(), integerUint8: z.literal(255).optional(), integerUint16: z.literal(65535).optional(), integerUint32: z.literal(4294967295).optional(), integerUint64: z.literal(BigInt('18446744073709551615')).optional(), stringInt64: z.literal(BigInt('-9223372036854775808')).optional(), stringUint64: z.literal(BigInt('18446744073709551615')).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/string-with-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.object({ foo: z.array(z.union([z.string(), z.string()])).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/string-with-guid-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zGetFooData = z.object({ body: z.never().optional(), path: z.object({ guidId: z.guid() }), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/client/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen'; type ReqInit = Omit & { body?: any; headers: ReturnType; }; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); const getConfig = (): Config => ({ ..._config }); const setConfig = (config: Config): Config => { _config = mergeConfigs(_config, config); return getConfig(); }; const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: undefined as string | undefined, }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security, }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body !== undefined && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; } // remove Content-Type header if body is empty to avoid sending invalid requests if (opts.body === undefined || opts.serializedBody === '') { opts.headers.delete('Content-Type'); } const url = buildUrl(opts); return { opts, url }; }; const request: Client['request'] = async (options) => { // @ts-expect-error const { opts, url } = await beforeRequest(options); const requestInit: ReqInit = { redirect: 'follow', ...opts, body: getValidRequestBody(opts), }; let request = new Request(url, requestInit); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = opts.fetch!; let response: Response; try { response = await _fetch(request); } catch (error) { // Handle fetch exceptions (AbortError, network errors, etc.) let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } finalError = finalError || ({} as unknown); if (opts.throwOnError) { throw finalError; } // Return error response return opts.responseStyle === 'data' ? undefined : { error: finalError, request, response: undefined as any, }; } for (const fn of interceptors.response.fns) { if (fn) { response = await fn(response, request, opts); } } const result = { request, response, }; if (response.ok) { const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'text': emptyData = await response[parseAs](); break; case 'formData': emptyData = new FormData(); break; case 'stream': emptyData = response.body; break; case 'json': default: emptyData = {}; break; } return opts.responseStyle === 'data' ? emptyData : { data: emptyData, ...result, }; } let data: any; switch (parseAs) { case 'arrayBuffer': case 'blob': case 'formData': case 'text': data = await response[parseAs](); break; case 'json': { // Some servers return 200 with no Content-Length and empty body. // response.json() would throw; read as text and parse if non-empty. const text = await response.text(); data = text ? JSON.parse(text) : {}; break; } case 'stream': return opts.responseStyle === 'data' ? response.body : { data: response.body, ...result, }; } if (parseAs === 'json') { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === 'data' ? data : { data, ...result, }; } const textError = await response.text(); let jsonError: unknown; try { jsonError = JSON.parse(textError); } catch { // noop } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error.fns) { if (fn) { finalError = (await fn(error, response, request, opts)) as string; } } finalError = finalError || ({} as string); if (opts.throwOnError) { throw finalError; } // TODO: we probably want to return error and improve types return opts.responseStyle === 'data' ? undefined : { error: finalError, ...result, }; }; const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => request({ ...options, method }); const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { const { opts, url } = await beforeRequest(options); return createSseClient({ ...opts, body: opts.body as BodyInit | null | undefined, headers: opts.headers as unknown as Record, method, onRequest: async (url, init) => { let request = new Request(url, init); for (const fn of interceptors.request.fns) { if (fn) { request = await fn(request, opts); } } return request; }, serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, url, }); }; const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); return { buildUrl: _buildUrl, connect: makeMethodFn('CONNECT'), delete: makeMethodFn('DELETE'), get: makeMethodFn('GET'), getConfig, head: makeMethodFn('HEAD'), interceptors, options: makeMethodFn('OPTIONS'), patch: makeMethodFn('PATCH'), post: makeMethodFn('POST'), put: makeMethodFn('PUT'), request, setConfig, sse: { connect: makeSseFn('CONNECT'), delete: makeSseFn('DELETE'), get: makeSseFn('GET'), head: makeSseFn('HEAD'), options: makeSseFn('OPTIONS'), patch: makeSseFn('PATCH'), post: makeSseFn('POST'), put: makeSseFn('PUT'), trace: makeSseFn('TRACE'), }, trace: makeMethodFn('TRACE'), } as Client; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type { Auth } from '../core/auth.gen'; export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen'; export { buildClientParams } from '../core/params.gen'; export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; export { createClient } from './client.gen'; export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen'; export { createConfig, mergeHeaders } from './utils.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; import type { ServerSentEventsOptions, ServerSentEventsResult, } from '../core/serverSentEvents.gen'; import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ baseUrl?: T['baseUrl']; /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Please don't use the Fetch client for Next.js applications. The `next` * options won't have any effect. * * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. */ next?: never; /** * Return the response data parsed in a specified format. By default, `auto` * will infer the appropriate method from the `Content-Type` response header. * You can override this behavior with any of the {@link Body} methods. * Select `stream` if you don't want to parse response data at all. * * @default 'auto' */ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * * @default 'fields' */ responseStyle?: ResponseStyle; /** * Throw an error instead of returning it in the response? * * @default false */ throwOnError?: T['throwOnError']; } export interface RequestOptions< TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, Pick< ServerSentEventsOptions, | 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay' > { /** * Any body that you want to add to your request. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} */ body?: unknown; path?: Record; query?: Record; /** * Security mechanism(s) to use for the request. */ security?: ReadonlyArray; url: Url; } export interface ResolvedRequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, > extends RequestOptions { serializedBody?: string; } export type RequestResult< TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields', > = ThrowOnError extends true ? Promise< TResponseStyle extends 'data' ? TData extends Record ? TData[keyof TData] : TData : { data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; response: Response; } >; export interface ClientOptions { baseUrl?: string; responseStyle?: ResponseStyle; throwOnError?: boolean; } type MethodFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => RequestResult; type SseFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'>, ) => Promise>; type RequestFn = < TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < TData extends { body?: unknown; path?: Record; query?: Record; url: string; }, >( options: TData & Options, ) => string; export type Client = CoreClient & { interceptors: Middleware; }; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = ( override?: Config, ) => Config & T>; export interface TDataShape { body?: unknown; headers?: unknown; path?: unknown; query?: unknown; url: string; } type OmitKeys = Pick>; export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields', > = OmitKeys< RequestOptions, 'body' | 'path' | 'query' | 'url' > & ([TData] extends [never] ? unknown : Omit); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/client/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, ...args }: QuerySerializerOptions = {}) => { const querySerializer = (queryParams: T) => { const search: string[] = []; if (queryParams && typeof queryParams === 'object') { for (const name in queryParams) { const value = queryParams[name]; if (value === undefined || value === null) { continue; } const options = parameters[name] || args; if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved: options.allowReserved, explode: true, name, style: 'form', value, ...options.array, }); if (serializedArray) search.push(serializedArray); } else if (typeof value === 'object') { const serializedObject = serializeObjectParam({ allowReserved: options.allowReserved, explode: true, name, style: 'deepObject', value: value as Record, ...options.object, }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved: options.allowReserved, name, value: value as string, }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join('&'); }; return querySerializer; }; /** * Infers parseAs value from provided Content-Type header. */ export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { // If no Content-Type header is provided, the best we can do is return the raw response body, // which is effectively the same as the 'stream' option. return 'stream'; } const cleanContent = contentType.split(';')[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } if (cleanContent === 'multipart/form-data') { return 'formData'; } if ( ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } if (cleanContent.startsWith('text/')) { return 'text'; } return; }; const checkForExistence = ( options: Pick & { headers: Headers; }, name?: string, ): boolean => { if (!name) { return false; } if ( options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`) ) { return true; } return false; }; export const setAuthParams = async ({ security, ...options }: Pick, 'security'> & Pick & { headers: Headers; }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? 'Authorization'; switch (auth.in) { case 'query': if (!options.query) { options.query = {}; } options.query[name] = token; break; case 'cookie': options.headers.append('Cookie', `${name}=${token}`); break; case 'header': default: options.headers.set(name, token); break; } } }; export const buildUrl: Client['buildUrl'] = (options) => getUrl({ baseUrl: options.baseUrl as string, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url, }); export const mergeConfigs = (a: Config, b: Config): Config => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith('/')) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; export const mergeHeaders = ( ...headers: Array['headers'] | undefined> ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type ErrInterceptor = ( error: Err, response: Res, request: Req, options: Options, ) => Err | Promise; type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, request: Req, options: Options, ) => Res | Promise; class Interceptors { fns: Array = []; clear(): void { this.fns = []; } eject(id: number | Interceptor): void { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = null; } } exists(id: number | Interceptor): boolean { const index = this.getInterceptorIndex(id); return Boolean(this.fns[index]); } getInterceptorIndex(id: number | Interceptor): number { if (typeof id === 'number') { return this.fns[id] ? id : -1; } return this.fns.indexOf(id); } update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; return id; } return false; } use(fn: Interceptor): number { this.fns.push(fn); return this.fns.length - 1; } } export interface Middleware { error: Interceptors>; request: Interceptors>; response: Interceptors>; } export const createInterceptors = (): Middleware< Req, Res, Err, Options > => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), }); const defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: 'form', }, object: { explode: true, style: 'deepObject', }, }); const defaultHeaders = { 'Content-Type': 'application/json', }; export const createConfig = ( override: Config & T> = {}, ): Config & T> => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: 'auto', querySerializer: defaultQuerySerializer, ...override, }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/client.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** * The `createClientConfig()` function will be called on client initialization * and the returned object will become the client's initial configuration. * * You may want to initialize your client this way instead of calling * `setConfig()`. This is useful for example if you're using Next.js * to ensure your client always has the correct values. */ export type CreateClientConfig = (override?: Config) => Config & T>; export const client = createClient(createConfig()); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/auth.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type AuthToken = string | undefined; export interface Auth { /** * Which part of the request do we use to send the auth? * * @default 'header' */ in?: 'header' | 'query' | 'cookie'; /** * Header or query parameter name. * * @default 'Authorization' */ name?: string; scheme?: 'basic' | 'bearer'; type: 'apiKey' | 'http'; } export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === 'bearer') { return `Bearer ${token}`; } if (auth.scheme === 'basic') { return `Basic ${btoa(token)}`; } return token; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/bodySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; export type BodySerializer = (body: unknown) => unknown; type QuerySerializerOptionsObject = { allowReserved?: boolean; array?: Partial>; object?: Partial>; }; export type QuerySerializerOptions = QuerySerializerOptionsObject & { /** * Per-parameter serialization overrides. When provided, these settings * override the global array/object settings for specific parameter names. */ parameters?: Record; }; const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { data.append(key, value.toISOString()); } else { data.append(key, JSON.stringify(value)); } }; const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { data.append(key, JSON.stringify(value)); } }; export const formDataBodySerializer = { bodySerializer: (body: unknown): FormData => { const data = new FormData(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeFormDataPair(data, key, v)); } else { serializeFormDataPair(data, key, value); } }); return data; }, }; export const jsonBodySerializer = { bodySerializer: (body: unknown): string => JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { bodySerializer: (body: unknown): string => { const data = new URLSearchParams(); Object.entries(body as Record).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); } else { serializeUrlSearchParamsPair(data, key, value); } }); return data.toString(); }, }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/params.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts type Slot = 'body' | 'headers' | 'path' | 'query'; export type Field = | { in: Exclude; /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If omitted, we use the same value as `key`. */ map?: string; } | { in: Extract; /** * Key isn't required for bodies. */ key?: string; map?: string; } | { /** * Field name. This is the name we want the user to see and use. */ key: string; /** * Field mapped name. This is the name we want to use in the request. * If `in` is omitted, `map` aliases `key` to the transport layer. */ map: Slot; }; export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: 'body', $headers_: 'headers', $path_: 'path', $query_: 'query', }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map< string, | { in: Slot; map?: string; } | { in?: never; map: Slot; } >; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) { map = new Map(); } for (const config of fields) { if ('in' in config) { if (config.key) { map.set(config.key, { in: config.in, map: config.map, }); } } else if ('key' in config) { map.set(config.key, { map: config.map, }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) { if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { delete params[slot as Slot]; } } }; export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, path: {}, query: {}, }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) { config = fields[index]; } if (!config) { continue; } if ('in' in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; if (field.in) { (params[field.in] as Record)[name] = arg; } } else { params.body = arg; } } else { for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { if (field.in) { const name = field.map || key; (params[field.in] as Record)[name] = value; } else { params[field.map] = value; } } else { const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } } } } } stripEmptySlots(params); return params; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/pathSerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; name: string; } export interface SerializerOptions { /** * @default true */ explode: boolean; style: T; } export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; type MatrixStyle = 'label' | 'matrix' | 'simple'; export type ObjectStyle = 'form' | 'deepObject'; type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; interface SerializePrimitiveParam extends SerializePrimitiveOptions { value: string; } export const separatorArrayExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { switch (style) { case 'form': return ','; case 'pipeDelimited': return '|'; case 'spaceDelimited': return '%20'; default: return ','; } }; export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { switch (style) { case 'label': return '.'; case 'matrix': return ';'; case 'simple': return ','; default: return '&'; } }; export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }: SerializeOptions & { value: unknown[]; }) => { if (!explode) { const joinedValues = ( allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) ).join(separatorArrayNoExplode(style)); switch (style) { case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; case 'simple': return joinedValues; default: return `${name}=${joinedValues}`; } } const separator = separatorArrayExplode(style); const joinedValues = value .map((v) => { if (style === 'label' || style === 'simple') { return allowReserved ? v : encodeURIComponent(v as string); } return serializePrimitiveParam({ allowReserved, name, value: v as string, }); }) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ allowReserved, name, value, }: SerializePrimitiveParam) => { if (value === undefined || value === null) { return ''; } if (typeof value === 'object') { throw new Error( 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions & { value: Record | Date; valueOnly?: boolean; }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { case 'form': return `${name}=${joinedValues}`; case 'label': return `.${joinedValues}`; case 'matrix': return `;${name}=${joinedValues}`; default: return joinedValues; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value) .map(([key, v]) => serializePrimitiveParam({ allowReserved, name: style === 'deepObject' ? `${name}[${key}]` : key, value: v as string, }), ) .join(separator); return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/queryKeySerializer.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts /** * JSON-friendly union that mirrors what Pinia Colada can hash. */ export type JsonValue = | null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }; /** * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } return value; }; /** * Safely stringifies a value and parses it back into a JsonValue. */ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { try { const json = JSON.stringify(input, queryKeyJsonReplacer); if (json === undefined) { return undefined; } return JSON.parse(json) as JsonValue; } catch { return undefined; } }; /** * Detects plain objects (including objects with a null prototype). */ const isPlainObject = (value: unknown): value is Record => { if (value === null || typeof value !== 'object') { return false; } const prototype = Object.getPrototypeOf(value as object); return prototype === Object.prototype || prototype === null; }; /** * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { const existing = result[key]; if (existing === undefined) { result[key] = value; continue; } if (Array.isArray(existing)) { (existing as string[]).push(value); } else { result[key] = [existing, value]; } } return result; }; /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Date) { return value.toISOString(); } if (Array.isArray(value)) { return stringifyToJsonValue(value); } if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } if (isPlainObject(value)) { return stringifyToJsonValue(value); } return undefined; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/serverSentEvents.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Config } from './types.gen'; export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom * fetch instance. * * @default globalThis.fetch */ fetch?: typeof fetch; /** * Implementing clients can call request interceptors inside this hook. */ onRequest?: (url: string, init: RequestInit) => Promise; /** * Callback invoked when a network or parsing error occurs during streaming. * * This option applies only if the endpoint returns a stream of events. * * @param error The error that occurred. */ onSseError?: (error: unknown) => void; /** * Callback invoked when an event is streamed from the server. * * This option applies only if the endpoint returns a stream of events. * * @param event Event streamed from the server. * @returns Nothing (void). */ onSseEvent?: (event: StreamEvent) => void; serializedBody?: RequestInit['body']; /** * Default retry delay in milliseconds. * * This option applies only if the endpoint returns a stream of events. * * @default 3000 */ sseDefaultRetryDelay?: number; /** * Maximum number of retry attempts before giving up. */ sseMaxRetryAttempts?: number; /** * Maximum retry delay in milliseconds. * * Applies only when exponential backoff is used. * * This option applies only if the endpoint returns a stream of events. * * @default 30000 */ sseMaxRetryDelay?: number; /** * Optional sleep function for retry backoff. * * Defaults to using `setTimeout`. */ sseSleepFn?: (ms: number) => Promise; url: string; }; export interface StreamEvent { data: TData; event?: string; id?: string; retry?: number; } export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, TNext >; }; export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; let attempt = 0; const signal = options.signal ?? new AbortController().signal; while (true) { if (signal.aborted) break; attempt++; const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers as Record | undefined); if (lastEventId !== undefined) { headers.set('Last-Event-ID', lastEventId); } try { const requestInit: RequestInit = { redirect: 'follow', ...options, body: options.serializedBody, headers, signal, }; let request = new Request(url, requestInit); if (onRequest) { request = await onRequest(url, requestInit); } // fetch must be assigned here, otherwise it would throw the error: // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation const _fetch = options.fetch ?? globalThis.fetch; const response = await _fetch(request); if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); if (!response.body) throw new Error('No body in SSE response'); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; const abortHandler = () => { try { reader.cancel(); } catch { // noop } }; signal.addEventListener('abort', abortHandler); try { while (true) { const { done, value } = await reader.read(); if (done) break; buffer += value; // Normalize line endings: CRLF -> LF, then CR -> LF buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); const chunks = buffer.split('\n\n'); buffer = chunks.pop() ?? ''; for (const chunk of chunks) { const lines = chunk.split('\n'); const dataLines: Array = []; let eventName: string | undefined; for (const line of lines) { if (line.startsWith('data:')) { dataLines.push(line.replace(/^data:\s*/, '')); } else if (line.startsWith('event:')) { eventName = line.replace(/^event:\s*/, ''); } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } } } let data: unknown; let parsedJson = false; if (dataLines.length) { const rawData = dataLines.join('\n'); try { data = JSON.parse(rawData); parsedJson = true; } catch { data = rawData; } } if (parsedJson) { if (responseValidator) { await responseValidator(data); } if (responseTransformer) { data = await responseTransformer(data); } } onSseEvent?.({ data, event: eventName, id: lastEventId, retry: retryDelay, }); if (dataLines.length) { yield data as any; } } } } finally { signal.removeEventListener('abort', abortHandler); reader.releaseLock(); } break; // exit loop on normal completion } catch (error) { // connection failed or aborted; retry after delay onSseError?.(error); if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { break; // stop after firing error } // exponential backoff: double retry each attempt, cap at 30s const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } }; const stream = createStream(); return { stream }; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'; export type Client< RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never, > = { /** * Returns the final request URL. */ buildUrl: BuildUrlFn; getConfig: () => Config; request: RequestFn; setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** * Auth token or a function returning auth token. The resolved value will be * added to the request payload as defined by its `security` array. */ auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; /** * A function for serializing request body parameter. By default, * {@link JSON.stringify()} will be used. */ bodySerializer?: BodySerializer | null; /** * An object containing any HTTP headers that you want to pre-populate your * `Headers` object with. * * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} */ headers?: | RequestInit['headers'] | Record< string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. * * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} */ method?: Uppercase; /** * A function for serializing request query parameters. By default, arrays * will be exploded in form style, objects will be exploded in deepObject * style, and reserved characters are percent-encoded. * * This method will have no effect if the native `paramsSerializer()` Axios * API function is used. * * {@link https://swagger.io/docs/specification/serialization/#query View examples} */ querySerializer?: QuerySerializer | QuerySerializerOptions; /** * A function validating request data. This is useful if you want to ensure * the request conforms to the desired shape, so it can be safely sent to * the server. */ requestValidator?: (data: unknown) => Promise; /** * A function transforming response data before it's returned. This is useful * for post-processing data, e.g. converting ISO strings into Date objects. */ responseTransformer?: (data: unknown) => Promise; /** * A function validating response data. This is useful if you want to ensure * the response conforms to the desired shape, so it can be safely passed to * the transformers and returned to the user. */ responseValidator?: (data: unknown) => Promise; } type IsExactlyNeverOrNeverUndefined = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false; export type OmitNever> = { [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/core/utils.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; import { type ArraySeparatorStyle, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen'; export interface PathSerializer { path: Record; url: string; } export const PATH_PARAM_RE = /\{[^{}]+\}/g; export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style: ArraySeparatorStyle = 'simple'; if (name.endsWith('*')) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith('.')) { name = name.substring(1); style = 'label'; } else if (name.startsWith(';')) { name = name.substring(1); style = 'matrix'; } const value = path[name]; if (value === undefined || value === null) { continue; } if (Array.isArray(value)) { url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } if (typeof value === 'object') { url = url.replace( match, serializeObjectParam({ explode, name, style, value: value as Record, valueOnly: true, }), ); continue; } if (style === 'matrix') { url = url.replace( match, `;${serializePrimitiveParam({ name, value: value as string, })}`, ); continue; } const replaceValue = encodeURIComponent( style === 'label' ? `.${value as string}` : (value as string), ); url = url.replace(match, replaceValue); } } return url; }; export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }: { baseUrl?: string; path?: Record; query?: Record; querySerializer: QuerySerializer; url: string; }) => { const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; let url = (baseUrl ?? '') + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ''; if (search.startsWith('?')) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; export function getValidRequestBody(options: { body?: unknown; bodySerializer?: BodySerializer | null; serializedBody?: unknown; }) { const hasBody = options.body !== undefined; const isSerializedBody = hasBody && options.bodySerializer; if (isSerializedBody) { if ('serializedBody' in options) { const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ''; return hasSerializedBody ? options.serializedBody : null; } // not all clients implement a serializedBody property (i.e. client-axios) return options.body !== '' ? options.body : null; } // plain/text body if (hasBody) { return options.body; } // no body was provided return undefined; } ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { type Options, postFoo } from './sdk.gen'; export type { Bar, ClientOptions, Foo, PostFooData, PostFooResponse, PostFooResponses, TypeID, UserId } from './types.gen'; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; import { postFooResponseTransformer } from './transformers.gen'; import type { PostFooData, PostFooResponses } from './types.gen'; import { zPostFooData, zPostFooResponse } from './zod.gen'; export type Options = Options2 & { /** * You can provide a client instance returned by `createClient()` instead of * individual options. This might be also useful if you want to implement a * custom client. */ client?: Client; /** * You can pass arbitrary values through the `meta` object. This can be * used to access values that aren't defined as part of the SDK function. */ meta?: Record; }; export const postFoo = (options?: Options) => (options?.client ?? client).post({ requestValidator: async (data) => await zPostFooData.parseAsync(data), responseTransformer: postFooResponseTransformer, responseValidator: async (data) => await zPostFooResponse.parseAsync(data), url: '/foo', ...options }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/transformers.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { PostFooResponse } from './types.gen'; const fooSchemaResponseTransformer = (data: any) => { data.foo = BigInt(data.foo.toString()); return data; }; export const postFooResponseTransformer = async (data: any): Promise => { data = fooSchemaResponseTransformer(data); return data; }; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; export type TypeID = `${T}_${string}`; export type UserId = TypeID<'user'>; export type Foo = { bar?: number; foo: bigint; id: UserId; }; export type Bar = { foo: number; [key: string]: number; }; export type PostFooData = { body?: never; path?: never; query?: never; url: '/foo'; }; export type PostFooResponses = { /** * OK */ 200: Foo; }; export type PostFooResponse = PostFooResponses[keyof PostFooResponses]; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/type-format/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.object({ bar: z.int().optional(), foo: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).default(BigInt(0)), id: z.string() }); export const zBar = z.object({ foo: z.int() }); export const zPostFooData = z.object({ body: z.never().optional(), path: z.never().optional(), query: z.never().optional() }); /** * OK */ export const zPostFooResponse = zFoo; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-bigint-min-max/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zFoo = z.object({ foo: z.coerce.bigint().gte(BigInt(0)).lte(BigInt(100)).optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-circular-ref/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBar = z.object({ bar: z.array(z.lazy((): any => zBar)).optional() }); export const zFoo = z.object({ foo: zBar.optional() }); export const zBaz = z.lazy((): any => zQux); /** * description caused circular reference error */ export const zQux = zBaz; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-circular-ref-2/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBar = z.object({ bar: z.array(z.lazy((): any => zBar)).nullable() }); export const zFoo = z.object({ foo: zBar }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-dates/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); /** * This is Foo parameter. */ export const zFoo2 = z.string(); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime({ offset: true }).optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-metadata/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).register(z.globalRegistry, { description: 'This is foo property.' }).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).register(z.globalRegistry, { description: 'This is baz property.' }).optional(), qux: z.int().gt(0).register(z.globalRegistry, { description: 'This is qux property.' }).optional().default(0) }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }).register(z.globalRegistry, { description: 'This is Bar schema.' }); /** * This is Foo parameter. */ export const zFoo2 = z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' }); export const zFoo3 = z.object({ foo: zBar.optional() }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().register(z.globalRegistry, { description: 'This is Foo parameter.' }).optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime().optional() }).optional() }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-metadata-fn/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).register(z.globalRegistry, { custom: 'value', title: 'string' }).readonly().default('baz'); export const zQux = z.record(z.string(), z.object({ qux: z.string().register(z.globalRegistry, { custom: 'value', title: 'string' }).optional() }).register(z.globalRegistry, { custom: 'value', title: 'object' })).register(z.globalRegistry, { custom: 'value', title: 'object' }); /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).register(z.globalRegistry, { custom: 'value', title: 'This is foo property.' }).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).register(z.globalRegistry, { custom: 'value', title: 'This is baz property.' }).optional(), qux: z.int().gt(0).register(z.globalRegistry, { custom: 'value', title: 'This is qux property.' }).optional().default(0) }).register(z.globalRegistry, { custom: 'value', title: 'object' }).nullable().default(null); /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }).register(z.globalRegistry, { custom: 'value', title: 'This is Bar schema.' }); /** * This is Foo parameter. */ export const zFoo2 = z.string().register(z.globalRegistry, { custom: 'value', title: 'This is Foo parameter.' }); export const zFoo3 = z.object({ foo: zBar.optional() }).register(z.globalRegistry, { custom: 'value', title: 'object' }); export const zPatchFooData = z.object({ body: z.object({ foo: z.string().register(z.globalRegistry, { custom: 'value', title: 'string' }).optional() }).register(z.globalRegistry, { custom: 'value', title: 'object' }), path: z.never().register(z.globalRegistry, { custom: 'value', title: 'never' }).optional(), query: z.object({ foo: z.string().register(z.globalRegistry, { custom: 'value', title: 'This is Foo parameter.' }).optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().register(z.globalRegistry, { custom: 'value', title: 'string' }).optional() }).register(z.globalRegistry, { custom: 'value', title: 'object' }).optional(), qux: z.iso.date().register(z.globalRegistry, { custom: 'value', title: 'string' }).optional(), quux: z.iso.datetime().register(z.globalRegistry, { custom: 'value', title: 'string' }).optional() }).register(z.globalRegistry, { custom: 'value', title: 'object' }).optional() }).register(z.globalRegistry, { custom: 'value', title: 'object' }); export const zPostFooData = z.object({ body: zFoo3, path: z.never().register(z.globalRegistry, { custom: 'value', title: 'never' }).optional(), query: z.never().register(z.globalRegistry, { custom: 'value', title: 'never' }).optional() }).register(z.globalRegistry, { custom: 'value', title: 'object' }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-string-constraints-union/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zLocaleOrLanguage = z.union([ z.string().length(5), z.string().length(2) ]); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-types/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zBaz = z.string().regex(/foo\nbar/).readonly().default('baz'); export type BazZodType = z.infer; export const zQux = z.record(z.string(), z.object({ qux: z.string().optional() })); export type QuxZodType = z.infer; /** * This is Foo schema. */ export const zFoo = z.object({ foo: z.string().regex(/^\d{3}-\d{2}-\d{4}$/).optional(), bar: z.lazy((): any => zBar).optional(), baz: z.array(z.lazy((): any => zFoo)).optional(), qux: z.int().gt(0).optional().default(0) }).nullable().default(null); export type FooZodType = z.infer; /** * This is Bar schema. */ export const zBar = z.object({ foo: zFoo.optional() }); export type BarZodType = z.infer; /** * This is Foo parameter. */ export const zFoo2 = z.string(); export type FooZodType2 = z.infer; export const zFoo3 = z.object({ foo: zBar.optional() }); export type FooZodType3 = z.infer; export const zPatchFooData = z.object({ body: z.object({ foo: z.string().optional() }), path: z.never().optional(), query: z.object({ foo: z.string().optional(), bar: zBar.optional(), baz: z.object({ baz: z.string().optional() }).optional(), qux: z.iso.date().optional(), quux: z.iso.datetime().optional() }).optional() }); export type PatchFooDataZodType = z.infer; export const zPostFooData = z.object({ body: zFoo3, path: z.never().optional(), query: z.never().optional() }); export type PostFooDataZodType = z.infer; ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/validators-union-merge/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zContact = z.union([ z.object({ email: z.string() }), z.object({ phone: z.string() }) ]); export const zUser = zContact.and(z.object({ username: z.string() })); export const zDogDetails = z.object({ breed: z.string(), barkVolume: z.int().gte(1).lte(10) }); export const zCatDetails = z.object({ furLength: z.enum([ 'short', 'medium', 'long' ]), purrs: z.boolean() }); export const zPetStore = z.object({ animals: z.array(z.object({ name: z.string(), type: z.enum(['dog', 'cat']).optional(), details: z.union([ zDogDetails, zCatDetails ]) })) }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/__snapshots__/3.1.x/v4/webhooks/zod.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import * as z from 'zod'; export const zSessionUserPhoneCalloutRingingWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutRingingWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingResumedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_resumed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionLiveStreamingStoppedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.live_streaming_stopped']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.iso.datetime(), live_streaming: z.object({ service: z.enum([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: z.object({ stream_url: z.string(), stream_key: z.string(), page_url: z.string(), resolution: z.string().optional() }), date_time: z.iso.datetime() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionStoppedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_stopped']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutRejectedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionAlertWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.alert']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), issues: z.array(z.enum([ 'Unstable audio quality', 'Unstable video quality', 'Unstable screen share quality', 'High CPU occupation', 'Call Reconnection' ])) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionSharingEndedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.sharing_ended']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), user_key: z.string().optional(), sharing_details: z.object({ content: z.enum([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: z.iso.datetime() }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingPausedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_paused']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionEndedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.ended']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.iso.datetime(), end_time: z.iso.datetime() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.iso.datetime() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionUnbindWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_unbind']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionLiveStreamingStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.live_streaming_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), start_time: z.iso.datetime(), live_streaming: z.object({ service: z.enum([ 'Facebook', 'Workplace_by_Facebook', 'YouTube', 'Custom_Live_Streaming_Service' ]), custom_live_streaming_settings: z.object({ stream_url: z.string(), stream_key: z.string(), page_url: z.string(), resolution: z.string().optional() }), date_time: z.iso.datetime() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutMissedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutAcceptedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserLeftWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.user_left']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), leave_time: z.iso.datetime(), leave_reason: z.string().optional(), user_key: z.string().optional(), phone_number: z.string().optional(), participant_uuid: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionSharingStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.sharing_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), user_key: z.string().optional(), sharing_details: z.object({ content: z.enum([ 'application', 'whiteboard', 'desktop', 'unknown' ]), date_time: z.iso.datetime() }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutCanceledWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingTranscriptCompletedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_transcript_completed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), download_token: z.string(), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE', 'TIMELINE' ]).optional(), file_size: z.number().optional(), file_extension: z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ]).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ]).optional() })) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingDeletedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_deleted']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), operator: z.email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutFailedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), reason_type: z.union([ z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(7), z.literal(8), z.literal(9), z.literal(10), z.literal(11), z.literal(12), z.literal(13), z.literal(14) ]), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingCompletedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_completed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), download_token: z.string(), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ]).optional(), file_size: z.number().optional(), file_extension: z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ]).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ]).optional() })), participant_audio_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum([ 'MP4', 'M4A', 'CHAT', 'TRANSCRIPT', 'CSV', 'CC', 'TB', 'CHAT_MESSAGE' ]).optional(), file_size: z.number().optional(), file_extension: z.enum([ 'MP4', 'M4A', 'TXT', 'VTT', 'CSV', 'JSON', 'JPG' ]).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum([ 'shared_screen_with_speaker_view(CC)', 'shared_screen_with_speaker_view', 'shared_screen_with_gallery_view', 'gallery_view', 'shared_screen', 'audio_only', 'audio_transcript', 'chat_file', 'active_speaker', 'host_video', 'audio_only_each_participant', 'cc_transcript', 'closed_caption', 'poll', 'timeline', 'thumbnail', 'chat_message' ]).optional(), user_id: z.string().optional(), user_key: z.string().optional() })).optional(), participant_video_files: z.array(z.object({ id: z.string().optional(), recording_start: z.string().optional(), recording_end: z.string().optional(), file_name: z.string().optional(), file_path: z.string().optional(), file_type: z.enum(['MP4']).optional(), file_size: z.number().optional(), file_extension: z.enum(['MP4']).optional(), download_url: z.string().optional(), status: z.enum(['completed']).optional(), recording_type: z.enum(['individual_user', 'individual_shared_screen']).optional(), user_id: z.string().optional(), user_key: z.string().optional() })).optional() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingTranscriptFailedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_transcript_failed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingTrashedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_trashed']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), operator: z.email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserJoinedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.user_joined']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.string(), session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), user: z.object({ id: z.string(), name: z.string(), join_time: z.iso.datetime(), user_key: z.string().optional(), phone_number: z.string().optional(), participant_uuid: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionStartedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_started']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionConnectedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_connected']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionStreamIngestionDisconnectedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.stream_ingestion_disconnected']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string().optional(), stream_ingestion: z.object({ stream_id: z.string(), stream_name: z.string(), stream_description: z.string().optional(), stream_key: z.string(), stream_url: z.string(), backup_stream_url: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingRecoveredWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_recovered']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), operator: z.email(), operator_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string() }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutMissedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserPhoneCalloutRejectedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), session_key: z.string(), user_key: z.string(), host_id: z.string(), participant: z.object({ invitee_name: z.string(), phone_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), from_number: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }) }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionUserRoomSystemCalloutAcceptedWebhookRequest = z.object({ body: z.object({ event: z.string(), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ id: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }).optional(), uuid: z.string().optional(), session_id: z.string(), session_name: z.string(), host_id: z.string(), message_id: z.string(), inviter_name: z.string(), participant: z.object({ call_type: z.string(), device_ip: z.string() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); export const zSessionRecordingStoppedWebhookRequest = z.object({ body: z.object({ event: z.enum(['session.recording_stopped']), event_ts: z.coerce.bigint().min(BigInt('-9223372036854775808'), { error: 'Invalid value: Expected int64 to be >= -9223372036854775808' }).max(BigInt('9223372036854775807'), { error: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), payload: z.object({ account_id: z.string(), object: z.object({ session_id: z.string(), session_name: z.string(), session_key: z.string(), start_time: z.iso.datetime(), timezone: z.string(), recording_file: z.object({ recording_start: z.string().optional(), recording_end: z.string().optional() }) }) }) }).optional(), path: z.never().optional(), query: z.never().optional() }); ================================================ FILE: packages/openapi-ts-tests/zod/v4/package.json ================================================ { "name": "@test/openapi-ts-zod-v4", "version": "0.0.0", "private": true, "type": "module", "scripts": { "typecheck": "tsgo --noEmit" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "typescript": "5.9.3", "zod": "4.3.6" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/openapi-ts-tests/zod/v4/test/3.0.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createZodConfig, getSnapshotsPath, getTempSnapshotsPath, zodVersions } from './utils'; const version = '3.0.x'; for (const zodVersion of zodVersions) { const outputDir = path.join(getTempSnapshotsPath(), version, zodVersion.folder); const snapshotsDir = path.join(getSnapshotsPath(), version, zodVersion.folder); describe(`OpenAPI ${version}`, () => { const createConfig = createZodConfig({ openApiVersion: version, outputDir, zodVersion, }); const scenarios = [ { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'circular.yaml', output: 'circular', }), description: 'generates circular schemas', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'validators.json', output: 'validators', }), description: 'generates validator schemas', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } ================================================ FILE: packages/openapi-ts-tests/zod/v4/test/3.1.x.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createZodConfig, getSnapshotsPath, getTempSnapshotsPath, zodVersions } from './utils'; const version = '3.1.x'; for (const zodVersion of zodVersions) { const outputDir = path.join(getTempSnapshotsPath(), version, zodVersion.folder); const snapshotsDir = path.join(getSnapshotsPath(), version, zodVersion.folder); describe(`OpenAPI ${version}`, () => { const createConfig = createZodConfig({ openApiVersion: version, outputDir, zodVersion, }); const scenarios = [ { config: createConfig({ input: 'array-items-one-of-length-1.yaml', output: 'array-items-one-of-length-1', }), description: 'generates correct array when items are oneOf array with single item', }, { config: createConfig({ input: 'defaults-with-ref-and-anyof.json', output: 'defaults-with-ref-and-anyof', }), description: 'preserves defaults with $ref and anyOf', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-null', }), description: 'handles null enums', }, { config: createConfig({ input: 'schema-const.yaml', output: 'schema-const', }), description: 'handles various constants', }, { config: createConfig({ input: 'validators.yaml', output: 'validators', }), description: 'generates validator schemas', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-dates', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, dates: { offset: true, }, name: 'zod', }, ], }), description: 'generates validator schemas with any offset', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-metadata', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, metadata: true, name: 'zod', }, ], }), description: 'generates validator schemas with metadata', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-metadata-fn', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, metadata: ({ $, node, schema }) => { node .prop('custom', $.literal('value')) .prop('title', $.literal(schema.description ?? schema.type ?? '')); }, name: 'zod', }, ], }), description: 'generates validator schemas with metadata function', }, { config: createConfig({ input: 'validators.yaml', output: 'validators-types', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', types: { infer: true, }, }, ], }), description: 'generates validator schemas with types', }, { config: createConfig({ input: 'validators-bigint-min-max.json', output: 'validators-bigint-min-max', }), description: 'validator schemas with BigInt and min/max constraints', }, { config: createConfig({ input: 'validators-circular-ref.json', output: 'validators-circular-ref', }), description: 'validator schemas with circular reference', }, { config: createConfig({ input: 'validators-circular-ref-2.yaml', output: 'validators-circular-ref-2', }), description: 'validator schemas with circular reference 2', }, { config: createConfig({ input: 'validators-union-merge.json', output: 'validators-union-merge', }), description: "validator schemas with merged unions (can't use .merge())", }, { config: createConfig({ input: 'validators-string-constraints-union.json', output: 'validators-string-constraints-union', }), description: 'validator schemas with string constraints union', }, { config: createConfig({ input: 'enum-null.json', output: 'enum-resolver-permissive', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', '~resolvers': { enum(ctx) { const { $, symbols } = ctx; const { z } = symbols; const { allStrings, enumMembers } = ctx.nodes.items(ctx); if (!allStrings || !enumMembers.length) { return; } const enumSchema = $(z) .attr('enum') .call($.array(...enumMembers)); return $(z) .attr('union') .call($.array(enumSchema, $(z).attr('string').call())); }, }, }, ], }), description: 'generates permissive enums with enum resolver', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } ================================================ FILE: packages/openapi-ts-tests/zod/v4/test/formats.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createZodConfig, getSnapshotsPath, getTempSnapshotsPath, zodVersions } from './utils'; const version = '3.1.x'; for (const zodVersion of zodVersions) { const outputDir = path.join(getTempSnapshotsPath(), version, zodVersion.folder); const snapshotsDir = path.join(getSnapshotsPath(), version, zodVersion.folder); describe(`OpenAPI ${version} Zod formats`, () => { const createConfig = createZodConfig({ openApiVersion: version, outputDir, zodVersion, }); const scenarios = [ { config: createConfig({ input: 'zoom-video-sdk.json', output: 'webhooks', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', }, ], }), description: 'webhook schemas', }, { config: createConfig({ input: 'string-with-format.yaml', output: 'string-with-format', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', }, ], }), description: 'generates anyOf string and binary string', }, { config: createConfig({ input: 'string-with-guid-format.yaml', output: 'string-with-guid-format', plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', }, ], }), description: 'handles string guid format', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } ================================================ FILE: packages/openapi-ts-tests/zod/v4/test/openapi.test.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import { createClient } from '@hey-api/openapi-ts'; import { getFilePaths } from '../../../utils'; import { createZodConfig, getSnapshotsPath, getTempSnapshotsPath, zodVersions } from './utils'; const versions = ['2.0.x', '3.0.x', '3.1.x']; for (const version of versions) { for (const zodVersion of zodVersions) { const outputDir = path.join(getTempSnapshotsPath(), version, zodVersion.folder); const snapshotsDir = path.join(getSnapshotsPath(), version, zodVersion.folder); describe(`OpenAPI ${version}`, () => { const createConfig = createZodConfig({ openApiVersion: version, outputDir, zodVersion, }); const scenarios = [ { config: createConfig({ input: 'array-items-all-of.yaml', output: 'array-items-all-of', }), description: 'generates correct array when items use allOf (intersection)', }, { config: createConfig({ input: 'full.yaml', output: 'default', }), description: 'generate Zod schemas with Zod plugin', }, { config: createConfig({ input: 'type-format.yaml', output: 'type-format', plugins: [ '@hey-api/transformers', '@hey-api/client-fetch', { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', }, { name: '@hey-api/sdk', transformer: true, validator: true, }, ], }), description: 'handles various schema types and formats', }, ]; it.each(scenarios)('$description', async ({ config }) => { await createClient(config); const filePaths = getFilePaths(config.output); await Promise.all( filePaths.map(async (filePath) => { const fileContent = fs.readFileSync(filePath, 'utf-8'); await expect(fileContent).toMatchFileSnapshot( path.join(snapshotsDir, filePath.slice(outputDir.length + 1)), ); }), ); }); }); } } ================================================ FILE: packages/openapi-ts-tests/zod/v4/test/utils.ts ================================================ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { type UserConfig } from '@hey-api/openapi-ts'; import { getSpecsPath } from '../../../utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export const createZodConfig = ({ openApiVersion, outputDir, zodVersion, }: { openApiVersion: string; outputDir: string; zodVersion: (typeof zodVersions)[number]; }) => (userConfig: UserConfig) => { const input = userConfig.input instanceof Array ? userConfig.input[0]! : userConfig.input; const inputPath = path.join( getSpecsPath(), openApiVersion, typeof input === 'string' ? input : (input.path as string), ); return { plugins: [ { compatibilityVersion: zodVersion.compatibilityVersion, name: 'zod', }, ], ...userConfig, input: typeof userConfig.input === 'string' ? inputPath : { ...userConfig.input, path: inputPath, }, logs: { level: 'silent', path: './logs', }, output: path.join(outputDir, typeof userConfig.output === 'string' ? userConfig.output : ''), } as const satisfies UserConfig; }; export const getSnapshotsPath = (): string => path.join(__dirname, '..', '__snapshots__'); export const getTempSnapshotsPath = (): string => path.join(__dirname, '..', '.gen', 'snapshots'); export const zodVersions = [ { compatibilityVersion: 3, folder: 'v3', }, { compatibilityVersion: 4, folder: 'v4', }, { compatibilityVersion: 'mini', folder: 'mini', }, ] as const; ================================================ FILE: packages/openapi-ts-tests/zod/v4/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["test/**/*", "__snapshots__/**/*"], "exclude": [".gen/**/*"], "references": [{ "path": "../../../openapi-ts" }] } ================================================ FILE: packages/openapi-ts-tests/zod/v4/turbo.json ================================================ { "$schema": "../../../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/openapi-ts-tests/zod/v4/vitest.setup.ts ================================================ import { fileURLToPath } from 'node:url'; import { beforeAll } from 'vitest'; beforeAll(() => { process.chdir(fileURLToPath(new URL('.', import.meta.url))); }); ================================================ FILE: packages/shared/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen ================================================ FILE: packages/shared/CHANGELOG.md ================================================ # @hey-api/shared ## 0.2.5 ### Patch Changes - **output**: pass context as second argument in `module.resolve()` function ([#3615](https://github.com/hey-api/openapi-ts/pull/3615)) ([`b6a65d6`](https://github.com/hey-api/openapi-ts/commit/b6a65d6bb3ff1895f2189af858e3424733154bdf)) by [@mrlubos](https://github.com/mrlubos) - **parser**: fix: self-referencing discriminator ([#3601](https://github.com/hey-api/openapi-ts/pull/3601)) ([`857eb19`](https://github.com/hey-api/openapi-ts/commit/857eb1983fa1ab0f048d426a31835ede563a2c00)) by [@pgraug](https://github.com/pgraug) - **output**: add `module` option ([#3616](https://github.com/hey-api/openapi-ts/pull/3616)) ([`e4eea23`](https://github.com/hey-api/openapi-ts/commit/e4eea23ab23fb704dfdb9aaad63989be34d5093c)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.7.4 ## 0.2.4 ### Patch Changes - **utils**: `outputHeaderToPrefix()` function signature change ([#3585](https://github.com/hey-api/openapi-ts/pull/3585)) ([`c076e4d`](https://github.com/hey-api/openapi-ts/commit/c076e4d3e9697d8bbc72db13a31d44627c814c2d)) by [@mrlubos](https://github.com/mrlubos) - **internal**: remove TypeScript from peer dependencies ([#3566](https://github.com/hey-api/openapi-ts/pull/3566)) ([`b5f1e4b`](https://github.com/hey-api/openapi-ts/commit/b5f1e4b5f64cbf0bad2eff888177ac9c1881ba3e)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.7.3 - @hey-api/types@0.1.4 ## 0.2.3 ### Patch Changes - **cli**: export isEnvironment function ([#3546](https://github.com/hey-api/openapi-ts/pull/3546)) ([`571bc8a`](https://github.com/hey-api/openapi-ts/commit/571bc8a32b55647083bb506d4a5b575c4736cb94)) by [@mrlubos](https://github.com/mrlubos) - **internal**: export more IR types ([#3513](https://github.com/hey-api/openapi-ts/pull/3513)) ([`ffe68cd`](https://github.com/hey-api/openapi-ts/commit/ffe68cd4303c39e71152f36c2057165468e64308)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: add `getName()` symbol hook ([#3556](https://github.com/hey-api/openapi-ts/pull/3556)) ([`68c750a`](https://github.com/hey-api/openapi-ts/commit/68c750ab7ad37c71c4f9b267ddc9e1c90c89924a)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.7.2 ## 0.2.2 ### Patch Changes - **output**: context file is optional ([#3486](https://github.com/hey-api/openapi-ts/pull/3486)) ([`942913a`](https://github.com/hey-api/openapi-ts/commit/942913af15ae10c5fc3c5e456800829b7dd9c10a)) by [@mrlubos](https://github.com/mrlubos) - **parser**: fix: explicit discriminator mapping wins over fallback in nested `allOf` ([#3490](https://github.com/hey-api/openapi-ts/pull/3490)) ([`a67d589`](https://github.com/hey-api/openapi-ts/commit/a67d589e1f8e5860bd05d5caff134dd6a7eed6e2)) by [@pgraug](https://github.com/pgraug) ### Updated Dependencies: - @hey-api/codegen-core@0.7.1 ## 0.2.1 ### Patch Changes - **internal**: export schema walker interfaces ([#3396](https://github.com/hey-api/openapi-ts/pull/3396)) ([`ea6f386`](https://github.com/hey-api/openapi-ts/commit/ea6f3865c8e381b3160e1526435c4522f0dc6aa4)) by [@mrlubos](https://github.com/mrlubos) - **parser(patch)**: support callback for `patch.schemas` ([#3415](https://github.com/hey-api/openapi-ts/pull/3415)) ([`e494f4d`](https://github.com/hey-api/openapi-ts/commit/e494f4dd828167a0096a0a488b222a013f911055)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: handle OpenAPI 3.1 `contentMediaType` keyword as binary format when file-like ([#3431](https://github.com/hey-api/openapi-ts/pull/3431)) ([`d6a8538`](https://github.com/hey-api/openapi-ts/commit/d6a85381e3c52b4fd1c4af43ee57506459db7a45)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **input**: fix: improve returned status code when spec fetch fails ([#3427](https://github.com/hey-api/openapi-ts/pull/3427)) ([`37dd92c`](https://github.com/hey-api/openapi-ts/commit/37dd92c6629511860ae434c64ac8af9154ed6aed)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: add `patch.input` and shorthand `patch()` option for full specification transformations ([#3411](https://github.com/hey-api/openapi-ts/pull/3411)) ([`ba9f893`](https://github.com/hey-api/openapi-ts/commit/ba9f893d71b959721e177717ae85fce34d697002)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: fix: preserve `unevaluatedProperties` keyword in transforms ([#3435](https://github.com/hey-api/openapi-ts/pull/3435)) ([`f659b38`](https://github.com/hey-api/openapi-ts/commit/f659b38701795d2c2b61c8d3f5c43af93893481a)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser(transforms)**: add `schemaName` transform ([#3416](https://github.com/hey-api/openapi-ts/pull/3416)) ([`4b9d032`](https://github.com/hey-api/openapi-ts/commit/4b9d032c6a144fa79cedc28e077782b9d67803a3)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser(patch)**: support callback for `patch.operations` ([#3420](https://github.com/hey-api/openapi-ts/pull/3420)) ([`e1cd970`](https://github.com/hey-api/openapi-ts/commit/e1cd970e4f3028b29ace44a58b2d2cae18a6c45f)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) - **parser**: add support for non-string discriminator property types ([#3385](https://github.com/hey-api/openapi-ts/pull/3385)) ([`dd0be9c`](https://github.com/hey-api/openapi-ts/commit/dd0be9c6ca93552c3367ca8e8ba785381295a112)) by [@SipanP](https://github.com/SipanP) ### Updated Dependencies: - @hey-api/json-schema-ref-parser@1.3.1 ## 0.2.0 ### Minor Changes - **utils**: rename `isTopLevelComponentRef` to `isTopLevelComponent` ([#3370](https://github.com/hey-api/openapi-ts/pull/3370)) ([`27cd91f`](https://github.com/hey-api/openapi-ts/commit/27cd91f530bd77da6ea95df1704b2947917b4626)) by [@mrlubos](https://github.com/mrlubos) ### Patch Changes ### Updated Dependencies: - @hey-api/json-schema-ref-parser@1.3.0 ## 0.1.2 ### Patch Changes - **parser**: add `getExportFromFilePath()` hook ([#3322](https://github.com/hey-api/openapi-ts/pull/3322)) ([`bfd43ec`](https://github.com/hey-api/openapi-ts/commit/bfd43ec6d638bfc97b6905dd9dee2c911ccea3e0)) by [@mrlubos](https://github.com/mrlubos) - **config**: `includeInEntry` accepts function in addition to primitive value ([#3322](https://github.com/hey-api/openapi-ts/pull/3322)) ([`bfd43ec`](https://github.com/hey-api/openapi-ts/commit/bfd43ec6d638bfc97b6905dd9dee2c911ccea3e0)) by [@mrlubos](https://github.com/mrlubos) - **transform(read-write)**: improve discriminated schemas split ([#3322](https://github.com/hey-api/openapi-ts/pull/3322)) ([`bfd43ec`](https://github.com/hey-api/openapi-ts/commit/bfd43ec6d638bfc97b6905dd9dee2c911ccea3e0)) by [@mrlubos](https://github.com/mrlubos) ### Updated Dependencies: - @hey-api/codegen-core@0.7.0 ## 0.1.1 ### Patch Changes ### Updated Dependencies: - @hey-api/codegen-core@0.6.1 ## 0.1.0 ### Minor Changes - **feat**: initial release ([#3251](https://github.com/hey-api/openapi-ts/pull/3251)) ([`7f19d59`](https://github.com/hey-api/openapi-ts/commit/7f19d5921dadfa96ecae84a5298b7aee1daee56d)) by [@mrlubos](https://github.com/mrlubos) ### Patch Changes ### Updated Dependencies: - @hey-api/codegen-core@0.6.0 - @hey-api/types@0.1.3 ================================================ FILE: packages/shared/LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/shared/package.json ================================================ { "name": "@hey-api/shared", "version": "0.2.5", "description": "Temporary home for cross-package utilities. Contents will migrate to proper packages as architecture stabilizes.", "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "files": [ "dist", "LICENSE.md", "README.md" ], "type": "module", "main": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "types": "./dist/index.d.mts", "import": "./dist/index.mjs" }, "./package.json": "./package.json" }, "scripts": { "build": "tsdown && pnpm check-exports", "check-exports": "attw --pack . --profile esm-only --ignore-rules cjs-resolves-to-esm", "dev": "tsdown --watch", "prepublishOnly": "pnpm build", "typecheck": "tsgo --noEmit" }, "dependencies": { "@hey-api/codegen-core": "workspace:*", "@hey-api/json-schema-ref-parser": "workspace:*", "@hey-api/types": "workspace:*", "ansi-colors": "4.1.3", "cross-spawn": "7.0.6", "open": "11.0.0", "semver": "7.7.3" }, "devDependencies": { "@types/bun": "1.3.8", "@types/cross-spawn": "6.0.6", "@types/semver": "7.7.1", "eslint": "9.39.1", "typescript": "5.9.3", "yaml": "2.8.2" }, "engines": { "node": ">=20.19.0" } } ================================================ FILE: packages/shared/src/__tests__/cli.test.ts ================================================ import { isEnvironment } from '../cli'; /** * Replicates the outputHeaderToPrefix logic from generate/client.ts for testing. */ function outputHeaderToPrefix(header: unknown): string { if (header == null || typeof header === 'function') return ''; const lines = typeof header === 'string' ? header.split(/\r?\n/) : (header as string[]).flatMap((line) => line.split(/\r?\n/)); const content = lines.join('\n'); return content ? `${content}\n\n` : ''; } describe('outputHeaderToPrefix logic', () => { it('returns default comment for string header', () => { const result = outputHeaderToPrefix('// This file is auto-generated by @hey-api/openapi-ts'); expect(result).toBe('// This file is auto-generated by @hey-api/openapi-ts\n\n'); }); it('returns joined lines for array header', () => { const result = outputHeaderToPrefix([ '// This file is auto-generated by @hey-api/openapi-ts', '// @ts-nocheck', ]); expect(result).toBe( '// This file is auto-generated by @hey-api/openapi-ts\n// @ts-nocheck\n\n', ); }); it('returns empty string for null header', () => { expect(outputHeaderToPrefix(null)).toBe(''); }); it('returns empty string for undefined header', () => { expect(outputHeaderToPrefix(undefined)).toBe(''); }); it('returns empty string for function header', () => { expect(outputHeaderToPrefix(() => '// dynamic')).toBe(''); }); it('handles string with embedded newlines', () => { const result = outputHeaderToPrefix('// line1\n// line2'); expect(result).toBe('// line1\n// line2\n\n'); }); }); describe('isEnvironment', () => { const originalEnv = process.env; beforeEach(() => { process.env = { ...originalEnv }; delete process.env.HEYAPI_CODEGEN_ENV; }); afterAll(() => { process.env = originalEnv; }); it('returns false when env var is not set', () => { expect(isEnvironment('development')).toBe(false); }); it('returns true when env var is set to "development"', () => { process.env.HEYAPI_CODEGEN_ENV = 'development'; expect(isEnvironment('development')).toBe(true); }); it('returns false when env var is set to other values', () => { process.env.HEYAPI_CODEGEN_ENV = '0'; expect(isEnvironment('development')).toBe(false); process.env.HEYAPI_CODEGEN_ENV = 'false'; expect(isEnvironment('development')).toBe(false); process.env.HEYAPI_CODEGEN_ENV = 'anything'; expect(isEnvironment('development')).toBe(false); }); }); ================================================ FILE: packages/shared/src/__tests__/error.test.ts ================================================ import { shouldReportCrash } from '../error'; describe('shouldReportCrash', () => { it('should return false when isInteractive is false', async () => { const result = await shouldReportCrash({ error: new Error('test error'), isInteractive: false, }); expect(result).toBe(false); }); it('should return false when isInteractive is undefined', async () => { const result = await shouldReportCrash({ error: new Error('test error'), isInteractive: undefined, }); expect(result).toBe(false); }); it('should not prompt when isInteractive is explicitly false', async () => { // Mock stdin and console.log to ensure we don't wait for user input const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined); const setEncodingSpy = vi .spyOn(process.stdin, 'setEncoding') .mockImplementation(() => process.stdin as any); const onceSpy = vi.spyOn(process.stdin, 'once').mockImplementation(() => process.stdin); const result = await shouldReportCrash({ error: new Error('test error'), isInteractive: false, }); expect(result).toBe(false); expect(logSpy).not.toHaveBeenCalled(); expect(setEncodingSpy).not.toHaveBeenCalled(); expect(onceSpy).not.toHaveBeenCalled(); logSpy.mockRestore(); setEncodingSpy.mockRestore(); onceSpy.mockRestore(); }); it('should prompt when isInteractive is true', async () => { // Mock stdin and console.log for interactive session const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined); const setEncodingSpy = vi .spyOn(process.stdin, 'setEncoding') .mockImplementation(() => process.stdin as any); const onceSpy = vi.spyOn(process.stdin, 'once').mockImplementation((_event, callback) => { // Simulate user typing 'n' setTimeout(() => { (callback as any)('n'); }, 0); return process.stdin; }); const result = await shouldReportCrash({ error: new Error('test error'), isInteractive: true, }); expect(result).toBe(false); // User said 'n' expect(logSpy).toHaveBeenCalledWith( expect.stringContaining('📢 Open a GitHub issue with crash details?'), ); logSpy.mockRestore(); setEncodingSpy.mockRestore(); onceSpy.mockRestore(); }); it('should handle user saying yes to crash report', async () => { // Mock stdin and console.log for interactive session const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined); const setEncodingSpy = vi .spyOn(process.stdin, 'setEncoding') .mockImplementation(() => process.stdin as any); const onceSpy = vi.spyOn(process.stdin, 'once').mockImplementation((_event, callback) => { // Simulate user typing 'y' setTimeout(() => { (callback as any)('y'); }, 0); return process.stdin; }); const result = await shouldReportCrash({ error: new Error('test error'), isInteractive: true, }); expect(result).toBe(true); // User said 'y' logSpy.mockRestore(); setEncodingSpy.mockRestore(); onceSpy.mockRestore(); }); }); ================================================ FILE: packages/shared/src/__tests__/getSpec.test.ts ================================================ import * as refParser from '@hey-api/json-schema-ref-parser'; import { getSpec } from '../getSpec'; vi.mock('@hey-api/json-schema-ref-parser', () => ({ getResolvedInput: vi.fn(({ pathOrUrlOrSchema }: { pathOrUrlOrSchema: string }) => ({ path: pathOrUrlOrSchema, schema: undefined, type: 'url', })), sendRequest: vi.fn(), })); const mockSendRequest = vi.mocked(refParser.sendRequest); describe('getSpec', () => { beforeEach(() => { vi.clearAllMocks(); }); describe('URL input', () => { it('returns error with status 500 and error message when GET request throws an exception', async () => { mockSendRequest.mockRejectedValueOnce(new Error('fetch failed')); const result = await getSpec({ fetchOptions: undefined, inputPath: 'http://example.com/openapi.json', timeout: undefined, watch: { headers: new Headers() }, }); expect(result.error).toBe('not-ok'); expect(result.response!.status).toBe(500); expect(await result.response!.text()).toBe('fetch failed'); }); it('returns error with status 500 and string message when non-Error is thrown during GET request', async () => { mockSendRequest.mockRejectedValueOnce('network unavailable'); const result = await getSpec({ fetchOptions: undefined, inputPath: 'http://example.com/openapi.json', timeout: undefined, watch: { headers: new Headers() }, }); expect(result.error).toBe('not-ok'); expect(result.response!.status).toBe(500); expect(await result.response!.text()).toBe('network unavailable'); }); it('returns error when GET response has status >= 300', async () => { mockSendRequest.mockResolvedValueOnce({ response: new Response(null, { status: 404, statusText: 'Not Found' }), }); const result = await getSpec({ fetchOptions: undefined, inputPath: 'http://example.com/openapi.json', timeout: undefined, watch: { headers: new Headers() }, }); expect(result.error).toBe('not-ok'); expect(result.response!.status).toBe(404); }); it('returns error with status 500 and error message when HEAD request throws an exception', async () => { mockSendRequest.mockRejectedValueOnce(new Error('connection refused')); const result = await getSpec({ fetchOptions: undefined, inputPath: 'http://example.com/openapi.json', timeout: undefined, watch: { headers: new Headers(), isHeadMethodSupported: true, lastValue: 'previous' }, }); expect(result.error).toBe('not-ok'); expect(result.response!.status).toBe(500); expect(await result.response!.text()).toBe('connection refused'); }); it('returns arrayBuffer on successful GET', async () => { const content = '{"openapi":"3.0.0"}'; const encoder = new TextEncoder(); const buffer = encoder.encode(content).buffer as ArrayBuffer; mockSendRequest.mockResolvedValueOnce({ response: new Response(buffer, { status: 200 }), }); const result = await getSpec({ fetchOptions: undefined, inputPath: 'http://example.com/openapi.json', timeout: undefined, watch: { headers: new Headers() }, }); expect(result.error).toBeUndefined(); expect(result.arrayBuffer).toBeDefined(); }); }); }); ================================================ FILE: packages/shared/src/cli.ts ================================================ import colors from 'ansi-colors'; import { loadPackageJson } from './tsConfig'; const textAscii = ` 888 | e 888~-_ 888 888___| e88~~8e Y88b / d8b 888 \\ 888 888 | d888 88b Y888/ /Y88b 888 | 888 888 | 8888__888 Y8/ / Y88b 888 / 888 888 | Y888 , Y /____Y88b 888_-~ 888 888 | "88___/ / / Y88b 888 888 _/ `; const asciiToLines = ( ascii: string, options?: { padding?: number; }, ) => { const lines: Array = []; const padding = Array.from({ length: options?.padding ?? 0 }).fill(''); lines.push(...padding); let maxLineLength = 0; let line = ''; for (const char of ascii) { if (char === '\n') { if (line) { lines.push(line); maxLineLength = Math.max(maxLineLength, line.length); line = ''; } } else { line += char; } } lines.push(...padding); return { lines, maxLineLength }; }; /** * Checks the current environment based on the HEYAPI_CODEGEN_ENV environment variable. */ export function isEnvironment(value: 'development'): boolean { return process.env.HEYAPI_CODEGEN_ENV === value; } // TODO: show ascii logo only in `--help` and `--version` commands export function printCliIntro(initialDir: string, showLogo: boolean = false): void { const packageJson = loadPackageJson(initialDir); if (packageJson) { if (showLogo) { const text = asciiToLines(textAscii, { padding: 1 }); for (const line of text.lines) { console.log(colors.cyan(line)); } } const versionString = isEnvironment('development') ? '[DEVELOPMENT]' : `v${packageJson.version}`; console.log(colors.gray(`${packageJson.name} ${versionString}`)); } console.log(''); } ================================================ FILE: packages/shared/src/config/engine.ts ================================================ import { ConfigError } from '../error'; export function checkNodeVersion(): void { if (typeof Bun !== 'undefined') { const [major] = Bun.version.split('.').map(Number); if (major! < 1) { throw new ConfigError( `Unsupported Bun version ${Bun.version}. Please use Bun 1.0.0 or newer.`, ); } } else if (typeof process !== 'undefined' && process.versions?.node) { const [major] = process.versions.node.split('.').map(Number); if (major! < 20) { throw new ConfigError( `Unsupported Node version ${process.versions.node}. Please use Node 20 or newer.`, ); } } } ================================================ FILE: packages/shared/src/config/input/__tests__/input.test.ts ================================================ import type { MaybeArray } from '@hey-api/types'; import { getInput } from '../input'; import type { UserInput, UserWatch } from '../types'; type UserConfig = { input: MaybeArray['path']>; watch?: UserWatch; }; describe('input config', () => { describe('getInput', () => { it('should handle string input', () => { const userConfig: UserConfig = { input: 'https://example.com/openapi.yaml', }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://example.com/openapi.yaml'); }); it('should transform ReadMe simple format input', () => { const userConfig: UserConfig = { input: 'readme:abc123', }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://dash.readme.com/api/v1/api-registry/abc123'); }); it('should transform ReadMe full format input', () => { const userConfig: UserConfig = { input: 'readme:@myorg/myproject#uuid123', }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://dash.readme.com/api/v1/api-registry/uuid123'); }); it('should handle ReadMe input with hyphens', () => { const userConfig: UserConfig = { input: 'readme:@my-org/my-project#test-uuid-123', }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://dash.readme.com/api/v1/api-registry/test-uuid-123'); }); it('should handle object input with ReadMe path', () => { const userConfig: UserConfig = { input: { fetch: { headers: { Authorization: 'Bearer token', }, }, path: 'readme:abc123', }, }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://dash.readme.com/api/v1/api-registry/abc123'); }); it('should handle object input with ReadMe full format path', () => { const userConfig: UserConfig = { input: { path: 'readme:@org/project#uuid', watch: true, }, }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://dash.readme.com/api/v1/api-registry/uuid'); expect(result.watch.enabled).toBe(true); }); it('should handle HeyAPI input format (existing functionality)', () => { const userConfig: UserConfig = { input: { organization: 'myorg', project: 'myproject', }, }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://get.heyapi.dev/myorg/myproject'); }); it('should handle object input (existing functionality)', () => { const userConfig: UserConfig = { input: { info: { title: 'Test API', version: '1.0.0' }, openapi: '3.0.0', }, }; const result = getInput(userConfig)[0]!; expect(result.path).toEqual({ info: { title: 'Test API', version: '1.0.0' }, openapi: '3.0.0', }); }); it('should not transform non-ReadMe string inputs', () => { const inputs = [ 'https://example.com/openapi.yaml', './local-file.yaml', '/absolute/path/to/file.json', 'file.yaml', ]; inputs.forEach((input) => { const userConfig: UserConfig = { input }; const result = getInput(userConfig)[0]!; expect(result.path).toBe(input); }); }); it('should handle watch options with ReadMe inputs', () => { const userConfig: UserConfig = { input: 'readme:abc123', watch: { enabled: true, interval: 2000, }, }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://dash.readme.com/api/v1/api-registry/abc123'); expect(result.watch.enabled).toBe(true); expect(result.watch.interval).toBe(2000); }); it('should preserve other input object properties when transforming ReadMe path', () => { const userConfig: UserConfig = { input: { fetch: { headers: { 'X-Custom': 'value' }, }, path: 'readme:test123', watch: { enabled: true, interval: 1500 }, }, }; const result = getInput(userConfig)[0]!; expect(result.path).toBe('https://dash.readme.com/api/v1/api-registry/test123'); // Note: fetch options are preserved in the input object, not in the result // The watch options should be processed separately expect(result.watch.enabled).toBe(true); expect(result.watch.interval).toBe(1500); }); }); describe('error handling', () => { it('should throw error for invalid ReadMe format', () => { const userConfig: UserConfig = { input: 'readme:', }; expect(() => getInput(userConfig)).toThrow('Invalid ReadMe shorthand format'); }); it('should throw error for invalid ReadMe UUID', () => { const userConfig: UserConfig = { input: 'readme:invalid uuid with spaces', }; expect(() => getInput(userConfig)).toThrow('Invalid ReadMe shorthand format'); }); it('should throw error for invalid ReadMe format in object input', () => { const userConfig: UserConfig = { input: { path: 'readme:@org/project', }, }; expect(() => getInput(userConfig)).toThrow('Invalid ReadMe shorthand format'); }); }); }); ================================================ FILE: packages/shared/src/config/input/__tests__/path.test.ts ================================================ import { compileInputPath } from '../path'; describe('compileInputPath', () => { it('with raw OpenAPI specification', () => { const path = compileInputPath({ path: { info: { version: '1.0.0', }, openapi: '3.1.0', }, }); expect(path).toEqual({ path: { info: { version: '1.0.0', }, openapi: '3.1.0', }, }); }); it('with arbitrary string', () => { const path = compileInputPath({ path: 'path/to/openapi.json', }); expect(path).toEqual({ path: 'path/to/openapi.json', }); }); it('with platform string', () => { const path = compileInputPath({ path: 'https://get.heyapi.dev/foo/bar?branch=main&commit_sha=sha&tags=a,b,c&version=1.0.0', registry: 'hey-api', }); expect(path).toEqual({ branch: 'main', commit_sha: 'sha', organization: 'foo', path: 'https://get.heyapi.dev/foo/bar?branch=main&commit_sha=sha&tags=a,b,c&version=1.0.0', project: 'bar', registry: 'hey-api', tags: ['a', 'b', 'c'], version: '1.0.0', }); }); it('with platform arguments', () => { const path = compileInputPath({ branch: 'main', commit_sha: 'sha', organization: 'foo', path: '', project: 'bar', tags: ['a', 'b', 'c'], version: '1.0.0', }); expect(path).toEqual({ branch: 'main', commit_sha: 'sha', organization: 'foo', path: 'https://get.heyapi.dev/foo/bar?branch=main&commit_sha=sha&tags=a,b,c&version=1.0.0', project: 'bar', tags: ['a', 'b', 'c'], version: '1.0.0', }); }); it('loads API key from HEY_API_TOKEN', () => { process.env.HEY_API_TOKEN = 'foo'; const path = compileInputPath({ path: 'https://get.heyapi.dev/foo/bar', registry: 'hey-api', }); delete process.env.HEY_API_TOKEN; expect(path).toEqual({ api_key: 'foo', organization: 'foo', path: 'https://get.heyapi.dev/foo/bar?api_key=foo', project: 'bar', registry: 'hey-api', }); }); }); ================================================ FILE: packages/shared/src/config/input/input.ts ================================================ import type { MaybeArray } from '@hey-api/types'; import { inputToApiRegistry } from '../../utils/input'; import { heyApiRegistryBaseUrl } from '../../utils/input/heyApi'; import type { Input, UserInput, UserWatch, Watch } from './types'; const defaultWatch: Watch = { enabled: false, interval: 1_000, timeout: 60_000, }; // watch only remote files function getWatch(input: Pick): Watch { let watch = { ...defaultWatch }; // we cannot watch spec passed as an object if (typeof input.path !== 'string') { return watch; } if (typeof input.watch === 'boolean') { watch.enabled = input.watch; } else if (typeof input.watch === 'number') { watch.enabled = true; watch.interval = input.watch; } else if (input.watch) { watch = { ...watch, ...input.watch, }; } return watch; } export function getInput(userConfig: { input: MaybeArray['path']>; watch?: UserWatch; }): ReadonlyArray { const userInputs = userConfig.input instanceof Array ? userConfig.input : [userConfig.input]; const inputs: Array = []; for (const userInput of userInputs) { let input: Input = { path: '', watch: defaultWatch, }; if (typeof userInput === 'string') { input.path = userInput; } else if ( userInput && (userInput.path !== undefined || userInput.organization !== undefined) ) { // @ts-expect-error input = { ...input, path: heyApiRegistryBaseUrl, ...userInput, }; if (input.watch !== undefined) { input.watch = getWatch(input); } } else { input = { ...input, path: userInput, }; } if (typeof input.path === 'string') { inputToApiRegistry(input as Input & { path: string }); } if ( userConfig.watch !== undefined && input.watch.enabled === defaultWatch.enabled && input.watch.interval === defaultWatch.interval && input.watch.timeout === defaultWatch.timeout ) { input.watch = getWatch({ path: input.path, // @ts-expect-error watch: userConfig.watch, }); } if (input.path) { inputs.push(input); } } return inputs; } ================================================ FILE: packages/shared/src/config/input/path.ts ================================================ import colors from 'ansi-colors'; import type { Input } from './types'; export function compileInputPath(input: Omit) { const result: Pick< Partial, | 'api_key' | 'branch' | 'commit_sha' | 'organization' | 'project' | 'registry' | 'tags' | 'version' > & Pick = { ...input, path: '', }; if (input.path && (typeof input.path !== 'string' || input.registry !== 'hey-api')) { result.path = input.path; return result; } const [basePath, baseQuery] = input.path.split('?'); const queryParts = (baseQuery || '').split('&'); const queryPath = queryParts.map((part) => part.split('=')); let path = basePath || ''; if (path.endsWith('/')) { path = path.slice(0, path.length - 1); } const [, pathUrl] = path.split('://'); const [baseUrl, organization, project] = (pathUrl || '').split('/'); result.organization = organization || input.organization; result.project = project || input.project; const queryParams: Array = []; const kApiKey = 'api_key'; result.api_key = queryPath.find(([key]) => key === kApiKey)?.[1] || input.api_key || process.env.HEY_API_TOKEN; if (result.api_key) { queryParams.push(`${kApiKey}=${result.api_key}`); } const kBranch = 'branch'; result.branch = queryPath.find(([key]) => key === kBranch)?.[1] || input.branch; if (result.branch) { queryParams.push(`${kBranch}=${result.branch}`); } const kCommitSha = 'commit_sha'; result.commit_sha = queryPath.find(([key]) => key === kCommitSha)?.[1] || input.commit_sha; if (result.commit_sha) { queryParams.push(`${kCommitSha}=${result.commit_sha}`); } const kTags = 'tags'; result.tags = queryPath.find(([key]) => key === kTags)?.[1]?.split(',') || input.tags; if (result.tags?.length) { queryParams.push(`${kTags}=${result.tags.join(',')}`); } const kVersion = 'version'; result.version = queryPath.find(([key]) => key === kVersion)?.[1] || input.version; if (result.version) { queryParams.push(`${kVersion}=${result.version}`); } if (!result.organization) { throw new Error( 'missing organization - from which Hey API Platform organization do you want to generate your output?', ); } if (!result.project) { throw new Error( 'missing project - from which Hey API Platform project do you want to generate your output?', ); } const query = queryParams.join('&'); const platformUrl = baseUrl || 'get.heyapi.dev'; const isLocalhost = platformUrl.startsWith('localhost'); const platformUrlWithProtocol = [isLocalhost ? 'http' : 'https', platformUrl].join('://'); const compiledPath = isLocalhost ? [platformUrlWithProtocol, 'v1', 'get', result.organization, result.project].join('/') : [platformUrlWithProtocol, result.organization, result.project].join('/'); result.path = query ? `${compiledPath}?${query}` : compiledPath; return result; } export function logInputPaths( inputPaths: ReadonlyArray>, jobIndex: number, ): void { const lines: Array = []; const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `); const count = inputPaths.length; const baseString = colors.cyan(`Generating from ${count} ${count === 1 ? 'input' : 'inputs'}:`); lines.push(`${jobPrefix}⏳ ${baseString}`); inputPaths.forEach((inputPath, index) => { const itemPrefixStr = ` [${index + 1}] `; const itemPrefix = colors.cyan(itemPrefixStr); const detailIndent = ' '.repeat(itemPrefixStr.length); if (typeof inputPath.path !== 'string') { lines.push(`${jobPrefix}${itemPrefix}raw OpenAPI specification`); return; } switch (inputPath.registry) { case 'hey-api': { const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/'); lines.push(`${jobPrefix}${itemPrefix}${baseInput}`); if (inputPath.branch) { lines.push( `${jobPrefix}${detailIndent}${colors.gray('branch:')} ${colors.green( inputPath.branch, )}`, ); } if (inputPath.commit_sha) { lines.push( `${jobPrefix}${detailIndent}${colors.gray('commit:')} ${colors.green( inputPath.commit_sha, )}`, ); } if (inputPath.tags?.length) { lines.push( `${jobPrefix}${detailIndent}${colors.gray('tags:')} ${colors.green( inputPath.tags.join(', '), )}`, ); } if (inputPath.version) { lines.push( `${jobPrefix}${detailIndent}${colors.gray('version:')} ${colors.green( inputPath.version, )}`, ); } lines.push( `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('Hey API')}`, ); break; } case 'readme': { const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/'); if (!baseInput) { lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`); } else { lines.push(`${jobPrefix}${itemPrefix}${baseInput}`); } // @ts-expect-error if (inputPath.uuid) { lines.push( `${jobPrefix}${detailIndent}${colors.gray('uuid:')} ${colors.green( // @ts-expect-error inputPath.uuid, )}`, ); } lines.push( `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('ReadMe')}`, ); break; } case 'scalar': { const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/'); lines.push(`${jobPrefix}${itemPrefix}${baseInput}`); lines.push( `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('Scalar')}`, ); break; } default: lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`); break; } }); for (const line of lines) { console.log(line); } } ================================================ FILE: packages/shared/src/config/input/types.ts ================================================ import type { AnyString } from '@hey-api/types'; type JsonSchema = Record; type ApiRegistryShorthands = | `https://get.heyapi.dev/${string}/${string}` | `${string}/${string}` | `readme:@${string}/${string}#${string}` | `readme:${string}` | `scalar:@${string}/${string}`; export type UserInput = { /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Projects are private by default, you will need to be authenticated * to download OpenAPI specifications. We recommend using project API * keys in CI workflows and personal API keys for local development. * * API key isn't required for public projects. You can also omit this * parameter and provide an environment variable `HEY_API_TOKEN`. */ api_key?: string; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * You can fetch the last build from branch by providing the branch * name. */ branch?: string; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * You can fetch an exact specification by providing a commit sha. * This will always return the same file. */ commit_sha?: string; /** * You can pass any valid Fetch API options to the request for fetching your * specification. This is useful if your file is behind auth for example. */ fetch?: RequestInit; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Organization created in Hey API Platform. */ organization?: string; /** * Path to the OpenAPI specification. This can be: * - path * - URL * - API registry shorthand * * Both JSON and YAML file formats are supported. You can also pass the parsed * object directly if you're fetching the file yourself. */ path?: ApiRegistryShorthands | AnyString | JsonSchema; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Project created in Hey API Platform. */ project?: string; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * If you're tagging your specifications with custom tags, you can use * them to filter the results. When you provide multiple tags, only * the first match will be returned. */ tags?: ReadonlyArray; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Every OpenAPI document contains a required version field. You can * use this value to fetch the last uploaded specification matching * the value. */ version?: string; /** * Regenerate the client when the input file changes? You can alternatively * pass a numeric value for the interval in ms. * * @default false */ watch?: UserWatch; }; export type Input = { /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Projects are private by default, you will need to be authenticated * to download OpenAPI specifications. We recommend using project API * keys in CI workflows and personal API keys for local development. * * API key isn't required for public projects. You can also omit this * parameter and provide an environment variable `HEY_API_TOKEN`. */ api_key?: string; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * You can fetch the last build from branch by providing the branch * name. */ branch?: string; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * You can fetch an exact specification by providing a commit sha. * This will always return the same file. */ commit_sha?: string; /** * You can pass any valid Fetch API options to the request for fetching your * specification. This is useful if your file is behind auth for example. */ fetch?: RequestInit; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Organization created in Hey API Platform. */ organization?: string; /** * Path to the OpenAPI specification. This can be: * - path * - URL * - API registry shorthand * * Both JSON and YAML file formats are supported. You can also pass the parsed * object directly if you're fetching the file yourself. */ path: ApiRegistryShorthands | AnyString | JsonSchema; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Project created in Hey API Platform. */ project?: string; /** * If input path was resolved to a registry, this contains the registry * identifier so we don't need to parse it again. * * @default undefined */ registry?: 'hey-api' | 'readme' | 'scalar'; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * If you're tagging your specifications with custom tags, you can use * them to filter the results. When you provide multiple tags, only * the first match will be returned. */ tags?: ReadonlyArray; /** * **Requires `path` to start with `https://get.heyapi.dev` or be undefined** * * Every OpenAPI document contains a required version field. You can * use this value to fetch the last uploaded specification matching * the value. */ version?: string; /** * Regenerate the client when the input file changes? You can alternatively * pass a numeric value for the interval in ms. */ watch: Watch; }; export type UserWatch = boolean | number | Watch; export type Watch = { /** * Whether this feature is enabled. * * @default false */ enabled?: boolean; /** * How often should we attempt to detect the input file change? (in ms) * * @default 1000 */ interval?: number; /** * How long will we wait before the request times out? * * @default 60_000 */ timeout?: number; }; ================================================ FILE: packages/shared/src/config/logs.ts ================================================ import type { Logs } from '../types/logs'; export function getLogs(userLogs: string | Logs | undefined): Logs { let logs: Logs = { file: true, level: 'info', path: process.cwd(), }; if (typeof userLogs === 'string') { logs.path = userLogs; } else { logs = { ...logs, ...userLogs, }; } return logs; } ================================================ FILE: packages/shared/src/config/output/postprocess.ts ================================================ import colors from 'ansi-colors'; import { sync } from 'cross-spawn'; type Output = { /** * The absolute path to the output folder. */ path: string; /** * Post-processing commands to run on the output folder, executed in order. */ postProcess: ReadonlyArray; }; export type UserPostProcessor = { /** * Arguments to pass to the command. Use `{{path}}` as a placeholder * for the output directory path. * * @example ['format', '--write', '{{path}}'] */ args: ReadonlyArray; /** * The command to run (e.g., 'biome', 'prettier', 'eslint'). */ command: string; /** * Display name for logging. Defaults to the command name. */ name?: string; }; export type PostProcessor = { /** * Arguments to pass to the command. */ args: ReadonlyArray; /** * The command to run. */ command: string; /** * Display name for logging. */ name: string; }; export function postprocessOutput( config: Output, postProcessors: Record, jobPrefix: string, ): void { for (const processor of config.postProcess) { const resolved = typeof processor === 'string' ? postProcessors[processor] : processor; // TODO: show warning if (!resolved) continue; const name = resolved.name ?? resolved.command; const args = resolved.args.map((arg) => arg.replace('{{path}}', config.path)); console.log(`${jobPrefix}🧹 Running ${colors.cyanBright(name)}`); sync(resolved.command, args); } } ================================================ FILE: packages/shared/src/config/output/source/config.ts ================================================ import { valueToObject } from '../../utils/config'; import type { SourceConfig, UserSourceConfig } from './types'; export function resolveSource(config: { source?: boolean | UserSourceConfig }): SourceConfig { const source = valueToObject({ defaultValue: { enabled: Boolean(config.source), extension: 'json', fileName: 'source', serialize: (input) => JSON.stringify(input, null, 2), }, mappers: { boolean: (enabled) => ({ enabled }), }, value: config.source, }); if (source.path === undefined || source.path === true) { source.path = ''; } else if (source.path === false) { source.path = null; } return source as SourceConfig; } ================================================ FILE: packages/shared/src/config/output/source/types.ts ================================================ import type { MaybePromise } from '@hey-api/types'; import type { FeatureToggle } from '../../shared'; // TODO: json-schema-ref-parser needs to expose source extension so // we can default to it type SourceExtension = 'json'; // type SourceExtension = 'json' | 'yaml'; export type UserSourceConfig = { /** * Callback invoked with the serialized source string. * * Runs after the `serialize` function. * * @example * source => console.log(source) */ callback?: (source: string) => MaybePromise; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; // * Only `'json'` and `'yaml'` are allowed. /** * File extension for the source file. * * @default 'json' */ extension?: SourceExtension; /** * Base file name for the source file. * * The extension from `extension` will be appended automatically. * * @default 'source' */ fileName?: string; /** * Target location for the source file. * * - `true` / `undefined` → write to output root (default) * - `string` → relative to output root or absolute path * - `false` / `null` → do not write * * @default true */ path?: boolean | string | null; /** * Function to serialize the input object into a string. * * @default * JSON.stringify(input, null, 2) * * @example * input => JSON.stringify(input, null, 0) // minified */ serialize?: (input: Record) => MaybePromise; }; export type SourceConfig = FeatureToggle & { /** * Callback invoked with the serialized source string. * * Runs after the `serialize` function. */ callback?: (source: string) => MaybePromise; /** * File extension for the source file. */ extension: SourceExtension; /** * Base file name for the source file. */ fileName: string; /** * Target location for the source file. */ path: string | null; /** * Function to serialize the input object into a string. */ serialize: (input: Record) => MaybePromise; }; ================================================ FILE: packages/shared/src/config/output/types.ts ================================================ import type { RenderContext } from '@hey-api/codegen-core'; import type { MaybeArray, MaybeFunc } from '@hey-api/types'; export type OutputHeader = MaybeFunc< ( ctx: Pick & Pick, 'file'> & { /** The default header value. */ defaultValue: ReadonlyArray; }, ) => MaybeArray | null | undefined >; ================================================ FILE: packages/shared/src/config/parser/config.ts ================================================ import { valueToObject } from '../utils/config'; import type { Parser, UserParser } from './types'; export const defaultPaginationKeywords = [ 'after', 'before', 'cursor', 'offset', 'page', 'start', ] as const; export function getParser(userConfig: { parser?: UserParser }): Parser { const parser = valueToObject({ defaultValue: { hooks: {}, pagination: { keywords: defaultPaginationKeywords, }, transforms: { enums: { case: 'PascalCase', enabled: false, mode: 'root', name: '{{name}}Enum', }, propertiesRequiredByDefault: false, readWrite: { enabled: true, requests: { case: 'preserve', name: '{{name}}Writable', }, responses: { case: 'preserve', name: '{{name}}', }, }, schemaName: undefined, }, validate_EXPERIMENTAL: false, }, mappers: { object: (fields, defaultValue) => ({ ...fields, pagination: valueToObject({ defaultValue: { ...(defaultValue.pagination as Extract< typeof defaultValue.pagination, Record >), }, value: fields.pagination, }), transforms: valueToObject({ defaultValue: { ...(defaultValue.transforms as Extract< typeof defaultValue.transforms, Record >), }, mappers: { object: (fields, defaultValue) => ({ ...fields, enums: valueToObject({ defaultValue: { ...(defaultValue.enums as Extract< typeof defaultValue.enums, Record >), enabled: fields.enums !== undefined ? Boolean(fields.enums) : ( defaultValue.enums as Extract< typeof defaultValue.enums, Record > ).enabled, }, mappers: { boolean: (enabled) => ({ enabled }), string: (mode) => ({ mode }), }, value: fields.enums, }), propertiesRequiredByDefault: fields.propertiesRequiredByDefault !== undefined ? fields.propertiesRequiredByDefault : defaultValue.propertiesRequiredByDefault, readWrite: valueToObject({ defaultValue: { ...(defaultValue.readWrite as Extract< typeof defaultValue.readWrite, Record >), enabled: fields.readWrite !== undefined ? Boolean(fields.readWrite) : ( defaultValue.readWrite as Extract< typeof defaultValue.readWrite, Record > ).enabled, }, mappers: { boolean: (enabled) => ({ enabled }), object: (fields, defaultValue) => ({ ...fields, requests: valueToObject({ defaultValue: { ...(defaultValue.requests as Extract< typeof defaultValue.requests, Record >), }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: fields.requests, }), responses: valueToObject({ defaultValue: { ...(defaultValue.responses as Extract< typeof defaultValue.responses, Record >), }, mappers: { function: (name) => ({ name }), string: (name) => ({ name }), }, value: fields.responses, }), }), }, value: fields.readWrite, }), schemaName: fields.schemaName !== undefined ? fields.schemaName : defaultValue.schemaName, }), }, value: fields.transforms, }), validate_EXPERIMENTAL: fields.validate_EXPERIMENTAL === true ? 'warn' : fields.validate_EXPERIMENTAL, }), }, value: userConfig.parser, }); return parser as Parser; } ================================================ FILE: packages/shared/src/config/parser/filters.ts ================================================ export type Filters = { /** * Include deprecated resources in the output? * * @default true */ deprecated?: boolean; operations?: { /** * Prevent operations matching the `exclude` filters from being processed. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['GET /api/v1/foo'] */ exclude?: ReadonlyArray; /** * Process only operations matching the `include` filters. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['GET /api/v1/foo'] */ include?: ReadonlyArray; }; /** * Keep reusable components without any references from operations in the * output? By default, we exclude orphaned resources. * * @default false */ orphans?: boolean; parameters?: { /** * Prevent parameters matching the `exclude` filters from being processed. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['QueryParam'] */ exclude?: ReadonlyArray; /** * Process only parameters matching the `include` filters. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['QueryParam'] */ include?: ReadonlyArray; }; /** * Should we preserve the key order when overwriting your input? This * option is disabled by default to improve performance. * * @default false */ preserveOrder?: boolean; requestBodies?: { /** * Prevent request bodies matching the `exclude` filters from being processed. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['Foo'] */ exclude?: ReadonlyArray; /** * Process only request bodies matching the `include` filters. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['Foo'] */ include?: ReadonlyArray; }; responses?: { /** * Prevent responses matching the `exclude` filters from being processed. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['Foo'] */ exclude?: ReadonlyArray; /** * Process only responses matching the `include` filters. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['Foo'] */ include?: ReadonlyArray; }; schemas?: { /** * Prevent schemas matching the `exclude` filters from being processed. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['Foo'] */ exclude?: ReadonlyArray; /** * Process only schemas matching the `include` filters. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['Foo'] */ include?: ReadonlyArray; }; tags?: { /** * Prevent tags matching the `exclude` filters from being processed. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['foo'] */ exclude?: ReadonlyArray; /** * Process only tags matching the `include` filters. * * In case of conflicts, `exclude` takes precedence over `include`. * * @example ['foo'] */ include?: ReadonlyArray; }; }; ================================================ FILE: packages/shared/src/config/parser/patch.ts ================================================ import type { MaybeFunc } from '@hey-api/types'; import type { OpenApi, OpenApiMetaObject, OpenApiOperationObject, OpenApiParameterObject, OpenApiRequestBodyObject, OpenApiResponseObject, OpenApiSchemaObject, } from '../../openApi/types'; export type PatchInputFn = ( spec: OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X, ) => void | Promise; export type Patch = | PatchInputFn | { /** * Patch the raw OpenAPI spec object in place. Called before all other * patch callbacks. Useful for bulk/structural transformations such as * adding new component definitions or modifying many operations at once. * * @param spec The OpenAPI spec object for the current version. * * @example * ```ts * input: (spec) => { * // Create new component parameters * if (!spec.components) spec.components = {}; * if (!spec.components.parameters) spec.components.parameters = {}; * spec.components.parameters.MyParam = { * in: 'query', * name: 'myParam', * schema: { type: 'string' } * }; * * // Inject parameters into operations * for (const [path, pathItem] of Object.entries(spec.paths ?? {})) { * if (pathItem?.get) { * if (!Array.isArray(pathItem.get.parameters)) { * pathItem.get.parameters = []; * } * pathItem.get.parameters.push({ * $ref: '#/components/parameters/MyParam' * }); * } * } * } * ``` */ input?: PatchInputFn; /** * Patch the OpenAPI meta object in place. Useful for modifying general metadata such as title, description, version, or custom fields before further processing. * * @param meta The OpenAPI meta object for the current version. */ meta?: ( meta: OpenApiMetaObject.V2_0_X | OpenApiMetaObject.V3_0_X | OpenApiMetaObject.V3_1_X, ) => void; /** * Patch OpenAPI operations in place. Each function receives the operation * object to be modified in place. Common use cases include injecting * `operationId` for specs that don't have them, adding `x-*` extensions, * setting `deprecated` based on path patterns, or injecting `security` * requirements globally. * * Can be: * - `Record`: Patch specific operations by `"METHOD /path"` key * - `function`: Bulk callback receives `(method, path, operation)` for every operation * * Both patterns support async functions for operations like fetching data * from external sources or performing I/O. * * @example * ```js * // Named operations * operations: { * 'GET /foo': (operation) => { * operation.responses['200'].description = 'Success'; * }, * 'POST /bar': (operation) => { * operation.deprecated = true; * } * } * * // Bulk callback for all operations * operations: (method, path, operation) => { * if (!operation.operationId) { * operation.operationId = method + buildOperationName(path); * } * } * * // Async example - inject operationId based on path patterns * operations: async (method, path, operation) => { * if (operation.operationId) return; * * const segments = path.split('/').filter(Boolean); * const parts = segments * .map((seg) => seg.startsWith('{') ? 'ById' : seg) * .join(''); * operation.operationId = method + parts; * } * ``` */ operations?: | Record< string, ( operation: | OpenApiOperationObject.V2_0_X | OpenApiOperationObject.V3_0_X | OpenApiOperationObject.V3_1_X, ) => void | Promise > | (( method: string, path: string, operation: | OpenApiOperationObject.V2_0_X | OpenApiOperationObject.V3_0_X | OpenApiOperationObject.V3_1_X, ) => void | Promise); /** * Patch OpenAPI parameters in place. The key is the parameter name, and the function receives the parameter object to modify directly. * * @example * parameters: { * limit: (parameter) => { * parameter.schema.type = 'integer'; * } * } */ parameters?: Record< string, (parameter: OpenApiParameterObject.V3_0_X | OpenApiParameterObject.V3_1_X) => void >; /** * Patch OpenAPI request bodies in place. The key is the request body name, and the function receives the request body object to modify directly. * * @example * requestBodies: { * CreateUserRequest: (requestBody) => { * requestBody.required = true; * } * } */ requestBodies?: Record< string, (requestBody: OpenApiRequestBodyObject.V3_0_X | OpenApiRequestBodyObject.V3_1_X) => void >; /** * Patch OpenAPI responses in place. The key is the response name, and the function receives the response object to modify directly. * * @example * responses: { * NotFound: (response) => { * response.description = 'Resource not found.'; * } * } */ responses?: Record< string, (response: OpenApiResponseObject.V3_0_X | OpenApiResponseObject.V3_1_X) => void >; /** * Each function receives the schema object to be modified in place. Common * use cases include fixing incorrect data types, removing unwanted * properties, adding missing fields, or standardizing date/time formats. * * Can be: * - `Record`: Patch specific named schemas * - `function`: Bulk callback receives `(name, schema)` for every schema * * Both patterns support async functions for operations like fetching data * from external sources or performing I/O. * * @example * ```js * // Named schemas * schemas: { * Foo: (schema) => { * // convert date-time format to timestamp * delete schema.properties.updatedAt.format; * schema.properties.updatedAt.type = 'number'; * }, * Bar: (schema) => { * // add missing property * schema.properties.metadata = { * additionalProperties: true, * type: 'object', * }; * schema.required = ['metadata']; * }, * Baz: (schema) => { * // remove property * delete schema.properties.internalField; * } * } * * // Bulk callback for all schemas * schemas: (name, schema) => { * const match = name.match(/_v(\d+)_(\d+)_(\d+)_/); * if (match) { * schema.description = (schema.description || '') + * `\n@version ${match[1]}.${match[2]}.${match[3]}`; * } * } * * // Async example - fetch metadata from external source * schemas: async (name, schema) => { * const metadata = await fetchSchemaMetadata(name); * if (metadata) { * schema.description = `${schema.description}\n\n${metadata.notes}`; * } * } * ``` */ schemas?: | Record< string, ( schema: | OpenApiSchemaObject.V2_0_X | OpenApiSchemaObject.V3_0_X | OpenApiSchemaObject.V3_1_X, ) => void | Promise > | (( name: string, schema: | OpenApiSchemaObject.V2_0_X | OpenApiSchemaObject.V3_0_X | OpenApiSchemaObject.V3_1_X, ) => void | Promise); /** * Patch the OpenAPI version string. The function receives the current version and should return the new version string. * Useful for normalizing or overriding the version value before further processing. * * @param version The current OpenAPI version string. * @returns The new version string to use. * * @example * version: (version) => version.replace(/^v/, '') */ version?: MaybeFunc<(version: string) => string>; }; ================================================ FILE: packages/shared/src/config/parser/types.ts ================================================ import type { Hooks } from '../../parser/hooks'; import type { Casing, NameTransformer } from '../../utils/naming/types'; import type { FeatureToggle, NamingOptions } from '../shared'; import type { Filters } from './filters'; import type { Patch } from './patch'; type EnumsMode = 'inline' | 'root'; export type UserParser = { /** * Filters can be used to select a subset of your input before it's passed * to plugins. */ filters?: Filters; /** * Optional hooks to override default plugin behavior. * * Use these to classify resources, control which outputs are generated, * or provide custom behavior for specific resources. */ hooks?: Hooks; /** * Pagination configuration. */ pagination?: { /** * Array of keywords to be considered as pagination field names. * These will be used to detect pagination fields in schemas and parameters. * * @default ['after', 'before', 'cursor', 'offset', 'page', 'start'] */ keywords?: ReadonlyArray; }; /** * Custom input transformations to execute before parsing. Use this * to modify, fix, or enhance input before it's passed to plugins. */ patch?: Patch; /** * Built-in transformations that modify or normalize the input before it's * passed to plugins. These options enable predictable, documented behaviors * and are distinct from custom patches. Use this to perform structural * changes to input in a standardized way. */ transforms?: { /** * Your input might contain two types of enums: * - enums defined as reusable components (root enums) * - non-reusable enums nested within other schemas (inline enums) * * You may want all enums to be reusable. This is because only root enums * are typically exported by plugins. Inline enums will never be directly * importable since they're nested inside other schemas. * * For example, to export nested enum types with the `@hey-api/typescript` * plugin, set `enums` to `root`. Likewise, if you don't want to export any * enum types, set `enums` to `inline`. * * @default false */ enums?: | boolean | EnumsMode | { /** * Casing convention for generated names. * * @default 'PascalCase' */ case?: Casing; /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Controls whether enums are promoted to reusable root components * ('root') or kept inline within schemas ('inline'). * * @default 'root' */ mode?: EnumsMode; /** * Customize the generated name of enums. * * @default '{{name}}Enum' */ name?: NameTransformer; }; /** * By default, any object schema with a missing `required` keyword is * interpreted as "no properties are required." This is the correct * behavior according to the OpenAPI standard. However, some specifications * interpret a missing `required` keyword as "all properties should be * required." * * This option allows you to change the default behavior so that * properties are required by default unless explicitly marked as optional. * * @default false */ propertiesRequiredByDefault?: boolean; /** * Your schemas might contain read-only or write-only fields. Using such * schemas directly could mean asking the user to provide a read-only * field in requests, or expecting a write-only field in responses. * * We separate schemas for requests and responses if direct usage * would result in such scenarios. You can still disable this * behavior if you prefer. * * @default true */ readWrite?: | boolean | { /** * Whether this feature is enabled. * * @default true */ enabled?: boolean; /** * Configuration for generated request-specific schemas. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default '{{name}}Writable' */ requests?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'preserve' */ case?: Casing; /** * Customize the generated name of schemas used in requests or * containing write-only fields. * * @default '{{name}}Writable' */ name?: NameTransformer; }; /** * Configuration for generated response-specific schemas. * * Can be: * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * * @default '{{name}}' */ responses?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'preserve' */ case?: Casing; /** * Customize the generated name of schemas used in responses or * containing read-only fields. We default to the original name * to avoid breaking output when a read-only field is added. * * @default '{{name}}' */ name?: NameTransformer; }; }; /** * Sometimes your schema names are auto-generated or follow a naming convention * that produces verbose or awkward type names. You can rename schema component * keys throughout the specification, automatically updating all `$ref` pointers. * * @example * ```ts * { * schemaName: (name) => name.replace(/_v\d+_\d+_\d+_/, '_') * } * ``` * * @default undefined */ schemaName?: NameTransformer; }; /** * **This is an experimental feature.** * * Validate the input before generating output? This is an experimental, * lightweight feature and support will be added on an ad hoc basis. Setting * `validate_EXPERIMENTAL` to `true` is the same as `warn`. * * @default false */ validate_EXPERIMENTAL?: boolean | 'strict' | 'warn'; }; export type Parser = { /** * Filters can be used to select a subset of your input before it's passed * to plugins. */ filters?: Filters; /** * Optional hooks to override default plugin behavior. * * Use these to classify resources, control which outputs are generated, * or provide custom behavior for specific resources. */ hooks: Hooks; /** * Pagination configuration. */ pagination: { /** * Array of keywords to be considered as pagination field names. * These will be used to detect pagination fields in schemas and parameters. * * @default ['after', 'before', 'cursor', 'offset', 'page', 'start'] */ keywords: ReadonlyArray; }; /** * Custom input transformations to execute before parsing. Use this * to modify, fix, or enhance input before it's passed to plugins. */ patch?: Patch; /** * Built-in transformations that modify or normalize the input before it's * passed to plugins. These options enable predictable, documented behaviors * and are distinct from custom patches. Use this to perform structural * changes to input in a standardized way. */ transforms: { /** * Your input might contain two types of enums: * - enums defined as reusable components (root enums) * - non-reusable enums nested within other schemas (inline enums) * * You may want all enums to be reusable. This is because only root enums * are typically exported by plugins. Inline enums will never be directly * importable since they're nested inside other schemas. * * For example, to export nested enum types with the `@hey-api/typescript` * plugin, set `enums` to `root`. Likewise, if you don't want to export any * enum types, set `enums` to `inline`. */ enums: NamingOptions & FeatureToggle & { /** * Controls whether enums are promoted to reusable root components * ('root') or kept inline within schemas ('inline'). * * @default 'root' */ mode: EnumsMode; }; /** * By default, any object schema with a missing `required` keyword is * interpreted as "no properties are required." This is the correct * behavior according to the OpenAPI standard. However, some specifications * interpret a missing `required` keyword as "all properties should be * required." * * This option allows you to change the default behavior so that * properties are required by default unless explicitly marked as optional. * * @default false */ propertiesRequiredByDefault: boolean; /** * Your schemas might contain read-only or write-only fields. Using such * schemas directly could mean asking the user to provide a read-only * field in requests, or expecting a write-only field in responses. * * We separate schemas for requests and responses if direct usage * would result in such scenarios. You can still disable this * behavior if you prefer. */ readWrite: FeatureToggle & { /** * Configuration for generated request-specific schemas. */ requests: NamingOptions; /** * Configuration for generated response-specific schemas. */ responses: NamingOptions; }; /** * Rename schema component keys and automatically update all `$ref` pointers * throughout the specification. * * @default undefined */ schemaName?: NameTransformer; }; /** * **This is an experimental feature.** * * Validate the input before generating output? This is an experimental, * lightweight feature and support will be added on an ad hoc basis. Setting * `validate_EXPERIMENTAL` to `true` is the same as `warn`. * * @default false */ validate_EXPERIMENTAL: false | 'strict' | 'warn'; }; ================================================ FILE: packages/shared/src/config/shared.ts ================================================ import type { NameConflictResolver, RenderContext, Symbol } from '@hey-api/codegen-core'; import type { AnyString, MaybeArray } from '@hey-api/types'; import type { Plugin } from '../plugins/types'; import type { Logs } from '../types/logs'; import type { Casing, NameTransformer } from '../utils/naming/types'; import type { Input, UserInput, UserWatch } from './input/types'; import type { PostProcessor } from './output/postprocess'; import type { SourceConfig, UserSourceConfig } from './output/source/types'; import type { OutputHeader } from './output/types'; import type { Parser, UserParser } from './parser/types'; export type FeatureToggle = { /** * Whether this feature is enabled. */ enabled: boolean; }; export type UserIndexExportOption = { /** * Whether exports should be re-exported from the entry file. * * - `true` — include all exports * - `false` — exclude all exports * - `(symbol) => boolean` — include exports matching the predicate * * @default false * @deprecated use `includeInEntry` instead */ exportFromIndex?: boolean | ((symbol: Symbol) => boolean); /** * Whether exports should be re-exported from the entry file. * * - `true` — include all exports * - `false` — exclude all exports * - `(symbol) => boolean` — include exports matching the predicate * * @default false */ includeInEntry?: boolean | ((symbol: Symbol) => boolean); }; export type IndexExportOption = { /** * Whether exports should be re-exported from the entry file. * * @deprecated use `includeInEntry` instead */ exportFromIndex: boolean | ((symbol: Symbol) => boolean); /** * Whether exports should be re-exported from the entry file. */ includeInEntry: boolean | ((symbol: Symbol) => boolean); }; export type UserCommentsOption = { /** * Whether to add comments to the generated code. * * @default true */ comments?: boolean; }; export type CommentsOption = { /** * Whether to add comments to the generated code. */ comments: boolean; }; export type NamingOptions = { /** * Casing convention for generated names. */ case: Casing; /** * Naming pattern for generated names. */ name: NameTransformer; }; /** * Base output shape all packages must satisfy. */ export interface BaseUserOutput { /** * Defines casing of the output fields. By default, we preserve `input` * values as data transforms incur a performance penalty at runtime. * * @default undefined */ case?: Casing; /** * Clean the `output` folder on every run? If disabled, this folder may * be used to store additional files. The default option is `true` to * reduce the risk of keeping outdated files around when configuration, * input, or package version changes. * * @default true */ clean?: boolean; /** * Whether to generate an entry file that re-exports symbols for convenient imports. * * Plugins control their inclusion via `includeInEntry`. * * @default true */ entryFile?: boolean; /** * Optional function to transform file names before they are used. * * @param name The original file name. * @returns The transformed file name. * @default '{{name}}' */ fileName?: | NameTransformer | { /** * Casing convention for generated names. * * @default 'preserve' */ case?: Casing; /** * Naming pattern for generated names. * * @default '{{name}}' */ name?: NameTransformer; /** * Suffix to append to file names (before the extension). For example, * with a suffix of `.gen`, `example.ts` becomes `example.gen.ts`. * * @default '.gen' * @example * // Given a suffix of `.gen` * 'index.ts' -> 'index.ts' (index files are not renamed) * 'user.ts' -> 'user.gen.ts' * 'order.gen.ts' -> 'order.gen.ts' (files already containing the suffix are not renamed) */ suffix?: string | null; }; /** * Text to include at the top of every generated file. */ header?: OutputHeader; /** * Whether to generate an entry file that re-exports symbols for convenient imports. * * Plugins control their inclusion via `includeInEntry`. * * @default true * @deprecated use `entryFile` instead */ indexFile?: boolean; /** * Options for module specifier resolution. */ module?: { /** * If specified, this will be the extension used when importing other * modules. By default, we don't add an extension unless we detect that * you're using a module resolution strategy that requires one. * * @default undefined */ extension?: TModuleExtension | AnyString | null; /** * Function to transform module specifiers. * * @default undefined */ resolve?: ResolveModuleFn; }; /** * Optional name conflict resolver to customize how naming conflicts * are handled. */ nameConflictResolver?: NameConflictResolver; /** * The absolute path to the output folder. */ path: string; /** * Optional function to transform module specifiers. * * @default undefined * @deprecated use `module.resolve` instead */ resolveModuleName?: ResolveModuleFn; /** * Configuration for generating a copy of the input source used to produce this output. * * Set to `false` to skip generating the source, or `true` to use defaults. * * You can also provide a configuration object to further customize behavior. * * @default false */ source?: boolean | UserSourceConfig; } /** * Base output shape all packages must satisfy. */ export interface BaseOutput { /** * Defines casing of the output fields. By default, we preserve `input` * values as data transforms incur a performance penalty at runtime. */ case: Casing | undefined; /** * Clean the `output` folder on every run? If disabled, this folder may * be used to store additional files. The default option is `true` to * reduce the risk of keeping outdated files around when configuration, * input, or package version changes. */ clean: boolean; /** Whether to generate an entry file that re-exports symbols for convenient imports. */ entryFile: boolean; /** * Optional function to transform file names before they are used. * * @param name The original file name. * @returns The transformed file name. */ fileName: NamingOptions & { /** * Suffix to append to file names (before the extension). For example, * with a suffix of `.gen`, `example.ts` becomes `example.gen.ts`. * * @example * // Given a suffix of `.gen` * 'index.ts' -> 'index.ts' (index files are not renamed) * 'user.ts' -> 'user.gen.ts' * 'order.gen.ts' -> 'order.gen.ts' (files already containing the suffix are not renamed) */ suffix: string | null; }; /** Text to include at the top of every generated file. */ header: OutputHeader; /** * Whether to generate an entry file that re-exports symbols for convenient imports. * * @deprecated use `entryFile` instead */ indexFile: boolean; /** Options for module specifier resolution. */ module: { /** The extension used when importing other modules. */ extension: TModuleExtension | AnyString | null; /** Function to transform module specifiers. */ resolve: ResolveModuleFn | undefined; }; /** Name conflict resolver to customize how naming conflicts are handled. */ nameConflictResolver: NameConflictResolver | undefined; /** The absolute path to the output folder. */ path: string; /** Post-processing commands to run on the output folder, executed in order. */ postProcess: ReadonlyArray; /** Configuration for generating a copy of the input source used to produce this output. */ source: SourceConfig; } /** * Core configuration shared across all packages. */ export type BaseUserConfig = { /** * Path to the config file. Set this value if you don't use the default * config file name, or it's not located in the project root. */ configFile?: string; /** * Skip writing files to disk? * * @default false */ dryRun?: boolean; /** * Path to the OpenAPI specification. This can be: * - path * - URL * - API registry shorthand * * Both JSON and YAML file formats are supported. You can also pass the parsed * object directly if you're fetching the file yourself. * * Alternatively, you can define a configuration object with more options. * * If you define an array, we will generate a single output from multiple * inputs. If you define an array of outputs with the same length, we will * generate multiple outputs, one for each input. */ input: MaybeArray['path']>; /** * Show an interactive error reporting tool when the program crashes? You * generally want to keep this disabled (default). * * @default false */ interactive?: boolean; /** * The relative location of the logs folder. * * @default process.cwd() */ logs?: string | Logs; /** * Path to the output folder. * * If you define an array of outputs with the same length as inputs, we will * generate multiple outputs, one for each input. */ output: MaybeArray; /** * Customize how the input is parsed and transformed before it's passed to * plugins. */ parser?: UserParser; /** * @deprecated use `input.watch` instead */ watch?: UserWatch; }; /** * Core configuration shared across all packages. */ export type BaseConfig = Omit< Required, 'input' | 'logs' | 'output' | 'parser' | 'plugins' | 'watch' > & { /** * Path to the input specification. */ input: ReadonlyArray; logs: Logs; /** * Path to the output folder. */ output: TOutput; /** * Customize how the input is parsed and transformed before it's passed to * plugins. */ parser: Parser; // Loose types - packages override via intersection pluginOrder: ReadonlyArray; plugins: Record | undefined>; }; /** * For shared utilities that operate on any config. */ export type AnyConfig = BaseConfig, BaseOutput>; /** * Function to transform module specifiers. */ export type ResolveModuleFn = (path: string, ctx: RenderContext) => string | undefined; ================================================ FILE: packages/shared/src/config/utils/config.ts ================================================ type ObjectType = Extract> extends never ? Record : Extract>; type NotArray = T extends Array ? never : T; type NotFunction = T extends (...args: Array) => any ? never : T; type PlainObject = T extends object ? NotFunction extends never ? never : NotArray extends never ? never : T : never; type MappersType = { boolean: T extends boolean ? (value: boolean) => Partial> : never; function: T extends (...args: Array) => any ? (value: (...args: Array) => any) => Partial> : never; number: T extends number ? (value: number) => Partial> : never; object?: PlainObject extends never ? never : (value: Partial>, defaultValue: PlainObject) => Partial>; string: T extends string ? (value: string) => Partial> : never; } extends infer U ? { [K in keyof U as U[K] extends never ? never : K]: U[K] } : never; type IsObjectOnly = T extends Record | undefined ? Extract) => any)> extends never ? true : false : false; export type ValueToObject = < T extends | undefined | string | boolean | number | ((...args: Array) => any) | Record, >( args: { defaultValue: ObjectType; value: T; } & (IsObjectOnly extends true ? { mappers?: MappersType; } : { mappers: MappersType; }), ) => PlainObject; const isPlainObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value) && typeof value !== 'function'; const mergeResult = (result: ObjectType, mapped: Record): ObjectType => { for (const [key, value] of Object.entries(mapped)) { if (value !== undefined && value !== '') { (result as Record)[key] = value; } } return result; }; export const valueToObject: ValueToObject = ({ defaultValue, mappers, value }) => { let result = { ...defaultValue }; switch (typeof value) { case 'boolean': if (mappers && 'boolean' in mappers) { const mapper = mappers.boolean as (value: boolean) => Record; result = mergeResult(result, mapper(value)); } break; case 'function': if (mappers && 'function' in mappers) { const mapper = mappers.function as ( value: (...args: Array) => any, ) => Record; result = mergeResult(result, mapper(value as (...args: Array) => any)); } break; case 'number': if (mappers && 'number' in mappers) { const mapper = mappers.number as (value: number) => Record; result = mergeResult(result, mapper(value)); } break; case 'string': if (mappers && 'string' in mappers) { const mapper = mappers.string as (value: string) => Record; result = mergeResult(result, mapper(value)); } break; case 'object': if (isPlainObject(value)) { if (mappers && 'object' in mappers && typeof mappers.object === 'function') { const mapper = mappers.object as ( value: Record, defaultValue: ObjectType, ) => Partial>; result = mergeResult(result, mapper(value, defaultValue)); } else { result = mergeResult(result, value); } } break; } return result as any; }; ================================================ FILE: packages/shared/src/config/utils/dependencies.ts ================================================ import type { RangeOptions, SemVer } from 'semver'; import * as semver from 'semver'; export type Dependency = { /** * Get the installed version of a package. * @param name The name of the package to get the version for. * @returns A SemVer object containing version information, or undefined if the package is not installed * or the version string is invalid. */ getVersion: (name: string) => SemVer | undefined; /** * Check if a given package is installed in the project. * @param name The name of the package to check. */ isInstalled: (name: string) => boolean; /** * Check if the installed version of a package or a given SemVer object satisfies a semver range. * @param nameOrVersion The name of the package to check, or a SemVer object. * @param range The semver range to check against. * @returns True if the version satisfies the range, false otherwise. */ satisfies: ( nameOrVersion: string | SemVer, range: string, optionsOrLoose?: boolean | RangeOptions, ) => boolean; }; export const satisfies: typeof semver.satisfies = (...args) => semver.satisfies(...args); export function dependencyFactory(dependencies: Record): Dependency { return { getVersion: (name) => { const version = dependencies[name]; if (!version) return; try { let parsed = semver.parse(version); if (parsed) return parsed; const min = semver.minVersion(version); if (min) return min; parsed = semver.coerce(version); if (parsed) return parsed; } catch { // noop } return; }, isInstalled: (name) => Boolean(dependencies[name]), satisfies: (nameOrVersion, range, optionsOrLoose) => { const version = typeof nameOrVersion === 'string' ? dependencies[nameOrVersion] : nameOrVersion; return version ? satisfies(version, range, optionsOrLoose) : false; }, }; } ================================================ FILE: packages/shared/src/debug/graph.ts ================================================ import type { Graph } from '../graph'; const analyzeStructure = (graph: Graph) => { let maxDepth = 0; let maxChildren = 0; const computeDepth = (pointer: string, depth: number): void => { maxDepth = Math.max(maxDepth, depth); const children = Array.from(graph.nodes.entries()) .filter(([, nodeInfo]) => nodeInfo.parentPointer === pointer) .map(([childPointer]) => childPointer); maxChildren = Math.max(maxChildren, children.length); for (const childPointer of children) { computeDepth(childPointer, depth + 1); } }; const totalNodes = graph.nodes.size; if (graph.nodes.has('#')) { computeDepth('#', 1); } return { maxChildren, maxDepth, totalNodes }; }; const exportForVisualization = (graph: Graph) => { const childrenMap = new Map(); for (const [pointer, nodeInfo] of graph.nodes) { if (!nodeInfo.parentPointer) continue; if (!childrenMap.has(nodeInfo.parentPointer)) { childrenMap.set(nodeInfo.parentPointer, []); } childrenMap.get(nodeInfo.parentPointer)!.push(pointer); } const nodes = Array.from(graph.nodes.keys()).map((pointer) => ({ children: childrenMap.get(pointer)?.length ?? 0, childrenPointers: childrenMap.get(pointer) || [], pointer, })); return nodes; }; export const graph = { analyzeStructure, exportForVisualization, } as const; ================================================ FILE: packages/shared/src/debug/index.ts ================================================ import { graph } from './graph'; import { ir } from './ir'; export const debugTools = { graph, ir, }; ================================================ FILE: packages/shared/src/debug/ir.ts ================================================ import colors from 'ansi-colors'; import type { IR } from '../ir/types'; import { httpMethods } from '../openApi/shared/utils/operation'; export interface PrintOptions { /** * Indentation depth for `JSON.stringify()` when printing objects. * * @default 2 */ depth?: number; /** * Which section of the IR to print. Use 'all' to print every section. * * @default 'all' */ section?: keyof IR.Model | 'all'; /** * How much detail to print. * * - `summary` → only keys, names, operationIds, status codes * - `full` → dump full JSON structures * * @default 'summary' */ verbosity?: 'full' | 'summary'; } const indent = (level: number) => ' '.repeat(level); const log = (message: string, level?: number) => console.log(`${indent(level ?? 0)}${message}`); const print = (ir: IR.Model, options: PrintOptions = {}) => { const { depth = 2, section = 'all', verbosity = 'summary' } = options; const printObject = ( obj: unknown, level: number, kind: 'responses' | 'requestBody' | 'schema' | 'generic' = 'generic', ) => { if (verbosity === 'summary' && obj && typeof obj === 'object') { if (kind === 'responses') { const count = Object.keys(obj).length; const noun = count === 1 ? 'code' : 'codes'; log(`responses: ${colors.yellow(`${count} ${noun}`)}`, level); } else if (kind === 'requestBody') { log(`requestBody: ${Object.keys(obj).join(', ')}`, level); } else if (kind === 'schema') { log(`schema keys: ${Object.keys(obj).join(', ')}`, level); } else { log(`keys: ${Object.keys(obj).join(', ')}`, level); } } else { log(JSON.stringify(obj, null, depth), level); } }; const printPathItem = ( key: string, item: IR.PathItemObject | IR.ReferenceObject, base: number = 1, ) => { if ('$ref' in item) { log(`${colors.cyan(key)} is a $ref → ${colors.yellow(item.$ref)}`, base); return; } for (const method of Object.keys(item) as Array) { if (!httpMethods.includes(method)) continue; const operation = item[method]!; log( `${colors.green(method.toUpperCase())} ${colors.cyan(key)} (${colors.magenta(operation.operationId ?? '')})`, base, ); if (operation.body) printObject(operation.body, base + 1, 'requestBody'); if (operation.responses) printObject(operation.responses, base + 1, 'responses'); } }; const sections = section === 'all' ? (Object.keys(ir) as unknown as ReadonlyArray) : [section]; for (const section of sections) { switch (section) { case 'components': if (ir.components?.schemas) { log(`Components: ${Object.keys(ir.components.schemas).length} schemas`); for (const [, schema] of Object.entries(ir.components.schemas)) { printObject(schema, 1, 'schema'); } } break; case 'paths': { const paths = ir.paths || {}; log(`paths (${Object.keys(paths).length} items):`); for (const [path, item] of Object.entries(paths)) { printPathItem(path, item); } break; } case 'servers': break; case 'webhooks': { const webhooks = ir.webhooks || {}; log(`webhooks (${Object.keys(webhooks).length} items):`); for (const [path, item] of Object.entries(webhooks)) { printPathItem(path, item); } break; } } } }; export const ir = { print, } as const; ================================================ FILE: packages/shared/src/error.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import colors from 'ansi-colors'; import open from 'open'; import { ensureDirSync } from './fs'; import { loadPackageJson } from './tsConfig'; type IJobError = { error: Error; jobIndex: number; }; /** * Represents a single configuration error. * * Used for reporting issues with a specific config instance. */ export class ConfigError extends Error { constructor(message: string) { super(message); this.name = 'ConfigError'; } } /** * Aggregates multiple config errors with their job indices for reporting. */ export class ConfigValidationError extends Error { readonly errors: ReadonlyArray; constructor(errors: Array) { super(`Found ${errors.length} configuration ${errors.length === 1 ? 'error' : 'errors'}.`); this.name = 'ConfigValidationError'; this.errors = errors; } } /** * Represents a runtime error originating from a specific job. * * Used for reporting job-level failures that are not config validation errors. */ export class JobError extends Error { readonly originalError: IJobError; constructor(message: string, error: IJobError) { super(message); this.name = 'JobError'; this.originalError = error; } } export class HeyApiError extends Error { args: ReadonlyArray; event: string; pluginName: string; constructor({ args, error, event, name, pluginName, }: { args: unknown[]; error: Error; event: string; name: string; pluginName: string; }) { const message = error instanceof Error ? error.message : 'Unknown error'; super(message); this.args = args; this.cause = error.cause; this.event = event; this.name = name || error.name; this.pluginName = pluginName; this.stack = error.stack; } } export function logCrashReport(error: unknown, logsDir: string): string | undefined { if (error instanceof ConfigError || error instanceof ConfigValidationError) { return; } if (error instanceof JobError) { error = error.originalError.error; } const logName = `openapi-ts-error-${Date.now()}.log`; const fullDir = path.resolve(process.cwd(), logsDir); ensureDirSync(fullDir); const logPath = path.resolve(fullDir, logName); let logContent = `[${new Date().toISOString()}] `; if (error instanceof HeyApiError) { logContent += `${error.name} during event "${error.event}"\n`; if (error.pluginName) { logContent += `Plugin: ${error.pluginName}\n`; } logContent += `Arguments: ${JSON.stringify(error.args, null, 2)}\n\n`; } const message = error instanceof Error ? error.message : String(error); const stack = error instanceof Error ? error.stack : undefined; logContent += `Error: ${message}\n`; if (stack) { logContent += `Stack:\n${stack}\n`; } fs.writeFileSync(logPath, logContent); return logPath; } export async function openGitHubIssueWithCrashReport( error: unknown, initialDir: string, ): Promise { const packageJson = loadPackageJson(initialDir); if (!packageJson?.bugs.url) return; if (error instanceof JobError) { error = error.originalError.error; } let body = ''; if (error instanceof HeyApiError) { if (error.pluginName) { body += `**Plugin**: \`${error.pluginName}\`\n`; } body += `**Event**: \`${error.event}\`\n`; body += `**Arguments**:\n\`\`\`ts\n${JSON.stringify(error.args, null, 2)}\n\`\`\`\n\n`; } const message = error instanceof Error ? error.message : String(error); const stack = error instanceof Error ? error.stack : undefined; body += `**Error**: \`${message}\`\n`; if (stack) { body += `\n**Stack Trace**:\n\`\`\`\n${stack}\n\`\`\``; } const search = new URLSearchParams({ body, labels: 'bug 🔥', title: 'Crash Report', }); const url = `${packageJson.bugs.url}new?${search.toString()}`; await open(url); } export function printCrashReport({ error, logPath, }: { error: unknown; logPath: string | undefined; }): void { if (error instanceof ConfigValidationError && error.errors.length) { const groupByJob = new Map>(); for (const { error: err, jobIndex } of error.errors) { if (!groupByJob.has(jobIndex)) { groupByJob.set(jobIndex, []); } groupByJob.get(jobIndex)!.push(err); } for (const [jobIndex, errors] of groupByJob.entries()) { const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `); const count = errors.length; const baseString = colors.red( `Found ${count} configuration ${count === 1 ? 'error' : 'errors'}:`, ); console.error(`${jobPrefix}❗️ ${baseString}`); errors.forEach((err, index) => { const itemPrefixStr = ` [${index + 1}] `; const itemPrefix = colors.red(itemPrefixStr); console.error(`${jobPrefix}${itemPrefix}${colors.white(err.message)}`); }); } } else { let jobPrefix = colors.gray('[root] '); if (error instanceof JobError) { jobPrefix = colors.gray(`[Job ${error.originalError.jobIndex + 1}] `); error = error.originalError.error; } const baseString = colors.red('Failed with the message:'); console.error(`${jobPrefix}❌ ${baseString}`); const itemPrefixStr = ` `; const itemPrefix = colors.red(itemPrefixStr); console.error( `${jobPrefix}${itemPrefix}${typeof error === 'string' ? error : error instanceof Error ? error.message : 'Unknown error'}`, ); } if (logPath) { const jobPrefix = colors.gray('[root] '); console.error(`${jobPrefix}${colors.cyan('📄 Crash log saved to:')} ${colors.gray(logPath)}`); } } export async function shouldReportCrash({ error, isInteractive, }: { error: unknown; isInteractive: boolean | undefined; }): Promise { if (!isInteractive || error instanceof ConfigError || error instanceof ConfigValidationError) { return false; } return new Promise((resolve) => { const jobPrefix = colors.gray('[root] '); console.log( `${jobPrefix}${colors.yellow('📢 Open a GitHub issue with crash details? (y/N):')}`, ); process.stdin.setEncoding('utf8'); process.stdin.once('data', (data: string) => { resolve(data.trim().toLowerCase() === 'y'); }); }); } ================================================ FILE: packages/shared/src/fs.ts ================================================ import type { PathLike } from 'node:fs'; import fs from 'node:fs'; export function ensureDirSync(path: PathLike): void { if (!fs.existsSync(path)) { fs.mkdirSync(path, { recursive: true }); } } ================================================ FILE: packages/shared/src/getSpec.ts ================================================ import { getResolvedInput, sendRequest } from '@hey-api/json-schema-ref-parser'; import type { MaybeArray } from '@hey-api/types'; import type { Input } from './config/input/types'; import type { WatchValues } from './types/watch'; const headersEntries = (headers: Headers): Array<[string, string]> => { const entries: Array<[string, string]> = []; headers.forEach((value, key) => { entries.push([key, value]); }); return entries; }; const mergeHeaders = ( ...headers: Array< | RequestInit['headers'] | Record | null | undefined | unknown> | undefined > ): Headers => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header) { continue; } const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v as string); } } else if (value !== undefined) { // assume object headers are meant to be JSON stringified, i.e. their // content value in OpenAPI specification is 'application/json' mergedHeaders.set( key, typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } } return mergedHeaders; }; type SpecResponse = { arrayBuffer: ArrayBuffer | undefined; error?: never; resolvedInput: ReturnType; response?: never; }; type SpecError = { arrayBuffer?: never; error: 'not-modified' | 'not-ok'; resolvedInput?: never; response: Response; }; /** * @internal */ export async function getSpec({ fetchOptions, inputPath, timeout, watch, }: { fetchOptions?: RequestInit; inputPath: Input['path']; timeout: number | undefined; watch: WatchValues; }): Promise { const resolvedInput = getResolvedInput({ pathOrUrlOrSchema: inputPath }); let arrayBuffer: ArrayBuffer | undefined; // boolean signals whether the file has **definitely** changed let hasChanged: boolean | undefined; let response: Response | undefined; if (resolvedInput.type === 'url') { // do NOT send HEAD request on first run or if unsupported if (watch.lastValue && watch.isHeadMethodSupported !== false) { try { const request = await sendRequest({ fetchOptions: { method: 'HEAD', ...fetchOptions, headers: mergeHeaders(fetchOptions?.headers, watch.headers), }, timeout, url: resolvedInput.path, }); if (request.response.status >= 300) { return { error: 'not-ok', response: request.response, }; } response = request.response; } catch (error) { const message = error instanceof Error ? error.message : String(error); return { error: 'not-ok', response: new Response(message, { status: 500 }), }; } if (!response.ok && watch.isHeadMethodSupported) { // assume the server is no longer running // do nothing, it might be restarted later return { error: 'not-ok', response, }; } if (watch.isHeadMethodSupported === undefined) { watch.isHeadMethodSupported = response.ok; } if (response.status === 304) { return { error: 'not-modified', response, }; } if (hasChanged === undefined) { const eTag = response.headers.get('ETag'); if (eTag) { hasChanged = eTag !== watch.headers.get('If-None-Match'); if (hasChanged) { watch.headers.set('If-None-Match', eTag); } } } if (hasChanged === undefined) { const lastModified = response.headers.get('Last-Modified'); if (lastModified) { hasChanged = lastModified !== watch.headers.get('If-Modified-Since'); if (hasChanged) { watch.headers.set('If-Modified-Since', lastModified); } } } // we definitely know the input has not changed if (hasChanged === false) { return { error: 'not-modified', response, }; } } try { const request = await sendRequest({ fetchOptions: { method: 'GET', ...fetchOptions, }, timeout, url: resolvedInput.path, }); if (request.response.status >= 300) { return { error: 'not-ok', response: request.response, }; } response = request.response; } catch (error) { const message = error instanceof Error ? error.message : String(error); return { error: 'not-ok', response: new Response(message, { status: 500 }), }; } if (!response.ok) { // assume the server is no longer running // do nothing, it might be restarted later return { error: 'not-ok', response, }; } arrayBuffer = response.body ? await response.arrayBuffer() : new ArrayBuffer(0); if (hasChanged === undefined) { const content = new TextDecoder().decode(arrayBuffer); hasChanged = content !== watch.lastValue; watch.lastValue = content; } } else { // we do not support watch mode for files or raw spec data if (!watch.lastValue) { watch.lastValue = resolvedInput.type; } else { hasChanged = false; } } if (hasChanged === false) { return { error: 'not-modified', response: response!, }; } return { arrayBuffer, resolvedInput, }; } ================================================ FILE: packages/shared/src/graph/__tests__/walk.test.ts ================================================ import { getIrPointerPriority, matchIrPointerToGroup, preferGroups } from '../../ir/graph'; import { buildGraph } from '../../openApi/shared/utils/graph'; import type { Graph } from '../types/graph'; import { walk } from '../walk'; const loggerStub = { timeEvent: () => ({ timeEnd: () => {} }), } as any; describe('walkTopological', () => { const makeGraph = (deps: Array<[string, Array]>, nodes: Array) => { const nodeDependencies = new Map>(); const subtreeDependencies = new Map>(); const reverseNodeDependencies = new Map>(); const nodesMap = new Map(); for (const name of nodes) { nodesMap.set(name, { key: null, node: {}, parentPointer: null }); } for (const [from, toList] of deps) { const s = new Set(toList); nodeDependencies.set(from, s); subtreeDependencies.set(from, new Set(toList)); for (const to of toList) { if (!reverseNodeDependencies.has(to)) reverseNodeDependencies.set(to, new Set()); reverseNodeDependencies.get(to)!.add(from); } } return { nodeDependencies, nodes: nodesMap, reverseNodeDependencies, subtreeDependencies, transitiveDependencies: new Map>(), } as unknown as Graph; }; it('walks nodes in topological order for a simple acyclic graph', () => { // Graph: A -> B -> C const graph = makeGraph( [ ['A', ['B']], ['B', ['C']], ], ['A', 'B', 'C'], ); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order.indexOf('C')).toBeLessThan(order.indexOf('B')); expect(order.indexOf('B')).toBeLessThan(order.indexOf('A')); expect(order).toHaveLength(3); }); it('walks nodes in topological order for multiple roots', () => { // Graph: A -> B, C -> D const graph = makeGraph( [ ['A', ['B']], ['C', ['D']], ], ['A', 'B', 'C', 'D'], ); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order.indexOf('B')).toBeLessThan(order.indexOf('A')); expect(order.indexOf('D')).toBeLessThan(order.indexOf('C')); expect(order).toHaveLength(4); }); it('walks nodes in topological order for a disconnected graph', () => { // Graph: A -> B, C (no deps), D (no deps) const graph = makeGraph([['A', ['B']]], ['A', 'B', 'C', 'D']); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order.indexOf('B')).toBeLessThan(order.indexOf('A')); expect(order).toHaveLength(4); expect(order).toContain('C'); expect(order).toContain('D'); }); it('walks nodes in topological order for a diamond dependency', () => { // Graph: A // / \ // B C // \ / // D const graph = makeGraph( [ ['A', ['B', 'C']], ['B', ['D']], ['C', ['D']], ], ['A', 'B', 'C', 'D'], ); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order.indexOf('D')).toBeLessThan(order.indexOf('B')); expect(order.indexOf('D')).toBeLessThan(order.indexOf('C')); expect(order.indexOf('B')).toBeLessThan(order.indexOf('A')); expect(order.indexOf('C')).toBeLessThan(order.indexOf('A')); expect(order).toHaveLength(4); }); it('walks nodes in topological order for a long chain', () => { // Graph: A -> B -> C -> D -> E const graph = makeGraph( [ ['A', ['B']], ['B', ['C']], ['C', ['D']], ['D', ['E']], ], ['A', 'B', 'C', 'D', 'E'], ); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order.indexOf('E')).toBeLessThan(order.indexOf('D')); expect(order.indexOf('D')).toBeLessThan(order.indexOf('C')); expect(order.indexOf('C')).toBeLessThan(order.indexOf('B')); expect(order.indexOf('B')).toBeLessThan(order.indexOf('A')); expect(order).toHaveLength(5); }); it('walks all nodes, including cycles', () => { // Graph: A <-> B (cycle), C (no deps) const graph = makeGraph( [ ['A', ['B']], ['B', ['A']], ], ['A', 'B', 'C'], ); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order.sort()).toEqual(['A', 'B', 'C']); }); it('matches ordering for validators-circular-ref spec', async () => { const specModule = await import('../../../../../specs/3.1.x/validators-circular-ref.json'); const spec = specModule.default ?? specModule; const { graph } = buildGraph(spec, loggerStub); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); const foo = '#/components/schemas/Foo'; const bar = '#/components/schemas/Bar'; const baz = '#/components/schemas/Baz'; const qux = '#/components/schemas/Qux'; // Bar should come before Foo because Foo depends on Bar expect(order.indexOf(bar)).toBeLessThan(order.indexOf(foo)); // Baz and Qux form a mutual $ref cycle; both must be present expect(order).toContain(baz); expect(order).toContain(qux); }); it('prefers schema group before parameter when safe (default)', () => { // parameter then schema in declaration order, no deps -> schema should move before parameter const param = '#/components/parameters/P'; const schema = '#/components/schemas/A'; const nodes = [param, schema]; const graph = makeGraph([], nodes); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { getPointerPriority: getIrPointerPriority, matchPointerToGroup: matchIrPointerToGroup, order: 'topological', preferGroups, }); expect(order.indexOf(schema)).toBeLessThan(order.indexOf(param)); }); it('does not apply preferGroups when it would violate dependencies (fallback)', () => { // declaration order: param, schema; schema depends on param -> cannot move before param const param = '#/components/parameters/P'; const schema = '#/components/schemas/S'; const nodes = [param, schema]; const nodeDependencies = new Map>(); nodeDependencies.set(schema, new Set([param])); const subtreeDependencies = new Map>(); const reverseNodeDependencies = new Map>(); const nodesMap = new Map(); for (const n of nodes) nodesMap.set(n, { key: null, node: {}, parentPointer: null }); const graph = { nodeDependencies, nodes: nodesMap, reverseNodeDependencies, subtreeDependencies, transitiveDependencies: new Map>(), } as unknown as Graph; const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); // schema depends on param so param must remain before schema expect(order.indexOf(param)).toBeLessThan(order.indexOf(schema)); }); it('ignores self-dependencies when ordering', () => { // Foo has self-ref only, Bar references Foo -> Foo should come before Bar const foo = '#/components/schemas/Foo'; const bar = '#/components/schemas/Bar'; const nodes = [foo, bar]; const nodeDependencies = new Map>(); nodeDependencies.set(foo, new Set([foo])); nodeDependencies.set(bar, new Set([foo])); const nodesMap = new Map(); for (const n of nodes) nodesMap.set(n, { key: null, node: {}, parentPointer: null }); const graph = { nodeDependencies, nodes: nodesMap, reverseNodeDependencies: new Map>(), subtreeDependencies: new Map>(), transitiveDependencies: new Map>(), } as unknown as Graph; const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); // Foo is a dependency of Bar, so Foo should come before Bar expect(order.indexOf(foo)).toBeLessThan(order.indexOf(bar)); }); it('uses subtreeDependencies when nodeDependencies are absent', () => { const parent = '#/components/schemas/Parent'; const child = '#/components/schemas/Child'; const nodes = [parent, child]; const nodeDependencies = new Map>(); const subtreeDependencies = new Map>(); subtreeDependencies.set(parent, new Set([child])); const nodesMap = new Map(); for (const n of nodes) nodesMap.set(n, { key: null, node: {}, parentPointer: null }); const graph = { nodeDependencies, nodes: nodesMap, reverseNodeDependencies: new Map>(), subtreeDependencies, transitiveDependencies: new Map>(), } as unknown as Graph; const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order.indexOf(child)).toBeLessThan(order.indexOf(parent)); }); it('preserves declaration order for equal-priority items (stability)', () => { const a = '#/components/schemas/A'; const b = '#/components/schemas/B'; const c = '#/components/schemas/C'; const nodes = [a, b, c]; const graph = makeGraph([], nodes); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'topological' }); expect(order).toEqual(nodes); }); it('walks nodes in declaration order when order=declarations', () => { const a = '#/components/schemas/A'; const b = '#/components/schemas/B'; const c = '#/components/schemas/C'; const nodes = [a, b, c]; const graph = makeGraph([], nodes); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { order: 'declarations' }); expect(order).toEqual(nodes); }); it('applies preferGroups ordering in declaration mode', () => { const param = '#/components/parameters/P'; const schema = '#/components/schemas/A'; const nodes = [param, schema]; const graph = makeGraph([], nodes); const order: Array = []; walk(graph, (pointer) => order.push(pointer), { matchPointerToGroup: matchIrPointerToGroup, order: 'declarations', preferGroups, }); // preferGroups puts schema before parameter expect(order.indexOf(schema)).toBeLessThan(order.indexOf(param)); }); }); ================================================ FILE: packages/shared/src/graph/index.ts ================================================ export type { Graph, NodeInfo } from './types/graph'; export type { GetPointerPriorityFn, MatchPointerToGroupFn, WalkOptions } from './types/walk'; export { walk } from './walk'; ================================================ FILE: packages/shared/src/graph/types/graph.ts ================================================ import type { Scope } from '../../openApi/shared/utils/graph'; /** * The main graph structure for OpenAPI node analysis. * * @property nodeDependencies - For each node with at least one dependency, the set of normalized JSON Pointers it references via $ref. Nodes with no dependencies are omitted. * @property nodes - Map from normalized JSON Pointer to NodeInfo for every node in the spec. * @property reverseNodeDependencies - For each node with at least one dependent, the set of nodes that reference it via $ref. Nodes with no dependents are omitted. */ export type Graph = { /** * For each node with at least one dependency, the set of normalized JSON Pointers it references via $ref. * Nodes with no dependencies are omitted from this map. */ nodeDependencies: Map>; /** * Map from normalized JSON Pointer to NodeInfo for every node in the spec. */ nodes: Map; /** * For each node with at least one dependent, the set of nodes that reference it via $ref. * Nodes with no dependents are omitted from this map. */ reverseNodeDependencies: Map>; /** * For each node, the set of direct $ref targets that appear anywhere inside the node's * subtree (the node itself and its children). This is populated during graph construction * and is used to compute top-level dependency relationships where $ref may be attached to * child pointers instead of the parent. */ subtreeDependencies: Map>; /** * For each node, the set of all (transitive) normalized JSON Pointers it references via $ref anywhere in its subtree. * This includes both direct and indirect dependencies, making it useful for filtering, codegen, and tree-shaking. */ transitiveDependencies: Map>; }; /** * Information about a node in the OpenAPI graph. * * @property deprecated - Whether the node is deprecated. Optional. * @property key - The property name or array index in the parent, or null for root. * @property node - The actual object at this pointer in the spec. * @property parentPointer - The JSON Pointer of the parent node, or null for root. * @property scopes - The set of access scopes for this node, if any. Optional. * @property tags - The set of tags for this node, if any. Optional. */ export type NodeInfo = { /** Whether the node is deprecated. Optional. */ deprecated?: boolean; /** The property name or array index in the parent, or null for root. */ key: string | number | null; /** The actual object at this pointer in the spec. */ node: unknown; /** The JSON Pointer of the parent node, or null for root. */ parentPointer: string | null; /** The set of access scopes for this node, if any. Optional. */ scopes?: Set; /** The set of tags for this node, if any. Optional. */ tags?: Set; }; ================================================ FILE: packages/shared/src/graph/types/walk.ts ================================================ import type { Graph, NodeInfo } from './graph'; export type WalkCallbackFn = (pointer: string, nodeInfo: NodeInfo) => void; export type GetPointerPriorityFn = (pointer: string) => number; export type MatchPointerToGroupFn = ( pointer: string, kind?: T, ) => PointerGroupMatch; type PointerGroupMatch = | { kind: T; matched: true } | { kind?: undefined; matched: false }; export type WalkOptions = { /** * Optional priority function used to compute a numeric priority for each * pointer. Lower values are emitted earlier. Useful to customize ordering * beyond the built-in group preferences. */ getPointerPriority?: GetPointerPriorityFn; /** * Optional function to match a pointer to a group name. * * @param pointer The pointer string * @returns The group name, or undefined if no match */ matchPointerToGroup?: MatchPointerToGroupFn; /** * Order of walking schemas. * * The "declarations" option ensures that schemas are walked in the order * they are declared in the input document. This is useful for scenarios where * the order of declaration matters, such as when generating code that relies * on the sequence of schema definitions. * * The "topological" option ensures that schemas are walked in an order * where dependencies are visited before the schemas that depend on them. * This is useful for scenarios where you need to process or generate * schemas in a way that respects their interdependencies. * * @default 'topological' */ order?: 'declarations' | 'topological'; /** * Optional grouping preference for walking. When provided, walk function * will prefer emitting kinds listed earlier in this array when it is safe * to do so (it will only apply the preference when doing so does not * violate dependency ordering). */ preferGroups?: ReadonlyArray; }; export type WalkFn = ( graph: Graph, callback: WalkCallbackFn, options?: WalkOptions, ) => void; ================================================ FILE: packages/shared/src/graph/walk.ts ================================================ import { MinHeap } from '../utils/minHeap'; import type { GetPointerPriorityFn, WalkFn } from './types/walk'; /** * Walk the nodes of the graph in declaration (insertion) order. * This is a cheap alternative to `walkTopological` when dependency ordering * is not required and the caller only wants nodes in the order they were * added to the graph. */ const walkDeclarations: WalkFn = (graph, callback, options) => { const pointers = Array.from(graph.nodes.keys()); if (options?.preferGroups && options.preferGroups.length > 0) { // emit nodes that match each preferred group in order, preserving insertion order const emitted = new Set(); if (options.matchPointerToGroup) { for (const kind of options.preferGroups) { for (const pointer of pointers) { const result = options.matchPointerToGroup(pointer); if (!result.matched) continue; if (result.kind === kind) { emitted.add(pointer); callback(pointer, graph.nodes.get(pointer)!); } } } } // emit anything not covered by the preferGroups (in declaration order) for (const pointer of pointers) { if (emitted.has(pointer)) continue; callback(pointer, graph.nodes.get(pointer)!); } return; } // fallback: simple declaration order for (const pointer of pointers) { callback(pointer, graph.nodes.get(pointer)!); } }; /** * Walks the nodes of the graph in topological order (dependencies before dependents). * Calls the callback for each node pointer in order. * Nodes in cycles are grouped together and emitted in arbitrary order within the group. * * @param graph - The dependency graph * @param callback - Function to call for each node pointer */ const walkTopological: WalkFn = (graph, callback, options) => { // stable Kahn's algorithm that respects declaration order as a tiebreaker. const pointers = Array.from(graph.nodes.keys()); // base insertion order const baseIndex = new Map(); pointers.forEach((pointer, index) => baseIndex.set(pointer, index)); // composite decl index: group priority then base insertion order const declIndex = new Map(); for (const pointer of pointers) { const priority = options?.getPointerPriority?.(pointer) ?? 10; const composite = priority * 1_000_000 + (baseIndex.get(pointer) ?? 0); declIndex.set(pointer, composite); } // build dependency sets for each pointer const depsOf = new Map>(); for (const pointer of pointers) { const raw = graph.subtreeDependencies?.get(pointer) ?? new Set(); const filtered = new Set(); for (const rawPointer of raw) { if (rawPointer === pointer) continue; // ignore self-dependencies for ordering if (graph.nodes.has(rawPointer)) { filtered.add(rawPointer); } } depsOf.set(pointer, filtered); } // build inDegree and dependents adjacency const inDegree = new Map(); const dependents = new Map>(); for (const pointer of pointers) { inDegree.set(pointer, 0); } for (const [pointer, deps] of depsOf) { inDegree.set(pointer, deps.size); for (const d of deps) { if (!dependents.has(d)) { dependents.set(d, new Set()); } dependents.get(d)!.add(pointer); } } // sort pointers by declaration order const sortByDecl = (arr: Array) => arr.sort((a, b) => declIndex.get(a)! - declIndex.get(b)!); // initialize queue with zero-inDegree nodes in declaration order // use min-heap prioritized by declaration index to avoid repeated full sorts const heap = new MinHeap(declIndex); for (const pointer of pointers) { if ((inDegree.get(pointer) ?? 0) === 0) { heap.push(pointer); } } const emitted = new Set(); const order: Array = []; while (!heap.isEmpty()) { const cur = heap.pop()!; if (emitted.has(cur)) continue; emitted.add(cur); order.push(cur); const deps = dependents.get(cur); if (!deps) continue; for (const dep of deps) { const v = (inDegree.get(dep) ?? 0) - 1; inDegree.set(dep, v); if (v === 0) { heap.push(dep); } } } // emit remaining nodes (cycles) in declaration order const remaining = pointers.filter((pointer) => !emitted.has(pointer)); sortByDecl(remaining); for (const pointer of remaining) { emitted.add(pointer); order.push(pointer); } // prefer specified groups when safe let finalOrder = order; if (options?.preferGroups && options.preferGroups.length > 0) { // build group priority map (lower = earlier) const groupPriority = new Map(); for (let i = 0; i < options.preferGroups.length; i++) { const k = options.preferGroups[i]; if (k) { groupPriority.set(k, i); } } const getGroup: GetPointerPriorityFn = (pointer) => { if (options.matchPointerToGroup) { const result = options.matchPointerToGroup(pointer); if (result.matched) { return groupPriority.has(result.kind) ? groupPriority.get(result.kind)! : options.preferGroups!.length; } } return options.preferGroups!.length; }; // proposed order: sort by (groupPriority, originalIndex) const proposed = [...order].sort((a, b) => { const ga = getGroup(a); const gb = getGroup(b); return ga !== gb ? ga - gb : order.indexOf(a) - order.indexOf(b); }); // build quick lookup of original index and proposed index const proposedIndex = new Map(); for (let i = 0; i < proposed.length; i++) { proposedIndex.set(proposed[i]!, i); } // only validate edges where group(dep) > group(node) const violated = (() => { for (const [node, deps] of depsOf) { for (const dep of deps) { const gDep = getGroup(dep); const gNode = getGroup(node); if (gDep <= gNode) continue; // not a crossing edge, cannot be violated by grouping const pDep = proposedIndex.get(dep)!; const pNode = proposedIndex.get(node)!; if (pDep >= pNode) { return true; } } } return false; })(); if (!violated) { finalOrder = proposed; } } for (const pointer of finalOrder) { callback(pointer, graph.nodes.get(pointer)!); } }; export const walk: WalkFn = (graph, callback, options) => { if (options?.order === 'topological') { return walkTopological(graph, callback, options); } return walkDeclarations(graph, callback, options); }; ================================================ FILE: packages/shared/src/index.ts ================================================ export { isEnvironment, printCliIntro } from './cli'; export { checkNodeVersion } from './config/engine'; export { getInput } from './config/input/input'; export { compileInputPath, logInputPaths } from './config/input/path'; export type { Input, UserInput, UserWatch, Watch } from './config/input/types'; export { getLogs } from './config/logs'; export type { PostProcessor, UserPostProcessor } from './config/output/postprocess'; export { postprocessOutput } from './config/output/postprocess'; export { resolveSource } from './config/output/source/config'; export type { SourceConfig, UserSourceConfig } from './config/output/source/types'; export type { OutputHeader } from './config/output/types'; export { defaultPaginationKeywords, getParser } from './config/parser/config'; export type { Filters } from './config/parser/filters'; export type { Patch } from './config/parser/patch'; export type { Parser, UserParser } from './config/parser/types'; export type { AnyConfig, BaseConfig, BaseOutput, BaseUserConfig, BaseUserOutput, CommentsOption, FeatureToggle, IndexExportOption, NamingOptions, ResolveModuleFn, UserCommentsOption, UserIndexExportOption, } from './config/shared'; export type { ValueToObject } from './config/utils/config'; export { valueToObject } from './config/utils/config'; export type { Dependency } from './config/utils/dependencies'; export { dependencyFactory, satisfies } from './config/utils/dependencies'; export { debugTools } from './debug'; export { ConfigError, ConfigValidationError, HeyApiError, JobError, logCrashReport, openGitHubIssueWithCrashReport, printCrashReport, shouldReportCrash, } from './error'; export { ensureDirSync } from './fs'; export { getSpec } from './getSpec'; export { Context } from './ir/context'; export { IntentContext } from './ir/intents'; export { createOperationKey, hasOperationDataRequired, operationPagination, operationResponsesMap, statusCodeToGroup, } from './ir/operation'; export { hasParameterGroupObjectRequired, hasParametersObjectRequired, parameterWithPagination, } from './ir/parameter'; export { deduplicateSchema } from './ir/schema'; export type { SchemaExtractor, SchemaProcessor, SchemaProcessorContext, SchemaProcessorResult, } from './ir/schema-processor'; export { createSchemaProcessor } from './ir/schema-processor'; export type { SchemaVisitor, SchemaVisitorContext, Walker } from './ir/schema-walker'; export { childContext, createSchemaWalker } from './ir/schema-walker'; export type { IR, IRModel, IROperationObject, IRParameterObject, IRParametersObject, IRSchemaObject, IRServerObject, } from './ir/types'; export { addItemsToSchema } from './ir/utils'; export { parseOpenApiSpec } from './openApi'; export type { OpenApiV2_0_X, OpenApiV2_0_XTypes } from './openApi/2.0.x'; export { parseV2_0_X } from './openApi/2.0.x'; export type { OpenApiV3_0_X, OpenApiV3_0_XTypes } from './openApi/3.0.x'; export { parseV3_0_X } from './openApi/3.0.x'; export type { OpenApiV3_1_X, OpenApiV3_1_XTypes } from './openApi/3.1.x'; export { parseV3_1_X } from './openApi/3.1.x'; export type { OperationsStrategy } from './openApi/shared/locations'; export type { OperationPathStrategy, OperationStructureStrategy } from './openApi/shared/locations'; export { OperationPath, OperationStrategy } from './openApi/shared/locations'; export type { CodeSampleObject, EnumExtensions, LinguistLanguages, } from './openApi/shared/types/openapi-spec-extensions'; export { buildGraph } from './openApi/shared/utils/graph'; export { patchOpenApiSpec } from './openApi/shared/utils/patch'; export type { OpenApi, OpenApiMetaObject, OpenApiOperationObject, OpenApiParameterObject, OpenApiRequestBodyObject, OpenApiResponseObject, OpenApiSchemaObject, } from './openApi/types'; export type { GetNameContext, Hooks } from './parser/hooks'; export type { SchemaWithType } from './plugins/shared/types/schema'; export { definePluginConfig, mappers } from './plugins/shared/utils/config'; export type { PluginInstanceTypes } from './plugins/shared/utils/instance'; export { PluginInstance } from './plugins/shared/utils/instance'; export { buildSymbolIn } from './plugins/symbol'; export type { AnyPluginName, DefinePlugin, Plugin, PluginConfigMap, PluginContext, PluginNames, } from './plugins/types'; export { findPackageJson, findTsConfigPath, loadPackageJson } from './tsConfig'; export type { Logs } from './types/logs'; export type { WatchValues } from './types/watch'; export { escapeComment } from './utils/escape'; export { utils } from './utils/exports'; export { outputHeaderToPrefix } from './utils/header'; export { inputToApiRegistry } from './utils/input'; export { heyApiRegistryBaseUrl } from './utils/input/heyApi'; export { MinHeap } from './utils/minHeap'; export { applyNaming, resolveNaming, toCase } from './utils/naming/naming'; export type { Casing, NameTransformer, NamingConfig, NamingRule } from './utils/naming/types'; export { pathToName } from './utils/path'; export { encodeJsonPointerSegment, isTopLevelComponent, jsonPointerToPath, normalizeJsonPointer, pathToJsonPointer, refToName, resolveRef, } from './utils/ref'; export { parseUrl } from './utils/url'; ================================================ FILE: packages/shared/src/ir/__tests__/graph.test.ts ================================================ import type { IrTopLevelKind } from '../graph'; import { matchIrPointerToGroup } from '../graph'; describe('matchIrPointerToGroup', () => { const cases: Array< [string, IrTopLevelKind | undefined, { kind?: IrTopLevelKind; matched: boolean }] > = [ ['#/components/schemas/Foo', undefined, { kind: 'schema', matched: true }], ['#/components/schemas/Foo', 'schema', { kind: 'schema', matched: true }], ['#/components/schemas/Foo', 'parameter', { matched: false }], ['#/components/parameters/Bar', undefined, { kind: 'parameter', matched: true }], ['#/components/parameters/Bar', 'parameter', { kind: 'parameter', matched: true }], ['#/components/parameters/Bar', 'schema', { matched: false }], ['#/components/requestBodies/Baz', undefined, { kind: 'requestBody', matched: true }], ['#/components/requestBodies/Baz', 'requestBody', { kind: 'requestBody', matched: true }], ['#/components/requestBodies/Baz', 'schema', { matched: false }], ['#/servers/0', undefined, { kind: 'server', matched: true }], ['#/servers/foo', undefined, { kind: 'server', matched: true }], ['#/paths/~1users/get', undefined, { kind: 'operation', matched: true }], ['#/paths/~1users/post', 'operation', { kind: 'operation', matched: true }], ['#/webhooks/foo/get', undefined, { kind: 'webhook', matched: true }], ['#/webhooks/foo/patch', 'webhook', { kind: 'webhook', matched: true }], ['#/not/a/top/level', undefined, { matched: false }], ['#/components/unknown/Foo', undefined, { matched: false }], ]; for (const [pointer, kind, expected] of cases) { it(`matches ${pointer} with kind=${kind}`, () => { const result = matchIrPointerToGroup(pointer, kind as IrTopLevelKind); expect(result.matched).toBe(expected.matched); if (expected.matched) { expect(result.kind).toBe(expected.kind); } else { expect(result.kind).toBeUndefined(); } }); } }); ================================================ FILE: packages/shared/src/ir/__tests__/mediaType.test.ts ================================================ import type { IRMediaType } from '../mediaType'; import { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../mediaType'; describe('isMediaTypeFileLike', () => { const scenarios: Array<{ mediaType: string; response: boolean; }> = [ { mediaType: 'application/json', response: false, }, { mediaType: 'application/json+download', response: true, }, { mediaType: 'application/json; charset=ascii', response: false, }, { mediaType: 'application/octet-stream', response: true, }, { mediaType: 'application/pdf', response: true, }, { mediaType: 'application/xml; charset=utf-8', response: true, }, { mediaType: 'application/zip', response: true, }, { mediaType: 'image/jpeg', response: false, }, { mediaType: 'image/jpeg; charset=utf-8', response: false, }, { mediaType: 'text/html; charset=utf-8', response: false, }, { mediaType: 'text/javascript; charset=ISO-8859-1', response: true, }, { mediaType: 'text/plain; charset=utf-8', response: false, }, { mediaType: 'video/mp4', response: true, }, ]; it.each(scenarios)( 'detects $mediaType as file-like? $response', async ({ mediaType, response }) => { expect(isMediaTypeFileLike({ mediaType })).toEqual(response); }, ); }); describe('mediaTypeToIrMediaType', () => { const scenarios: Array<{ mediaType: string; response: IRMediaType | undefined; }> = [ { mediaType: 'multipart/form-data', response: 'form-data', }, { mediaType: 'application/json', response: 'json', }, { mediaType: 'text/plain; charset=utf-8', response: 'text', }, { mediaType: 'application/x-www-form-urlencoded', response: 'url-search-params', }, { mediaType: 'application/octet-stream', response: 'octet-stream', }, { mediaType: 'application/foo', response: undefined, }, ]; it.each(scenarios)('ir media type for $mediaType: $response', async ({ mediaType, response }) => { expect(mediaTypeToIrMediaType({ mediaType })).toEqual(response); }); }); ================================================ FILE: packages/shared/src/ir/__tests__/pagination.test.ts ================================================ import { defaultPaginationKeywords } from '../../config/parser/config'; import type { Parser } from '../../config/parser/types'; import type { Context } from '../context'; import { operationPagination } from '../operation'; import { getPaginationKeywordsRegExp } from '../pagination'; import type { IR } from '../types'; describe('paginationKeywordsRegExp', () => { const defaultScenarios: ReadonlyArray<{ result: boolean; value: string; }> = [ { result: true, value: 'after', }, { result: true, value: 'before', }, { result: true, value: 'cursor', }, { result: true, value: 'offset', }, { result: true, value: 'page', }, { result: true, value: 'start', }, { result: false, value: 'my_start', }, { result: false, value: 'start_my', }, ]; it.each(defaultScenarios)('is $value pagination param? $output', async ({ result, value }) => { const paginationRegExp = getPaginationKeywordsRegExp({ keywords: defaultPaginationKeywords, }); expect(paginationRegExp.test(value)).toEqual(result); }); const customScenarios: ReadonlyArray<{ result: boolean; value: string; }> = [ { result: true, value: 'customPagination' }, { result: true, value: 'pageSize' }, { result: true, value: 'perPage' }, { result: false, value: 'page' }, ]; it.each(customScenarios)( 'with custom config, $value should match? $result', async ({ result, value }) => { const pagination: Parser['pagination'] = { keywords: ['customPagination', 'pageSize', 'perPage'], }; const paginationRegExp = getPaginationKeywordsRegExp(pagination); expect(paginationRegExp.test(value)).toEqual(result); }, ); }); describe('operationPagination', () => { const queryParam = ( name: string, type: IR.SchemaObject['type'] = 'string', pagination = false, ): IR.ParameterObject => ({ explode: true, location: 'query', name, schema: { type }, style: 'form', ...(pagination ? { pagination: true } : {}), }); const emptyContext = {} as Context; const baseOperationMeta = { method: 'post' as const, path: '/test' as const, }; const queryScenarios: ReadonlyArray<{ hasPagination: boolean; operation: IR.OperationObject; }> = [ { hasPagination: true, operation: { ...baseOperationMeta, id: 'op1', method: 'get', parameters: { query: { page: queryParam('page', 'integer', true), }, }, }, }, { hasPagination: false, operation: { ...baseOperationMeta, id: 'op2', method: 'get', parameters: { query: { sort: queryParam('sort', 'string'), }, }, }, }, { hasPagination: true, operation: { ...baseOperationMeta, id: 'op3', method: 'get', parameters: { query: { pagesize: queryParam('pageSize', 'string', true), }, }, }, }, ]; it.each(queryScenarios)( 'query params for $operation.id → $hasPagination', ({ hasPagination, operation }: (typeof queryScenarios)[number]) => { const pagination = operationPagination({ context: emptyContext, operation, }); expect(Boolean(pagination)).toEqual(hasPagination); if (pagination && pagination.in !== 'body') { const parameter = operation.parameters?.[pagination.in]?.[pagination.name.toLocaleLowerCase()]; if (parameter) { expect(pagination.name).toBe(parameter.name); } } }, ); it('body.pagination === true returns entire body', () => { const operation: IR.OperationObject = { ...baseOperationMeta, body: { mediaType: 'application/json', pagination: true, schema: { properties: { page: { type: 'integer' }, }, type: 'object', }, }, id: 'bodyTrue', }; const result = operationPagination({ context: emptyContext, operation }); expect(result?.in).toEqual('body'); expect(result?.name).toEqual('body'); expect(result?.schema?.type).toEqual('object'); }); it('body.pagination = "pagination" returns the matching property', () => { const operation: IR.OperationObject = { ...baseOperationMeta, body: { mediaType: 'application/json', pagination: 'pagination', schema: { properties: { pagination: { properties: { page: { type: 'integer' }, }, type: 'object', }, }, type: 'object', }, }, id: 'bodyField', }; const result = operationPagination({ context: emptyContext, operation }); expect(result?.in).toEqual('body'); expect(result?.name).toEqual('pagination'); expect(result?.schema?.type).toEqual('object'); }); it('resolves $ref and uses the resolved pagination property', () => { const context: Context = { resolveIrRef: vi.fn().mockReturnValue({ properties: { pagination: { properties: { page: { type: 'integer' }, }, type: 'object', }, }, type: 'object', }), } as unknown as Context; const operation: IR.OperationObject = { ...baseOperationMeta, body: { mediaType: 'application/json', pagination: 'pagination', schema: { $ref: '#/components/schemas/PaginationBody' }, }, id: 'refPagination', }; const result = operationPagination({ context, operation }); expect(context.resolveIrRef).toHaveBeenCalledWith('#/components/schemas/PaginationBody'); expect(result?.in).toEqual('body'); expect(result?.name).toEqual('pagination'); expect(result?.schema?.type).toEqual('object'); }); it('falls back to query when pagination key not found in body', () => { const operation: IR.OperationObject = { ...baseOperationMeta, body: { mediaType: 'application/json', pagination: 'pagination', schema: { properties: { notPagination: { type: 'string' }, }, type: 'object', }, }, id: 'fallback', parameters: { query: { cursor: queryParam('cursor', 'string', true), }, }, }; const result = operationPagination({ context: emptyContext, operation }); expect(result?.in).toEqual('query'); expect(result?.name).toEqual('cursor'); expect(result?.schema?.type).toEqual('string'); }); }); ================================================ FILE: packages/shared/src/ir/__tests__/schema.test.ts ================================================ import { deduplicateSchema } from '../schema'; import type { IR } from '../types'; describe('deduplicateSchema', () => { const scenarios: ReadonlyArray<{ description: string; detectFormat?: boolean; result: IR.SchemaObject; schema: IR.SchemaObject; }> = [ { description: 'keeps multiple strings if they have different formats', result: { items: [ { format: 'uuid', type: 'string', }, { type: 'string', }, ], logicalOperator: 'or', }, schema: { items: [ { format: 'uuid', type: 'string', }, { type: 'string', }, ], logicalOperator: 'or', }, }, { description: 'discards duplicate strings if they have different formats and `detectFormat` is `false`', detectFormat: false, result: { format: 'uuid', type: 'string', }, schema: { items: [ { format: 'uuid', type: 'string', }, { type: 'string', }, ], logicalOperator: 'or', }, }, ]; it.each(scenarios)('$description', ({ detectFormat, result, schema }) => { expect(deduplicateSchema({ detectFormat, schema })).toEqual(result); }); }); ================================================ FILE: packages/shared/src/ir/context.ts ================================================ import type { Logger, Project } from '@hey-api/codegen-core'; import type { AnyConfig } from '../config/shared'; import type { Dependency } from '../config/utils/dependencies'; import { dependencyFactory } from '../config/utils/dependencies'; import type { Graph } from '../graph'; import { PluginInstance } from '../plugins/shared/utils/instance'; import type { Plugin, PluginConfigMap, PluginNames } from '../plugins/types'; import { resolveRef } from '../utils/ref'; import type { ExampleIntent } from './intents'; import type { IR } from './types'; export class Context = any, Config extends AnyConfig = AnyConfig> { /** * Configuration for parsing and generating the output. This * is a mix of user-provided and default values. */ config: Config; /** * The code generation project instance used to manage files, symbols, */ gen: Project; /** * The dependency graph built from the intermediate representation. */ graph: Graph | undefined; /** * Intents declared by plugins. */ intents: Array = []; /** * Intermediate representation model obtained from `spec`. */ ir: IR.Model = {}; /** * Logger instance. */ logger: Logger; /** * The package metadata and utilities for the current context, constructed * from the provided dependencies. Used for managing package-related * information such as name, version, and dependency resolution during * code generation. */ package: Dependency; /** * A map of registered plugin instances, keyed by plugin name. Plugins are * registered through the `registerPlugin` method and can be accessed by * their configured name from the config. */ plugins: Partial>> = {}; /** * Resolved specification from `input`. */ spec: Spec; constructor({ config, dependencies, logger, project, spec, }: { config: Config; dependencies: Record; logger: Logger; project: Project; spec: Spec; }) { this.config = config; this.gen = project; this.logger = logger; this.package = dependencyFactory(dependencies); this.spec = spec; } /** * Returns a resolved and dereferenced schema from `spec`. */ dereference(schema: { $ref: string }) { const resolved = this.resolveRef(schema.$ref); const dereferenced = { ...schema, ...resolved, } as T; // @ts-expect-error delete dereferenced.$ref; return dereferenced; } /** * Registers a new plugin to the global context. * * @param name Plugin name. * @returns Registered plugin instance. */ private registerPlugin( name: T, ): T extends keyof PluginConfigMap ? PluginInstance : PluginInstance { const plugin = (this.config.plugins as Record>)[name]!; const instance = new PluginInstance({ api: plugin.api, config: plugin.config as any, context: this as any, dependencies: plugin.dependencies ?? [], gen: this.gen, handler: plugin.handler, name: plugin.name, }); (this.plugins as Record)[instance.name] = instance; return instance as T extends keyof PluginConfigMap ? PluginInstance : PluginInstance; } /** * Registers all plugins in the order specified by the configuration and returns * an array of the registered PluginInstance objects. Each plugin is instantiated * and added to the context's plugins map. * * @returns {ReadonlyArray} An array of registered plugin instances in order. */ registerPlugins(): ReadonlyArray { return this.config.pluginOrder.map((name) => this.registerPlugin(name)); } // TODO: parser - works the same as resolveRef, but for IR schemas. // for now, they map 1:1, but if they diverge (like with OpenAPI 2.0), // we will want to rewrite $refs at parse time, so they continue pointing // to the correct IR location resolveIrRef($ref: string) { return resolveRef({ $ref, spec: this.ir, }); } /** * Returns a resolved reference from `spec`. */ resolveRef($ref: string) { return resolveRef({ $ref, spec: this.spec, }); } } ================================================ FILE: packages/shared/src/ir/graph.ts ================================================ import type { GetPointerPriorityFn, MatchPointerToGroupFn } from '../graph'; export const irTopLevelKinds = [ 'operation', 'parameter', 'requestBody', 'schema', 'server', 'webhook', ] as const; export type IrTopLevelKind = (typeof irTopLevelKinds)[number]; /** * Checks if a pointer matches a known top-level IR component (schema, parameter, etc) and returns match info. * * @param pointer - The IR pointer string (e.g. '#/components/schemas/Foo') * @param kind - (Optional) The component kind to check * @returns { matched: true, kind: IrTopLevelKind } | { matched: false } - Whether it matched, and the matched kind if so */ export const matchIrPointerToGroup: MatchPointerToGroupFn = (pointer, kind) => { const patterns: Record = { operation: /^#\/paths\/[^/]+\/(get|put|post|delete|options|head|patch|trace)$/, parameter: /^#\/components\/parameters\/[^/]+$/, requestBody: /^#\/components\/requestBodies\/[^/]+$/, schema: /^#\/components\/schemas\/[^/]+$/, server: /^#\/servers\/(\d+|[^/]+)$/, webhook: /^#\/webhooks\/[^/]+\/(get|put|post|delete|options|head|patch|trace)$/, }; if (kind) { return patterns[kind].test(pointer) ? { kind, matched: true } : { matched: false }; } for (const key of Object.keys(patterns)) { const kind = key as IrTopLevelKind; if (patterns[kind].test(pointer)) { return { kind, matched: true }; } } return { matched: false }; }; // default grouping preference (earlier groups emitted first when safe) export const preferGroups = [ 'server', 'schema', 'parameter', 'requestBody', 'operation', 'webhook', ] satisfies ReadonlyArray; type KindPriority = Record; // default group priority (lower = earlier) // built from `preferGroups` so the priority order stays in sync with the prefer-groups array. const kindPriority: KindPriority = (() => { const partial: Partial = {}; for (let i = 0; i < preferGroups.length; i++) { const k = preferGroups[i]; if (k) partial[k] = i; } // Ensure all known kinds exist in the map (fall back to a high index). for (const k of irTopLevelKinds) { if (partial[k] === undefined) { partial[k] = preferGroups.length; } } return partial as KindPriority; })(); const defaultPriority = 10; export const getIrPointerPriority: GetPointerPriorityFn = (pointer) => { const result = matchIrPointerToGroup(pointer); if (result.matched) { return kindPriority[result.kind] ?? defaultPriority; } return defaultPriority; }; ================================================ FILE: packages/shared/src/ir/intents.ts ================================================ import type { MaybePromise } from '@hey-api/types'; import type { CodeSampleObject } from '..//openApi/shared/types'; import type { IR } from './types'; export interface ExampleIntent { run(ctx: IntentContext): MaybePromise; } export class IntentContext = any> { private spec: Spec; constructor(spec: Spec) { this.spec = spec; } private getOperation(path: string, method: string): Record | undefined { const paths = (this.spec as any).paths; if (!paths) return; return paths[path]?.[method]; } setExample(operation: IR.OperationObject, example: CodeSampleObject): void { const source = this.getOperation(operation.path, operation.method); if (!source) return; source['x-codeSamples'] ||= []; source['x-codeSamples'].push(example); } } ================================================ FILE: packages/shared/src/ir/mediaType.ts ================================================ const fileLikeRegExp = /^(application\/(pdf|rtf|msword|vnd\.(ms-|openxmlformats-officedocument\.)|zip|x-(7z|tar|rar|zip|iso)|octet-stream|gzip|x-msdownload|json\+download|xml|x-yaml|x-7z-compressed|x-tar)|text\/(yaml|css|javascript)|audio\/(mpeg|wav)|video\/(mp4|x-matroska)|image\/(vnd\.adobe\.photoshop|svg\+xml))(; ?charset=[^;]+)?$/i; const jsonMimeRegExp = /^application\/(.*\+)?json(;.*)?$/i; const multipartFormDataMimeRegExp = /^multipart\/form-data(;.*)?$/i; const textMimeRegExp = /^text\/[a-z0-9.+-]+(;.*)?$/i; const xWwwFormUrlEncodedMimeRegExp = /^application\/x-www-form-urlencoded(;.*)?$/i; const octetStreamMimeRegExp = /^application\/octet-stream(;.*)?$/i; export type IRMediaType = 'form-data' | 'json' | 'text' | 'url-search-params' | 'octet-stream'; export const isMediaTypeFileLike = ({ mediaType }: { mediaType: string }): boolean => { fileLikeRegExp.lastIndex = 0; return fileLikeRegExp.test(mediaType); }; export const mediaTypeToIrMediaType = ({ mediaType, }: { mediaType: string; }): IRMediaType | undefined => { jsonMimeRegExp.lastIndex = 0; if (jsonMimeRegExp.test(mediaType)) { return 'json'; } multipartFormDataMimeRegExp.lastIndex = 0; if (multipartFormDataMimeRegExp.test(mediaType)) { return 'form-data'; } textMimeRegExp.lastIndex = 0; if (textMimeRegExp.test(mediaType)) { return 'text'; } xWwwFormUrlEncodedMimeRegExp.lastIndex = 0; if (xWwwFormUrlEncodedMimeRegExp.test(mediaType)) { return 'url-search-params'; } octetStreamMimeRegExp.lastIndex = 0; if (octetStreamMimeRegExp.test(mediaType)) { return 'octet-stream'; } return; }; ================================================ FILE: packages/shared/src/ir/operation.ts ================================================ import type { Context } from './context'; import type { Pagination } from './pagination'; import { hasParametersObjectRequired, parameterWithPagination } from './parameter'; import { deduplicateSchema } from './schema'; import type { IR } from './types'; import { addItemsToSchema } from './utils'; export const hasOperationDataRequired = (operation: IR.OperationObject): boolean => { if (hasParametersObjectRequired(operation.parameters)) { return true; } if (operation.body?.required) { return true; } return false; }; export const createOperationKey = ({ method, path }: { method: string; path: string }) => `${method.toUpperCase()} ${path}`; export const operationPagination = ({ context, operation, }: { context: Context; operation: IR.OperationObject; }): Pagination | undefined => { const body = operation.body; if (!body || !body.pagination) { return parameterWithPagination({ context, parameters: operation.parameters, }); } if (body.pagination === true) { return { in: 'body', name: 'body', schema: body.schema, }; } const schema = body.schema; const resolvedSchema = schema.$ref ? context.resolveIrRef(schema.$ref) : schema; const finalSchema = 'schema' in resolvedSchema ? resolvedSchema.schema : resolvedSchema; const paginationProp = finalSchema?.properties?.[body.pagination]; if (!paginationProp) { return parameterWithPagination({ context, parameters: operation.parameters, }); } return { in: 'body', name: body.pagination, schema: paginationProp, }; }; type StatusGroup = '1XX' | '2XX' | '3XX' | '4XX' | '5XX' | 'default'; export const statusCodeToGroup = ({ statusCode }: { statusCode: string }): StatusGroup => { switch (statusCode) { case '1XX': return '1XX'; case '2XX': return '2XX'; case '3XX': return '3XX'; case '4XX': return '4XX'; case '5XX': return '5XX'; case 'default': return 'default'; default: return `${statusCode[0]}XX` as StatusGroup; } }; interface OperationResponsesMap { /** * A deduplicated union of all error types. Unknown types are omitted. */ error?: IR.SchemaObject; /** * An object containing a map of status codes for each error type. */ errors?: IR.SchemaObject; /** * A deduplicated union of all response types. Unknown types are omitted. */ response?: IR.SchemaObject; /** * An object containing a map of status codes for each response type. */ responses?: IR.SchemaObject; } export const operationResponsesMap = (operation: IR.OperationObject): OperationResponsesMap => { const result: OperationResponsesMap = {}; if (!operation.responses) { return result; } const errors: Omit & Pick, 'properties'> = { properties: {}, type: 'object', }; const responses: Omit & Pick, 'properties'> = { properties: {}, type: 'object', }; // store default response to be evaluated last let defaultResponse: IR.ResponseObject | undefined; for (const name in operation.responses) { const response = operation.responses[name]!; switch (statusCodeToGroup({ statusCode: name })) { case '1XX': case '3XX': // TODO: parser - handle informational and redirection status codes break; case '2XX': responses.properties[name] = response.schema; break; case '4XX': case '5XX': errors.properties[name] = response.schema; break; case 'default': defaultResponse = response; break; } } // infer default response type if (defaultResponse) { let inferred = false; // assume default is intended for success if none exists yet if (!Object.keys(responses.properties).length) { responses.properties.default = defaultResponse.schema; inferred = true; } const description = (defaultResponse.schema.description ?? '').toLocaleLowerCase(); const $ref = (defaultResponse.schema.$ref ?? '').toLocaleLowerCase(); // TODO: parser - this could be rewritten using regular expressions const successKeywords = ['success']; if ( successKeywords.some((keyword) => description.includes(keyword) || $ref.includes(keyword)) ) { responses.properties.default = defaultResponse.schema; inferred = true; } // TODO: parser - this could be rewritten using regular expressions const errorKeywords = ['error', 'problem']; if (errorKeywords.some((keyword) => description.includes(keyword) || $ref.includes(keyword))) { errors.properties.default = defaultResponse.schema; inferred = true; } // if no keyword match, assume default schema is intended for error if (!inferred) { errors.properties.default = defaultResponse.schema; } } const errorKeys = Object.keys(errors.properties); if (errorKeys.length) { errors.required = errorKeys; result.errors = errors; let errorUnion = addItemsToSchema({ items: Object.values(errors.properties), mutateSchemaOneItem: true, schema: {}, }); errorUnion = deduplicateSchema({ schema: errorUnion }); if (Object.keys(errorUnion).length && errorUnion.type !== 'unknown') { result.error = errorUnion; } } const responseKeys = Object.keys(responses.properties); if (responseKeys.length) { responses.required = responseKeys; result.responses = responses; let responseUnion = addItemsToSchema({ items: Object.values(responses.properties), mutateSchemaOneItem: true, schema: {}, }); responseUnion = deduplicateSchema({ schema: responseUnion }); if (Object.keys(responseUnion).length && responseUnion.type !== 'unknown') { result.response = responseUnion; } } return result; }; ================================================ FILE: packages/shared/src/ir/pagination.ts ================================================ import type { Parser } from '../config/parser/types'; import type { IR } from './types'; export function getPaginationKeywordsRegExp(pagination: Parser['pagination']): RegExp { const pattern = `^(${pagination.keywords.join('|')})$`; return new RegExp(pattern); } export interface Pagination { in: 'body' | 'cookie' | 'header' | 'path' | 'query'; name: string; schema: IR.SchemaObject; } ================================================ FILE: packages/shared/src/ir/parameter.ts ================================================ import type { Context } from './context'; import type { Pagination } from './pagination'; import type { IR } from './types'; const getPaginationSchema = ({ context, parameter, }: { context: Context; parameter: IR.ParameterObject; }): IR.SchemaObject | undefined => { if (!parameter.pagination) { return; } if (parameter.pagination === true) { return parameter.schema; } let schema = parameter.schema; if (schema.$ref) { schema = context.resolveIrRef(schema.$ref); } return schema.properties![parameter.pagination]!; }; export const hasParameterGroupObjectRequired = ( parameterGroup?: Record, ): boolean => { for (const name in parameterGroup) { if (parameterGroup[name]!.required) { return true; } } return false; }; export const hasParametersObjectRequired = ( parameters: IR.ParametersObject | undefined, ): boolean => { if (!parameters) { return false; } if (hasParameterGroupObjectRequired(parameters.cookie)) { return true; } if (hasParameterGroupObjectRequired(parameters.header)) { return true; } if (hasParameterGroupObjectRequired(parameters.path)) { return true; } if (hasParameterGroupObjectRequired(parameters.query)) { return true; } return false; }; export const parameterWithPagination = ({ context, parameters, }: { context: Context; parameters: IR.ParametersObject | undefined; }): Pagination | undefined => { if (!parameters) { return; } for (const name in parameters.cookie) { const parameter = parameters.cookie[name]!; if (parameter.pagination) { return { in: parameter.location, name: parameter.pagination === true ? parameter.name : `${parameter.name}.${parameter.pagination}`, schema: getPaginationSchema({ context, parameter })!, }; } } for (const name in parameters.header) { const parameter = parameters.header[name]!; if (parameter.pagination) { return { in: parameter.location, name: parameter.pagination === true ? parameter.name : `${parameter.name}.${parameter.pagination}`, schema: getPaginationSchema({ context, parameter })!, }; } } for (const name in parameters.path) { const parameter = parameters.path[name]!; if (parameter.pagination) { return { in: parameter.location, name: parameter.pagination === true ? parameter.name : `${parameter.name}.${parameter.pagination}`, schema: getPaginationSchema({ context, parameter })!, }; } } for (const name in parameters.query) { const parameter = parameters.query[name]!; if (parameter.pagination) { return { in: parameter.location, name: parameter.pagination === true ? parameter.name : `${parameter.name}.${parameter.pagination}`, schema: getPaginationSchema({ context, parameter })!, }; } } return; }; ================================================ FILE: packages/shared/src/ir/schema-processor.ts ================================================ import { pathToJsonPointer } from '../utils/ref'; import type { IR } from './types'; export interface SchemaProcessor { /** Current inherited context (set by withContext) */ readonly context: { readonly anchor: string | undefined; readonly tags: ReadonlyArray | undefined; }; /** Check if pointer was already emitted */ hasEmitted: (path: ReadonlyArray) => boolean; /** Mark pointer as emitted. Returns false if already emitted. */ markEmitted: (path: ReadonlyArray) => boolean; /** Execute with inherited context for nested extractions */ withContext: (ctx: { anchor?: string; tags?: ReadonlyArray }, fn: () => T) => T; } export interface SchemaProcessorContext { meta: { resource: string; resourceId: string; role?: string }; namingAnchor?: string; path: ReadonlyArray; schema: IR.SchemaObject; tags?: ReadonlyArray; } export interface SchemaProcessorResult< Context extends SchemaProcessorContext = SchemaProcessorContext, > { process: (ctx: Context) => void; } export type SchemaExtractor = ( ctx: Context, ) => IR.SchemaObject; export function createSchemaProcessor(): SchemaProcessor { const emitted = new Set(); let contextTags: ReadonlyArray | undefined; let contextAnchor: string | undefined; return { get context() { return { anchor: contextAnchor, tags: contextTags, }; }, hasEmitted(path) { return emitted.has(pathToJsonPointer(path)); }, markEmitted(path) { const pointer = pathToJsonPointer(path); if (emitted.has(pointer)) return false; emitted.add(pointer); return true; }, withContext(ctx, fn) { const prevTags = contextTags; const prevAnchor = contextAnchor; contextTags = ctx.tags; contextAnchor = ctx.anchor; try { return fn(); } finally { contextTags = prevTags; contextAnchor = prevAnchor; } }, }; } ================================================ FILE: packages/shared/src/ir/schema-walker.ts ================================================ import type { Ref } from '@hey-api/codegen-core'; import { fromRef, ref } from '@hey-api/codegen-core'; import type { SchemaWithType } from '../plugins/shared/types/schema'; import { deduplicateSchema } from './schema'; import type { IR } from './types'; /** * Context passed to all visitor methods. */ export interface SchemaVisitorContext { /** Current path in the schema tree. */ path: Ref>; /** The plugin instance. */ plugin: TPlugin; } /** * The walk function signature. Fully generic over TResult. */ export type Walker = ( schema: IR.SchemaObject, ctx: SchemaVisitorContext, ) => TResult; /** * The visitor interface. Plugins define their own TResult type. * * The walker handles orchestration (dispatch, deduplication, path tracking). * Result shape and semantics are entirely plugin-defined. */ export interface SchemaVisitor { /** * Apply modifiers to a result. */ applyModifiers( result: TResult, ctx: SchemaVisitorContext, context?: { /** Is this property optional? */ optional?: boolean; }, ): unknown; array( schema: SchemaWithType<'array'>, ctx: SchemaVisitorContext, walk: Walker, ): TResult; boolean(schema: SchemaWithType<'boolean'>, ctx: SchemaVisitorContext): TResult; enum( schema: SchemaWithType<'enum'>, ctx: SchemaVisitorContext, walk: Walker, ): TResult; integer(schema: SchemaWithType<'integer'>, ctx: SchemaVisitorContext): TResult; /** * Called before any dispatch logic. Return a result to short-circuit, * or undefined to continue normal dispatch. */ intercept?( schema: IR.SchemaObject, ctx: SchemaVisitorContext, walk: Walker, ): TResult | undefined; /** * Handle intersection types. Receives already-walked child results. */ intersection( items: Array, schemas: ReadonlyArray, parentSchema: IR.SchemaObject, ctx: SchemaVisitorContext, ): TResult; never(schema: SchemaWithType<'never'>, ctx: SchemaVisitorContext): TResult; null(schema: SchemaWithType<'null'>, ctx: SchemaVisitorContext): TResult; number(schema: SchemaWithType<'number'>, ctx: SchemaVisitorContext): TResult; object( schema: SchemaWithType<'object'>, ctx: SchemaVisitorContext, walk: Walker, ): TResult; /** * Called after each typed schema visitor returns. */ postProcess?( result: TResult, schema: IR.SchemaObject, ctx: SchemaVisitorContext, ): TResult; /** * Handle $ref to another schema. */ reference($ref: string, schema: IR.SchemaObject, ctx: SchemaVisitorContext): TResult; string(schema: SchemaWithType<'string'>, ctx: SchemaVisitorContext): TResult; tuple( schema: SchemaWithType<'tuple'>, ctx: SchemaVisitorContext, walk: Walker, ): TResult; undefined(schema: SchemaWithType<'undefined'>, ctx: SchemaVisitorContext): TResult; /** * Handle union types. Receives already-walked child results. */ union( items: Array, schemas: ReadonlyArray, parentSchema: IR.SchemaObject, ctx: SchemaVisitorContext, ): TResult; unknown(schema: SchemaWithType<'unknown'>, ctx: SchemaVisitorContext): TResult; void(schema: SchemaWithType<'void'>, ctx: SchemaVisitorContext): TResult; } /** * Create a schema walker from a visitor. * * The walker handles: * - Dispatch order ($ref → type → items → fallback) * - Deduplication of union/intersection schemas * - Path tracking for child schemas */ export function createSchemaWalker( visitor: SchemaVisitor, ): Walker { const walk: Walker = (schema, ctx) => { // escape hatch if (visitor.intercept) { const intercepted = visitor.intercept(schema, ctx, walk); if (intercepted !== undefined) { return intercepted; } } if (schema.$ref) { return visitor.reference(schema.$ref, schema, ctx); } if (schema.type) { let result = visitTyped(schema as SchemaWithType, ctx, visitor, walk); if (visitor.postProcess) { result = visitor.postProcess(result, schema, ctx); } return result; } if (schema.items) { const deduplicated = deduplicateSchema({ schema }); // deduplication might collapse to a single schema if (!deduplicated.items) { return walk(deduplicated, ctx); } const itemResults = deduplicated.items.map((item, index) => walk(item, { ...ctx, path: ref([...fromRef(ctx.path), 'items', index]), }), ); return deduplicated.logicalOperator === 'and' ? visitor.intersection(itemResults, deduplicated.items, schema, ctx) : visitor.union(itemResults, deduplicated.items, schema, ctx); } // fallback return visitor.unknown({ type: 'unknown' }, ctx); }; return walk; } /** * Dispatch to the appropriate visitor method based on schema type. */ function visitTyped( schema: SchemaWithType, ctx: SchemaVisitorContext, visitor: SchemaVisitor, walk: Walker, ): TResult { switch (schema.type) { case 'array': return visitor.array(schema as SchemaWithType<'array'>, ctx, walk); case 'boolean': return visitor.boolean(schema as SchemaWithType<'boolean'>, ctx); case 'enum': return visitor.enum(schema as SchemaWithType<'enum'>, ctx, walk); case 'integer': return visitor.integer(schema as SchemaWithType<'integer'>, ctx); case 'never': return visitor.never(schema as SchemaWithType<'never'>, ctx); case 'null': return visitor.null(schema as SchemaWithType<'null'>, ctx); case 'number': return visitor.number(schema as SchemaWithType<'number'>, ctx); case 'object': return visitor.object(schema as SchemaWithType<'object'>, ctx, walk); case 'string': return visitor.string(schema as SchemaWithType<'string'>, ctx); case 'tuple': return visitor.tuple(schema as SchemaWithType<'tuple'>, ctx, walk); case 'undefined': return visitor.undefined(schema as SchemaWithType<'undefined'>, ctx); case 'unknown': return visitor.unknown(schema as SchemaWithType<'unknown'>, ctx); case 'void': return visitor.void(schema as SchemaWithType<'void'>, ctx); } } /** * Helper to create a child context with an extended path. */ export function childContext( ctx: SchemaVisitorContext, ...segments: ReadonlyArray ): SchemaVisitorContext { return { ...ctx, path: ref([...fromRef(ctx.path), ...segments]), }; } ================================================ FILE: packages/shared/src/ir/schema.ts ================================================ import type { IR } from './types'; /** * Ensure we don't produce redundant types, e.g. string | string. */ export function deduplicateSchema({ detectFormat = true, schema, }: { detectFormat?: boolean; schema: T; }): T { if (!schema.items) { return schema; } const uniqueItems: Array = []; const typeIds: Array = []; for (const item of schema.items) { // skip nested schemas for now, handle if necessary if ((!item.type && item.items) || schema.type === 'tuple') { uniqueItems.push(item); continue; } if ( // no `type` might still include `$ref` or `const` !item.type || item.type === 'boolean' || item.type === 'integer' || item.type === 'null' || item.type === 'number' || item.type === 'string' || item.type === 'unknown' || item.type === 'void' ) { // const needs namespace to handle empty string values, otherwise // fallback would equal an actual value and we would skip an item const constant = item.const !== undefined ? `const-${item.const}` : ''; const format = item.format !== undefined && detectFormat ? `format-${item.format}` : ''; // Include validation constraints in the type ID to avoid incorrect deduplication const constraints = [ item.minLength !== undefined ? `minLength-${item.minLength}` : '', item.maxLength !== undefined ? `maxLength-${item.maxLength}` : '', item.minimum !== undefined ? `minimum-${item.minimum}` : '', item.maximum !== undefined ? `maximum-${item.maximum}` : '', item.exclusiveMinimum !== undefined ? `exclusiveMinimum-${item.exclusiveMinimum}` : '', item.exclusiveMaximum !== undefined ? `exclusiveMaximum-${item.exclusiveMaximum}` : '', item.minItems !== undefined ? `minItems-${item.minItems}` : '', item.maxItems !== undefined ? `maxItems-${item.maxItems}` : '', item.pattern !== undefined ? `pattern-${item.pattern}` : '', ].join(''); const typeId = `${item.$ref ?? ''}${item.type ?? ''}${constant}${format}${constraints}`; if (!typeIds.includes(typeId)) { typeIds.push(typeId); uniqueItems.push(item); } continue; } uniqueItems.push(item); } let result = { ...schema }; result.items = uniqueItems; if ( result.items.length <= 1 && result.type !== 'array' && result.type !== 'enum' && result.type !== 'tuple' ) { // bring the only item up to clean up the schema const liftedSchema = result.items[0]; delete result.logicalOperator; delete result.items; result = { ...result, ...liftedSchema, }; } // exclude unknown if it's the only type left if (result.type === 'unknown') { return {} as T; } return result; } ================================================ FILE: packages/shared/src/ir/types.ts ================================================ /* eslint-disable @typescript-eslint/no-namespace */ import type { Symbol } from '@hey-api/codegen-core'; import type { JsonSchemaDraft2020_12 } from '../openApi/3.1.x/types/json-schema-draft-2020-12'; import type { ReferenceObject as IRReferenceObject, SecuritySchemeObject, ServerObject, } from '../openApi/3.1.x/types/spec'; import type { IRMediaType } from './mediaType'; /** * OpenAPI Specification Extensions. * * See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. */ export interface SpecificationExtensions { [extension: `x-${string}`]: unknown; } interface IRBodyObject { mediaType: string; /** * Does body control pagination? We handle only simple values * for now, up to 1 nested field. */ pagination?: boolean | string; required?: boolean; schema: IRSchemaObject; type?: IRMediaType; } interface IRComponentsObject { parameters?: Record; requestBodies?: Record; schemas?: Record; } export interface IROperationObject extends SpecificationExtensions { body?: IRBodyObject; deprecated?: boolean; description?: string; id: string; method: keyof IRPathItemObject; operationId?: string; parameters?: IRParametersObject; path: keyof IRPathsObject; responses?: IRResponsesObject; security?: ReadonlyArray; servers?: ReadonlyArray; summary?: string; tags?: ReadonlyArray; } export interface IRParametersObject { cookie?: Record; header?: Record; path?: Record; query?: Record; } export interface IRParameterObject extends Pick, SpecificationExtensions { /** * Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored. */ allowReserved?: boolean; /** * When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When `style` is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored. */ explode: boolean; /** * Endpoint parameters must specify their location. */ location: 'cookie' | 'header' | 'path' | 'query'; name: string; /** * Does this parameter control pagination? We handle only simple values * for now, up to 1 nested field. */ pagination?: boolean | string; required?: boolean; schema: IRSchemaObject; /** * Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. */ style: 'deepObject' | 'form' | 'label' | 'matrix' | 'pipeDelimited' | 'simple' | 'spaceDelimited'; } interface IRPathsObject { [path: `/${string}`]: IRPathItemObject; } interface IRPathItemObject { delete?: IROperationObject; get?: IROperationObject; head?: IROperationObject; options?: IROperationObject; patch?: IROperationObject; post?: IROperationObject; put?: IROperationObject; trace?: IROperationObject; } interface IRRequestBodyObject extends Pick { required?: boolean; schema: IRSchemaObject; } interface IRResponsesObject { /** * Any {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#http-status-codes HTTP status code} can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. */ [statusCode: string]: IRResponseObject | undefined; /** * The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. */ default?: IRResponseObject; } interface IRResponseObject { // TODO: parser - handle headers, links, and possibly other media types? mediaType?: string; schema: IRSchemaObject; } export interface IRSchemaObject extends Pick< JsonSchemaDraft2020_12, | '$ref' | 'const' | 'default' | 'deprecated' | 'description' | 'exclusiveMaximum' | 'exclusiveMinimum' | 'maximum' | 'maxItems' | 'maxLength' | 'minimum' | 'minItems' | 'minLength' | 'pattern' | 'required' | 'title' | 'example' >, SpecificationExtensions { /** * If the schema is intended to be used as an object property, it can be * marked as read-only or write-only. This value controls whether the schema * receives the "readonly" TypeScript keyword. */ accessScope?: 'read' | 'write'; /** * If type is `object`, `additionalProperties` can be used to either define * a schema for properties not included in `properties` or disallow such * properties altogether. */ additionalProperties?: IRSchemaObject | false; /** * Any string value is accepted as `format`. */ format?: JsonSchemaDraft2020_12['format'] | 'binary' | 'integer'; /** * If schema resolves into multiple items instead of a simple `type`, they * will be included in `items` array. */ items?: ReadonlyArray; /** * When resolving a list of items, we need to know the relationship between * them. `logicalOperator` specifies this logical relationship. * * @default 'or' */ logicalOperator?: 'and' | 'or'; /** * When used with `$ref` or `symbolRef`, specifies properties to omit from the referenced schema. * Useful for handling discriminator property conflicts in allOf compositions. */ omit?: ReadonlyArray; /** * When type is `object`, `patternProperties` can be used to define a schema * for properties that match a specific regex pattern. */ patternProperties?: Record; /** * When type is `object`, `properties` will contain a map of its properties. */ properties?: Record; /** * The names of `properties` can be validated against a schema, irrespective * of their values. This can be useful if you don't want to enforce specific * properties, but you want to make sure that the names of those properties * follow a specific convention. */ propertyNames?: IRSchemaObject; /** * Reference to symbol instead of `$ref` string. */ symbolRef?: Symbol; /** * Each schema eventually resolves into `type`. */ type?: | 'array' | 'boolean' | 'enum' | 'integer' | 'never' | 'null' | 'number' | 'object' | 'string' | 'tuple' | 'undefined' | 'unknown' | 'void'; } type IRSecurityObject = SecuritySchemeObject; // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Interface rather than type alias avoids TS4023 errors when bundled dist is consumed by tsgo/TypeScript 7 export interface IRServerObject extends ServerObject {} type IRWebhookObject = IRPathItemObject; export interface IRModel { components?: IRComponentsObject; paths?: IRPathsObject; servers?: ReadonlyArray; webhooks?: Record; } export namespace IR { export type BodyObject = IRBodyObject; export type ComponentsObject = IRComponentsObject; export type Model = IRModel; export type OperationObject = IROperationObject; export type ParameterObject = IRParameterObject; export type ParametersObject = IRParametersObject; export type PathItemObject = IRPathItemObject; export type PathsObject = IRPathsObject; export type ReferenceObject = IRReferenceObject; export type RequestBodyObject = IRRequestBodyObject; export type ResponseObject = IRResponseObject; export type ResponsesObject = IRResponsesObject; export type SchemaObject = IRSchemaObject; export type SecurityObject = IRSecurityObject; export type ServerObject = IRServerObject; export type WebhookObject = IRWebhookObject; } ================================================ FILE: packages/shared/src/ir/utils.ts ================================================ import type { IR } from './types'; /** * Simply adds `items` to the schema. Also handles setting the logical operator * and avoids setting it for a single item or tuples. */ export function addItemsToSchema({ items, logicalOperator = 'or', mutateSchemaOneItem = false, schema, }: { items: Array; logicalOperator?: IR.SchemaObject['logicalOperator']; mutateSchemaOneItem?: boolean; schema: IR.SchemaObject; }): IR.SchemaObject { if (!items.length) { return schema; } if (schema.type === 'tuple') { schema.items = items; return schema; } if (items.length !== 1) { schema.items = items; schema.logicalOperator = logicalOperator; return schema; } if (mutateSchemaOneItem) { // bring composition up to avoid extraneous brackets schema = { ...schema, ...items[0], }; return schema; } schema.items = items; return schema; } ================================================ FILE: packages/shared/src/openApi/2.0.x/index.ts ================================================ export { parseV2_0_X } from './parser'; export type { OpenApiV2_0_X } from './types/spec'; import type { InfoObject, OperationObject, SchemaObject } from './types/spec'; export interface OpenApiV2_0_XTypes { InfoObject: InfoObject; OperationObject: OperationObject; SchemaObject: SchemaObject; } ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/__tests__/operation.test.ts ================================================ import type { Context } from '../../../../ir/context'; import type { ParameterObject, SecuritySchemeObject } from '../../types/spec'; import { parsePathOperation } from '../operation'; type ParseOperationProps = Parameters[0]; const createContext = () => ({ config: { parser: { pagination: { keywords: ['after', 'before', 'cursor', 'offset', 'page', 'start'], }, }, plugins: {}, }, dereference: (obj: any): T => obj as T, ir: { components: { schemas: {}, }, paths: {}, servers: [], }, resolveRef: () => // Mock implementation undefined, }) as unknown as Context; describe('operation', () => { const context = createContext(); it('should parse operation correctly', () => { const method = 'get'; const operation: ParseOperationProps['operation'] = { operationId: 'testOperation', responses: {}, security: [ { apiKeyAuth: [], basicAuthRule: [], }, { apiKeyAuth: [], oauthRule: [], }, ], summary: 'Test Operation', }; const path = '/test'; const securitySchemesMap = new Map([ ['apiKeyAuth', { in: 'header', name: 'Auth', type: 'apiKey' }], ['basicAuthRule', { description: 'Basic Auth', type: 'basic' }], [ 'oauthRule', { description: 'OAuth2', flow: 'password', scopes: { read: 'Grants read access', write: 'Grants write access', }, tokenUrl: 'https://example.com/oauth/token', type: 'oauth2', }, ], ]); const state: ParseOperationProps['state'] = { ids: new Map(), }; parsePathOperation({ context, method, operation, path, securitySchemesMap, state, }); expect(context.ir.paths?.[path]?.[method]).toEqual({ id: 'testOperation', method, operationId: 'testOperation', path, security: [ { in: 'header', name: 'Auth', type: 'apiKey' }, { description: 'Basic Auth', scheme: 'basic', type: 'http' }, { description: 'OAuth2', flows: { password: { scopes: { read: 'Grants read access', write: 'Grants write access', }, tokenUrl: 'https://example.com/oauth/token', }, }, type: 'oauth2', }, ], summary: 'Test Operation', }); }); it('should parse body parameter when consumes is undefined', () => { const context = createContext(); const method = 'post'; const bodyParam: ParameterObject = { description: 'Request body', in: 'body', name: 'body', required: true, schema: { properties: { id: { type: 'string' }, name: { type: 'string' }, }, required: ['id'], type: 'object', }, }; const operation: ParseOperationProps['operation'] = { operationId: 'createItem', requestBody: [bodyParam], responses: { '201': { description: 'Created', }, }, summary: 'Create an item', }; const path = '/items'; const securitySchemesMap = new Map(); const state: ParseOperationProps['state'] = { ids: new Map(), }; parsePathOperation({ context, method, operation, path, securitySchemesMap, state, }); const result = context.ir.paths?.[path]?.[method]; expect(result).toBeDefined(); expect(result?.body).toBeDefined(); expect(result?.body?.mediaType).toBe('application/json'); expect(result?.body?.required).toBe(true); expect(result?.body?.schema.type).toBe('object'); }); it('should parse body parameter with array schema', () => { const context = createContext(); const method = 'post'; const bodyParam: ParameterObject = { description: 'add items', in: 'body', name: 'request', required: true, schema: { items: { properties: { count: { type: 'number' }, id: { type: 'integer' }, }, type: 'object', }, type: 'array', }, }; const operation: ParseOperationProps['operation'] = { operationId: 'addItems', requestBody: [bodyParam], responses: { '201': { description: 'Created', }, }, }; const path = '/api/v1/items'; const securitySchemesMap = new Map(); const state: ParseOperationProps['state'] = { ids: new Map(), }; parsePathOperation({ context, method, operation, path, securitySchemesMap, state, }); const result = context.ir.paths?.[path]?.[method]; expect(result).toBeDefined(); expect(result?.body).toBeDefined(); expect(result?.body?.mediaType).toBe('application/json'); expect(result?.body?.required).toBe(true); expect(result?.body?.schema.type).toBe('array'); }); it('should use consumes when specified', () => { const context = createContext(); const method = 'post'; const bodyParam: ParameterObject = { description: 'XML body', in: 'body', name: 'body', required: true, schema: { type: 'object', }, }; const operation: ParseOperationProps['operation'] = { consumes: ['application/xml'], operationId: 'createXml', requestBody: [bodyParam], responses: { '201': { description: 'Created', }, }, }; const path = '/items'; const securitySchemesMap = new Map(); const state: ParseOperationProps['state'] = { ids: new Map(), }; parsePathOperation({ context, method, operation, path, securitySchemesMap, state, }); const result = context.ir.paths?.[path]?.[method]; expect(result).toBeDefined(); expect(result?.body).toBeDefined(); expect(result?.body?.mediaType).toBe('application/xml'); }); }); ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/__tests__/server.test.ts ================================================ import type { Context } from '../../../../ir/context'; import type { OpenApi } from '../../../types'; import { parseServers } from '../server'; describe('parseServers', () => { it('host + basePath + schemes', () => { const context: Partial>> = { config: { input: [ // @ts-expect-error { path: '', }, ], }, ir: {}, spec: { basePath: '/v1', host: 'foo.com', schemes: ['http', 'https'], }, }; parseServers({ context: context as Context }); expect(context.ir!.servers).toEqual([ { url: 'http://foo.com/v1', }, { url: 'https://foo.com/v1', }, ]); }); it('schemes + host', () => { const context: Partial>> = { config: { input: [ // @ts-expect-error { path: '', }, ], }, ir: {}, spec: { host: 'foo.com', schemes: ['ws'], }, }; parseServers({ context: context as Context }); expect(context.ir!.servers).toEqual([ { url: 'ws://foo.com', }, ]); }); it('host + basePath', () => { const context: Partial>> = { config: { input: [ // @ts-expect-error { path: '', }, ], }, ir: {}, spec: { basePath: '/v1', host: 'foo.com', }, }; parseServers({ context: context as Context }); expect(context.ir!.servers).toEqual([ { url: 'foo.com/v1', }, ]); }); it('host', () => { const context: Partial>> = { config: { input: [ // @ts-expect-error { path: '', }, ], }, ir: {}, spec: { host: 'foo.com', }, }; parseServers({ context: context as Context }); expect(context.ir!.servers).toEqual([ { url: 'foo.com', }, ]); }); it('basePath', () => { const context: Partial>> = { config: { input: [ // @ts-expect-error { path: '', }, ], }, ir: {}, spec: { basePath: '/v1', }, }; parseServers({ context: context as Context }); expect(context.ir!.servers).toEqual([ { url: '/v1', }, ]); }); }); ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/__tests__/validate.test.ts ================================================ import path from 'node:path'; import { Logger } from '@hey-api/codegen-core'; import { getSpecsPath, specFileToJson } from '../../../__tests__/utils'; import type { ValidatorResult } from '../../../shared/utils/validator'; import { validateOpenApiSpec } from '../validate'; const specsFolder = path.join(getSpecsPath(), '2.0.x', 'invalid'); describe('validate', () => { const scenarios: Array< ValidatorResult & { description: string; file: string; } > = [ { description: 'operationId must be unique', file: path.join(specsFolder, 'operationId-unique.yaml'), issues: [ { code: 'duplicate_key', context: { key: 'operationId', value: 'foo', }, message: 'Duplicate `operationId` found. Each `operationId` must be unique.', path: ['paths', '/foo', 'post', 'operationId'], severity: 'error', }, ], valid: false, }, ]; it.each(scenarios)('$description', ({ file, issues, valid }) => { const spec = specFileToJson(file); const logger = new Logger(); const result = validateOpenApiSpec(spec, logger); expect(result.valid).toBe(valid); expect(result.issues).toEqual(issues); }); }); ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/filter.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { createOperationKey } from '../../../ir/operation'; import { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter'; import { httpMethods } from '../../../openApi/shared/utils/operation'; import type { OpenApiV2_0_X, OperationObject, PathItemObject, PathsObject } from '../types/spec'; /** * Replace source spec with filtered version. */ export const filterSpec = ({ logger, operations, preserveOrder, schemas, spec, }: { logger: Logger; operations: Set; parameters: Set; preserveOrder: boolean; requestBodies: Set; responses: Set; schemas: Set; spec: OpenApiV2_0_X; }) => { const eventFilterSpec = logger.timeEvent('filter-spec'); if (spec.definitions) { const filtered: typeof spec.definitions = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.definitions)) { if (schemas.has(addNamespace('schema', name))) { filtered[name] = source; } } } else { for (const key of schemas) { const { name } = removeNamespace(key); const source = spec.definitions[name]; if (source) { filtered[name] = source; } } } spec.definitions = filtered; } if (spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { // @ts-expect-error const operation = pathItem[method] as OperationObject; if (!operation) { continue; } const key = addNamespace('operation', createOperationKey({ method, path })); if (!operations.has(key)) { // @ts-expect-error delete pathItem[method]; } } // remove paths that have no operations left if (!Object.keys(pathItem).length) { delete spec.paths[path]; } } } eventFilterSpec.timeEnd(); }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/index.ts ================================================ import type { Context } from '../../../ir/context'; import { buildResourceMetadata } from '../../../openApi/shared/graph/meta'; import { transformOpenApiSpec } from '../../../openApi/shared/transforms'; import type { State } from '../../../openApi/shared/types/state'; import { createFilteredDependencies, createFilters, hasFilters, } from '../../../openApi/shared/utils/filter'; import { buildGraph } from '../../../openApi/shared/utils/graph'; import { mergeParametersObjects } from '../../../openApi/shared/utils/parameter'; import { handleValidatorResult } from '../../../openApi/shared/utils/validator'; import type { OpenApiV2_0_X, OperationObject, PathItemObject, PathsObject, SecuritySchemeObject, } from '../types/spec'; import { filterSpec } from './filter'; import { parsePathOperation } from './operation'; import { parametersArrayToObject } from './parameter'; import { parseSchema } from './schema'; import { parseServers } from './server'; import { validateOpenApiSpec } from './validate'; type PathKeys = keyof T extends infer K ? K extends `/${string}` ? K : never : never; export const parseV2_0_X = (context: Context) => { if (context.config.parser.validate_EXPERIMENTAL) { const result = validateOpenApiSpec(context.spec, context.logger); handleValidatorResult({ context, result }); } const shouldFilterSpec = hasFilters(context.config.parser.filters); if (shouldFilterSpec) { const filters = createFilters(context.config.parser.filters, context.spec, context.logger); const { graph } = buildGraph(context.spec, context.logger); const { resourceMetadata } = buildResourceMetadata(graph, context.logger); const sets = createFilteredDependencies({ filters, logger: context.logger, resourceMetadata, }); filterSpec({ ...sets, logger: context.logger, preserveOrder: filters.preserveOrder, spec: context.spec, }); } transformOpenApiSpec({ context }); const state: State = { ids: new Map(), }; const securitySchemesMap = new Map(); for (const name in context.spec.securityDefinitions) { const securitySchemeObject = context.spec.securityDefinitions[name]!; securitySchemesMap.set(name, securitySchemeObject); } if (context.spec.definitions) { for (const name in context.spec.definitions) { const $ref = `#/definitions/${name}`; const schema = context.spec.definitions[name]!; parseSchema({ $ref, context, schema, }); } } parseServers({ context }); for (const path in context.spec.paths) { if (path.startsWith('x-')) continue; const pathItem = context.spec.paths[path as PathKeys]!; const finalPathItem = pathItem.$ref ? { ...context.resolveRef(pathItem.$ref), ...pathItem, } : pathItem; const commonOperation: OperationObject = { consumes: context.spec.consumes, produces: context.spec.produces, responses: {}, security: context.spec.security, }; const operationArgs: Omit[0], 'method'> = { context, operation: { ...commonOperation, parameters: parametersArrayToObject({ context, operation: commonOperation, parameters: finalPathItem.parameters, }), }, path: path as PathKeys, securitySchemesMap, state, }; if (finalPathItem.delete) { const parameters = mergeParametersObjects({ source: parametersArrayToObject({ context, operation: finalPathItem.delete, parameters: finalPathItem.delete.parameters, }), target: operationArgs.operation.parameters, }); parsePathOperation({ ...operationArgs, method: 'delete', operation: { ...operationArgs.operation, ...finalPathItem.delete, parameters, }, }); } if (finalPathItem.get) { const parameters = mergeParametersObjects({ source: parametersArrayToObject({ context, operation: finalPathItem.get, parameters: finalPathItem.get.parameters, }), target: operationArgs.operation.parameters, }); parsePathOperation({ ...operationArgs, method: 'get', operation: { ...operationArgs.operation, ...finalPathItem.get, parameters, }, }); } if (finalPathItem.head) { const parameters = mergeParametersObjects({ source: parametersArrayToObject({ context, operation: finalPathItem.head, parameters: finalPathItem.head.parameters, }), target: operationArgs.operation.parameters, }); parsePathOperation({ ...operationArgs, method: 'head', operation: { ...operationArgs.operation, ...finalPathItem.head, parameters, }, }); } if (finalPathItem.options) { const parameters = mergeParametersObjects({ source: parametersArrayToObject({ context, operation: finalPathItem.options, parameters: finalPathItem.options.parameters, }), target: operationArgs.operation.parameters, }); parsePathOperation({ ...operationArgs, method: 'options', operation: { ...operationArgs.operation, ...finalPathItem.options, parameters, }, }); } if (finalPathItem.patch) { const parameters = mergeParametersObjects({ source: parametersArrayToObject({ context, operation: finalPathItem.patch, parameters: finalPathItem.patch.parameters, }), target: operationArgs.operation.parameters, }); parsePathOperation({ ...operationArgs, method: 'patch', operation: { ...operationArgs.operation, ...finalPathItem.patch, parameters, }, }); } if (finalPathItem.post) { const parameters = mergeParametersObjects({ source: parametersArrayToObject({ context, operation: finalPathItem.post, parameters: finalPathItem.post.parameters, }), target: operationArgs.operation.parameters, }); parsePathOperation({ ...operationArgs, method: 'post', operation: { ...operationArgs.operation, ...finalPathItem.post, parameters, }, }); } if (finalPathItem.put) { const parameters = mergeParametersObjects({ source: parametersArrayToObject({ context, operation: finalPathItem.put, parameters: finalPathItem.put.parameters, }), target: operationArgs.operation.parameters, }); parsePathOperation({ ...operationArgs, method: 'put', operation: { ...operationArgs.operation, ...finalPathItem.put, parameters, }, }); } } }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/mediaType.ts ================================================ import type { IRMediaType } from '../../../ir/mediaType'; import { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType'; import type { ReferenceObject, ResponseObject, SchemaObject } from '../types/spec'; interface Content { mediaType: string; schema: SchemaObject | ReferenceObject | undefined; type: IRMediaType | undefined; } export const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => { const { mediaType, schema } = content; if (schema && '$ref' in schema) { return { allOf: [{ ...schema }], }; } if (!schema) { if (isMediaTypeFileLike({ mediaType })) { return { format: 'binary', type: 'string', }; } return; } if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) { return { ...schema, format: 'binary', }; } return schema; }; export const mediaTypeObjects = ({ mimeTypes, response, }: { mimeTypes: ReadonlyArray | undefined; response: Pick; }): ReadonlyArray => { const objects: Array = []; for (const mediaType of mimeTypes ?? []) { objects.push({ mediaType, schema: response.schema, type: mediaTypeToIrMediaType({ mediaType }), }); } return objects; }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/operation.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import type { State } from '../../../openApi/shared/types/state'; import { operationToId } from '../../../openApi/shared/utils/operation'; import type { OperationObject, ParameterObject, PathItemObject, ResponseObject, SchemaObject, SecuritySchemeObject, } from '../types/spec'; import { contentToSchema, mediaTypeObjects } from './mediaType'; import { paginationField } from './pagination'; import { parseExtensions, schemaToIrSchema } from './schema'; interface Operation extends Omit, Pick { requestBody?: OperationObject['parameters']; } const parseOperationJsDoc = ({ irOperation, operation, }: { irOperation: IR.OperationObject; operation: Operation; }) => { if (operation.deprecated !== undefined) { irOperation.deprecated = operation.deprecated; } if (operation.description) { irOperation.description = operation.description; } if (operation.summary) { irOperation.summary = operation.summary; } if (operation.tags?.length) { irOperation.tags = operation.tags; } }; const initIrOperation = ({ context, method, operation, path, state, }: Pick & { context: Context; operation: Operation; state: State; }): IR.OperationObject => { const irOperation: IR.OperationObject = { id: operationToId({ context, id: operation.operationId, method, path, state, }), method, path, }; if (operation.operationId) { irOperation.operationId = operation.operationId; } parseOperationJsDoc({ irOperation, operation, }); parseExtensions({ source: operation, target: irOperation, }); return irOperation; }; const operationToIrOperation = ({ context, method, operation, path, securitySchemesMap, state, }: Pick & { context: Context; operation: Operation; securitySchemesMap: Map; state: State; }): IR.OperationObject => { const irOperation = initIrOperation({ context, method, operation, path, state, }); if (operation.parameters) { irOperation.parameters = operation.parameters; } let isRequestBodyRequired = false; const requestBodyObject: IR.BodyObject = { mediaType: '', schema: { properties: {}, required: [], type: 'object', }, }; const requestBodyObjectRequired: Array = []; // Check if there are any body parameters (not formData) to determine default media type const hasBodyParameter = operation.requestBody?.some((param) => { const resolvedParam = '$ref' in param ? context.resolveRef(param.$ref) : param; return resolvedParam.in === 'body'; }); for (const requestBodyParameter of operation.requestBody ?? []) { const requestBody = '$ref' in requestBodyParameter ? context.resolveRef(requestBodyParameter.$ref) : requestBodyParameter; const schema: SchemaObject = requestBody.in === 'body' ? requestBody.schema : { ...requestBody, format: requestBody.type === 'file' ? 'binary' : requestBody.format, required: undefined, type: requestBody.type === 'file' ? 'string' : requestBody.type, }; // Only default to JSON if we have body parameters and no consumes specified // FormData parameters without consumes should not get a default media type let mimeTypes = operation.consumes; if (!mimeTypes && hasBodyParameter && requestBody.in === 'body') { mimeTypes = ['application/json']; } const contents = mediaTypeObjects({ mimeTypes, response: { schema }, }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { const pagination = paginationField({ context, name: '', schema: content.schema && '$ref' in content.schema ? { allOf: [{ ...content.schema }], description: requestBody.description, } : { description: requestBody.description, ...content.schema, }, }); const irSchema = schemaToIrSchema({ context, schema: '$ref' in requestBody ? { allOf: [ { ...requestBody, $ref: requestBody.$ref as string, required: [], type: 'string', }, ], description: requestBody.description, } : content.schema && '$ref' in content.schema ? { allOf: [{ ...content.schema }], description: requestBody.description, } : { description: requestBody.description, ...content.schema, }, state: undefined, }); requestBodyObject.mediaType = content.mediaType; if (requestBody.in === 'body') { requestBodyObject.schema = irSchema; } else { requestBodyObject.schema.properties![requestBody.name] = irSchema; if (requestBody.required) { requestBodyObjectRequired.push(requestBody.name); } } if (pagination) { requestBodyObject.pagination = pagination; } if (content.type) { requestBodyObject.type = content.type; } } if (requestBody.required) { isRequestBodyRequired = true; } } if (requestBodyObject.mediaType) { if (requestBodyObjectRequired.length) { requestBodyObject.schema.required = requestBodyObjectRequired; } irOperation.body = requestBodyObject; if (isRequestBodyRequired) { irOperation.body.required = isRequestBodyRequired; } } for (const name in operation.responses) { if (!irOperation.responses) { irOperation.responses = {}; } const response = operation.responses[name]!; const responseObject = '$ref' in response ? context.resolveRef(response.$ref) : response; const contents = mediaTypeObjects({ // assume JSON by default mimeTypes: operation.produces ? operation.produces : ['application/json'], response: responseObject, }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { irOperation.responses[name] = { mediaType: content.mediaType, schema: schemaToIrSchema({ context, schema: { description: responseObject.description, ...contentToSchema({ content }), }, state: undefined, }), }; } else { irOperation.responses[name] = { schema: { description: responseObject.description, // TODO: parser - cover all statues with empty response bodies // 1xx, 204, 205, 304 type: name === '204' ? 'void' : 'unknown', }, }; } } if (operation.security) { const securitySchemeObjects: Map = new Map(); for (const securityRequirementObject of operation.security) { for (const name in securityRequirementObject) { const securitySchemeObject = securitySchemesMap.get(name); if (!securitySchemeObject) { continue; } let irSecuritySchemeObject: IR.SecurityObject | undefined; if (securitySchemeObject.type === 'apiKey') { irSecuritySchemeObject = securitySchemeObject; } if (securitySchemeObject.type === 'basic') { irSecuritySchemeObject = { description: securitySchemeObject.description, scheme: 'basic', type: 'http', }; } if (securitySchemeObject.type === 'oauth2') { irSecuritySchemeObject = { description: securitySchemeObject.description, flows: {}, type: 'oauth2', }; switch (securitySchemeObject.flow) { case 'accessCode': irSecuritySchemeObject.flows.authorizationCode = { authorizationUrl: securitySchemeObject.authorizationUrl!, scopes: securitySchemeObject.scopes, tokenUrl: securitySchemeObject.tokenUrl!, }; break; case 'application': irSecuritySchemeObject.flows.clientCredentials = { scopes: securitySchemeObject.scopes, tokenUrl: securitySchemeObject.tokenUrl!, }; break; case 'implicit': irSecuritySchemeObject.flows.implicit = { authorizationUrl: securitySchemeObject.authorizationUrl!, scopes: securitySchemeObject.scopes, }; break; case 'password': irSecuritySchemeObject.flows.password = { scopes: securitySchemeObject.scopes, tokenUrl: securitySchemeObject.tokenUrl!, }; break; } } if (!irSecuritySchemeObject) { continue; } securitySchemeObjects.set(name, irSecuritySchemeObject); } } if (securitySchemeObjects.size) { irOperation.security = Array.from(securitySchemeObjects.values()); } } // TODO: parser - handle servers // qux: operation.servers return irOperation; }; export const parsePathOperation = ({ context, method, operation, path, securitySchemesMap, state, }: { context: Context; method: Extract< keyof PathItemObject, 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace' >; operation: Operation; path: keyof IR.PathsObject; securitySchemesMap: Map; state: State; }) => { if (!context.ir.paths) { context.ir.paths = {}; } if (!context.ir.paths[path]) { context.ir.paths[path] = {}; } context.ir.paths[path][method] = operationToIrOperation({ context, method, operation, path, securitySchemesMap, state, }); }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/pagination.ts ================================================ import type { Context } from '../../../ir/context'; import { getPaginationKeywordsRegExp } from '../../../ir/pagination'; import type { SchemaType } from '../../../openApi/shared/types/schema'; import type { ParameterObject, ReferenceObject } from '../types/spec'; import type { SchemaObject } from '../types/spec'; import { getSchemaType } from './schema'; const isPaginationType = (schemaType: SchemaType | undefined): boolean => schemaType === 'boolean' || schemaType === 'integer' || schemaType === 'number' || schemaType === 'string'; // We handle only simple values for now, up to 1 nested field export const paginationField = ({ context, name, schema, }: { context: Context; name: string; schema: | ParameterObject | SchemaObject | ReferenceObject | { in: undefined; }; }): boolean | string => { const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination); if (paginationRegExp.test(name)) { return true; } if ('$ref' in schema) { const ref = context.resolveRef(schema.$ref ?? ''); if ('in' in ref && ref.in) { const refSchema = 'schema' in ref ? ref.schema : { ...ref, in: undefined, }; return paginationField({ context, name, schema: refSchema, }); } return paginationField({ context, name, schema: ref, }); } if ('in' in schema) { if (!schema.in) { return false; } const finalSchema = 'schema' in schema ? schema.schema : { ...schema, in: undefined, }; return paginationField({ context, name, schema: finalSchema, }); } for (const name in schema.properties) { const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination); if (paginationRegExp.test(name)) { const property = schema.properties[name]!; if (typeof property !== 'boolean' && !('$ref' in property)) { const schemaType = getSchemaType({ schema: property }); // TODO: resolve deeper references if (isPaginationType(schemaType)) { return name; } } } } for (const allOf of schema.allOf ?? []) { const pagination = paginationField({ context, name, schema: allOf, }); if (pagination) { return pagination; } } return false; }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/parameter.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import type { OperationObject, ParameterObject, ReferenceObject, SchemaObject, } from '../types/spec'; import { paginationField } from './pagination'; import { parseExtensions, schemaToIrSchema } from './schema'; type Parameter = Exclude; /** * Returns default parameter `explode` based on value of `collectionFormat`. */ const defaultExplode = (collectionFormat: Parameter['collectionFormat']): boolean => { switch (collectionFormat) { case 'multi': return true; case 'csv': case 'pipes': case 'ssv': case 'tsv': default: return false; } }; /** * Returns default parameter `style` based on value of `in`. */ const defaultStyle = (_in: Parameter['in']): Required['style'] => { switch (_in) { case 'header': case 'path': return 'simple'; case 'query': default: return 'form'; } }; export const parametersArrayToObject = ({ context, operation, parameters, }: { context: Context; operation: OperationObject; parameters?: ReadonlyArray; }): IR.ParametersObject | undefined => { if (!parameters || !Object.keys(parameters).length) { return; } const parametersObject: IR.ParametersObject = {}; for (const parameterOrReference of parameters) { const parameter = '$ref' in parameterOrReference ? context.dereference(parameterOrReference) : parameterOrReference; // push request body parameters into a separate field if (parameter.in === 'body' || parameter.in === 'formData') { // @ts-expect-error if (!operation.requestBody) { // @ts-expect-error operation.requestBody = []; } // @ts-expect-error operation.requestBody.push(parameter); continue; } if (!parametersObject[parameter.in]) { parametersObject[parameter.in] = {}; } // lowercase keys for case insensitive access parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({ $ref: `#/todo/real/path/to/parameter/${parameter.name}`, context, parameter, }); } return parametersObject; }; const parameterToIrParameter = ({ $ref, context, parameter, }: { $ref: string; context: Context; parameter: Parameter; }): IR.ParameterObject => { const schema = parameter; const finalSchema: SchemaObject = schema && '$ref' in schema ? { allOf: [ { ...schema, $ref: schema.$ref as string, required: Array.isArray(schema.required) ? schema.required : [], type: schema.type as SchemaObject['type'], }, ], description: parameter.description, } : { description: parameter.description, ...schema, required: Array.isArray(schema.required) ? schema.required : [], type: schema.type as SchemaObject['type'], }; const pagination = paginationField({ context, name: parameter.name, schema: finalSchema, }); const style = defaultStyle(parameter.in); const explode = defaultExplode(parameter.collectionFormat); const allowReserved = false; const irParameter: IR.ParameterObject = { allowReserved, explode, location: parameter.in as IR.ParameterObject['location'], name: parameter.name, schema: schemaToIrSchema({ context, schema: finalSchema, state: { $ref, circularReferenceTracker: new Set(), }, }), style, }; if (parameter.description) { irParameter.description = parameter.description; } if (pagination) { irParameter.pagination = pagination; } if (parameter.required) { irParameter.required = parameter.required; } parseExtensions({ source: parameter, target: irParameter, }); return irParameter; }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/schema.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import { addItemsToSchema } from '../../../ir/utils'; import type { SchemaState, SchemaType, SchemaWithRequired, } from '../../../openApi/shared/types/schema'; import { discriminatorValues } from '../../../openApi/shared/utils/discriminator'; import { isTopLevelComponent, refToName } from '../../../utils/ref'; import type { SchemaObject } from '../types/spec'; export const getSchemaType = ({ schema, }: { schema: SchemaObject; }): SchemaType | undefined => { if (schema.type) { return schema.type; } // infer object based on the presence of properties if (schema.properties) { return 'object'; } return; }; const parseSchemaJsDoc = ({ irSchema, schema, }: { irSchema: IR.SchemaObject; schema: SchemaObject; }) => { if (schema.example) { irSchema.example = schema.example; } if (schema.description) { irSchema.description = schema.description; } if (schema.title) { irSchema.title = schema.title; } }; const parseSchemaMeta = ({ irSchema, schema, }: { irSchema: IR.SchemaObject; schema: SchemaObject; }) => { if (schema.default !== undefined) { irSchema.default = schema.default; } if (schema.exclusiveMaximum) { if (schema.maximum !== undefined) { irSchema.exclusiveMaximum = schema.maximum; } } else if (schema.maximum !== undefined) { irSchema.maximum = schema.maximum; } if (schema.exclusiveMinimum) { if (schema.minimum !== undefined) { irSchema.exclusiveMinimum = schema.minimum; } } else if (schema.minimum !== undefined) { irSchema.minimum = schema.minimum; } if (schema.format) { irSchema.format = schema.format; } if (schema.maxItems !== undefined) { irSchema.maxItems = schema.maxItems; } if (schema.maxLength !== undefined) { irSchema.maxLength = schema.maxLength; } if (schema.minItems !== undefined) { irSchema.minItems = schema.minItems; } if (schema.minLength !== undefined) { irSchema.minLength = schema.minLength; } if (schema.pattern) { irSchema.pattern = schema.pattern; } if (schema.readOnly) { irSchema.accessScope = 'read'; } }; const parseArray = ({ context, irSchema = {}, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { if (schema.maxItems && schema.maxItems === schema.minItems) { irSchema.type = 'tuple'; } else { irSchema.type = 'array'; } let schemaItems: Array = []; if (schema.items) { const irItemsSchema = schemaToIrSchema({ context, schema: schema.items, state, }); if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) { schemaItems = Array(schema.maxItems).fill(irItemsSchema); } else { if ('$ref' in schema.items) { schemaItems.push(irItemsSchema); } else { const ofArray = schema.items.allOf; if (ofArray && ofArray.length > 1 && !schema.items['x-nullable']) { // bring composition up to avoid incorrectly nested arrays irSchema = { ...irSchema, ...irItemsSchema, }; } else { schemaItems.push(irItemsSchema); } } } } irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseBoolean = ({ irSchema = {}, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { irSchema.type = 'boolean'; return irSchema; }; const parseNumber = ({ irSchema = {}, schema, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { irSchema.type = schema.type; return irSchema; }; const parseObject = ({ context, irSchema = {}, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { irSchema.type = 'object'; const schemaProperties: Record = {}; for (const name in schema.properties) { const property = schema.properties[name]!; if (typeof property === 'boolean') { // TODO: parser - handle boolean properties } else { const irPropertySchema = schemaToIrSchema({ context, schema: property, state, }); schemaProperties[name] = irPropertySchema; } } if (Object.keys(schemaProperties).length) { irSchema.properties = schemaProperties; } if (schema.additionalProperties === undefined) { if (!irSchema.properties) { irSchema.additionalProperties = { type: 'unknown', }; } } else if (typeof schema.additionalProperties === 'boolean') { // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf // This would override inherited properties from other schemas in the composition const isEmptyObjectInAllOf = state.inAllOf && schema.additionalProperties === false && (!schema.properties || !Object.keys(schema.properties).length); if (!isEmptyObjectInAllOf) { irSchema.additionalProperties = { type: schema.additionalProperties ? 'unknown' : 'never', }; } } else { const irAdditionalPropertiesSchema = schemaToIrSchema({ context, schema: schema.additionalProperties, state, }); irSchema.additionalProperties = irAdditionalPropertiesSchema; } if (schema.required) { irSchema.required = schema.required; } return irSchema; }; const parseString = ({ irSchema = {}, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { irSchema.type = 'string'; return irSchema; }; export const parseExtensions = ({ source, target }: { source: object; target: object }) => { for (const key in source) { if (key.startsWith('x-')) { (target as Record)[key] = (source as Record)[key]; } } }; const initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => { const irSchema: IR.SchemaObject = {}; parseSchemaJsDoc({ irSchema, schema, }); parseExtensions({ source: schema, target: irSchema, }); return irSchema; }; const parseAllOf = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); const schemaItems: Array = []; const schemaType = getSchemaType({ schema }); const compositionSchemas = schema.allOf; for (const compositionSchema of compositionSchemas) { const originalInAllOf = state.inAllOf; // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components if (!('$ref' in compositionSchema)) { state.inAllOf = true; } const irCompositionSchema = schemaToIrSchema({ context, schema: compositionSchema, state, }); state.inAllOf = originalInAllOf; if (state.inAllOf === undefined) { delete state.inAllOf; } if (schema.required) { if (irCompositionSchema.required) { irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required]; } else { irCompositionSchema.required = schema.required; } } schemaItems.push(irCompositionSchema); if (compositionSchema.$ref) { const ref = context.resolveRef(compositionSchema.$ref); // `$ref` should be passed from the root `parseSchema()` call if (ref.discriminator && state.$ref) { const values = discriminatorValues(state.$ref); const valueSchemas: ReadonlyArray = values.map((value) => ({ const: value, type: 'string', })); const irDiscriminatorSchema: IR.SchemaObject = { properties: { [ref.discriminator]: valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!, }, type: 'object', }; if (ref.required?.includes(ref.discriminator)) { irDiscriminatorSchema.required = [ref.discriminator]; } schemaItems.push(irDiscriminatorSchema); } } } if (schemaType === 'object') { const irObjectSchema = parseOneType({ context, schema: { ...schema, type: 'object', }, state, }); if (irObjectSchema.properties) { for (const requiredProperty of irObjectSchema.required ?? []) { if (!irObjectSchema.properties[requiredProperty]) { for (const compositionSchema of compositionSchemas) { // TODO: parser - this could be probably resolved more accurately const finalCompositionSchema = compositionSchema.$ref ? context.resolveRef(compositionSchema.$ref) : compositionSchema; if (getSchemaType({ schema: finalCompositionSchema }) === 'object') { const irCompositionSchema = parseOneType({ context, schema: { ...finalCompositionSchema, type: 'object', }, state, }); if (irCompositionSchema.properties?.[requiredProperty]) { irObjectSchema.properties[requiredProperty] = irCompositionSchema.properties[requiredProperty]; break; } } } } } schemaItems.push(irObjectSchema); } } irSchema = addItemsToSchema({ items: schemaItems, logicalOperator: 'and', mutateSchemaOneItem: true, schema: irSchema, }); if (schema['x-nullable']) { // nest composition to avoid producing an intersection with null const nestedItems: Array = [ { type: 'null', }, ]; if (schemaItems.length) { nestedItems.unshift(irSchema); } irSchema = { items: nestedItems, logicalOperator: 'or', }; // TODO: parser - this is a hack to bring back up meta fields // without it, some schemas were missing original deprecated if (nestedItems[0]!.deprecated) { irSchema.deprecated = nestedItems[0]!.deprecated; } // TODO: parser - this is a hack to bring back up meta fields // without it, some schemas were missing original description if (nestedItems[0]!.description) { irSchema.description = nestedItems[0]!.description; } } return irSchema; }; const parseEnum = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); irSchema.type = 'enum'; const schemaItems: Array = []; for (const [index, enumValue] of schema.enum.entries()) { const typeOfEnumValue = typeof enumValue; let enumType: SchemaType | 'null' | undefined; if ( typeOfEnumValue === 'string' || typeOfEnumValue === 'number' || typeOfEnumValue === 'boolean' ) { enumType = typeOfEnumValue; } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) { enumType = 'array'; } else if (enumValue === null) { // nullable must be true if (schema['x-nullable']) { enumType = 'null'; } } else { console.warn( '🚨', `unhandled "${typeOfEnumValue}" typeof value "${enumValue}" for enum`, schema.enum, ); } if (!enumType) { continue; } const irTypeSchema = parseOneType({ context, schema: { description: schema['x-enum-descriptions']?.[index], title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index], // cast enum to string temporarily type: enumType === 'null' ? 'string' : enumType, }, state, }); irTypeSchema.const = enumValue; // cast enum back if (enumType === 'null') { irTypeSchema.type = enumType; } if (irTypeSchema.type === 'array') { irTypeSchema.type = 'tuple'; } schemaItems.push(irTypeSchema); } irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseRef = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { const irSchema: IR.SchemaObject = {}; // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/definitions/Foo/properties/bar) // to avoid generating orphaned named types or referencing unregistered symbols const isComponentsRef = isTopLevelComponent(schema.$ref); if (!isComponentsRef) { if (!state.circularReferenceTracker.has(schema.$ref)) { const refSchema = context.resolveRef(schema.$ref); const originalRef = state.$ref; state.$ref = schema.$ref; const irSchema = schemaToIrSchema({ context, schema: refSchema, state, }); state.$ref = originalRef; return irSchema; } // Fallback to preserving the ref if circular } // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` irSchema.$ref = decodeURI(schema.$ref); // rewrite definitions refs as the internal schema follows OpenAPI 3.x syntax // and stores all definitions as reusable schemas irSchema.$ref = irSchema.$ref.replace(/#\/definitions\/([^/]+)/g, '#/components/schemas/$1'); if (!state.circularReferenceTracker.has(schema.$ref)) { const refSchema = context.resolveRef(schema.$ref); const originalRef = state.$ref; state.$ref = schema.$ref; schemaToIrSchema({ context, schema: refSchema, state, }); state.$ref = originalRef; } return irSchema; }; const parseNullableType = ({ context, irSchema, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); } const typeIrSchema: IR.SchemaObject = {}; parseSchemaMeta({ irSchema: typeIrSchema, schema }); if (typeIrSchema.default === null) { // clear to avoid duplicate default inside the non-null schema. // this would produce incorrect validator output delete typeIrSchema.default; } const schemaItems: Array = [ parseOneType({ context, irSchema: typeIrSchema, schema, state, }), { type: 'null', }, ]; irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseType = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { const irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); const type = getSchemaType({ schema }); if (!type) { return irSchema; } if (schema['x-nullable']) { return parseNullableType({ context, irSchema, schema: { ...schema, type, }, state, }); } return parseOneType({ context, irSchema, schema: { ...schema, type, }, state, }); }; const parseOneType = ({ context, irSchema, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); } switch (schema.type) { case 'array': return parseArray({ context, irSchema, schema, state, }); case 'boolean': return parseBoolean({ context, irSchema, schema, state, }); case 'integer': case 'number': return parseNumber({ context, irSchema, schema, state, }); case 'object': return parseObject({ context, irSchema, schema, state, }); case 'string': return parseString({ context, irSchema, schema, state, }); default: // gracefully handle invalid type return parseUnknown({ context, irSchema, schema, }); } }; const parseUnknown = ({ irSchema, schema, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); } irSchema.type = 'unknown'; parseSchemaMeta({ irSchema, schema }); return irSchema; }; export const schemaToIrSchema = ({ context, schema, state, }: { context: Context; schema: SchemaObject; state: SchemaState | undefined; }): IR.SchemaObject => { if (!state) { state = { circularReferenceTracker: new Set(), }; } if (state.$ref) { state.circularReferenceTracker.add(state.$ref); } if (schema.$ref) { return parseRef({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.enum) { return parseEnum({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.allOf) { return parseAllOf({ context, schema: schema as SchemaWithRequired, state, }); } // infer object based on the presence of properties if (schema.type || schema.properties) { return parseType({ context, schema: schema as SchemaWithRequired, state, }); } return parseUnknown({ context, schema }); }; export const parseSchema = ({ $ref, context, schema, }: { $ref: string; context: Context; schema: SchemaObject; }) => { if (!context.ir.components) { context.ir.components = {}; } if (!context.ir.components.schemas) { context.ir.components.schemas = {}; } context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({ context, schema, state: { $ref, circularReferenceTracker: new Set(), }, }); }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/server.ts ================================================ import type { Context } from '../../../ir/context'; import { parseUrl } from '../../../utils/url'; export const parseServers = ({ context }: { context: Context }) => { let schemes: ReadonlyArray = context.spec.schemes ?? []; let host = context.spec.host ?? ''; const path = context.spec.basePath ?? ''; for (const input of context.config.input) { if (typeof input.path === 'string') { const url = parseUrl(input.path); if (!schemes.length) { if (url.protocol) { schemes = [url.protocol] as typeof schemes; } } if (!host) { host = `${url.host}${url.port ? `:${url.port}` : ''}`; } } } if (!schemes.length) { schemes = ['']; } const servers = schemes .map((scheme) => `${scheme ? `${scheme}://` : ''}${host}${path}`) .filter(Boolean); if (servers.length) { context.ir.servers = servers.map((url) => ({ url, })); } }; ================================================ FILE: packages/shared/src/openApi/2.0.x/parser/validate.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { createOperationKey } from '../../../ir/operation'; import { httpMethods } from '../../../openApi/shared/utils/operation'; import type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator'; import type { OpenApiV2_0_X, PathItemObject, PathsObject } from '../types/spec'; export const validateOpenApiSpec = (spec: OpenApiV2_0_X, logger: Logger): ValidatorResult => { const eventValidate = logger.timeEvent('validate'); const issues: Array = []; const operationIds = new Map(); if (spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { if (method === 'trace') { continue; } const operation = pathItem[method]; if (!operation) { continue; } const operationKey = createOperationKey({ method, path }); if (operation.operationId) { if (!operationIds.has(operation.operationId)) { operationIds.set(operation.operationId, operationKey); } else { issues.push({ code: 'duplicate_key', context: { key: 'operationId', value: operation.operationId, }, message: 'Duplicate `operationId` found. Each `operationId` must be unique.', path: ['paths', path, method, 'operationId'], severity: 'error', }); } } } } } eventValidate.timeEnd(); return { issues, valid: !issues.some((issue) => issue.severity === 'error'), }; }; ================================================ FILE: packages/shared/src/openApi/2.0.x/types/json-schema-draft-4.ts ================================================ import type { AnyString } from '@hey-api/types'; import type { EnumExtensions } from '../../../openApi/shared/types'; export interface JsonSchemaDraft4 extends EnumExtensions { /** * A schema can reference another schema using the `$ref` keyword. The value of `$ref` is a URI-reference that is resolved against the schema's {@link https://json-schema.org/understanding-json-schema/structuring#base-uri Base URI}. When evaluating a `$ref`, an implementation uses the resolved identifier to retrieve the referenced schema and applies that schema to the {@link https://json-schema.org/learn/glossary#instance instance}. * * The `$ref` keyword may be used to create recursive schemas that refer to themselves. */ $ref?: string; /** * The `default` keyword specifies a default value. This value is not used to fill in missing values during the validation process. Non-validation tools such as documentation generators or form generators may use this value to give hints to users about how to use a value. However, `default` is typically used to express that if a value is missing, then the value is semantically the same as if the value was present with the default value. The value of `default` should validate against the schema in which it resides, but that isn't required. */ default?: unknown; /** * The `title` and `description` keywords must be strings. A "title" will preferably be short, whereas a "description" will provide a more lengthy explanation about the purpose of the data described by the schema. */ description?: string; /** * The `enum` {@link https://json-schema.org/learn/glossary#keyword keyword} is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique. * * You can use `enum` even without a type, to accept values of different types. */ enum?: ReadonlyArray; /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ exclusiveMaximum?: boolean; /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ exclusiveMinimum?: boolean; /** * The `format` keyword allows for basic semantic identification of certain kinds of string values that are commonly used. For example, because JSON doesn't have a "DateTime" type, dates need to be encoded as strings. `format` allows the schema author to indicate that the string value should be interpreted as a date. By default, `format` is just an annotation and does not effect validation. * * Optionally, validator {@link https://json-schema.org/learn/glossary#implementation implementations} can provide a configuration option to enable `format` to function as an assertion rather than just an annotation. That means that validation will fail if, for example, a value with a `date` format isn't in a form that can be parsed as a date. This can allow values to be constrained beyond what the other tools in JSON Schema, including {@link https://json-schema.org/understanding-json-schema/reference/regular_expressions Regular Expressions} can do. * * There is a bias toward networking-related formats in the JSON Schema specification, most likely due to its heritage in web technologies. However, custom formats may also be used, as long as the parties exchanging the JSON documents also exchange information about the custom format types. A JSON Schema validator will ignore any format type that it does not understand. */ format?: JsonSchemaFormats; /** * The length of the array can be specified using the `minItems` and `maxItems` keywords. The value of each keyword must be a non-negative number. These keywords work whether doing {@link https://json-schema.org/understanding-json-schema/reference/array#items list validation} or {@link https://json-schema.org/understanding-json-schema/reference/array#tupleValidation tuple-validation}. */ maxItems?: number; /** * The length of a string can be constrained using the `minLength` and `maxLength` {@link https://json-schema.org/learn/glossary#keyword keywords}. For both keywords, the value must be a non-negative number. */ maxLength?: number; /** * The number of properties on an object can be restricted using the `minProperties` and `maxProperties` keywords. Each of these must be a non-negative integer. */ maxProperties?: number; /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ maximum?: number; /** * The length of the array can be specified using the `minItems` and `maxItems` keywords. The value of each keyword must be a non-negative number. These keywords work whether doing {@link https://json-schema.org/understanding-json-schema/reference/array#items list validation} or {@link https://json-schema.org/understanding-json-schema/reference/array#tupleValidation tuple-validation}. */ minItems?: number; /** * The length of a string can be constrained using the `minLength` and `maxLength` {@link https://json-schema.org/learn/glossary#keyword keywords}. For both keywords, the value must be a non-negative number. */ minLength?: number; /** * The number of properties on an object can be restricted using the `minProperties` and `maxProperties` keywords. Each of these must be a non-negative integer. */ minProperties?: number; /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ minimum?: number; /** * Numbers can be restricted to a multiple of a given number, using the `multipleOf` keyword. It may be set to any positive number. The multiple can be a floating point number. */ multipleOf?: number; /** * The `pattern` keyword is used to restrict a string to a particular regular expression. The regular expression syntax is the one defined in JavaScript ({@link https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ ECMA 262} specifically) with Unicode support. See {@link https://json-schema.org/understanding-json-schema/reference/regular_expressions Regular Expressions} for more information. */ pattern?: string; /** * By default, the properties defined by the `properties` keyword are not required. However, one can provide a list of required properties using the `required` keyword. * * The `required` keyword takes an array of zero or more strings. Each of these strings must be unique. */ required?: ReadonlyArray; /** * The `title` and `description` keywords must be strings. A "title" will preferably be short, whereas a "description" will provide a more lengthy explanation about the purpose of the data described by the schema. */ title?: string; /** * Primitive data types in the Swagger Specification are based on the types supported by the {@link https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5 JSON-Schema Draft 4}. Models are described using the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#schema-object Schema Object} which is a subset of JSON Schema Draft 4. */ type?: JsonSchemaTypes; /** * A schema can ensure that each of the items in an array is unique. Simply set the `uniqueItems` keyword to `true`. */ uniqueItems?: boolean; } type JsonSchemaFormats = 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri' | AnyString; type JsonSchemaTypes = 'array' | 'boolean' | 'integer' | 'number' | 'object' | 'string'; ================================================ FILE: packages/shared/src/openApi/2.0.x/types/openapi-spec-extensions.ts ================================================ export interface OpenApiV2_0_X_Nullable_Extensions { /** * OpenAPI 2.0 does not natively support null as a type, but you can use * `x-nullable` to polyfill this functionality. */ 'x-nullable'?: boolean; } ================================================ FILE: packages/shared/src/openApi/2.0.x/types/spec.ts ================================================ import type { CodeSampleObject, EnumExtensions } from '../../../openApi/shared/types'; import type { JsonSchemaDraft4 } from './json-schema-draft-4'; import type { OpenApiV2_0_X_Nullable_Extensions } from './openapi-spec-extensions'; /** * This is the root document object for the API specification. It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) together into one document. */ export interface OpenApiV2_0_X { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * The base path on which the API is served, which is relative to the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerHost `host`}. If it is not included, the API is served directly under the `host`. The value MUST start with a leading slash (`/`). The `basePath` does not support {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-templating path templating}. */ basePath?: string; /** * A list of MIME types the APIs can consume. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#mime-types Mime Types}. */ consumes?: ReadonlyArray; /** * An object to hold data types produced and consumed by operations. */ definitions?: DefinitionsObject; /** * Additional external documentation. */ externalDocs?: ExternalDocumentationObject; /** * The host (name or ip) serving the API. This MUST be the host only and does not include the scheme nor sub-paths. It MAY include a port. If the `host` is not included, the host serving the documentation is to be used (including the port). The `host` does not support {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-templating path templating}. */ host?: string; /** * **Required**. Provides metadata about the API. The metadata can be used by the clients if needed. */ info: InfoObject; /** * An object to hold parameters that can be used across operations. This property _does not_ define global parameters for all operations. */ parameters?: ParametersDefinitionsObject; /** * **Required**. The available paths and operations for the API. */ paths: PathsObject; /** * A list of MIME types the APIs can produce. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#mime-types Mime Types}. */ produces?: ReadonlyArray; /** * An object to hold responses that can be used across operations. This property _does not_ define global responses for all operations. */ responses?: ResponsesDefinitionsObject; /** * The transfer protocol of the API. Values MUST be from the list: `"http"`, `"https"`, `"ws"`, `"wss"`. If the `schemes` is not included, the default scheme to be used is the one used to access the Swagger definition itself. */ schemes?: ReadonlyArray<'http' | 'https' | 'ws' | 'wss'>; /** * A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition. */ security?: ReadonlyArray; /** * Security scheme definitions that can be used across the specification. */ securityDefinitions?: SecurityDefinitionsObject; /** * **Required**. Specifies the Swagger Specification version being used. It can be used by the Swagger UI and other clients to interpret the API listing. The value MUST be `"2.0"`. */ swagger: string; /** * A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#operation-object Operation Object} must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. */ tags?: ReadonlyArray; } /** * Contact information for the exposed API. * * @example * ```yaml * name: API Support * url: http://www.swagger.io/support * email: support@swagger.io * ``` */ export interface ContactObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * The email address of the contact person/organization. MUST be in the format of an email address. */ email?: string; /** * The identifying name of the contact person/organization. */ name?: string; /** * The URL pointing to the contact information. MUST be in the format of a URL. */ url?: string; } /** * An object to hold data types that can be consumed and produced by operations. These data types can be primitives, arrays or models. * * **Definitions Object Example** * * @example * ```yaml * Category: * type: object * properties: * id: * type: integer * format: int64 * name: * type: string * Tag: * type: object * properties: * id: * type: integer * format: int64 * name: * type: string * ``` */ export interface DefinitionsObject { /** * A single definition, mapping a "name" to the schema it defines. */ [name: string]: SchemaObject; } /** * Allows sharing examples for operation responses. * * **Example Object Example** * * Example response for application/json mimetype of a Pet data type: * * @example * ```yaml * application/json: * name: Puma * type: Dog * color: Black * gender: Female * breed: Mixed * ``` */ export interface ExampleObject { /** * The name of the property MUST be one of the Operation `produces` values (either implicit or inherited). The value SHOULD be an example of what such a response would look like. */ [mimeType: string]: unknown; } /** * Allows referencing an external resource for extended documentation. * * @example * ```yaml * description: Find more info here * url: https://swagger.io * ``` */ export interface ExternalDocumentationObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * A short description of the target documentation. {@link https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown GFM syntax} can be used for rich text representation. */ description?: string; /** * **Required**. The URL for the target documentation. Value MUST be in the format of a URL. */ url: string; } /** * **Header Object Example** * * A simple header with of an integer type: * * @example * ```yaml * description: The number of allowed requests in the current period * type: integer * ``` */ export interface HeaderObject extends EnumExtensions, OpenApiV2_0_X_Nullable_Extensions { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * Determines the format of the array if type array is used. Possible values are: * * - `csv` - comma separated values `foo,bar`. * - `ssv` - space separated values `foo bar`. * - `tsv` - tab separated values `foo\tbar`. * - `pipes` - pipe separated values `foo|bar`. * * Default value is `csv`. */ collectionFormat?: 'csv' | 'pipes' | 'ssv' | 'tsv'; /** * Declares the value of the item that the server will use if none is provided. (Note: "default" has no meaning for required items.) See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2}. Unlike JSON Schema this value MUST conform to the defined {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#itemsType `type`} for the data type. */ default?: unknown; /** * A short description of the header. */ description?: string; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1}. */ enum?: ReadonlyArray; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2}. */ exclusiveMaximum?: boolean; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3}. */ exclusiveMinimum?: boolean; /** * The extending format for the previously mentioned {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#stType `type`}. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#dataTypeFormat Data Type Formats} for further details. */ format?: string; /** * **Required if {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterType `type`} is "array"**. Describes the type of items in the array. */ items?: ItemsObject; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2}. */ maxItems?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1}. */ maxLength?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2}. */ maximum?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3}. */ minItems?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2}. */ minLength?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3}. */ minimum?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1}. */ multipleOf?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3}. */ pattern?: string; /** * Required. The type of the object. The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, or `"array"`. */ type: 'array' | 'boolean' | 'integer' | 'number' | 'string'; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4}. */ uniqueItems?: boolean; } /** * Lists the headers that can be sent as part of a response. * * **Headers Object Example** * * Rate-limit headers: * * @example * ```yaml * X-Rate-Limit-Limit: * description: The number of allowed requests in the current period * type: integer * X-Rate-Limit-Remaining: * description: The number of remaining requests in the current period * type: integer * X-Rate-Limit-Reset: * description: The number of seconds left in the current period * type: integer * ``` */ export interface HeadersObject { /** * The name of the property corresponds to the name of the header. The value describes the type of the header. */ [name: string]: HeaderObject; } /** * The object provides metadata about the API. The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. * * @example * ```yaml * title: Swagger Sample App * description: This is a sample server Petstore server. * termsOfService: http://swagger.io/terms/ * contact: * name: API Support * url: http://www.swagger.io/support * email: support@swagger.io * license: * name: Apache 2.0 * url: http://www.apache.org/licenses/LICENSE-2.0.html * version: 1.0.1 * ``` */ export interface InfoObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * The contact information for the exposed API. */ contact?: ContactObject; /** * A short description of the application. {@link https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown GFM syntax} can be used for rich text representation. */ description?: string; /** * The license information for the exposed API. */ license?: LicenseObject; /** * The Terms of Service for the API. */ termsOfService?: string; /** * **Required**. The title of the application. */ title: string; /** * **Required** Provides the version of the application API (not to be confused with the specification version). */ version: string; } /** * A limited subset of JSON-Schema's items object. It is used by parameter definitions that are not located {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn `in`} `"body"`. * * **Items Object Examples** * * Items must be of type string and have the minimum length of 2 characters: * * @example * ```yaml * type: string * minLength: 2 * ``` * * An array of arrays, the internal array being of type integer, numbers must be between 0 and 63 (inclusive): * * @example * ```yaml * type: array * items: * type: integer * minimum: 0 * maximum: 63 * ``` */ export interface ItemsObject extends EnumExtensions, OpenApiV2_0_X_Nullable_Extensions { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * Determines the format of the array if type array is used. Possible values are: * * - `csv` - comma separated values `foo,bar`. * - `ssv` - space separated values `foo bar`. * - `tsv` - tab separated values `foo\tbar`. * - `pipes` - pipe separated values `foo|bar`. * * Default value is `csv`. */ collectionFormat?: 'csv' | 'pipes' | 'ssv' | 'tsv'; /** * Declares the value of the item that the server will use if none is provided. (Note: "default" has no meaning for required items.) See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2}. Unlike JSON Schema this value MUST conform to the defined {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#itemsType `type`} for the data type. */ default?: unknown; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1}. */ enum?: ReadonlyArray; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2}. */ exclusiveMaximum?: boolean; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3}. */ exclusiveMinimum?: boolean; /** * The extending format for the previously mentioned {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterType `type`}. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#dataTypeFormat Data Type Formats} for further details. */ format?: string; /** * **Required if {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterType `type`} is "array"**. Describes the type of items in the array. */ items?: ItemsObject; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2}. */ maxItems?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1}. */ maxLength?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2}. */ maximum?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3}. */ minItems?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2}. */ minLength?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3}. */ minimum?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1}. */ multipleOf?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3}. */ pattern?: string; /** * **Required**. The internal type of the array. The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, or `"array"`. Files and models are not allowed. */ type: 'array' | 'boolean' | 'integer' | 'number' | 'string'; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4}. */ uniqueItems?: boolean; } /** * License information for the exposed API. * * @example * ```yaml * name: Apache 2.0 * url: http://www.apache.org/licenses/LICENSE-2.0.html * ``` */ export interface LicenseObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * **Required**. The license name used for the API. */ name: string; /** * A URL to the license used for the API. MUST be in the format of a URL. */ url?: string; } /** * Describes a single API operation on a path. * * @example * ```yaml * tags: * - pet * summary: Updates a pet in the store with form data * description: "" * operationId: updatePetWithForm * consumes: * - application/x-www-form-urlencoded * produces: * - application/json * - application/xml * parameters: * - name: petId * in: path * description: ID of pet that needs to be updated * required: true * type: string * - name: name * in: formData * description: Updated name of the pet * required: false * type: string * - name: status * in: formData * description: Updated status of the pet * required: false * type: string * responses: * '200': * description: Pet updated. * '405': * description: Invalid input * security: * - petstore_auth: * - write:pets * - read:pets * ``` */ export interface OperationObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * A list of MIME types the operation can consume. This overrides the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerConsumes `consumes`} definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#mime-types Mime Types}. */ consumes?: ReadonlyArray; /** * Declares this operation to be deprecated. Usage of the declared operation should be refrained. Default value is `false`. */ deprecated?: boolean; /** * A verbose explanation of the operation behavior. {@link https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown GFM syntax} can be used for rich text representation. */ description?: string; /** * Additional external documentation for this operation. */ externalDocs?: ExternalDocumentationObject; /** * Unique string used to identify the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is recommended to follow common programming naming conventions. */ operationId?: string; /** * A list of parameters that are applicable for this operation. If a parameter is already defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#pathItemParameters Path Item}, the new definition will override it, but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterName name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn location}. The list can use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#reference-object Reference Object} to link to parameters that are defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerParameters Swagger Object's parameters}. There can be one "body" parameter at most. */ parameters?: ReadonlyArray; /** * A list of MIME types the operation can produce. This overrides the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerProduces `produces`} definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#mime-types Mime Types}. */ produces?: ReadonlyArray; /** * **Required**. The list of possible responses as they are returned from executing this operation. */ responses: ResponsesObject; /** * The transfer protocol for the operation. Values MUST be from the list: `"http"`, `"https"`, `"ws"`, `"wss"`. The value overrides the Swagger Object {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerSchemes `schemes`} definition. */ schemes?: ReadonlyArray<'http' | 'https' | 'ws' | 'wss'>; /** * A declaration of which security schemes are applied for this operation. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). This definition overrides any declared top-level {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerSecurity `security`}. To remove a top-level security declaration, an empty array can be used. */ security?: ReadonlyArray; /** * A short summary of what the operation does. For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters. */ summary?: string; /** * A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. */ tags?: ReadonlyArray; /** * A list of code samples associated with an operation. */ 'x-codeSamples'?: ReadonlyArray; } /** * Describes a single operation parameter. * * A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterName name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn location}. * * There are five possible parameter types. * * - Path - Used together with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-templating Path Templating}, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. * - Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. * - Header - Custom headers that are expected as part of the request. * - Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be _one_ body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation. * - Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded`, `multipart/form-data` or both are used as the content type of the request (in Swagger's definition, the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#operationConsumes `consumes`} property of an operation). This is the only parameter type that can be used to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult {@link http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4 http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4}): * - `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple parameters that are being transferred. * - `multipart/form-data` - each parameter takes a section in the payload with an internal header. For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is `submit-name`. This type of form parameters is more commonly used for file transfers. * * **Parameter Object Examples** * * Body Parameters * * A body parameter with a referenced schema definition (normally for a model definition): * * @example * ```yaml * name: user * in: body * description: user to add to the system * required: true * schema: * $ref: '#/definitions/User' * ``` * * A body parameter that is an array of string values: * * @example * ```yaml * name: user * in: body * description: user to add to the system * required: true * schema: * type: array * items: * type: string * ``` * * Other Parameters * * A header parameter with an array of 64 bit integer numbers: * * @example * ```yaml * name: token * in: header * description: token to be passed as a header * required: true * type: array * items: * type: integer * format: int64 * collectionFormat: csv * ``` * * A path parameter of a string value: * * @example * ```yaml * name: username * in: path * description: username to fetch * required: true * type: string * ``` * * An optional query parameter of a string value, allowing multiple values by repeating the query parameter: * * @example * ```yaml * name: id * in: query * description: ID of the object to fetch * required: false * type: array * items: * type: string * collectionFormat: multi * ``` * * A form data with file type for a file upload: * * @example * ```yaml * name: avatar * in: formData * description: The avatar of the user * required: true * type: file * ``` */ export type ParameterObject = EnumExtensions & OpenApiV2_0_X_Nullable_Extensions & { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * A brief description of the parameter. This could contain examples of use. {@link https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown GFM syntax} can be used for rich text representation. */ description?: string; /** * **Required**. The name of the parameter. Parameter names are _case sensitive_. * * - If {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn `in`} is `"path"`, the `name` field MUST correspond to the associated path segment from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#pathsPath path} field in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#paths-object Paths Object}. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-templating Path Templating} for further information. * - For all other cases, the `name` corresponds to the parameter name used based on the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn `in`} property. */ name: string; /** * Determines whether this parameter is mandatory. If the parameter is {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn `in`} "path", this property is **required** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. */ required?: boolean; } & ( | { /** * **Required**. The location of the parameter. Possible values are "query", "header", "path", "formData" or "body". */ in: 'body'; /** * **Required**. The schema defining the type used for the body parameter. */ schema: SchemaObject; } | { /** * Sets the ability to pass empty-valued parameters. This is valid only for either `query` or `formData` parameters and allows you to send a parameter with a name only or an empty value. Default value is `false`. */ allowEmptyValue?: boolean; /** * Determines the format of the array if type array is used. Possible values are: * * - `csv` - comma separated values `foo,bar`. * - `ssv` - space separated values `foo bar`. * - `tsv` - tab separated values `foo\tbar`. * - `pipes` - pipe separated values `foo|bar`. * - `multi` - corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`. This is valid only for parameters {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn `in`} "query" or "formData". * * Default value is `csv`. */ collectionFormat?: 'csv' | 'multi' | 'pipes' | 'ssv' | 'tsv'; /** * Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2}. Unlike JSON Schema this value MUST conform to the defined {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterType `type`} for this parameter. */ default?: unknown; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1}. */ enum?: ReadonlyArray; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2}. */ exclusiveMaximum?: boolean; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3}. */ exclusiveMinimum?: boolean; /** * The extending format for the previously mentioned {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterType `type`}. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#dataTypeFormat Data Type Formats} for further details. */ format?: string; /** * **Required**. The location of the parameter. Possible values are "query", "header", "path", "formData" or "body". */ in: 'formData' | 'header' | 'path' | 'query'; /** * **Required if {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterType `type`} is "array"**. Describes the type of items in the array. */ items?: ItemsObject; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2}. */ maxItems?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1}. */ maxLength?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2}. */ maximum?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3}. */ minItems?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2}. */ minLength?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3}. */ minimum?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1}. */ multipleOf?: number; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3}. */ pattern?: string; /** * **Required**. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, `"array"` or `"file"`. If `type` is `"file"`, the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#operationConsumes `consumes`} MUST be either `"multipart/form-data"`, `"application/x-www-form-urlencoded"` or both and the parameter MUST be {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn `in`} `"formData"`. */ type: 'array' | 'boolean' | 'file' | 'integer' | 'number' | 'string'; /** * See {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4}. */ uniqueItems?: boolean; } ); /** * An object to hold parameters to be reused across operations. Parameter definitions can be referenced to the ones defined here. * * This does _not_ define global operation parameters. * * **Parameters Definition Object Example** * * @example * ```yaml * skipParam: * name: skip * in: query * description: number of items to skip * required: true * type: integer * format: int32 * limitParam: * name: limit * in: query * description: max records to return * required: true * type: integer * format: int32 * ``` */ export interface ParametersDefinitionsObject { /** * A single parameter definition, mapping a "name" to the parameter it defines. */ [name: string]: ParameterObject; } /** * Describes the operations available on a single path. A Path Item may be empty, due to {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#security-filtering ACL constraints}. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. * * @example * ```yaml * get: * description: Returns pets based on ID * summary: Find pets by ID * operationId: getPetsById * produces: * - application/json * - text/html * responses: * '200': * description: pet response * schema: * type: array * items: * $ref: '#/definitions/Pet' * default: * description: error payload * schema: * $ref: '#/definitions/ErrorModel' * parameters: * - name: id * in: path * description: ID of pet to use * required: true * type: array * items: * type: string * collectionFormat: csv * ``` */ export interface PathItemObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * Allows for an external definition of this path item. The referenced structure MUST be in the format of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-item-object Path Item Object}. If there are conflicts between the referenced definition and this Path Item's definition, the behavior is _undefined_. */ $ref?: string; /** * A definition of a DELETE operation on this path. */ delete?: OperationObject; /** * A definition of a GET operation on this path. */ get?: OperationObject; /** * A definition of a HEAD operation on this path. */ head?: OperationObject; /** * A definition of a OPTIONS operation on this path. */ options?: OperationObject; /** * A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterName name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameterIn location}. The list can use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#reference-object Reference Object} to link to parameters that are defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerParameters Swagger Object's parameters}. There can be one "body" parameter at most. */ parameters?: ReadonlyArray; /** * A definition of a PATCH operation on this path. */ patch?: OperationObject; /** * A definition of a POST operation on this path. */ post?: OperationObject; /** * A definition of a PUT operation on this path. */ put?: OperationObject; } /** * Holds the relative paths to the individual endpoints. The path is appended to the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerBasePath `basePath`} in order to construct the full URL. The Paths may be empty, due to {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#security-filtering ACL constraints}. * * @example * ```yaml * /pets: * get: * description: Returns all pets from the system that the user has access to * produces: * - application/json * responses: * '200': * description: A list of pets. * schema: * type: array * items: * $ref: '#/definitions/pet' * ``` */ export interface PathsObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * A relative path to an individual endpoint. The field name MUST begin with a slash. The path is appended to the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerBasePath `basePath`} in order to construct the full URL. {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-templating Path templating} is allowed. */ [path: `/${string}`]: PathItemObject; } /** * A simple object to allow referencing other definitions in the specification. It can be used to reference parameters and responses that are defined at the top level for reuse. * * The Reference Object is a {@link http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-02 JSON Reference} that uses a {@link http://tools.ietf.org/html/rfc6901 JSON Pointer} as its value. For this specification, only {@link https://tools.ietf.org/html/draft-zyp-json-schema-04#section-7.2.3 canonical dereferencing} is supported. * * **Reference Object Example** * * @example * ```yaml * $ref: '#/definitions/Pet' * ``` * * **Relative Schema File Example** * * @example * ```yaml * $ref: 'Pet.yaml' * ``` * * **Relative Files With Embedded Schema Example** * * @example * ```yaml * $ref: 'definitions.yaml#/Pet' * ``` */ export interface ReferenceObject { /** * **Required**. The reference string. */ $ref: string; } /** * Describes a single response from an API Operation. * * **Response Object Examples** * * Response of an array of a complex type: * * @example * ```yaml * description: A complex object array response * schema: * type: array * items: * $ref: '#/definitions/VeryComplexType' * ``` * * Response with a string type: * * @example * ```yaml * description: A simple string response * schema: * type: string * ``` * * Response with headers: * * @example * ```yaml * description: A simple string response * schema: * type: string * headers: * X-Rate-Limit-Limit: * description: The number of allowed requests in the current period * type: integer * X-Rate-Limit-Remaining: * description: The number of remaining requests in the current period * type: integer * X-Rate-Limit-Reset: * description: The number of seconds left in the current period * type: integer * ``` * * Response with no return value: * * @example * ```yaml * description: object created * ``` */ export interface ResponseObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * **Required**. A short description of the response. {@link https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown GFM syntax} can be used for rich text representation. */ description: string; /** * An example of the response message. */ examples?: ExampleObject; /** * A list of headers that are sent with the response. */ headers?: HeadersObject; /** * A definition of the response structure. It can be a primitive, an array or an object. If this field does not exist, it means no content is returned as part of the response. As an extension to the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#schema-object Schema Object}, its root `type` value may also be `"file"`. This SHOULD be accompanied by a relevant `produces` mime-type. */ schema?: SchemaObject; } /** * An object to hold responses to be reused across operations. Response definitions can be referenced to the ones defined here. * * This does _not_ define global operation responses. * * **Responses Definitions Object Example** * * @example * ```yaml * NotFound: * description: Entity not found. * IllegalInput: * description: Illegal input for operation. * GeneralError: * description: General Error * schema: * $ref: '#/definitions/GeneralError' * ``` */ export interface ResponsesDefinitionsObject { /** * A single response definition, mapping a "name" to the response it defines. */ [name: string]: ResponseObject; } /** * A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. It is not expected from the documentation to necessarily cover all possible HTTP response codes, since they may not be known in advance. However, it is expected from the documentation to cover a successful operation response and any known errors. * * The `default` can be used as the default response object for all HTTP codes that are not covered individually by the specification. * * The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call. * * **Responses Object Example** * * A 200 response for successful operation and a default response for others (implying an error): * * @example * ```yaml * '200': * description: a pet to be returned * schema: * $ref: '#/definitions/Pet' * default: * description: Unexpected error * schema: * $ref: '#/definitions/ErrorModel' * ``` */ export interface ResponsesObject { /** * Any {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#http-status-codes HTTP status code} can be used as the property name (one property per HTTP status code). Describes the expected response for that HTTP status code. {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#reference-object Reference Object} can be used to link to a response that is defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerResponses Swagger Object's responses} section. */ [httpStatusCode: string]: ResponseObject | ReferenceObject | undefined; /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: any; /** * The documentation of responses other than the ones declared for specific HTTP response codes. It can be used to cover undeclared responses. {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#reference-object Reference Object} can be used to link to a response that is defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swaggerResponses Swagger Object's responses} section. */ default?: ResponseObject | ReferenceObject; } /** * The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is based on the {@link http://json-schema.org/ JSON Schema Specification Draft 4} and uses a predefined subset of it. On top of this subset, there are extensions provided by this specification to allow for more complete documentation. * * Further information about the properties can be found in {@link https://tools.ietf.org/html/draft-zyp-json-schema-04 JSON Schema Core} and {@link https://tools.ietf.org/html/draft-fge-json-schema-validation-00 JSON Schema Validation}. Unless stated otherwise, the property definitions follow the JSON Schema specification as referenced here. * * The following properties are taken directly from the JSON Schema definition and follow the same specifications: * * - $ref - As a {@link https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 JSON Reference} * - format (See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#dataTypeFormat Data Type Formats} for further details) * - title * - description ({@link https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown GFM syntax} can be used for rich text representation) * - default (Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object) * - multipleOf * - maximum * - exclusiveMaximum * - minimum * - exclusiveMinimum * - maxLength * - minLength * - pattern * - maxItems * - minItems * - uniqueItems * - maxProperties * - minProperties * - required * - enum * - type * * The following properties are taken from the JSON Schema definition but their definitions were adjusted to the Swagger Specification. Their definition is the same as the one from JSON Schema, only where the original definition references the JSON Schema definition, the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#schema-object Schema Object} definition is used instead. * * - items * - allOf * - properties * - additionalProperties * * Other than the JSON Schema subset fields, the following fields may be used for further schema documentation. * * **Composition and Inheritance (Polymorphism)** * * Swagger allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. `allOf` takes in an array of object definitions that are validated _independently_ but together compose a single object. * * While composition offers model extensibility, it does not imply a hierarchy between the models. To support polymorphism, Swagger adds the support of the `discriminator` field. When used, the `discriminator` will be the name of the property used to decide which schema definition is used to validate the structure of the model. As such, the `discriminator` field MUST be a required field. The value of the chosen property has to be the friendly name given to the model under the `definitions` property. As such, inline schema definitions, which do not have a given id, _cannot_ be used in polymorphism. * * **XML Modeling** * * The {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#schemaXml xml} property allows extra definitions when translating the JSON definition to XML. The {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#xml-object XML Object} contains additional information about the available options. * * **Schema Object Examples** * * Primitive Sample * * Unlike previous versions of Swagger, Schema definitions can be used to describe primitive and arrays as well. * * @example * ```yaml * type: string * format: email * ``` * * Simple Model * * @example * ```yaml * type: object * required: * - name * properties: * name: * type: string * address: * $ref: '#/definitions/Address' * age: * type: integer * format: int32 * minimum: 0 * ``` * * Model with Map/Dictionary Properties * * For a simple string to string mapping: * * @example * ```yaml * type: object * additionalProperties: * type: string * ``` * * For a string to model mapping: * * @example * ```yaml * type: object * additionalProperties: * $ref: '#/definitions/ComplexModel' * ``` * * Model with Example * * @example * ```yaml * type: object * properties: * id: * type: integer * format: int64 * name: * type: string * required: * - name * example: * name: Puma * id: 1 * ``` * * Models with Composition * * @example * ```yaml * definitions: * ErrorModel: * type: object * required: * - message * - code * properties: * message: * type: string * code: * type: integer * minimum: 100 * maximum: 600 * ExtendedErrorModel: * allOf: * - $ref: '#/definitions/ErrorModel' * - type: object * required: * - rootCause * properties: * rootCause: * type: string * ``` * * Models with Polymorphism Support * * @example * ```yaml * definitions: * Pet: * type: object * discriminator: petType * properties: * name: * type: string * petType: * type: string * required: * - name * - petType * Cat: * description: A representation of a cat * allOf: * - $ref: '#/definitions/Pet' * - type: object * properties: * huntingSkill: * type: string * description: The measured skill for hunting * default: lazy * enum: * - clueless * - lazy * - adventurous * - aggressive * required: * - huntingSkill * Dog: * description: A representation of a dog * allOf: * - $ref: '#/definitions/Pet' * - type: object * properties: * packSize: * type: integer * format: int32 * description: the size of the pack the dog is from * default: 0 * minimum: 0 * required: * - packSize * ``` */ export interface SchemaObject extends JsonSchemaDraft4, OpenApiV2_0_X_Nullable_Extensions { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * The `additionalProperties` keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the `properties` keyword or match any of the regular expressions in the `patternProperties` keyword. By default any additional properties are allowed. * * The value of the `additionalProperties` keyword is a schema that will be used to validate any properties in the {@link https://json-schema.org/learn/glossary#instance instance} that are not matched by `properties` or `patternProperties`. Setting the `additionalProperties` schema to `false` means no additional properties will be allowed. * * It's important to note that `additionalProperties` only recognizes properties declared in the same {@link https://json-schema.org/learn/glossary#subschema subschema} as itself. So, `additionalProperties` can restrict you from "extending" a schema using {@link https://json-schema.org/understanding-json-schema/reference/combining combining} keywords such as {@link https://json-schema.org/understanding-json-schema/reference/combining#allof allOf}. */ additionalProperties?: SchemaObject | boolean; /** * `allOf`: (AND) Must be valid against _all_ of the {@link https://json-schema.org/learn/glossary#subschema subschemas} * * To validate against `allOf`, the given data must be valid against all of the given subschemas. * * {@link https://json-schema.org/understanding-json-schema/reference/combining#allof allOf} can not be used to "extend" a schema to add more details to it in the sense of object-oriented inheritance. {@link https://json-schema.org/learn/glossary#instance Instances} must independently be valid against "all of" the schemas in the `allOf`. See the section on {@link https://json-schema.org/understanding-json-schema/reference/object#extending Extending Closed Schemas} for more information. */ allOf?: ReadonlyArray; /** * Adds support for polymorphism. The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the `required` property list. When used, the value MUST be the name of this schema or any schema that inherits it. */ discriminator?: string; /** * A free-form property to include an example of an instance for this schema. */ example?: unknown; /** * Additional external documentation for this schema. */ externalDocs?: ExternalDocumentationObject; /** * List validation is useful for arrays of arbitrary length where each item matches the same schema. For this kind of array, set the `items` {@link https://json-schema.org/learn/glossary#keyword keyword} to a single schema that will be used to validate all of the items in the array. * * The `items` keyword can be used to control whether it's valid to have additional items in a tuple beyond what is defined in `prefixItems`. The value of the `items` keyword is a schema that all additional items must pass in order for the keyword to validate. * * Note that `items` doesn't "see inside" any {@link https://json-schema.org/learn/glossary#instance instances} of `allOf`, `anyOf`, or `oneOf` in the same {@link https://json-schema.org/learn/glossary#subschema subschema}. */ items?: SchemaObject; /** * The properties (key-value pairs) on an object are defined using the `properties` {@link https://json-schema.org/learn/glossary#keyword keyword}. The value of `properties` is an object, where each key is the name of a property and each value is a {@link https://json-schema.org/learn/glossary#schema schema} used to validate that property. Any property that doesn't match any of the property names in the `properties` keyword is ignored by this keyword. */ properties?: Record; /** * Relevant only for Schema `"properties"` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but MUST NOT be sent as part of the request. Properties marked as `readOnly` being `true` SHOULD NOT be in the `required` list of the defined schema. Default value is `false`. */ readOnly?: boolean; /** * This MAY be used only on properties schemas. It has no effect on root schemas. Adds Additional metadata to describe the XML representation format of this property. */ xml?: XMLObject; } /** * Lists the available scopes for an OAuth2 security scheme. * * **Scopes Object Example** * * @example * ```yaml * write:pets: modify pets in your account * read:pets: read your pets * ``` */ export interface ScopesObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: any; /** * Maps between a name of a scope to a short description of it (as the value of the property). */ [name: string]: string; } /** * A declaration of the security schemes available to be used in the specification. This does not enforce the security schemes on the operations and only serves to provide the relevant details for each scheme. * * **Security Definitions Object Example** * * @example * ```yaml * api_key: * type: apiKey * name: api_key * in: header * petstore_auth: * type: oauth2 * authorizationUrl: http://swagger.io/api/oauth/dialog * flow: implicit * scopes: * write:pets: modify pets in your account * read:pets: read your pets * ``` */ export interface SecurityDefinitionsObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: any; /** * A single security scheme definition, mapping a "name" to the scheme it defines. */ [name: string]: SecuritySchemeObject; } /** * Lists the required security schemes to execute this operation. The object can have multiple security schemes declared in it which are all required (that is, there is a logical AND between the schemes). * * The name used for each property MUST correspond to a security scheme declared in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#security-definitions-object Security Definitions}. * * **Security Requirement Object Examples** * * Non-OAuth2 Security Requirement * * @example * ```yaml * api_key: [] * ``` * * OAuth2 Security Requirement * * @example * ```yaml * petstore_auth: * - write:pets * - read:pets * ``` */ export interface SecurityRequirementObject { /** * Each name must correspond to a security scheme which is declared in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#securityDefinitions Security Definitions}. If the security scheme is of type `"oauth2"`, then the value is a list of scope names required for the execution. For other security scheme types, the array MUST be empty. */ [name: string]: ReadonlyArray; } /** * Allows the definition of a security scheme that can be used by the operations. Supported schemes are basic authentication, an API key (either as a header or as a query parameter) and OAuth2's common flows (implicit, password, application and access code). * * **Security Scheme Object Example** * * Basic Authentication Sample * * @example * ```yaml * type: basic * ``` * * API Key Sample * * @example * ```yaml * type: apiKey * name: api_key * in: header * ``` * * Implicit OAuth2 Sample * * @example * ```yaml * type: oauth2 * authorizationUrl: http://swagger.io/api/oauth/dialog * flow: implicit * scopes: * write:pets: modify pets in your account * read:pets: read your pets * ``` */ export type SecuritySchemeObject = { /** * A short description for security scheme. */ description?: string; } & ( | { /** * **Required** The location of the API key. Valid values are `"query"` or `"header"`. */ in: 'header' | 'query'; /** * **Required**. The name of the header or query parameter to be used. */ name: string; /** * **Required**. The type of the security scheme. Valid values are `"basic"`, `"apiKey"` or `"oauth2"`. */ type: 'apiKey'; } | { /** * **Required (`"implicit"`, `"accessCode"`)**. The authorization URL to be used for this flow. This SHOULD be in the form of a URL. */ authorizationUrl?: string; /** * **Required**. The flow used by the OAuth2 security scheme. Valid values are `"implicit"`, `"password"`, `"application"` or `"accessCode"`. */ flow: 'accessCode' | 'application' | 'implicit' | 'password'; /** * **Required**. The available scopes for the OAuth2 security scheme. */ scopes: ScopesObject; /** * **Required (`"password"`, `"application"`, `"accessCode"`)**. The token URL to be used for this flow. This SHOULD be in the form of a URL. */ tokenUrl?: string; /** * **Required**. The type of the security scheme. Valid values are `"basic"`, `"apiKey"` or `"oauth2"`. */ type: 'oauth2'; } | { /** * **Required**. The type of the security scheme. Valid values are `"basic"`, `"apiKey"` or `"oauth2"`. */ type: 'basic'; } ); /** * Allows adding meta data to a single tag that is used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#operation-object Operation Object}. It is not mandatory to have a Tag Object per tag used there. * * **Tag Object Example** * * @example * ```yaml * name: pet * description: Pets operations * ``` */ export interface TagObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * A short description for the tag. {@link https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown GFM syntax} can be used for rich text representation. */ description?: string; /** * Additional external documentation for this tag. */ externalDocs?: ExternalDocumentationObject; /** * **Required**. The name of the tag. */ name: string; } /** * A metadata object that allows for more fine-tuned XML model definitions. * * When using arrays, XML element names are _not_ inferred (for singular/plural forms) and the `name` property should be used to add that information. See examples for expected behavior. */ export interface XMLObject { /** * Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#specification-extensions Vendor Extensions} for further details. */ [name: `x-${string}`]: unknown; /** * Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. */ attribute?: boolean; /** * Replaces the name of the element/attribute used for the described schema property. When defined within the Items Object (`items`), it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. */ name?: string; /** * The URL of the namespace definition. Value SHOULD be in the form of a URL. */ namespace?: string; /** * The prefix to be used for the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#xmlName name}. */ prefix?: string; /** * MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). */ wrapped?: boolean; } ================================================ FILE: packages/shared/src/openApi/3.0.x/index.ts ================================================ export { parseV3_0_X } from './parser'; export type { OpenApiV3_0_X } from './types/spec'; import type { InfoObject, OperationObject, ParameterObject, ReferenceObject, RequestBodyObject, ResponseObject, SchemaObject, } from './types/spec'; export interface OpenApiV3_0_XTypes { InfoObject: InfoObject; OperationObject: OperationObject; ParameterObject: ParameterObject; ReferenceObject: ReferenceObject; RequestBodyObject: RequestBodyObject; ResponseObject: ResponseObject; SchemaObject: SchemaObject; } ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/__tests__/operation.test.ts ================================================ import type { Context } from '../../../../ir/context'; import type { SecuritySchemeObject } from '../../types/spec'; import { parsePathOperation } from '../operation'; type ParseOperationProps = Parameters[0]; describe('operation', () => { const context = { config: { plugins: {}, }, ir: { paths: {}, servers: [], }, } as unknown as Context; it('should parse operation correctly', () => { const method = 'get'; const operation: ParseOperationProps['operation'] = { operationId: 'testOperation', responses: {}, security: [ { apiKeyAuth: [], }, { apiKeyAuth: [], }, { oauthRule: ['read'], }, { oauthRule: ['write'], }, ], summary: 'Test Operation', }; const path = '/test'; const oauth2: SecuritySchemeObject = { description: 'OAuth2', flows: { password: { scopes: { read: 'Grants read access', write: 'Grants write access', }, tokenUrl: 'https://example.com/oauth/token', }, }, type: 'oauth2', }; const securitySchemesMap = new Map([ ['apiKeyAuth', { in: 'header', name: 'Auth', type: 'apiKey' }], ['basicAuthRule', { description: 'Basic Auth', scheme: 'basic', type: 'http' }], ['oauthRule', oauth2], ]); const state: ParseOperationProps['state'] = { ids: new Map(), }; parsePathOperation({ context, method, operation, path, securitySchemesMap, state, }); expect(context.ir.paths?.[path]?.[method]).toEqual({ id: 'testOperation', method, operationId: 'testOperation', path, security: [{ in: 'header', name: 'Auth', type: 'apiKey' }, oauth2], summary: 'Test Operation', }); }); }); ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/__tests__/validate.test.ts ================================================ import path from 'node:path'; import { Logger } from '@hey-api/codegen-core'; import { getSpecsPath, specFileToJson } from '../../../__tests__/utils'; import type { ValidatorResult } from '../../../shared/utils/validator'; import { validateOpenApiSpec } from '../validate'; const specsFolder = path.join(getSpecsPath(), '3.0.x', 'invalid'); describe('validate', () => { const scenarios: Array< ValidatorResult & { description: string; file: string; } > = [ { description: 'servers must be array', file: path.join(specsFolder, 'servers-array.yaml'), issues: [ { code: 'invalid_type', message: '`servers` must be an array.', path: [], severity: 'error', }, ], valid: false, }, { description: 'servers entry must be object', file: path.join(specsFolder, 'servers-entry.yaml'), issues: [ { code: 'invalid_type', context: { actual: 'string', expected: 'object', }, message: 'Each entry in `servers` must be an object.', path: ['servers', 0], severity: 'error', }, ], valid: false, }, { description: 'servers entry required fields', file: path.join(specsFolder, 'servers-required.yaml'), issues: [ { code: 'missing_required_field', context: { field: 'url', }, message: 'Missing required field `url` in server object.', path: ['servers', 0], severity: 'error', }, ], valid: false, }, { description: 'operationId must be unique', file: path.join(specsFolder, 'operationId-unique.yaml'), issues: [ { code: 'duplicate_key', context: { key: 'operationId', value: 'foo', }, message: 'Duplicate `operationId` found. Each `operationId` must be unique.', path: ['paths', '/foo', 'post', 'operationId'], severity: 'error', }, ], valid: false, }, ]; it.each(scenarios)('$description', ({ file, issues, valid }) => { const spec = specFileToJson(file); const logger = new Logger(); const result = validateOpenApiSpec(spec, logger); expect(result.valid).toBe(valid); expect(result.issues).toEqual(issues); }); }); ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/filter.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { createOperationKey } from '../../../ir/operation'; import { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter'; import { httpMethods } from '../../../openApi/shared/utils/operation'; import type { OpenApiV3_0_X, PathItemObject, PathsObject } from '../types/spec'; /** * Replace source spec with filtered version. */ export const filterSpec = ({ logger, operations, parameters, preserveOrder, requestBodies, responses, schemas, spec, }: { logger: Logger; operations: Set; parameters: Set; preserveOrder: boolean; requestBodies: Set; responses: Set; schemas: Set; spec: OpenApiV3_0_X; }) => { const eventFilterSpec = logger.timeEvent('filter-spec'); if (spec.components) { if (spec.components.parameters) { const filtered: typeof spec.components.parameters = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.parameters)) { if (parameters.has(addNamespace('parameter', name))) { filtered[name] = source; } } } else { for (const key of parameters) { const { name } = removeNamespace(key); const source = spec.components.parameters[name]; if (source) { filtered[name] = source; } } } spec.components.parameters = filtered; } if (spec.components.requestBodies) { const filtered: typeof spec.components.requestBodies = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.requestBodies)) { if (requestBodies.has(addNamespace('body', name))) { filtered[name] = source; } } } else { for (const key of requestBodies) { const { name } = removeNamespace(key); const source = spec.components.requestBodies[name]; if (source) { filtered[name] = source; } } } spec.components.requestBodies = filtered; } if (spec.components.responses) { const filtered: typeof spec.components.responses = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.responses)) { if (responses.has(addNamespace('response', name))) { filtered[name] = source; } } } else { for (const key of responses) { const { name } = removeNamespace(key); const source = spec.components.responses[name]; if (source) { filtered[name] = source; } } } spec.components.responses = filtered; } if (spec.components.schemas) { const filtered: typeof spec.components.schemas = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.schemas)) { if (schemas.has(addNamespace('schema', name))) { filtered[name] = source; } } } else { for (const key of schemas) { const { name } = removeNamespace(key); const source = spec.components.schemas[name]; if (source) { filtered[name] = source; } } } spec.components.schemas = filtered; } } if (spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { const operation = pathItem[method]; if (!operation) { continue; } const key = addNamespace('operation', createOperationKey({ method, path })); if (!operations.has(key)) { delete pathItem[method]; } } // remove paths that have no operations left if (!Object.keys(pathItem).length) { delete spec.paths[path]; } } } eventFilterSpec.timeEnd(); }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/index.ts ================================================ import type { Context } from '../../../ir/context'; import { buildResourceMetadata } from '../../../openApi/shared/graph/meta'; import { transformOpenApiSpec } from '../../../openApi/shared/transforms'; import type { State } from '../../../openApi/shared/types/state'; import { createFilteredDependencies, createFilters, hasFilters, } from '../../../openApi/shared/utils/filter'; import { buildGraph } from '../../../openApi/shared/utils/graph'; import { mergeParametersObjects } from '../../../openApi/shared/utils/parameter'; import { handleValidatorResult } from '../../../openApi/shared/utils/validator'; import type { OpenApiV3_0_X, ParameterObject, PathItemObject, PathsObject, RequestBodyObject, SecuritySchemeObject, } from '../types/spec'; import { filterSpec } from './filter'; import { parsePathOperation } from './operation'; import { parametersArrayToObject, parseParameter } from './parameter'; import { parseRequestBody } from './requestBody'; import { parseSchema } from './schema'; import { parseServers } from './server'; import { validateOpenApiSpec } from './validate'; export const parseV3_0_X = (context: Context) => { if (context.config.parser.validate_EXPERIMENTAL) { const result = validateOpenApiSpec(context.spec, context.logger); handleValidatorResult({ context, result }); } const shouldFilterSpec = hasFilters(context.config.parser.filters); if (shouldFilterSpec) { const filters = createFilters(context.config.parser.filters, context.spec, context.logger); const { graph } = buildGraph(context.spec, context.logger); const { resourceMetadata } = buildResourceMetadata(graph, context.logger); const sets = createFilteredDependencies({ filters, logger: context.logger, resourceMetadata, }); filterSpec({ ...sets, logger: context.logger, preserveOrder: filters.preserveOrder, spec: context.spec, }); } transformOpenApiSpec({ context }); const state: State = { ids: new Map(), }; const securitySchemesMap = new Map(); // TODO: parser - handle more component types, old parser handles only parameters and schemas if (context.spec.components) { for (const name in context.spec.components.securitySchemes) { const securityOrReference = context.spec.components.securitySchemes[name]!; const securitySchemeObject = '$ref' in securityOrReference ? context.resolveRef(securityOrReference.$ref) : securityOrReference; securitySchemesMap.set(name, securitySchemeObject); } for (const name in context.spec.components.parameters) { const $ref = `#/components/parameters/${name}`; const parameterOrReference = context.spec.components.parameters[name]!; const parameter = '$ref' in parameterOrReference ? context.resolveRef(parameterOrReference.$ref) : parameterOrReference; parseParameter({ $ref, context, parameter, }); } for (const name in context.spec.components.requestBodies) { const $ref = `#/components/requestBodies/${name}`; const requestBodyOrReference = context.spec.components.requestBodies[name]!; const requestBody = '$ref' in requestBodyOrReference ? context.resolveRef(requestBodyOrReference.$ref) : requestBodyOrReference; parseRequestBody({ $ref, context, requestBody, }); } for (const name in context.spec.components.schemas) { const $ref = `#/components/schemas/${name}`; const schema = context.spec.components.schemas[name]!; parseSchema({ $ref, context, schema, }); } } parseServers({ context }); for (const path in context.spec.paths) { if (path.startsWith('x-')) continue; const pathItem = context.spec.paths[path as keyof PathsObject]! as PathItemObject; const finalPathItem = pathItem.$ref ? { ...context.resolveRef(pathItem.$ref), ...pathItem, } : pathItem; const operationArgs: Omit[0], 'method' | 'operation'> & { operation: Omit[0]['operation'], 'responses'>; } = { context, operation: { description: finalPathItem.description, parameters: parametersArrayToObject({ context, parameters: finalPathItem.parameters, }), security: context.spec.security, servers: finalPathItem.servers, summary: finalPathItem.summary, }, path: path as `/${string}`, securitySchemesMap, state, }; if (finalPathItem.delete) { parsePathOperation({ ...operationArgs, method: 'delete', operation: { ...operationArgs.operation, ...finalPathItem.delete, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.delete.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.get) { parsePathOperation({ ...operationArgs, method: 'get', operation: { ...operationArgs.operation, ...finalPathItem.get, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.get.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.head) { parsePathOperation({ ...operationArgs, method: 'head', operation: { ...operationArgs.operation, ...finalPathItem.head, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.head.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.options) { parsePathOperation({ ...operationArgs, method: 'options', operation: { ...operationArgs.operation, ...finalPathItem.options, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.options.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.patch) { parsePathOperation({ ...operationArgs, method: 'patch', operation: { ...operationArgs.operation, ...finalPathItem.patch, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.patch.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.post) { parsePathOperation({ ...operationArgs, method: 'post', operation: { ...operationArgs.operation, ...finalPathItem.post, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.post.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.put) { parsePathOperation({ ...operationArgs, method: 'put', operation: { ...operationArgs.operation, ...finalPathItem.put, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.put.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.trace) { parsePathOperation({ ...operationArgs, method: 'trace', operation: { ...operationArgs.operation, ...finalPathItem.trace, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.trace.parameters, }), target: operationArgs.operation.parameters, }), }, }); } } }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/mediaType.ts ================================================ import type { IRMediaType } from '../../../ir/mediaType'; import { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType'; import type { MediaTypeObject, ReferenceObject, SchemaObject } from '../types/spec'; interface Content { mediaType: string; schema: SchemaObject | ReferenceObject | undefined; type: IRMediaType | undefined; } export const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => { const { mediaType, schema } = content; if (schema && '$ref' in schema) { return { allOf: [{ ...schema }], }; } if (!schema) { if (isMediaTypeFileLike({ mediaType })) { return { format: 'binary', type: 'string', }; } return; } if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) { return { ...schema, format: 'binary', }; } return schema; }; export const mediaTypeObjects = ({ content, }: { content: Record | undefined; }): ReadonlyArray => { const objects: Array = []; for (const mediaType in content) { objects.push({ mediaType, schema: content[mediaType]!.schema, type: mediaTypeToIrMediaType({ mediaType }), }); } return objects; }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/operation.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import type { State } from '../../../openApi/shared/types/state'; import { operationToId } from '../../../openApi/shared/utils/operation'; import type { OperationObject, PathItemObject, ReferenceObject, RequestBodyObject, ResponseObject, SecuritySchemeObject, } from '../types/spec'; import { contentToSchema, mediaTypeObjects } from './mediaType'; import { paginationField } from './pagination'; import { parseExtensions, schemaToIrSchema } from './schema'; interface Operation extends Omit, Pick {} const parseOperationJsDoc = ({ irOperation, operation, }: { irOperation: IR.OperationObject; operation: Operation; }) => { if (operation.deprecated !== undefined) { irOperation.deprecated = operation.deprecated; } if (operation.description) { irOperation.description = operation.description; } if (operation.summary) { irOperation.summary = operation.summary; } if (operation.tags?.length) { irOperation.tags = operation.tags; } }; const initIrOperation = ({ context, method, operation, path, state, }: Pick & { context: Context; operation: Operation; state: State; }): IR.OperationObject => { const irOperation: IR.OperationObject = { id: operationToId({ context, id: operation.operationId, method, path, state, }), method, path, }; if (operation.operationId) { irOperation.operationId = operation.operationId; } parseOperationJsDoc({ irOperation, operation, }); parseExtensions({ source: operation, target: irOperation, }); return irOperation; }; const operationToIrOperation = ({ context, method, operation, path, securitySchemesMap, state, }: Pick & { context: Context; operation: Operation; securitySchemesMap: Map; state: State; }): IR.OperationObject => { const irOperation = initIrOperation({ context, method, operation, path, state, }); if (operation.parameters) { irOperation.parameters = operation.parameters; } if (operation.requestBody) { const requestBody = '$ref' in operation.requestBody ? context.resolveRef(operation.requestBody.$ref) : operation.requestBody; const contents = mediaTypeObjects({ content: requestBody.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { const pagination = paginationField({ context, name: '', schema: content.schema && '$ref' in content.schema ? { allOf: [{ ...content.schema }], description: requestBody.description, } : { description: requestBody.description, ...content.schema, }, }); irOperation.body = { mediaType: content.mediaType, schema: schemaToIrSchema({ context, schema: '$ref' in operation.requestBody ? { allOf: [{ ...operation.requestBody }], description: requestBody.description, } : content.schema && '$ref' in content.schema ? { allOf: [{ ...content.schema }], description: requestBody.description, } : { description: requestBody.description, ...content.schema, }, state: undefined, }), }; if (pagination) { irOperation.body.pagination = pagination; } if (requestBody.required) { irOperation.body.required = requestBody.required; } if (content.type) { irOperation.body.type = content.type; } } } for (const name in operation.responses) { if (name.startsWith('x-')) continue; if (!irOperation.responses) { irOperation.responses = {}; } const response = operation.responses[name]! as ResponseObject | ReferenceObject; const responseObject = '$ref' in response ? context.resolveRef(response.$ref) : response; const contents = mediaTypeObjects({ content: responseObject.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { irOperation.responses[name] = { mediaType: content.mediaType, schema: schemaToIrSchema({ context, schema: { description: responseObject.description, ...contentToSchema({ content }), }, state: undefined, }), }; } else { irOperation.responses[name] = { schema: { description: responseObject.description, // TODO: parser - cover all statues with empty response bodies // 1xx, 204, 205, 304 type: name === '204' ? 'void' : 'unknown', }, }; } } if (operation.security) { const securitySchemeObjects: Map = new Map(); for (const securityRequirementObject of operation.security) { for (const name in securityRequirementObject) { const securitySchemeObject = securitySchemesMap.get(name); if (!securitySchemeObject) { continue; } securitySchemeObjects.set(name, securitySchemeObject); } } if (securitySchemeObjects.size) { irOperation.security = Array.from(securitySchemeObjects.values()); } } // TODO: parser - handle servers // qux: operation.servers return irOperation; }; export const parsePathOperation = ({ context, method, operation, path, securitySchemesMap, state, }: { context: Context; method: Extract< keyof PathItemObject, 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace' >; operation: Operation; path: keyof IR.PathsObject; securitySchemesMap: Map; state: State; }) => { if (!context.ir.paths) { context.ir.paths = {}; } if (!context.ir.paths[path]) { context.ir.paths[path] = {}; } if (operation.servers) { context.ir.servers = [...(context.ir.servers ?? []), ...operation.servers]; } context.ir.paths[path][method] = operationToIrOperation({ context, method, operation, path, securitySchemesMap, state, }); }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/pagination.ts ================================================ import type { Context } from '../../../ir/context'; import { getPaginationKeywordsRegExp } from '../../../ir/pagination'; import type { SchemaType } from '../../../openApi/shared/types/schema'; import type { ParameterObject, ReferenceObject, RequestBodyObject } from '../types/spec'; import type { SchemaObject } from '../types/spec'; import { mediaTypeObjects } from './mediaType'; import { getSchemaType } from './schema'; const isPaginationType = (schemaType: SchemaType | undefined): boolean => schemaType === 'boolean' || schemaType === 'integer' || schemaType === 'number' || schemaType === 'string'; // We handle only simple values for now, up to 1 nested field export const paginationField = ({ context, name, schema, }: { context: Context; name: string; schema: SchemaObject | ReferenceObject; }): boolean | string => { const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination); if (paginationRegExp.test(name)) { return true; } if ('$ref' in schema) { const ref = context.resolveRef(schema.$ref); if ('content' in ref || 'in' in ref) { let refSchema: SchemaObject | ReferenceObject | undefined; if ('in' in ref) { refSchema = ref.schema; } if (!refSchema) { // parameter or body const contents = mediaTypeObjects({ content: ref.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content?.schema) { refSchema = content.schema; } } if (!refSchema) { return false; } return paginationField({ context, name, schema: refSchema, }); } return paginationField({ context, name, schema: ref, }); } for (const name in schema.properties) { const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination); if (paginationRegExp.test(name)) { const property = schema.properties[name]!; if (typeof property !== 'boolean' && !('$ref' in property)) { const schemaType = getSchemaType({ schema: property }); // TODO: resolve deeper references if (isPaginationType(schemaType)) { return name; } } } } for (const allOf of schema.allOf ?? []) { const pagination = paginationField({ context, name, schema: allOf, }); if (pagination) { return pagination; } } return false; }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/parameter.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import { refToName } from '../../../utils/ref'; import type { ParameterObject, ReferenceObject, SchemaObject } from '../types/spec'; import { mediaTypeObjects } from './mediaType'; import { paginationField } from './pagination'; import { parseExtensions, schemaToIrSchema } from './schema'; /** * Returns default parameter `allowReserved` based on value of `in`. */ const defaultAllowReserved = (_in: ParameterObject['in']): boolean | undefined => { switch (_in) { // this keyword only applies to parameters with an `in` value of `query` case 'query': return false; default: return; } }; /** * Returns default parameter `explode` based on value of `style`. */ const defaultExplode = (style: Required['style']): boolean => { switch (style) { // default value for `deepObject` is `false`, but that behavior is undefined // so we use `true` to make this work with the `client-fetch` package case 'deepObject': case 'form': return true; default: return false; } }; /** * Returns default parameter `style` based on value of `in`. */ const defaultStyle = (_in: ParameterObject['in']): Required['style'] => { switch (_in) { case 'header': case 'path': return 'simple'; case 'cookie': case 'query': return 'form'; } }; export const parametersArrayToObject = ({ context, parameters, }: { context: Context; parameters?: ReadonlyArray; }): IR.ParametersObject | undefined => { if (!parameters || !Object.keys(parameters).length) { return; } const parametersObject: IR.ParametersObject = {}; for (const parameterOrReference of parameters) { const parameter = '$ref' in parameterOrReference ? context.dereference(parameterOrReference) : parameterOrReference; if (!parametersObject[parameter.in]) { parametersObject[parameter.in] = {}; } // lowercase keys for case insensitive access parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({ $ref: `#/todo/real/path/to/parameter/${parameter.name}`, context, parameter, }); } return parametersObject; }; const parameterToIrParameter = ({ $ref, context, parameter, }: { $ref: string; context: Context; parameter: ParameterObject; }): IR.ParameterObject => { // TODO: parser - fix let schema = parameter.schema; if (!schema) { const contents = mediaTypeObjects({ content: parameter.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { schema = content.schema; } } const finalSchema: SchemaObject = schema && '$ref' in schema ? { allOf: [{ ...schema }], deprecated: parameter.deprecated, description: parameter.description, } : { deprecated: parameter.deprecated, description: parameter.description, ...schema, }; const pagination = paginationField({ context, name: parameter.name, schema: finalSchema, }); const style = parameter.style || defaultStyle(parameter.in); const explode = parameter.explode !== undefined ? parameter.explode : defaultExplode(style); const allowReserved = parameter.allowReserved !== undefined ? parameter.allowReserved : defaultAllowReserved(parameter.in); const irParameter: IR.ParameterObject = { allowReserved, explode, location: parameter.in, name: parameter.name, schema: schemaToIrSchema({ context, schema: finalSchema, state: { $ref, circularReferenceTracker: new Set(), }, }), style, }; if (parameter.deprecated) { irParameter.deprecated = parameter.deprecated; } if (parameter.description) { irParameter.description = parameter.description; } if (pagination) { irParameter.pagination = pagination; } if (parameter.required) { irParameter.required = parameter.required; } parseExtensions({ source: parameter, target: irParameter, }); return irParameter; }; export const parseParameter = ({ $ref, context, parameter, }: { $ref: string; context: Context; parameter: ParameterObject; }) => { if (!context.ir.components) { context.ir.components = {}; } if (!context.ir.components.parameters) { context.ir.components.parameters = {}; } context.ir.components.parameters[refToName($ref)] = parameterToIrParameter({ $ref, context, parameter, }); }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/requestBody.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import { refToName } from '../../../utils/ref'; import type { RequestBodyObject, SchemaObject } from '../types/spec'; import { mediaTypeObjects } from './mediaType'; import { schemaToIrSchema } from './schema'; const requestBodyToIrRequestBody = ({ $ref, context, requestBody, }: { $ref: string; context: Context; requestBody: RequestBodyObject; }): IR.RequestBodyObject => { // TODO: parser - fix const contents = mediaTypeObjects({ content: requestBody.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; const schema = content ? content.schema : undefined; const finalSchema: SchemaObject = { description: requestBody.description, ...schema, }; const irRequestBody: IR.RequestBodyObject = { schema: schemaToIrSchema({ context, schema: finalSchema, state: { $ref, circularReferenceTracker: new Set(), }, }), }; if (requestBody.description) { irRequestBody.description = requestBody.description; } if (requestBody.required) { irRequestBody.required = requestBody.required; } return irRequestBody; }; export const parseRequestBody = ({ $ref, context, requestBody, }: { $ref: string; context: Context; requestBody: RequestBodyObject; }) => { if (!context.ir.components) { context.ir.components = {}; } if (!context.ir.components.requestBodies) { context.ir.components.requestBodies = {}; } context.ir.components.requestBodies[refToName($ref)] = requestBodyToIrRequestBody({ $ref, context, requestBody, }); }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/schema.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import { addItemsToSchema } from '../../../ir/utils'; import type { SchemaState, SchemaType, SchemaWithRequired, } from '../../../openApi/shared/types/schema'; import { convertDiscriminatorValue, type DiscriminatorPropertyType, discriminatorValues, } from '../../../openApi/shared/utils/discriminator'; import { isTopLevelComponent, refToName } from '../../../utils/ref'; import type { ReferenceObject, SchemaObject } from '../types/spec'; export const getSchemaType = ({ schema, }: { schema: SchemaObject; }): SchemaType | undefined => { if (schema.type) { return schema.type; } // infer object based on the presence of properties if (schema.properties) { return 'object'; } return; }; /** * Finds the type of a discriminator property by looking it up in the provided schemas. * Searches through properties and allOf chains to find the property definition. */ const findDiscriminatorPropertyType = ({ context, propertyName, schemas, }: { context: Context; propertyName: string; schemas: ReadonlyArray; }): DiscriminatorPropertyType => { for (const schema of schemas) { const resolved = '$ref' in schema ? context.resolveRef(schema.$ref) : schema; // Check direct properties const property = resolved.properties?.[propertyName]; if (property) { const resolvedProperty = '$ref' in property ? context.resolveRef(property.$ref) : property; if ( resolvedProperty.type === 'boolean' || resolvedProperty.type === 'integer' || resolvedProperty.type === 'number' ) { return resolvedProperty.type; } } // Check allOf chains if (resolved.allOf) { const foundType = findDiscriminatorPropertyType({ context, propertyName, schemas: resolved.allOf, }); if (foundType !== 'string') { return foundType; } } } return 'string'; }; /** * Recursively finds discriminators in a schema, including nested allOf compositions. * This is needed when a schema extends another schema via allOf, and that parent * schema is itself an allOf composition with discriminators in inline schemas. */ const findDiscriminatorsInSchema = ({ context, discriminators = [], schema, }: { context: Context; discriminators?: Array<{ discriminator: NonNullable; oneOf?: SchemaObject['oneOf']; }>; schema: SchemaObject; }): Array<{ discriminator: NonNullable; oneOf?: SchemaObject['oneOf']; }> => { // Check if this schema has a discriminator if (schema.discriminator) { discriminators.push({ discriminator: schema.discriminator, oneOf: schema.oneOf, }); } // If this schema is an allOf composition, recursively search in its components if (schema.allOf) { for (const compositionSchema of schema.allOf) { let resolvedSchema: SchemaObject; if ('$ref' in compositionSchema) { resolvedSchema = context.resolveRef(compositionSchema.$ref); } else { resolvedSchema = compositionSchema; } findDiscriminatorsInSchema({ context, discriminators, schema: resolvedSchema, }); } } return discriminators; }; /** * Gets the discriminator value for a schema. * Returns only the schema's own discriminator value, not child values. */ const getAllDiscriminatorValues = ({ discriminator, schemaRef, }: { discriminator: NonNullable; schemaRef: string; }): Array => { const values: Array = []; // Check each entry in the discriminator mapping for (const [value, mappedSchemaRef] of Object.entries(discriminator.mapping || {})) { if (mappedSchemaRef === schemaRef) { // This is the current schema's own value values.push(value); } } return values; }; const parseSchemaJsDoc = ({ irSchema, schema, }: { irSchema: IR.SchemaObject; schema: SchemaObject; }) => { if (schema.deprecated !== undefined) { irSchema.deprecated = schema.deprecated; } if (schema.example) { irSchema.example = schema.example; } if (schema.description) { irSchema.description = schema.description; } if (schema.title) { irSchema.title = schema.title; } }; const parseSchemaMeta = ({ irSchema, schema, }: { irSchema: IR.SchemaObject; schema: SchemaObject; }) => { if (schema.default !== undefined) { irSchema.default = schema.default; } if (schema.exclusiveMaximum) { if (schema.maximum !== undefined) { irSchema.exclusiveMaximum = schema.maximum; } } else if (schema.maximum !== undefined) { irSchema.maximum = schema.maximum; } if (schema.exclusiveMinimum) { if (schema.minimum !== undefined) { irSchema.exclusiveMinimum = schema.minimum; } } else if (schema.minimum !== undefined) { irSchema.minimum = schema.minimum; } if (schema.format) { irSchema.format = schema.format; } if (schema.maxItems !== undefined) { irSchema.maxItems = schema.maxItems; } if (schema.maxLength !== undefined) { irSchema.maxLength = schema.maxLength; } if (schema.minItems !== undefined) { irSchema.minItems = schema.minItems; } if (schema.minLength !== undefined) { irSchema.minLength = schema.minLength; } if (schema.pattern) { irSchema.pattern = schema.pattern; } if (schema.readOnly) { irSchema.accessScope = 'read'; } else if (schema.writeOnly) { irSchema.accessScope = 'write'; } }; const parseArray = ({ context, irSchema = {}, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { if (schema.maxItems && schema.maxItems === schema.minItems) { irSchema.type = 'tuple'; } else { irSchema.type = 'array'; } let schemaItems: Array = []; if (schema.items) { const irItemsSchema = schemaToIrSchema({ context, schema: schema.items, state, }); if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) { schemaItems = Array(schema.maxItems).fill(irItemsSchema); } else { if ('$ref' in schema.items) { schemaItems.push(irItemsSchema); } else { const ofArray = schema.items.allOf || schema.items.anyOf || schema.items.oneOf; if (ofArray && ofArray.length > 1 && !schema.items.nullable) { // bring composition up to avoid incorrectly nested arrays irSchema = { ...irSchema, ...irItemsSchema, }; } else { schemaItems.push(irItemsSchema); } } } } irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseBoolean = ({ irSchema = {}, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { irSchema.type = 'boolean'; return irSchema; }; const parseNumber = ({ irSchema = {}, schema, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { irSchema.type = schema.type; return irSchema; }; const parseObject = ({ context, irSchema = {}, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { irSchema.type = 'object'; const schemaProperties: Record = {}; for (const name in schema.properties) { const property = schema.properties[name]!; if (typeof property === 'boolean') { // TODO: parser - handle boolean properties } else { schemaProperties[name] = schemaToIrSchema({ context, schema: property, state, }); } } if (Object.keys(schemaProperties).length) { irSchema.properties = schemaProperties; } if (schema.additionalProperties === undefined) { if (!irSchema.properties) { irSchema.additionalProperties = { type: 'unknown', }; } } else if (typeof schema.additionalProperties === 'boolean') { // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf // This would override inherited properties from other schemas in the composition const isEmptyObjectInAllOf = state.inAllOf && schema.additionalProperties === false && (!schema.properties || !Object.keys(schema.properties).length); if (!isEmptyObjectInAllOf) { irSchema.additionalProperties = { type: schema.additionalProperties ? 'unknown' : 'never', }; } } else { const irAdditionalPropertiesSchema = schemaToIrSchema({ context, schema: schema.additionalProperties, state, }); irSchema.additionalProperties = irAdditionalPropertiesSchema; } if (schema.required) { irSchema.required = schema.required; } if (schema.discriminator && state.$ref) { const values = getAllDiscriminatorValues({ discriminator: schema.discriminator, schemaRef: state.$ref, }); if (values.length) { const propertyType = findDiscriminatorPropertyType({ context, propertyName: schema.discriminator.propertyName, schemas: [schema], }); const valueSchemas: ReadonlyArray = values.map((value) => convertDiscriminatorValue(value, propertyType), ); if (!irSchema.properties) { irSchema.properties = {}; } irSchema.properties[schema.discriminator.propertyName] = valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!; } } return irSchema; }; const parseString = ({ irSchema = {}, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { irSchema.type = 'string'; return irSchema; }; export const parseExtensions = ({ source, target }: { source: object; target: object }) => { for (const key in source) { if (key.startsWith('x-')) { (target as Record)[key] = (source as Record)[key]; } } }; const initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => { const irSchema: IR.SchemaObject = {}; parseSchemaJsDoc({ irSchema, schema, }); parseExtensions({ source: schema, target: irSchema, }); return irSchema; }; const parseAllOf = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); const schemaItems: Array = []; const schemaType = getSchemaType({ schema }); const compositionSchemas = schema.allOf; // Collect discriminator information to add after all compositions are processed type DiscriminatorInfo = { discriminator: NonNullable; isExplicitMapping: boolean; isRequired: boolean; values: ReadonlyArray; }; const discriminatorsToAdd: Array = []; for (const compositionSchema of compositionSchemas) { const originalInAllOf = state.inAllOf; // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components if (!('$ref' in compositionSchema)) { state.inAllOf = true; } const irCompositionSchema = schemaToIrSchema({ context, schema: compositionSchema, state, }); state.inAllOf = originalInAllOf; if (state.inAllOf === undefined) { delete state.inAllOf; } if (schema.required) { if (irCompositionSchema.required) { irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required]; } else { irCompositionSchema.required = schema.required; } } schemaItems.push(irCompositionSchema); if ('$ref' in compositionSchema) { const ref = context.resolveRef(compositionSchema.$ref); // `$ref` should be passed from the root `parseSchema()` call if (state.$ref) { // Find all discriminators in the referenced schema, including nested allOf compositions const discriminators = findDiscriminatorsInSchema({ context, schema: ref, }); for (const { discriminator, oneOf } of discriminators) { const values = discriminatorValues( state.$ref, discriminator.mapping, // If the ref has oneOf, we only use the schema name as the value // only if current schema is part of the oneOf. Else it is extending // the ref schema oneOf ? () => oneOf.some((o) => '$ref' in o && o.$ref === state.$ref) : undefined, ); if (values.length === 0) { continue; } // True when state.$ref appears directly in the mapping; false when the // value fell back to the schema name because no mapping entry matched. const isExplicitMapping = discriminator.mapping !== undefined && Object.values(discriminator.mapping).includes(state.$ref); // An explicit mapping always beats a same-property fallback collected // earlier (e.g. from a grandparent discriminator that doesn't list this // schema). Replace it; otherwise skip the duplicate. const existingIndex = discriminatorsToAdd.findIndex( (d) => d.discriminator.propertyName === discriminator.propertyName, ); if (existingIndex !== -1) { if (isExplicitMapping && !discriminatorsToAdd[existingIndex]!.isExplicitMapping) { discriminatorsToAdd.splice(existingIndex, 1); } else { continue; } } const isRequired = discriminators.some( (d) => d.discriminator.propertyName === discriminator.propertyName && (ref.required?.includes(d.discriminator.propertyName) || (ref.allOf && ref.allOf.some((item) => { const resolvedItem = '$ref' in item ? context.resolveRef(item.$ref) : item; return resolvedItem.required?.includes(d.discriminator.propertyName); }))), ); discriminatorsToAdd.push({ discriminator, isExplicitMapping, isRequired, values, }); } } } } // Now add discriminators after all compositions have been processed for (const { discriminator, isRequired, values } of discriminatorsToAdd) { // Get all discriminator values including children for union types const allValues = getAllDiscriminatorValues({ discriminator, schemaRef: state.$ref!, }); // Use allValues if we found children, otherwise use the original values const finalValues = allValues.length > 0 ? allValues : values; // Detect the actual type of the discriminator property const propertyType = findDiscriminatorPropertyType({ context, propertyName: discriminator.propertyName, schemas: compositionSchemas, }); const valueSchemas: ReadonlyArray = finalValues.map((value) => convertDiscriminatorValue(value, propertyType), ); const discriminatorProperty: IR.SchemaObject = valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!; // Check if any $ref schemas in schemaItems have this discriminator property // If yes, mark them to omit it to avoid conflicts for (const item of schemaItems) { if (item.$ref || item.symbolRef) { // Check if the referenced schema has this property const hasProperty = (() => { if (!item.$ref) return false; try { const refSchema = context.resolveRef(item.$ref); // Check if the discriminator property exists in the ref schema return ( refSchema.properties?.[discriminator.propertyName] !== undefined || (refSchema.allOf && refSchema.allOf.some((allOfItem) => { const resolved = '$ref' in allOfItem ? context.resolveRef(allOfItem.$ref) : allOfItem; return resolved.properties?.[discriminator.propertyName] !== undefined; })) ); } catch { return false; } })(); if (hasProperty) { // Mark this ref to omit the discriminator property if (!item.omit) { item.omit = [discriminator.propertyName]; } else if (!item.omit.includes(discriminator.propertyName)) { item.omit = [...item.omit, discriminator.propertyName]; } } } } // Find the inline schema (non-$ref) to merge the discriminator property into // The inline schema should be the last non-$ref item in schemaItems let inlineSchema: IR.SchemaObject | undefined; for (let i = schemaItems.length - 1; i >= 0; i--) { const item = schemaItems[i]!; // Check if this is not a $ref schema by looking for properties or checking if it came from an inline schema if (item.type === 'object' || item.properties) { inlineSchema = item; break; } } // If we found an inline schema, add the discriminator property to it if (inlineSchema) { if (!inlineSchema.properties) { inlineSchema.properties = {}; } inlineSchema.properties[discriminator.propertyName] = discriminatorProperty; if (isRequired) { if (!inlineSchema.required) { inlineSchema.required = []; } if (!inlineSchema.required.includes(discriminator.propertyName)) { inlineSchema.required = [...inlineSchema.required, discriminator.propertyName]; } } } else { // Fallback: create a separate discriminator schema if no inline schema found const irDiscriminatorSchema: IR.SchemaObject = { properties: { [discriminator.propertyName]: discriminatorProperty, }, type: 'object', }; if (isRequired) { irDiscriminatorSchema.required = [discriminator.propertyName]; } schemaItems.push(irDiscriminatorSchema); } } if (schemaType === 'object') { const irObjectSchema = parseOneType({ context, schema: { ...schema, type: 'object', }, state, }); if (irObjectSchema.properties) { for (const requiredProperty of irObjectSchema.required ?? []) { if (!irObjectSchema.properties[requiredProperty]) { for (const compositionSchema of compositionSchemas) { // TODO: parser - this could be probably resolved more accurately const finalCompositionSchema = '$ref' in compositionSchema ? context.resolveRef(compositionSchema.$ref) : compositionSchema; if (getSchemaType({ schema: finalCompositionSchema }) === 'object') { const irCompositionSchema = parseOneType({ context, schema: { ...finalCompositionSchema, type: 'object', }, state, }); if (irCompositionSchema.properties?.[requiredProperty]) { irObjectSchema.properties[requiredProperty] = irCompositionSchema.properties[requiredProperty]; break; } } } } } schemaItems.push(irObjectSchema); } } irSchema = addItemsToSchema({ items: schemaItems, logicalOperator: 'and', mutateSchemaOneItem: true, schema: irSchema, }); if (schema.nullable) { // nest composition to avoid producing an intersection with null const nestedItems: Array = [ { type: 'null', }, ]; if (schemaItems.length) { nestedItems.unshift(irSchema); } irSchema = { items: nestedItems, logicalOperator: 'or', }; // TODO: parser - this is a hack to bring back up meta fields // without it, some schemas were missing original deprecated if (nestedItems[0]!.deprecated) { irSchema.deprecated = nestedItems[0]!.deprecated; } // TODO: parser - this is a hack to bring back up meta fields // without it, some schemas were missing original description if (nestedItems[0]!.description) { irSchema.description = nestedItems[0]!.description; } } return irSchema; }; const parseAnyOf = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); const schemaItems: Array = []; const schemaType = getSchemaType({ schema }); const compositionSchemas = schema.anyOf; const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType({ context, propertyName: schema.discriminator.propertyName, schemas: compositionSchemas, }) : undefined; for (const compositionSchema of compositionSchemas) { let irCompositionSchema = schemaToIrSchema({ context, schema: compositionSchema, state, }); // `$ref` should be defined with discriminators if (schema.discriminator && irCompositionSchema.$ref != null) { const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping); const valueSchemas: ReadonlyArray = values.map((value) => convertDiscriminatorValue(value, discriminatorPropertyType!), ); const irDiscriminatorSchema: IR.SchemaObject = { properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!, }, type: 'object', }; irCompositionSchema = { items: [irDiscriminatorSchema, irCompositionSchema], logicalOperator: 'and', }; } schemaItems.push(irCompositionSchema); } if (schema.nullable) { schemaItems.push({ type: 'null' }); } irSchema = addItemsToSchema({ items: schemaItems, mutateSchemaOneItem: true, schema: irSchema, }); if (schemaType === 'object') { // nest composition to avoid producing a union with object properties const irObjectSchema = parseOneType({ context, schema: { ...schema, type: 'object', }, state, }); if (irObjectSchema.properties) { irSchema = { items: [irSchema, irObjectSchema], logicalOperator: 'and', }; } } return irSchema; }; const parseEnum = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); irSchema.type = 'enum'; const schemaItems: Array = []; for (const [index, enumValue] of schema.enum.entries()) { const typeOfEnumValue = typeof enumValue; let enumType: SchemaType | 'null' | undefined; if ( typeOfEnumValue === 'string' || typeOfEnumValue === 'number' || typeOfEnumValue === 'boolean' ) { enumType = typeOfEnumValue; } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) { enumType = 'array'; } else if (enumValue === null) { // nullable must be true if (schema.nullable) { enumType = 'null'; } } else { console.warn( '🚨', `unhandled "${typeOfEnumValue}" typeof value "${enumValue}" for enum`, schema.enum, ); } if (!enumType) { continue; } const irTypeSchema = parseOneType({ context, schema: { description: schema['x-enum-descriptions']?.[index], title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index], // cast enum to string temporarily type: enumType === 'null' ? 'string' : enumType, }, state, }); irTypeSchema.const = enumValue; // cast enum back if (enumType === 'null') { irTypeSchema.type = enumType; } if (irTypeSchema.type === 'array') { irTypeSchema.type = 'tuple'; } schemaItems.push(irTypeSchema); } irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseOneOf = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); let schemaItems: Array = []; const schemaType = getSchemaType({ schema }); const compositionSchemas = schema.oneOf; const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType({ context, propertyName: schema.discriminator.propertyName, schemas: compositionSchemas, }) : undefined; for (const compositionSchema of compositionSchemas) { let irCompositionSchema = schemaToIrSchema({ context, schema: compositionSchema, state, }); // `$ref` should be defined with discriminators if (schema.discriminator && irCompositionSchema.$ref != null) { const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping); const valueSchemas: ReadonlyArray = values.map((value) => convertDiscriminatorValue(value, discriminatorPropertyType!), ); const irDiscriminatorSchema: IR.SchemaObject = { properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!, }, required: [schema.discriminator.propertyName], type: 'object', }; irCompositionSchema = { items: [irDiscriminatorSchema, irCompositionSchema], logicalOperator: 'and', }; } // since we know oneOf will be using "or" logical operator, if the parsed // composition schema also has an "or" operator, we can bring it up // to avoid unnecessary brackets if ( irCompositionSchema.logicalOperator === 'or' && irCompositionSchema.type !== 'array' && irCompositionSchema.items ) { schemaItems = schemaItems.concat(irCompositionSchema.items); } else { schemaItems.push(irCompositionSchema); } } if (schema.nullable) { schemaItems.push({ type: 'null' }); } irSchema = addItemsToSchema({ items: schemaItems, mutateSchemaOneItem: true, schema: irSchema, }); if (schemaType === 'object') { // nest composition to avoid producing a union with object properties const irObjectSchema = parseOneType({ context, schema: { ...schema, type: 'object', }, state, }); if (irObjectSchema.properties) { irSchema = { items: [irSchema, irObjectSchema], logicalOperator: 'and', }; } } return irSchema; }; const parseRef = ({ context, schema, state, }: { context: Context; schema: ReferenceObject; state: SchemaState; }): IR.SchemaObject => { // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/components/schemas/Foo/properties/bar) // to avoid generating orphaned named types or referencing unregistered symbols const isComponentsRef = isTopLevelComponent(schema.$ref); if (!isComponentsRef) { if (!state.circularReferenceTracker.has(schema.$ref)) { const refSchema = context.resolveRef(schema.$ref); const originalRef = state.$ref; state.$ref = schema.$ref; const irSchema = schemaToIrSchema({ context, schema: refSchema, state, }); state.$ref = originalRef; return irSchema; } // Fallback to preserving the ref if circular } const irSchema: IR.SchemaObject = {}; // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` irSchema.$ref = decodeURI(schema.$ref); if (!state.circularReferenceTracker.has(schema.$ref)) { const refSchema = context.resolveRef(schema.$ref); const originalRef = state.$ref; state.$ref = schema.$ref; schemaToIrSchema({ context, schema: refSchema, state, }); state.$ref = originalRef; } return irSchema; }; const parseNullableType = ({ context, irSchema, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); } const typeIrSchema: IR.SchemaObject = {}; parseSchemaMeta({ irSchema: typeIrSchema, schema }); if (typeIrSchema.default === null) { // clear to avoid duplicate default inside the non-null schema. // this would produce incorrect validator output delete typeIrSchema.default; } const schemaItems: Array = [ parseOneType({ context, irSchema: typeIrSchema, schema, state, }), { type: 'null', }, ]; irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseType = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { const irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); const type = getSchemaType({ schema }); if (!type) { return irSchema; } if (!schema.nullable) { return parseOneType({ context, irSchema, schema: { ...schema, type, }, state, }); } return parseNullableType({ context, irSchema, schema: { ...schema, type, }, state, }); }; const parseOneType = ({ context, irSchema, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); } switch (schema.type) { case 'array': return parseArray({ context, irSchema, schema, state, }); case 'boolean': return parseBoolean({ context, irSchema, schema, state, }); case 'integer': case 'number': return parseNumber({ context, irSchema, schema, state, }); case 'object': return parseObject({ context, irSchema, schema, state, }); case 'string': return parseString({ context, irSchema, schema, state, }); default: // gracefully handle invalid type return parseUnknown({ context, irSchema, schema, }); } }; const parseUnknown = ({ irSchema, schema, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); } irSchema.type = 'unknown'; parseSchemaMeta({ irSchema, schema }); return irSchema; }; export const schemaToIrSchema = ({ context, schema, state, }: { context: Context; schema: SchemaObject | ReferenceObject; state: SchemaState | undefined; }): IR.SchemaObject => { if (!state) { state = { circularReferenceTracker: new Set(), }; } if (state.$ref) { state.circularReferenceTracker.add(state.$ref); } if ('$ref' in schema) { return parseRef({ context, schema, state, }); } if (schema.enum) { return parseEnum({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.allOf) { return parseAllOf({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.anyOf) { return parseAnyOf({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.oneOf) { return parseOneOf({ context, schema: schema as SchemaWithRequired, state, }); } // infer object based on the presence of properties if (schema.type || schema.properties) { return parseType({ context, schema: schema as SchemaWithRequired, state, }); } return parseUnknown({ context, schema }); }; export const parseSchema = ({ $ref, context, schema, }: { $ref: string; context: Context; schema: SchemaObject | ReferenceObject; }) => { if (!context.ir.components) { context.ir.components = {}; } if (!context.ir.components.schemas) { context.ir.components.schemas = {}; } context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({ context, schema, state: { $ref, circularReferenceTracker: new Set(), }, }); }; ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/server.ts ================================================ import type { Context } from '../../../ir/context'; import { parseUrl } from '../../../utils/url'; export function parseServers({ context }: { context: Context }): void { if (context.spec.servers) { context.ir.servers = context.spec.servers; return; } for (const input of context.config.input) { if (typeof input.path === 'string') { const url = parseUrl(input.path); context.ir.servers = [ { url: `${url.protocol ? `${url.protocol}://` : ''}${url.host}${url.port ? `:${url.port}` : ''}`, }, ]; } } if (!context.ir.servers) { context.ir.servers = [ { url: '/', }, ]; } } ================================================ FILE: packages/shared/src/openApi/3.0.x/parser/validate.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { createOperationKey } from '../../../ir/operation'; import { httpMethods } from '../../../openApi/shared/utils/operation'; import type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator'; import type { OpenApiV3_0_X, PathItemObject, PathsObject } from '../types/spec'; export const validateOpenApiSpec = (spec: OpenApiV3_0_X, logger: Logger): ValidatorResult => { const eventValidate = logger.timeEvent('validate'); const issues: Array = []; const operationIds = new Map(); if (spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { const operation = pathItem[method]; if (!operation) { continue; } const operationKey = createOperationKey({ method, path }); if (operation.operationId) { if (!operationIds.has(operation.operationId)) { operationIds.set(operation.operationId, operationKey); } else { issues.push({ code: 'duplicate_key', context: { key: 'operationId', value: operation.operationId, }, message: 'Duplicate `operationId` found. Each `operationId` must be unique.', path: ['paths', path, method, 'operationId'], severity: 'error', }); } } } } } if (spec.servers) { if (typeof spec.servers !== 'object' || !Array.isArray(spec.servers)) { issues.push({ code: 'invalid_type', message: '`servers` must be an array.', path: [], severity: 'error', }); } for (let index = 0; index < spec.servers.length; index++) { const server = spec.servers[index]; if (!server || typeof server !== 'object') { issues.push({ code: 'invalid_type', context: { actual: typeof server, expected: 'object', }, message: 'Each entry in `servers` must be an object.', path: ['servers', index], severity: 'error', }); } else { if (!server.url) { issues.push({ code: 'missing_required_field', context: { field: 'url', }, message: 'Missing required field `url` in server object.', path: ['servers', index], severity: 'error', }); } } } } eventValidate.timeEnd(); return { issues, valid: !issues.some((issue) => issue.severity === 'error'), }; }; ================================================ FILE: packages/shared/src/openApi/3.0.x/types/spec.ts ================================================ import type { AnyString } from '@hey-api/types'; import type { CodeSampleObject, EnumExtensions } from '../../../openApi/shared/types'; /** * OpenAPI Specification Extensions. * * See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. */ export interface SpecificationExtensions { [extension: `x-${string}`]: unknown; } /** * This is the root object of the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#openapi-description OpenAPI Description}. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. */ export interface OpenApiV3_0_X extends SpecificationExtensions { /** * An element to hold various Objects for the OpenAPI Description. */ components?: ComponentsObject; /** * Additional external documentation. */ externalDocs?: ExternalDocumentationObject; /** * **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. */ info: InfoObject; /** * **REQUIRED**. This string MUST be the {@link https://semver.org/spec/v2.0.0.html semantic version number} of the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#versions OpenAPI Specification version} that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is _not_ related to the API {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#infoVersion `info.version`} string. */ openapi: '3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.0.4'; /** * **REQUIRED**. The available paths and operations for the API. */ paths: PathsObject; /** * A declaration of which security mechanisms can be used across the API. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. Individual operations can override this definition. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement (`{}`) can be included in the array. */ security?: ReadonlyArray; /** * An array of Server Objects, which provide connectivity information to a target server. If the `servers` field is not provided, or is an empty array, the default value would be a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#server-object Server Object} with a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#server-url url} value of `/`. */ servers?: ReadonlyArray; /** * A list of tags used by the OpenAPI Description with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#operation-object Operation Object} must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. */ tags?: ReadonlyArray; } /** * A map of possible out-of band callbacks related to the parent operation. Each value in the map is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-item-object Path Item Object} that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the Path Item Object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface CallbackObject extends SpecificationExtensions { /** * A Path Item Object used to define a callback request and expected responses. A {@link https://learn.openapis.org/examples/v3.0/callback-example.html complete example} is available. */ [expression: string]: PathItemObject | ReferenceObject | unknown; } /** * Holds a set of reusable objects for different aspects of the OAS. All objects defined within the Components Object will have no effect on the API unless they are explicitly referenced from outside the Components Object. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. * * TODO: examples */ export interface ComponentsObject extends SpecificationExtensions { /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#callback-object Callback Objects}. */ callbacks?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#example-object Example Objects}. */ examples?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#header-object Header Objects}. */ headers?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#link-object Link Objects}. */ linkes?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-object Parameter Objects}. */ parameters?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#request-body-object Request Body Objects}. */ requestBodies?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#response-object Response Objects}. */ responses?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Objects}. */ schemas?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#security-scheme-object Security Scheme Objects}. */ securitySchemes?: Record; } /** * Contact information for the exposed API. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * ```yaml * name: API Support * url: https://www.example.com/support * email: support@example.com * ``` */ export interface ContactObject extends SpecificationExtensions { /** * The email address of the contact person/organization. This MUST be in the form of an email address. */ email?: string; /** * The identifying name of the contact person/organization. */ name?: string; /** * The URL for the contact information. This MUST be in the form of a URL. */ url?: string; } /** * When request bodies or response payloads may be one of a number of different schemas, a Discriminator Object gives a hint about the expected schema of the document. This hint can be used to aid in serialization, deserialization, and validation. The Discriminator Object does this by implicitly or explicitly associating the possible values of a named property with alternative schemas. * * Note that `discriminator` MUST NOT change the validation outcome of the schema. * * **Conditions for Using the Discriminator Object** * * TODO: content, examples */ export interface DiscriminatorObject { /** * An object to hold mappings between payload values and schema names or URI references. */ mapping?: Record; /** * **REQUIRED**. The name of the property in the payload that will hold the discriminating value. This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined. */ propertyName: string; } /** * A single encoding definition applied to a single schema property. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-b-data-type-conversion Appendix B} for a discussion of converting values of various types to string representations. * * Properties are correlated with `multipart` parts using the {@link https://www.rfc-editor.org/rfc/rfc7578#section-4.2 `name` parameter} of `Content-Disposition: form-data`, and with `application/x-www-form-urlencoded` using the query string parameter names. In both cases, their order is implementation-defined. * * See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-e-percent-encoding-and-form-media-types Appendix E} for a detailed examination of percent-encoding concerns for form media types. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: default values examples * TODO: examples */ export interface EncodingObject extends SpecificationExtensions { /** * When this is true, parameter values are serialized using reserved expansion, as defined by {@link https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.3 RFC6570}, which allows {@link https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 RFC3986's reserved character set}, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are {@link https://datatracker.ietf.org/doc/html/rfc3986#section-3.4 not allowed in the query string} (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see Appendices {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-c-using-rfc6570-based-serialization C} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-e-percent-encoding-and-form-media-types E} for details. The default value is `false`. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. */ allowReserved?: boolean; /** * The `Content-Type` for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g. `image/png`) or a wildcard media type (e.g. `image/*`). Default value depends on the property type as shown in the table below. */ contentType?: string; /** * When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this field has no effect. When {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#encoding-style `style`} is `"form"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. */ explode?: boolean; /** * A map allowing additional information to be provided as headers. `Content-Type` is described separately and SHALL be ignored in this section. This field SHALL be ignored if the request body media type is not a `multipart`. */ headers?: Record; /** * Describes how a specific property value will be serialized depending on its type. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-object Parameter Object} for details on the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-style `style`} field. The behavior follows the same values as `query` parameters, including default values. Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. */ style?: | 'deepObject' | 'form' | 'label' | 'matrix' | 'pipeDelimited' | 'simple' | 'spaceDelimited'; } /** * An object grouping an internal or external example value with basic `summary` and `description` metadata. This object is typically used in fields named `examples` (plural), and is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#reference-object referenceable} alternative to older `example` (singular) fields that do not support referencing or metadata. * * Examples allow demonstration of the usage of properties, parameters and objects within OpenAPI. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * In all cases, the example value SHOULD be compatible with the schema of its associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible. * * TODO: examples */ export interface ExampleObject extends SpecificationExtensions { /** * Long description for the example. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#relative-references-in-urls Relative References}. */ externalValue?: string; /** * Short description for the example. */ summary?: string; /** * Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. */ value?: unknown; } /** * Allows referencing an external resource for extended documentation. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * **External Documentation Object Example** * * ```yaml * description: Find more info here * url: https://example.com * ``` */ export interface ExternalDocumentationObject extends SpecificationExtensions { /** * A description of the target documentation. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * **REQUIRED**. The URL for the target documentation. This MUST be in the form of a URL. */ url: string; } /** * Describes a single header for {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#response-headers HTTP responses} and for {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#encoding-headers individual parts in `multipart` representations}; see the relevant {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#response-object Response Object} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#encoding-object Encoding Object} documentation for restrictions on which headers can be described. * * The Header Object follows the structure of the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-object Parameter Object}, including determining its serialization strategy based on whether `schema` or `content` is present, with the following changes: * 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. * 1. `in` MUST NOT be specified, it is implicitly in `header`. * 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-style `style`}). This means that `allowEmptyValue` and `allowReserved` MUST NOT be used, and `style`, if used, MUST be limited to `"simple"`. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export type HeaderObject = Omit; /** * The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * ```yaml * title: Example Pet Store App * description: This is an example server for a pet store. * termsOfService: https://example.com/terms/ * contact: * name: API Support * url: https://www.example.com/support * email: support@example.com * license: * name: Apache 2.0 * url: https://www.apache.org/licenses/LICENSE-2.0.html * version: 1.0.1 * ``` */ export interface InfoObject extends SpecificationExtensions { /** * The contact information for the exposed API. */ contact?: ContactObject; /** * A description of the API. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * The license information for the exposed API. */ license?: LicenseObject; /** * A URL for the Terms of Service for the API. This MUST be in the form of a URL. */ termsOfService?: string; /** * **REQUIRED**. The title of the API. */ title: string; /** * **REQUIRED**. The version of the OpenAPI Document (which is distinct from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#oas-version OpenAPI Specification version} or the version of the API being described or the version of the OpenAPI Description). */ version: string; } /** * License information for the exposed API. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * ```yaml * name: Apache 2.0 * url: https://www.apache.org/licenses/LICENSE-2.0.html * ``` */ export interface LicenseObject extends SpecificationExtensions { /** * **REQUIRED**. The license name used for the API. */ name: string; /** * A URL for the license used for the API. This MUST be in the form of a URL. */ url?: string; } /** * The Link Object represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. * * Unlike _dynamic links_ (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response. * * For computing links and providing instructions to execute them, a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#runtime-expressions runtime expression} is used for accessing values in an operation and using them as parameters while invoking the linked operation. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * A linked operation MUST be identified using either an `operationRef` or `operationId`. The identified or reference operation MUST be unique, and in the case of an `operationId`, it MUST be resolved within the scope of the OpenAPI Description (OAD). Because of the potential for name clashes, the `operationRef` syntax is preferred for multi-document OADs. However, because use of an operation depends on its URL path template in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#paths-object Paths Object}, operations from any {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-item-object Path Item Object} that is referenced multiple times within the OAD cannot be resolved unambiguously. In such ambiguous cases, the resulting behavior is implementation-defined and MAY result in an error. * * Note that it is not possible to provide a constant value to `parameters` that matches the syntax of a runtime expression. It is possible to have ambiguous parameter names, e.g. `name: "id"`, `in: "path"` and `name: "path.id", in: "query"`; this is NOT RECOMMENDED and the behavior is implementation-defined, however implementations SHOULD prefer the qualified interpretation (`path.id` as a path parameter), as the names can always be qualified to disambiguate them (e.g. using `query.path.id` for the query parameter). * * TODO: examples */ export interface LinkObject extends SpecificationExtensions { /** * A description of the link. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. */ operationId?: string; /** * A URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#operation-object Operation Object}. */ operationRef?: string; /** * A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used (optionally qualified with the parameter location, e.g. `path.id` for an `id` parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. */ parameters?: Record; /** * A literal value or {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#runtime-expressions {expression}} to use as a request body when calling the target operation. */ requestBody?: unknown | string; /** * A server object to be used by the target operation. */ server?: ServerObject; } /** * Each Media Type Object provides schema and examples for the media type identified by its key. * * When `example` or `examples` are provided, the example SHOULD match the specified schema and be in the correct format as specified by the media type and its encoding. The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#working-with-examples Working With Examples} for further guidance regarding the different ways of specifying examples, including non-JSON/YAML values. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface MediaTypeObject extends SpecificationExtensions { /** * A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The `encoding` field SHALL only apply to {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#request-body-object Request Body Objects}, and only when the media type is `multipart` or `application/x-www-form-urlencoded`. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object. */ encoding?: Record; /** * Example of the media type; see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#working-with-examples Working With Examples}. */ example?: unknown; /** * Examples of the media type; see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#working-with-examples Working With Examples}. */ examples?: Record; /** * The schema defining the content of the request, response, parameter, or header. */ schema?: SchemaObject | ReferenceObject; } /** * Configuration details for a supported OAuth Flow * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface OAuthFlowObject extends SpecificationExtensions { /** * **REQUIRED (`"implicit"`, `"authorizationCode"`)**. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. */ authorizationUrl?: string; /** * The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. */ refreshUrl?: string; /** * **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. */ scopes: Record; /** * **REQUIRED (`"password"`, `"clientCredentials"`, `"authorizationCode"`)**. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. */ tokenUrl?: string; } /** * Allows configuration of the supported OAuth Flows. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. */ export interface OAuthFlowsObject extends SpecificationExtensions { /** * Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. */ authorizationCode?: OAuthFlowObject; /** * Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. */ clientCredentials?: OAuthFlowObject; /** * Configuration for the OAuth Implicit flow */ implicit?: OAuthFlowObject; /** * Configuration for the OAuth Resource Owner Password flow */ password?: OAuthFlowObject; } /** * Describes a single API operation on a path. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface OperationObject extends SpecificationExtensions { /** * A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#callback-object Callback Object} that describes a request that may be initiated by the API provider and the expected responses. */ callbacks?: Record; /** * Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. */ deprecated?: boolean; /** * A verbose explanation of the operation behavior. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Additional external documentation for this operation. */ externalDocs?: ExternalDocumentationObject; /** * Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. */ operationId?: string; /** * A list of parameters that are applicable for this operation. If a parameter is already defined in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-item-parameters Path Item}, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-name name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-in location}. The list can use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#reference-object Reference Object} to link to parameters that are defined in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#components-parameters OpenAPI Object's `components.parameters`}. */ parameters?: ReadonlyArray; /** * The request body applicable for this operation. The `requestBody` is only supported in HTTP methods where the HTTP 1.1 specification {@link https://tools.ietf.org/html/rfc7231#section-4.3.1 RFC7231} has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as {@link https://tools.ietf.org/html/rfc7231#section-4.3.1 GET}, {@link https://tools.ietf.org/html/rfc7231#section-4.3.2 HEAD} and {@link https://tools.ietf.org/html/rfc7231#section-4.3.5 DELETE}), `requestBody` SHALL be ignored by consumers. */ requestBody?: RequestBodyObject | ReferenceObject; /** * **REQUIRED**. The list of possible responses as they are returned from executing this operation. */ responses: ResponsesObject; /** * A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#oas-security `security`}. To remove a top-level security declaration, an empty array can be used. */ security?: ReadonlyArray; /** * An alternative `servers` array to service this operation. If a `servers` array is specified at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-item-servers Path Item Object} or {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#oas-servers OpenAPI Object} level, it will be overridden by this value. */ servers?: ReadonlyArray; /** * A short summary of what the operation does. */ summary?: string; /** * A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. */ tags?: ReadonlyArray; /** * A list of code samples associated with an operation. */ 'x-codeSamples'?: ReadonlyArray; } /** * Describes a single operation parameter. * * A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-name name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-in location}. * * See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-e-percent-encoding-and-form-media-types Appendix E} for a detailed examination of percent-encoding concerns, including interactions with the `application/x-www-form-urlencoded` query string format. * * **Parameter Locations** * * There are four possible parameter locations specified by the `in` field: * * - path - Used together with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-templating Path Templating}, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. * - query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. * - header - Custom headers that are expected as part of the request. Note that {@link https://tools.ietf.org/html/rfc7230#section-3.2 RFC7230} states header names are case insensitive. * - cookie - Used to pass a specific cookie value to the API. * * **Fixed Fields** * * The rules for serialization of the parameter are specified in one of two ways. Parameter Objects MUST include either a `content` field or a `schema` field, but not both. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-b-data-type-conversion Appendix B} for a discussion of converting values of various types to string representations. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * Note that while `"Cookie"` as a `name` is not forbidden if `in` is `"header"`, the effect of defining a cookie parameter that way is undefined; use `in: "cookie"` instead. * * **Fixed Fields for use with schema** * * For simpler scenarios, a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-schema `schema`} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-style `style`} can describe the structure and syntax of the parameter. When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the parameter. The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema. * * Serializing with `schema` is NOT RECOMMENDED for `in: "cookie"` parameters, `in: "header"` parameters that use HTTP header parameters (name=value pairs following a `;`) in their values, or `in: "header"` parameters where values might have non-URL-safe characters; see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-d-serializing-headers-and-cookies Appendix D} for details. * * See also {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-c-using-rfc6570-based-serialization Appendix C: Using RFC6570-Based Serialization} for additional guidance. * * **Fixed Fields for use with `content`** * * For more complex scenarios, the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-content `content`} field can define the media type and schema of the parameter, as well as give examples of its use. Using `content` with a `text/plain` media type is RECOMMENDED for `in: "header"` and `in: "cookie"` parameters where the `schema` strategy is not appropriate. * * **Style Values** * * In order to support common ways of serializing simple parameters, a set of `style` values are defined. * * See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-e-percent-encoding-and-form-media-types Appendix E} for a discussion of percent-encoding, including when delimiters need to be percent-encoded and options for handling collisions with percent-encoded data. * * TODO: examples */ export interface ParameterObject extends SpecificationExtensions { /** * If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is `false`. If {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-style `style`} is used, and if {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#style-examples behavior is _n/a_ (cannot be serialized)}, the value of `allowEmptyValue` SHALL be ignored. Interactions between this field and the parameter's {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} are implementation-defined. This field is valid only for `query` parameters. Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision. */ allowEmptyValue?: boolean; /** * When this is true, parameter values are serialized using reserved expansion, as defined by {@link https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.3 RFC6570}, which allows {@link https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 RFC3986's reserved character set}, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are {@link https://datatracker.ietf.org/doc/html/rfc3986#section-3.4 not allowed in the query string} (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see Appendices {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-c-using-rfc6570-based-serialization C} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#appendix-e-percent-encoding-and-form-media-types E} for details. This field only applies to parameters with an `in` value of `query`. The default value is `false`. */ allowReserved?: boolean; /** * A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. */ content?: Record; /** * Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. */ deprecated?: boolean; /** * A brief description of the parameter. This could contain examples of use. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Example of the parameter's potential value; see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#working-with-examples Working With Examples}. */ example?: unknown; /** * Examples of the parameter's potential value; see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#working-with-examples Working With Examples}. */ examples?: Record; /** * When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this field has no effect. When {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-style `style`} is `"form"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined. */ explode?: boolean; /** * **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. */ in: 'cookie' | 'header' | 'path' | 'query'; /** * **REQUIRED**. The name of the parameter. Parameter names are _case sensitive_. * - If {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-in `in`} is `"path"`, the `name` field MUST correspond to a template expression occurring within the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#paths-path path} field in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#paths-object Paths Object}. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-templating Path Templating} for further information. * - If {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-in `in`} is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored. * - For all other cases, the `name` corresponds to the parameter name used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-in `in`} field. */ name: string; /** * Determines whether this parameter is mandatory. If the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-in parameter location} is `"path"`, this field is **REQUIRED** and its value MUST be `true`. Otherwise, the field MAY be included and its default value is `false`. */ required?: boolean; /** * The schema defining the type used for the parameter. */ schema?: SchemaObject | ReferenceObject; /** * Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `"query"` - `"form"`; for `"path"` - `"simple"`; for `"header"` - `"simple"`; for `"cookie"` - `"form"`. */ style?: | 'deepObject' | 'form' | 'label' | 'matrix' | 'pipeDelimited' | 'simple' | 'spaceDelimited'; } /** * Describes the operations available on a single path. A Path Item MAY be empty, due to {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#security-filtering ACL constraints}. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface PathItemObject extends SpecificationExtensions { /** * Allows for a referenced definition of this path item. The value MUST be in the form of a URL, and the referenced structure MUST be in the form of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-item-object Path Item Object}. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#relative-references-in-urls Relative References}. */ $ref?: string; /** * A definition of a DELETE operation on this path. */ delete?: OperationObject; /** * An optional string description, intended to apply to all operations in this path. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * A definition of a GET operation on this path. */ get?: OperationObject; /** * A definition of a HEAD operation on this path. */ head?: OperationObject; /** * A definition of a OPTIONS operation on this path. */ options?: OperationObject; /** * A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-name name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#parameter-in location}. The list can use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#reference-object Reference Object} to link to parameters that are defined in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#components-parameters OpenAPI Object's `components.parameters`}. */ parameters?: ReadonlyArray; /** * A definition of a PATCH operation on this path. */ patch?: OperationObject; /** * A definition of a POST operation on this path. */ post?: OperationObject; /** * A definition of a PUT operation on this path. */ put?: OperationObject; /** * An alternative `servers` array to service all operations in this path. If a `servers` array is specified at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#oas-servers OpenAPI Object} level, it will be overridden by this value. */ servers?: ReadonlyArray; /** * An optional string summary, intended to apply to all operations in this path. */ summary?: string; /** * A definition of a TRACE operation on this path. */ trace?: OperationObject; } /** * Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#server-object Server Object} in order to construct the full URL. The Paths Object MAY be empty, due to {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#security-filtering Access Control List (ACL) constraints}. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface PathsObject extends SpecificationExtensions { /** * A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#server-object Server Object}'s `url` field in order to construct the full URL. {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#path-templating Path templating} is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. */ [path: `/${string}`]: PathItemObject; } /** * A simple object to allow referencing other components in the OpenAPI Description, internally and externally. * * The Reference Object is defined by {@link https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 JSON Reference} and follows the same structure, behavior and rules. * * For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification. * * This object cannot be extended with additional properties, and any properties added SHALL be ignored. * * **Reference Object Example** * * ```yaml * $ref: '#/components/schemas/Pet' * ``` * * **Relative Schema Document Example** * * ```yaml * $ref: Pet.yaml * ``` * * **Relative Documents with Embedded Schema Example** * * ```yaml * $ref: definitions.yaml#/Pet * ``` */ export interface ReferenceObject { /** * **REQUIRED**. The reference string. */ $ref: string; } /** * Describes a single request body. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface RequestBodyObject extends SpecificationExtensions { /** * **REQUIRED**. The content of the request body. The key is a media type or {@link https://tools.ietf.org/html/rfc7231#appendix-D media type range} and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. `"text/plain"` overrides `"text/*"` */ content: Record; /** * A brief description of the request body. This could contain examples of use. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Determines if the request body is required in the request. Defaults to `false`. */ required?: boolean; } /** * Describes a single response from an API operation, including design-time, static `links` to operations based on the response. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface ResponseObject extends SpecificationExtensions { /** * A map containing descriptions of potential response payloads. The key is a media type or {@link https://tools.ietf.org/html/rfc7231#appendix-D media type range} and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. `"text/plain"` overrides `"text/*"` */ content?: Record; /** * **REQUIRED**. A description of the response. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description: string; /** * Maps a header name to its definition. {@link https://tools.ietf.org/html/rfc7230#section-3.2 RFC7230} states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. */ headers?: Record; /** * A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#components-object Component Objects}. */ links?: Record; } /** * A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. * * The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors. * * The `default` MAY be used as a default Response Object for all HTTP codes that are not covered individually by the Responses Object. * * The Responses Object MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface ResponsesObject extends SpecificationExtensions { /** * Any {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#http-status-codes HTTP status code} can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#reference-object Reference Object} can link to a response that is defined in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#components-responses OpenAPI Object's `components.responses`} section. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `200` and `299`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. */ [httpStatusCode: string]: ResponseObject | ReferenceObject | undefined | unknown; /** * The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#reference-object Reference Object} can link to a response that the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#components-responses OpenAPI Object's `components.responses`} section defines. */ default?: ResponseObject | ReferenceObject; } /** * The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the [[JSON-Schema-05|JSON Schema Specification Draft Wright-00]]. * * For more information about the keywords, see {@link https://tools.ietf.org/html/draft-wright-json-schema-00 JSON Schema Core} and {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00 JSON Schema Validation}. Unless stated otherwise, the keyword definitions follow those of JSON Schema and do not add any additional semantics. * * **JSON Schema Keywords** * * The following keywords are taken directly from the JSON Schema definition and follow the same specifications: * - title * - multipleOf * - maximum * - exclusiveMaximum * - minimum * - exclusiveMinimum * - maxLength * - minLength * - pattern (This string SHOULD be a valid regular expression, according to the {@link https://www.ecma-international.org/ecma-262/5.1/#sec-15.10.1 Ecma-262 Edition 5.1 regular expression} dialect) * - maxItems * - minItems * - uniqueItems * - maxProperties * - minProperties * - required * - enum * * The following keywords are taken from the JSON Schema definition but their definitions were adjusted to the OpenAPI Specification. * * - type - Value MUST be a string. Multiple types via an array are not supported. * - allOf - Inline or referenced schema MUST be of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema. * - oneOf - Inline or referenced schema MUST be of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema. * - anyOf - Inline or referenced schema MUST be of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema. * - not - Inline or referenced schema MUST be of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema. * - items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema. `items` MUST be present if `type` is `"array"`. * - properties - Property definitions MUST be a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema (inline or referenced). * - additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`. * - description - {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. * - format - See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#data-type-format Data Type Formats} for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. * - default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined `type` for the Schema Object defined at the same level. For example, if `type` is `"string"`, then `default` can be `"foo"` but cannot be `1`. * * Alternatively, any time a Schema Object can be used, a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#reference-object Reference Object} can be used in its place. This allows referencing definitions instead of defining them inline. * * Additional keywords defined by the JSON Schema specification that are not mentioned here are strictly unsupported. * * Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation: * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * **Composition and Inheritance (Polymorphism)** * * TODO: content, examples */ export interface SchemaObject extends EnumExtensions, SpecificationExtensions { /** * The value of "additionalProperties" MUST be a boolean or a schema. * * If "additionalProperties" is absent, it may be considered present with an empty schema as a value. * * If "additionalProperties" is true, validation always succeeds. * * If "additionalProperties" is false, validation succeeds only if the instance is an object and all properties on the instance were covered by "properties" and/or "patternProperties". * * If "additionalProperties" is an object, validate the value as a schema to all of the properties that weren't validated by "properties" nor "patternProperties". * * Value can be boolean or object. Inline or referenced schema MUST be of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object} and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`. */ additionalProperties?: boolean | SchemaObject | ReferenceObject; /** * This keyword's value MUST be an array. This array MUST have at least one element. * * Elements of the array MUST be objects. Each object MUST be a valid Schema Object. * * An instance validates successfully against this keyword if it validates successfully against all schemas defined by this keyword's value. */ allOf?: ReadonlyArray; /** * This keyword's value MUST be an array. This array MUST have at least one element. * * Elements of the array MUST be objects. Each object MUST be a valid Schema Object. * * An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword's value. */ anyOf?: ReadonlyArray; /** * The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined `type` for the Schema Object defined at the same level. For example, if `type` is `"string"`, then `default` can be `"foo"` but cannot be `1`. */ default?: unknown; /** * Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is `false`. */ deprecated?: boolean; /** * The value of both of these keywords MUST be a string. * * Both of these keywords can be used to decorate a user interface with information about the data produced by this user interface. A title will preferrably be short, whereas a description will provide explanation about the purpose of the instance described by this schema. * * Both of these keywords MAY be used in root schemas, and in any subschemas. */ description?: string; /** * Adds support for polymorphism. The discriminator is used to determine which of a set of schemas a payload is expected to satisfy. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#composition-and-inheritance-polymorphism Composition and Inheritance} for more details. */ discriminator?: DiscriminatorObject; /** * The value of this keyword MUST be an array. This array SHOULD have at least one element. Elements in the array SHOULD be unique. * * Elements in the array MAY be of any type, including null. * * An instance validates successfully against this keyword if its value is equal to one of the elements in this keyword's array value. */ enum?: ReadonlyArray; /** * A free-form field to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. */ example?: unknown; /** * The value of "exclusiveMaximum" MUST be a boolean, representing whether the limit in "maximum" is exclusive or not. An undefined value is the same as false. * * If "exclusiveMaximum" is true, then a numeric instance SHOULD NOT be equal to the value specified in "maximum". If "exclusiveMaximum" is false (or not specified), then a numeric instance MAY be equal to the value of "maximum". */ exclusiveMaximum?: boolean; /** * The value of "exclusiveMinimum" MUST be a boolean, representing whether the limit in "minimum" is exclusive or not. An undefined value is the same as false. * * If "exclusiveMinimum" is true, then a numeric instance SHOULD NOT be equal to the value specified in "minimum". If "exclusiveMinimum" is false (or not specified), then a numeric instance MAY be equal to the value of "minimum". */ exclusiveMinimum?: boolean; /** * Additional external documentation for this schema. */ externalDocs?: ExternalDocumentationObject; /** * While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. */ format?: Format; /** * `items` MUST be present if `type` is `"array"`. */ items?: SchemaObject | ReferenceObject; /** * The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0. * * An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword. */ maxItems?: number; /** * The value of this keyword MUST be a non-negative integer. * * The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0. * * A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. * * The length of a string instance is defined as the number of its characters as defined by {@link https://datatracker.ietf.org/doc/html/rfc7159 RFC 7159} [RFC7159]. */ maxLength?: number; /** * The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0. * * An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. */ maxProperties?: number; /** * The value of "maximum" MUST be a number, representing an upper limit for a numeric instance. * * If the instance is a number, then this keyword validates if "exclusiveMaximum" is true and instance is less than the provided value, or else if the instance is less than or exactly equal to the provided value. */ maximum?: number; /** * The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0. * * An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this keyword. * * If this keyword is not present, it may be considered present with a value of 0. */ minItems?: number; /** * A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. * * The length of a string instance is defined as the number of its characters as defined by {@link https://datatracker.ietf.org/doc/html/rfc7159 RFC 7159} [RFC7159]. * * The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0. * * "minLength", if absent, may be considered as being present with integer value 0. */ minLength?: number; /** * The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0. * * An object instance is valid against "minProperties" if its number of properties is greater than, or equal to, the value of this keyword. * * If this keyword is not present, it may be considered present with a value of 0. */ minProperties?: number; /** * The value of "minimum" MUST be a number, representing a lower limit for a numeric instance. * * If the instance is a number, then this keyword validates if "exclusiveMinimum" is true and instance is greater than the provided value, or else if the instance is greater than or exactly equal to the provided value. */ minimum?: number; /** * The value of "multipleOf" MUST be a number, strictly greater than 0. * * A numeric instance is only valid if division by this keyword's value results in an integer. */ multipleOf?: number; /** * This keyword's value MUST be an object. This object MUST be a valid Schema Object. * * An instance is valid against this keyword if it fails to validate successfully against the schema defined by this keyword. */ not?: SchemaObject | ReferenceObject; /** * This keyword only takes effect if `type` is explicitly defined within the same Schema Object. A `true` value indicates that both `null` values and values of the type specified by `type` are allowed. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of `null` as a value. A `false` value leaves the specified or default `type` unmodified. The default value is `false`. */ nullable?: boolean; /** * This keyword's value MUST be an array. This array MUST have at least one element. * * Elements of the array MUST be objects. Each object MUST be a valid Schema Object. * * An instance validates successfully against this keyword if it validates successfully against exactly one schema defined by this keyword's value. */ oneOf?: ReadonlyArray; /** * The value of this keyword MUST be a string. This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect. * * A string instance is considered valid if the regular expression matches the instance successfully. Recall: regular expressions are not implicitly anchored. */ pattern?: string; /** * The value of "properties" MUST be an object. Each value of this object MUST be an object, and each object MUST be a valid Schema Object. * * If absent, it can be considered the same as an empty object. */ properties?: Record; /** * Relevant only for Schema Object `properties` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as `readOnly` being `true` and is in the `required` list, the `required` will take effect on the response only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. */ readOnly?: boolean; /** * The value of this keyword MUST be an array. This array MUST have at least one element. Elements of this array MUST be strings, and MUST be unique. * * An object instance is valid against this keyword if its property set contains all elements in this keyword's array value. */ required?: ReadonlyArray; /** * The value of both of these keywords MUST be a string. * * Both of these keywords can be used to decorate a user interface with information about the data produced by this user interface. A title will preferrably be short, whereas a description will provide explanation about the purpose of the instance described by this schema. * * Both of these keywords MAY be used in root schemas, and in any subschemas. */ title?: string; /** * The value of this keyword MUST be a string. * * An instance matches successfully if its primitive type is one of the types defined by keyword. Recall: "number" includes "integer". */ type?: 'array' | 'boolean' | 'integer' | 'number' | 'object' | 'string'; /** * The value of this keyword MUST be a boolean. * * If this keyword has boolean value false, the instance validates successfully. If it has boolean value true, the instance validates successfully if all of its elements are unique. * * If not present, this keyword may be considered present with boolean value false. */ uniqueItems?: boolean; /** * Relevant only for Schema Object `properties` definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as `writeOnly` being `true` and is in the `required` list, the `required` will take effect on the request only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. */ writeOnly?: boolean; /** * This MAY be used only on property schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. */ xml?: XMLObject; } /** * Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#security-scheme-object Security Schemes} under the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#components-object Components Object}. * * A Security Requirement Object MAY refer to multiple security schemes in which case all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. * * When the `security` field is defined on the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#openapi-object OpenAPI Object} or {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#operation-object Operation Object} and contains multiple Security Requirement Objects, only one of the entries in the list needs to be satisfied to authorize the request. This enables support for scenarios where the API allows multiple, independent security schemes. * * An empty Security Requirement Object (`{}`) indicates anonymous access is supported. * * TODO: examples */ export interface SecurityRequirementObject { /** * Each name MUST correspond to a security scheme which is declared in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#security-scheme-object Security Schemes} under the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#components-object Components Object}. If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty. */ [name: string]: ReadonlyArray; } /** * Defines a security scheme that can be used by the operations. * * Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter, or as a query parameter), OAuth2's common flows (implicit, password, client credentials, and authorization code) as defined in {@link https://tools.ietf.org/html/rfc6749 RFC6749}, and [[OpenID-Connect-Core]]. Please note that as of 2020, the implicit flow is about to be deprecated by {@link https://tools.ietf.org/html/draft-ietf-oauth-security-topics OAuth 2.0 Security Best Current Practice}. Recommended for most use cases is Authorization Code Grant flow with PKCE. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export type SecuritySchemeObject = SpecificationExtensions & { /** * A description for security scheme. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; } & ( | { /** * **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"`, or `"cookie"`. */ in: 'cookie' | 'header' | 'query'; /** * **REQUIRED**. The name of the header, query or cookie parameter to be used. */ name: string; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. */ type: 'apiKey'; } | { /** * A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. */ bearerFormat?: string; /** * **REQUIRED**. The name of the HTTP Authentication scheme to be used in the {@link https://tools.ietf.org/html/rfc7235#section-5.1 Authorization header as defined in RFC7235}. The values used SHOULD be registered in the {@link https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml IANA Authentication Scheme registry}. The value is case-insensitive, as defined in {@link https://datatracker.ietf.org/doc/html/rfc7235#section-2.1 RFC7235}. */ scheme: string; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. */ type: 'http'; } | { /** * **REQUIRED**. An object containing configuration information for the flow types supported. */ flows: OAuthFlowsObject; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. */ type: 'oauth2'; } | { /** * **REQUIRED**. {@link https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig Well-known URL} to discover the [[OpenID-Connect-Discovery]] {@link https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata provider metadata}. */ openIdConnectUrl: string; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. */ type: 'openIdConnect'; } ); /** * An object representing a Server. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * TODO: examples */ export interface ServerObject extends SpecificationExtensions { /** * An optional string describing the host designated by the URL. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Variable substitutions will be made when a variable is named in `{`braces`}`. */ url: string; /** * A map between a variable name and its value. The value is used for substitution in the server's URL template. */ variables?: Record; } /** * An object representing a Server Variable for server URL template substitution. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. */ export interface ServerVariableObject extends SpecificationExtensions { /** * **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. If the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#server-variable-enum `enum`} is defined, the value SHOULD exist in the enum's values. Note that this behavior is different from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#schema-object Schema Object}'s `default` keyword, which documents the receiver's behavior rather than inserting the value into the data. */ default: string; /** * An optional description for the server variable. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty. */ enum?: ReadonlyArray; } /** * Adds metadata to a single tag that is used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#operation-object Operation Object}. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * **Tag Object Example** * * ```yaml * name: pet * description: Pets operations * ``` */ export interface TagObject extends SpecificationExtensions { /** * A description for the tag. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Additional external documentation for this tag. */ externalDocs?: ExternalDocumentationObject; /** * **REQUIRED**. The name of the tag. */ name: string; } /** * A metadata object that allows for more fine-tuned XML model definitions. * * When using arrays, XML element names are _not_ inferred (for singular/plural forms) and the `name` field SHOULD be used to add that information. See examples for expected behavior. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#specification-extensions Specification Extensions}. * * The `namespace` field is intended to match the syntax of {@link https://www.w3.org/TR/xml-names11/ XML namespaces}, although there are a few caveats: * - Version 3.0.3 and earlier of this specification erroneously used the term "absolute URI" instead of "non-relative URI", so authors using namespaces that include a fragment should check tooling support carefully. * - XML allows but discourages relative URI-references, while this specification outright forbids them. * - XML 1.1 allows IRIs ({@link https://datatracker.ietf.org/doc/html/rfc3987 RFC3987}) as namespaces, and specifies that namespaces are compared without any encoding or decoding, which means that IRIs encoded to meet this specification's URI syntax requirement cannot be compared to IRIs as-is. * * TODO: examples */ export interface XMLObject extends SpecificationExtensions { /** * Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. */ attribute?: boolean; /** * Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `"array"` (outside the `items`), it will affect the wrapping element if and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. */ name?: string; /** * The URI of the namespace definition. Value MUST be in the form of a non-relative URI. */ namespace?: string; /** * The prefix to be used for the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#xml-name name}. */ prefix?: string; /** * MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `"array"` (outside the `items`). */ wrapped?: boolean; } type JsonSchemaFormats = 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uriref'; type OpenApiSchemaFormats = | 'int32' | 'int64' | 'float' | 'double' | 'byte' | 'binary' | 'date' | 'date-time' | 'password'; type Format = JsonSchemaFormats | OpenApiSchemaFormats | AnyString; ================================================ FILE: packages/shared/src/openApi/3.1.x/index.ts ================================================ export { parseV3_1_X } from './parser'; export type { OpenApiV3_1_X } from './types/spec'; import type { InfoObject, OperationObject, ParameterObject, ReferenceObject, RequestBodyObject, ResponseObject, SchemaObject, } from './types/spec'; export interface OpenApiV3_1_XTypes { InfoObject: InfoObject; OperationObject: OperationObject; ParameterObject: ParameterObject; ReferenceObject: ReferenceObject; RequestBodyObject: RequestBodyObject; ResponseObject: ResponseObject; SchemaObject: SchemaObject; } ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/__tests__/operation.test.ts ================================================ import type { Context } from '../../../../ir/context'; import type { SecuritySchemeObject } from '../../types/spec'; import { parsePathOperation } from '../operation'; type ParseOperationProps = Parameters[0]; describe('operation', () => { const context = { config: { plugins: {}, }, ir: { paths: {}, servers: [], }, } as unknown as Context; it('should parse operation correctly', () => { const method = 'get'; const operation: ParseOperationProps['operation'] = { operationId: 'testOperation', responses: {}, security: [ { apiKeyAuth: [], }, { apiKeyAuth: [], }, { oauthRule: ['read'], }, { oauthRule: ['write'], }, ], summary: 'Test Operation', }; const path = '/test'; const oauth2: SecuritySchemeObject = { description: 'OAuth2', flows: { password: { scopes: { read: 'Grants read access', write: 'Grants write access', }, tokenUrl: 'https://example.com/oauth/token', }, }, type: 'oauth2', }; const securitySchemesMap = new Map([ ['apiKeyAuth', { in: 'header', name: 'Auth', type: 'apiKey' }], ['basicAuthRule', { description: 'Basic Auth', scheme: 'basic', type: 'http' }], ['oauthRule', oauth2], ]); const state: ParseOperationProps['state'] = { ids: new Map(), }; parsePathOperation({ context, method, operation, path, securitySchemesMap, state, }); expect(context.ir.paths?.[path]?.[method]).toEqual({ id: 'testOperation', method, operationId: 'testOperation', path, security: [{ in: 'header', name: 'Auth', type: 'apiKey' }, oauth2], summary: 'Test Operation', }); }); }); ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/__tests__/validate.test.ts ================================================ import path from 'node:path'; import { Logger } from '@hey-api/codegen-core'; import { getSpecsPath, specFileToJson } from '../../../__tests__/utils'; import type { ValidatorResult } from '../../../shared/utils/validator'; import { validateOpenApiSpec } from '../validate'; const specsFolder = path.join(getSpecsPath(), '3.1.x', 'invalid'); describe('validate', () => { const scenarios: Array< ValidatorResult & { description: string; file: string; } > = [ { description: 'servers must be array', file: path.join(specsFolder, 'servers-array.yaml'), issues: [ { code: 'invalid_type', message: '`servers` must be an array.', path: [], severity: 'error', }, ], valid: false, }, { description: 'servers entry must be object', file: path.join(specsFolder, 'servers-entry.yaml'), issues: [ { code: 'invalid_type', context: { actual: 'string', expected: 'object', }, message: 'Each entry in `servers` must be an object.', path: ['servers', 0], severity: 'error', }, ], valid: false, }, { description: 'servers entry required fields', file: path.join(specsFolder, 'servers-required.yaml'), issues: [ { code: 'missing_required_field', context: { field: 'url', }, message: 'Missing required field `url` in server object.', path: ['servers', 0], severity: 'error', }, ], valid: false, }, { description: 'operationId must be unique', file: path.join(specsFolder, 'operationId-unique.yaml'), issues: [ { code: 'duplicate_key', context: { key: 'operationId', value: 'foo', }, message: 'Duplicate `operationId` found. Each `operationId` must be unique.', path: ['paths', '/foo', 'post', 'operationId'], severity: 'error', }, ], valid: false, }, ]; it.each(scenarios)('$description', ({ file, issues, valid }) => { const spec = specFileToJson(file); const logger = new Logger(); const result = validateOpenApiSpec(spec, logger); expect(result.valid).toBe(valid); expect(result.issues).toEqual(issues); }); }); ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/filter.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { createOperationKey } from '../../../ir/operation'; import { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter'; import { httpMethods } from '../../../openApi/shared/utils/operation'; import type { OpenApiV3_1_X, PathItemObject, PathsObject } from '../types/spec'; /** * Replace source spec with filtered version. */ export const filterSpec = ({ logger, operations, parameters, preserveOrder, requestBodies, responses, schemas, spec, }: { logger: Logger; operations: Set; parameters: Set; preserveOrder: boolean; requestBodies: Set; responses: Set; schemas: Set; spec: OpenApiV3_1_X; }) => { const eventFilterSpec = logger.timeEvent('filter-spec'); if (spec.components) { if (spec.components.parameters) { const filtered: typeof spec.components.parameters = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.parameters)) { if (parameters.has(addNamespace('parameter', name))) { filtered[name] = source; } } } else { for (const key of parameters) { const { name } = removeNamespace(key); const source = spec.components.parameters[name]; if (source) { filtered[name] = source; } } } spec.components.parameters = filtered; } if (spec.components.requestBodies) { const filtered: typeof spec.components.requestBodies = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.requestBodies)) { if (requestBodies.has(addNamespace('body', name))) { filtered[name] = source; } } } else { for (const key of requestBodies) { const { name } = removeNamespace(key); const source = spec.components.requestBodies[name]; if (source) { filtered[name] = source; } } } spec.components.requestBodies = filtered; } if (spec.components.responses) { const filtered: typeof spec.components.responses = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.responses)) { if (responses.has(addNamespace('response', name))) { filtered[name] = source; } } } else { for (const key of responses) { const { name } = removeNamespace(key); const source = spec.components.responses[name]; if (source) { filtered[name] = source; } } } spec.components.responses = filtered; } if (spec.components.schemas) { const filtered: typeof spec.components.schemas = {}; if (preserveOrder) { for (const [name, source] of Object.entries(spec.components.schemas)) { if (schemas.has(addNamespace('schema', name))) { filtered[name] = source; } } } else { for (const key of schemas) { const { name } = removeNamespace(key); const source = spec.components.schemas[name]; if (source) { filtered[name] = source; } } } spec.components.schemas = filtered; } } if (spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { const operation = pathItem[method]; if (!operation) { continue; } const key = addNamespace('operation', createOperationKey({ method, path })); if (!operations.has(key)) { delete pathItem[method]; } } // remove paths that have no operations left if (!Object.keys(pathItem).length) { delete spec.paths[path]; } } } eventFilterSpec.timeEnd(); }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/index.ts ================================================ import type { Context } from '../../../ir/context'; import { buildResourceMetadata } from '../../../openApi/shared/graph/meta'; import { transformOpenApiSpec } from '../../../openApi/shared/transforms'; import type { State } from '../../../openApi/shared/types/state'; import { createFilteredDependencies, createFilters, hasFilters, } from '../../../openApi/shared/utils/filter'; import { buildGraph } from '../../../openApi/shared/utils/graph'; import { mergeParametersObjects } from '../../../openApi/shared/utils/parameter'; import { handleValidatorResult } from '../../../openApi/shared/utils/validator'; import type { OpenApiV3_1_X, ParameterObject, PathItemObject, PathsObject, RequestBodyObject, SecuritySchemeObject, } from '../types/spec'; import { filterSpec } from './filter'; import { parsePathOperation } from './operation'; import { parametersArrayToObject, parseParameter } from './parameter'; import { parseRequestBody } from './requestBody'; import { parseSchema } from './schema'; import { parseServers } from './server'; import { validateOpenApiSpec } from './validate'; import { parseWebhooks } from './webhook'; export const parseV3_1_X = (context: Context) => { if (context.config.parser.validate_EXPERIMENTAL) { const result = validateOpenApiSpec(context.spec, context.logger); handleValidatorResult({ context, result }); } const shouldFilterSpec = hasFilters(context.config.parser.filters); if (shouldFilterSpec) { const filters = createFilters(context.config.parser.filters, context.spec, context.logger); const { graph } = buildGraph(context.spec, context.logger); const { resourceMetadata } = buildResourceMetadata(graph, context.logger); const sets = createFilteredDependencies({ filters, logger: context.logger, resourceMetadata, }); filterSpec({ ...sets, logger: context.logger, preserveOrder: filters.preserveOrder, spec: context.spec, }); } transformOpenApiSpec({ context }); const state: State = { ids: new Map(), }; const securitySchemesMap = new Map(); // TODO: parser - handle more component types, old parser handles only parameters and schemas if (context.spec.components) { for (const name in context.spec.components.securitySchemes) { const securityOrReference = context.spec.components.securitySchemes[name]!; const securitySchemeObject = '$ref' in securityOrReference ? context.resolveRef(securityOrReference.$ref) : securityOrReference; securitySchemesMap.set(name, securitySchemeObject); } for (const name in context.spec.components.parameters) { const $ref = `#/components/parameters/${name}`; const parameterOrReference = context.spec.components.parameters[name]!; const parameter = '$ref' in parameterOrReference ? context.resolveRef(parameterOrReference.$ref) : parameterOrReference; parseParameter({ $ref, context, parameter, }); } for (const name in context.spec.components.requestBodies) { const $ref = `#/components/requestBodies/${name}`; const requestBodyOrReference = context.spec.components.requestBodies[name]!; const requestBody = '$ref' in requestBodyOrReference ? context.resolveRef(requestBodyOrReference.$ref) : requestBodyOrReference; parseRequestBody({ $ref, context, requestBody, }); } for (const name in context.spec.components.schemas) { const $ref = `#/components/schemas/${name}`; const schema = context.spec.components.schemas[name]!; parseSchema({ $ref, context, schema, }); } } parseServers({ context }); for (const path in context.spec.paths) { if (path.startsWith('x-')) continue; const pathItem = context.spec.paths[path as keyof PathsObject]! as PathItemObject; const finalPathItem = pathItem.$ref ? { ...context.resolveRef(pathItem.$ref), ...pathItem, } : pathItem; const operationArgs: Omit[0], 'method'> = { context, operation: { description: finalPathItem.description, parameters: parametersArrayToObject({ context, parameters: finalPathItem.parameters, }), security: context.spec.security, servers: finalPathItem.servers, summary: finalPathItem.summary, }, path: path as `/${string}`, securitySchemesMap, state, }; if (finalPathItem.delete) { parsePathOperation({ ...operationArgs, method: 'delete', operation: { ...operationArgs.operation, ...finalPathItem.delete, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.delete.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.get) { parsePathOperation({ ...operationArgs, method: 'get', operation: { ...operationArgs.operation, ...finalPathItem.get, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.get.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.head) { parsePathOperation({ ...operationArgs, method: 'head', operation: { ...operationArgs.operation, ...finalPathItem.head, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.head.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.options) { parsePathOperation({ ...operationArgs, method: 'options', operation: { ...operationArgs.operation, ...finalPathItem.options, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.options.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.patch) { parsePathOperation({ ...operationArgs, method: 'patch', operation: { ...operationArgs.operation, ...finalPathItem.patch, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.patch.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.post) { parsePathOperation({ ...operationArgs, method: 'post', operation: { ...operationArgs.operation, ...finalPathItem.post, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.post.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.put) { parsePathOperation({ ...operationArgs, method: 'put', operation: { ...operationArgs.operation, ...finalPathItem.put, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.put.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalPathItem.trace) { parsePathOperation({ ...operationArgs, method: 'trace', operation: { ...operationArgs.operation, ...finalPathItem.trace, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalPathItem.trace.parameters, }), target: operationArgs.operation.parameters, }), }, }); } } parseWebhooks({ context, securitySchemesMap }); }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/mediaType.ts ================================================ import type { IRMediaType } from '../../../ir/mediaType'; import { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType'; import type { MediaTypeObject, SchemaObject } from '../types/spec'; interface Content { mediaType: string; schema: SchemaObject | undefined; type: IRMediaType | undefined; } export const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => { const { mediaType, schema } = content; if (!schema) { if (isMediaTypeFileLike({ mediaType })) { return { format: 'binary', type: 'string', }; } return; } if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) { return { ...schema, format: 'binary', }; } return schema; }; export const mediaTypeObjects = ({ content, }: { content: Record | undefined; }): ReadonlyArray => { const objects: Array = []; for (const mediaType in content) { objects.push({ mediaType, schema: content[mediaType]!.schema, type: mediaTypeToIrMediaType({ mediaType }), }); } return objects; }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/operation.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import type { State } from '../../../openApi/shared/types/state'; import type { httpMethods } from '../../../openApi/shared/utils/operation'; import { operationToId } from '../../../openApi/shared/utils/operation'; import type { OperationObject, ReferenceObject, RequestBodyObject, ResponseObject, SecuritySchemeObject, } from '../types/spec'; import { contentToSchema, mediaTypeObjects } from './mediaType'; import { paginationField } from './pagination'; import { parseExtensions, schemaToIrSchema } from './schema'; export interface Operation extends Omit, Pick {} const parseOperationJsDoc = ({ irOperation, operation, }: { irOperation: IR.OperationObject; operation: Operation; }) => { if (operation.deprecated !== undefined) { irOperation.deprecated = operation.deprecated; } if (operation.description) { irOperation.description = operation.description; } if (operation.summary) { irOperation.summary = operation.summary; } if (operation.tags?.length) { irOperation.tags = operation.tags; } }; const initIrOperation = ({ context, method, operation, path, state, }: Pick & { context: Context; operation: Operation; state: State; }): IR.OperationObject => { const irOperation: IR.OperationObject = { id: operationToId({ context, id: operation.operationId, method, path, state, }), method, path, }; if (operation.operationId) { irOperation.operationId = operation.operationId; } parseOperationJsDoc({ irOperation, operation, }); parseExtensions({ source: operation, target: irOperation, }); return irOperation; }; const operationToIrOperation = ({ context, method, operation, path, securitySchemesMap, state, }: Pick & { context: Context; operation: Operation; securitySchemesMap: Map; state: State; }): IR.OperationObject => { const irOperation = initIrOperation({ context, method, operation, path, state, }); if (operation.parameters) { irOperation.parameters = operation.parameters; } if (operation.requestBody) { const requestBody = '$ref' in operation.requestBody ? context.resolveRef(operation.requestBody.$ref) : operation.requestBody; const contents = mediaTypeObjects({ content: requestBody.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { const pagination = paginationField({ context, name: '', schema: { description: requestBody.description, ...content.schema, }, }); irOperation.body = { mediaType: content.mediaType, schema: schemaToIrSchema({ context, schema: { description: requestBody.description, ...('$ref' in operation.requestBody ? operation.requestBody : content.schema), }, state: undefined, }), }; if (pagination) { irOperation.body.pagination = pagination; } if (requestBody.required) { irOperation.body.required = requestBody.required; } if (content.type) { irOperation.body.type = content.type; } } } for (const name in operation.responses) { if (name.startsWith('x-')) continue; if (!irOperation.responses) { irOperation.responses = {}; } const response = operation.responses[name]! as ResponseObject | ReferenceObject; const responseObject = '$ref' in response ? context.resolveRef(response.$ref) : response; const contents = mediaTypeObjects({ content: responseObject.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { irOperation.responses[name] = { mediaType: content.mediaType, schema: schemaToIrSchema({ context, schema: { description: responseObject.description, ...contentToSchema({ content }), }, state: undefined, }), }; } else { irOperation.responses[name] = { schema: { description: responseObject.description, // TODO: parser - cover all statues with empty response bodies // 1xx, 204, 205, 304 type: name === '204' ? 'void' : 'unknown', }, }; } } if (operation.security) { const securitySchemeObjects: Map = new Map(); for (const securityRequirementObject of operation.security) { for (const name in securityRequirementObject) { const securitySchemeObject = securitySchemesMap.get(name); if (!securitySchemeObject) { continue; } securitySchemeObjects.set(name, securitySchemeObject); } } if (securitySchemeObjects.size) { irOperation.security = Array.from(securitySchemeObjects.values()); } } // TODO: parser - handle servers // qux: operation.servers return irOperation; }; const parseOperationObject = ({ context, method, operation, path, securitySchemesMap, state, }: { context: Context; method: (typeof httpMethods)[number]; operation: Operation; path: keyof IR.PathsObject; securitySchemesMap: Map; state: State; }) => { if (operation.servers) { context.ir.servers = [...(context.ir.servers ?? []), ...operation.servers]; } const parsed = operationToIrOperation({ context, method, operation, path, securitySchemesMap, state, }); return { parsed }; }; export const parsePathOperation = ({ context, method, path, ...options }: { context: Context; method: (typeof httpMethods)[number]; operation: Operation; path: keyof IR.PathsObject; securitySchemesMap: Map; state: State; }) => { if (!context.ir.paths) { context.ir.paths = {}; } if (!context.ir.paths[path]) { context.ir.paths[path] = {}; } const { parsed } = parseOperationObject({ context, method, path, ...options, }); context.ir.paths[path][method] = parsed; }; export const parseWebhookOperation = ({ context, key, method, ...options }: { context: Context; key: string; method: (typeof httpMethods)[number]; operation: Operation; securitySchemesMap: Map; state: State; }) => { if (!context.ir.webhooks) { context.ir.webhooks = {}; } if (!context.ir.webhooks[key]) { context.ir.webhooks[key] = {}; } const { parsed } = parseOperationObject({ context, method, path: key as `/${string}`, ...options, }); context.ir.webhooks[key][method] = parsed; }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/pagination.ts ================================================ import type { Context } from '../../../ir/context'; import { getPaginationKeywordsRegExp } from '../../../ir/pagination'; import type { SchemaType } from '../../../openApi/shared/types/schema'; import type { ParameterObject, RequestBodyObject } from '../types/spec'; import type { SchemaObject } from '../types/spec'; import { mediaTypeObjects } from './mediaType'; import { getSchemaTypes } from './schema'; const isPaginationType = (schemaTypes: ReadonlyArray>): boolean => schemaTypes.includes('boolean') || schemaTypes.includes('integer') || schemaTypes.includes('number') || schemaTypes.includes('string'); // We handle only simple values for now, up to 1 nested field export const paginationField = ({ context, name, schema, }: { context: Context; name: string; schema: SchemaObject; }): boolean | string => { const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination); if (paginationRegExp.test(name)) { return true; } if (schema.$ref) { const ref = context.resolveRef(schema.$ref); if ('content' in ref || 'in' in ref) { let refSchema: SchemaObject | undefined; if ('in' in ref) { refSchema = ref.schema; } if (!refSchema) { // parameter or body const contents = mediaTypeObjects({ content: ref.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content?.schema) { refSchema = content.schema; } } if (!refSchema) { return false; } return paginationField({ context, name, schema: refSchema, }); } return paginationField({ context, name, schema: ref, }); } for (const name in schema.properties) { const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination); if (paginationRegExp.test(name)) { const property = schema.properties[name]!; if (typeof property !== 'boolean') { // TODO: resolve deeper references const schemaTypes = getSchemaTypes({ schema: property }); if (!schemaTypes.length) { const compositionSchemas = property.anyOf ?? property.oneOf; const nonNullCompositionSchemas = (compositionSchemas ?? []).filter( (schema) => schema.type !== 'null', ); if (nonNullCompositionSchemas.length === 1) { const schemaTypes = getSchemaTypes({ schema: nonNullCompositionSchemas[0]!, }); if (isPaginationType(schemaTypes)) { return name; } } } if (isPaginationType(schemaTypes)) { return name; } } } } for (const allOf of schema.allOf ?? []) { const pagination = paginationField({ context, name, schema: allOf, }); if (pagination) { return pagination; } } return false; }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/parameter.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import { refToName } from '../../../utils/ref'; import type { ParameterObject, ReferenceObject, SchemaObject } from '../types/spec'; import { mediaTypeObjects } from './mediaType'; import { paginationField } from './pagination'; import { parseExtensions, schemaToIrSchema } from './schema'; /** * Returns default parameter `allowReserved` based on value of `in`. */ const defaultAllowReserved = (_in: ParameterObject['in']): boolean | undefined => { switch (_in) { // this keyword only applies to parameters with an `in` value of `query` case 'query': return false; default: return; } }; /** * Returns default parameter `explode` based on value of `style`. */ const defaultExplode = (style: Required['style']): boolean => { switch (style) { // default value for `deepObject` is `false`, but that behavior is undefined // so we use `true` to make this work with the `client-fetch` package case 'deepObject': case 'form': return true; default: return false; } }; /** * Returns default parameter `style` based on value of `in`. */ const defaultStyle = (_in: ParameterObject['in']): Required['style'] => { switch (_in) { case 'header': case 'path': return 'simple'; case 'cookie': case 'query': return 'form'; } }; export const parametersArrayToObject = ({ context, parameters, }: { context: Context; parameters?: ReadonlyArray; }): IR.ParametersObject | undefined => { if (!parameters || !Object.keys(parameters).length) { return; } const parametersObject: IR.ParametersObject = {}; for (const parameterOrReference of parameters) { const parameter = '$ref' in parameterOrReference ? context.dereference(parameterOrReference) : parameterOrReference; if (!parametersObject[parameter.in]) { parametersObject[parameter.in] = {}; } // lowercase keys for case insensitive access parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({ $ref: `#/todo/real/path/to/parameter/${parameter.name}`, context, parameter, }); } return parametersObject; }; const parameterToIrParameter = ({ $ref, context, parameter, }: { $ref: string; context: Context; parameter: ParameterObject; }): IR.ParameterObject => { // TODO: parser - fix let schema = parameter.schema; if (!schema) { const contents = mediaTypeObjects({ content: parameter.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; if (content) { schema = content.schema; } } const finalSchema: SchemaObject = { deprecated: parameter.deprecated, description: parameter.description, ...schema, }; const pagination = paginationField({ context, name: parameter.name, schema: finalSchema, }); const style = parameter.style || defaultStyle(parameter.in); const explode = parameter.explode !== undefined ? parameter.explode : defaultExplode(style); const allowReserved = parameter.allowReserved !== undefined ? parameter.allowReserved : defaultAllowReserved(parameter.in); const irParameter: IR.ParameterObject = { allowReserved, explode, location: parameter.in, name: parameter.name, schema: schemaToIrSchema({ context, schema: finalSchema, state: { $ref, circularReferenceTracker: new Set(), }, }), style, }; if (parameter.deprecated) { irParameter.deprecated = parameter.deprecated; } if (parameter.description) { irParameter.description = parameter.description; } if (pagination) { irParameter.pagination = pagination; } if (parameter.required) { irParameter.required = parameter.required; } parseExtensions({ source: parameter, target: irParameter, }); return irParameter; }; export const parseParameter = ({ $ref, context, parameter, }: { $ref: string; context: Context; parameter: ParameterObject; }) => { if (!context.ir.components) { context.ir.components = {}; } if (!context.ir.components.parameters) { context.ir.components.parameters = {}; } context.ir.components.parameters[refToName($ref)] = parameterToIrParameter({ $ref, context, parameter, }); }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/requestBody.ts ================================================ import type { Context } from '../../../ir/context'; import type { IR } from '../../../ir/types'; import { refToName } from '../../../utils/ref'; import type { RequestBodyObject, SchemaObject } from '../types/spec'; import { mediaTypeObjects } from './mediaType'; import { schemaToIrSchema } from './schema'; const requestBodyToIrRequestBody = ({ $ref, context, requestBody, }: { $ref: string; context: Context; requestBody: RequestBodyObject; }): IR.RequestBodyObject => { // TODO: parser - fix const contents = mediaTypeObjects({ content: requestBody.content }); // TODO: add support for multiple content types, for now prefer JSON const content = contents.find((content) => content.type === 'json') || contents[0]; const schema = content ? content.schema : undefined; const finalSchema: SchemaObject = { description: requestBody.description, ...schema, }; const irRequestBody: IR.RequestBodyObject = { schema: schemaToIrSchema({ context, schema: finalSchema, state: { $ref, circularReferenceTracker: new Set(), }, }), }; if (requestBody.description) { irRequestBody.description = requestBody.description; } if (requestBody.required) { irRequestBody.required = requestBody.required; } return irRequestBody; }; export const parseRequestBody = ({ $ref, context, requestBody, }: { $ref: string; context: Context; requestBody: RequestBodyObject; }) => { if (!context.ir.components) { context.ir.components = {}; } if (!context.ir.components.requestBodies) { context.ir.components.requestBodies = {}; } context.ir.components.requestBodies[refToName($ref)] = requestBodyToIrRequestBody({ $ref, context, requestBody, }); }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/schema.ts ================================================ import type { Context } from '../../../ir/context'; import { isMediaTypeFileLike } from '../../../ir/mediaType'; import type { IR } from '../../../ir/types'; import { addItemsToSchema } from '../../../ir/utils'; import type { SchemaState, SchemaType, SchemaWithRequired, } from '../../../openApi/shared/types/schema'; import { convertDiscriminatorValue, type DiscriminatorPropertyType, discriminatorValues, } from '../../../openApi/shared/utils/discriminator'; import { isTopLevelComponent, refToName } from '../../../utils/ref'; import type { SchemaObject } from '../types/spec'; export const getSchemaTypes = ({ schema, }: { schema: SchemaObject; }): ReadonlyArray> => { if (typeof schema.type === 'string') { return [schema.type]; } if (schema.type) { return schema.type; } // infer object based on the presence of properties if (schema.properties) { return ['object']; } return []; }; /** * Finds the type of a discriminator property by looking it up in the provided schemas. * Searches through properties and allOf chains to find the property definition. */ const findDiscriminatorPropertyType = ({ context, propertyName, schemas, }: { context: Context; propertyName: string; schemas: ReadonlyArray; }): DiscriminatorPropertyType => { for (const schema of schemas) { const resolved = schema.$ref ? context.resolveRef(schema.$ref) : schema; // Check direct properties const property = resolved.properties?.[propertyName]; if (property === true) { continue; } if (property) { const resolvedProperty = property.$ref ? context.resolveRef(property.$ref) : property; // Handle both single type and array of types (3.1.x supports type arrays) const propertyTypes = Array.isArray(resolvedProperty.type) ? resolvedProperty.type : resolvedProperty.type ? [resolvedProperty.type] : []; for (const propType of propertyTypes) { if (propType === 'boolean' || propType === 'integer' || propType === 'number') { return propType; } } } // Check allOf chains if (resolved.allOf) { const foundType = findDiscriminatorPropertyType({ context, propertyName, schemas: resolved.allOf, }); if (foundType !== 'string') { return foundType; } } } return 'string'; }; /** * Recursively finds discriminators in a schema, including nested allOf compositions. * This is needed when a schema extends another schema via allOf, and that parent * schema is itself an allOf composition with discriminators in inline schemas. */ const findDiscriminatorsInSchema = ({ context, discriminators = [], schema, }: { context: Context; discriminators?: Array<{ discriminator: NonNullable; oneOf?: SchemaObject['oneOf']; }>; schema: SchemaObject; }): Array<{ discriminator: NonNullable; oneOf?: SchemaObject['oneOf']; }> => { // Check if this schema has a discriminator if (schema.discriminator) { discriminators.push({ discriminator: schema.discriminator, oneOf: schema.oneOf, }); } // If this schema is an allOf composition, recursively search in its components if (schema.allOf) { for (const compositionSchema of schema.allOf) { let resolvedSchema: SchemaObject; if (compositionSchema.$ref) { resolvedSchema = context.resolveRef(compositionSchema.$ref); } else { resolvedSchema = compositionSchema; } findDiscriminatorsInSchema({ context, discriminators, schema: resolvedSchema, }); } } return discriminators; }; /** * Gets the discriminator value for a schema. * Returns only the schema's own discriminator value, not child values. */ const getAllDiscriminatorValues = ({ discriminator, schemaRef, }: { discriminator: NonNullable; schemaRef: string; }): Array => { const values: Array = []; // Check each entry in the discriminator mapping for (const [value, mappedSchemaRef] of Object.entries(discriminator.mapping || {})) { if (mappedSchemaRef === schemaRef) { // This is the current schema's own value values.push(value); } } return values; }; const parseSchemaJsDoc = ({ irSchema, schema, }: { irSchema: IR.SchemaObject; schema: SchemaObject; }) => { if (schema.deprecated !== undefined) { irSchema.deprecated = schema.deprecated; } if (schema.example) { irSchema.example = schema.example; } if (schema.description) { irSchema.description = schema.description; } if (schema.title) { irSchema.title = schema.title; } }; const parseSchemaMeta = ({ irSchema, schema, }: { irSchema: IR.SchemaObject; schema: SchemaObject; }) => { if (schema.const !== undefined) { irSchema.const = schema.const; // try to infer schema type if (!schema.type) { if (schema.const === null) { irSchema.type = 'null'; } else { switch (typeof schema.const) { case 'bigint': case 'number': irSchema.type = 'number'; break; case 'boolean': irSchema.type = 'boolean'; break; case 'string': irSchema.type = 'string'; break; } } } } if (schema.default !== undefined) { irSchema.default = schema.default; } if (schema.exclusiveMaximum !== undefined) { irSchema.exclusiveMaximum = schema.exclusiveMaximum; } if (schema.exclusiveMinimum !== undefined) { irSchema.exclusiveMinimum = schema.exclusiveMinimum; } if (schema.format) { irSchema.format = schema.format; } else if ( schema.contentMediaType && isMediaTypeFileLike({ mediaType: schema.contentMediaType }) ) { irSchema.format = 'binary'; } if (schema.maximum !== undefined) { irSchema.maximum = schema.maximum; } if (schema.maxItems !== undefined) { irSchema.maxItems = schema.maxItems; } if (schema.maxLength !== undefined) { irSchema.maxLength = schema.maxLength; } if (schema.minimum !== undefined) { irSchema.minimum = schema.minimum; } if (schema.minItems !== undefined) { irSchema.minItems = schema.minItems; } if (schema.minLength !== undefined) { irSchema.minLength = schema.minLength; } if (schema.pattern) { irSchema.pattern = schema.pattern; } if (schema.readOnly) { irSchema.accessScope = 'read'; } else if (schema.writeOnly) { irSchema.accessScope = 'write'; } }; const parseArray = ({ context, irSchema = {}, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { if ( (schema.prefixItems && schema.prefixItems.length) || (schema.maxItems && schema.maxItems === schema.minItems) || schema.const !== undefined ) { irSchema.type = 'tuple'; } else { irSchema.type = 'array'; } let schemaItems: Array = []; for (const item of schema.prefixItems ?? []) { const irItemSchema = schemaToIrSchema({ context, schema: item, state, }); schemaItems.push(irItemSchema); } if (schema.items) { const irItemsSchema = schemaToIrSchema({ context, schema: schema.items, state, }); if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) { schemaItems = Array(schema.maxItems).fill(irItemsSchema); } else { const ofArray = schema.items.allOf || schema.items.anyOf || schema.items.oneOf; if ( ofArray && ofArray.length > 1 && !getSchemaTypes({ schema: schema.items }).includes('null') ) { // bring composition up to avoid incorrectly nested arrays irSchema = { ...irSchema, ...irItemsSchema, }; } else { schemaItems.push(irItemsSchema); } } } irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseBoolean = ({ irSchema = {}, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; }): IR.SchemaObject => { irSchema.type = 'boolean'; return irSchema; }; const parseNull = ({ irSchema = {}, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; }) => { irSchema.type = 'null'; return irSchema; }; const parseNumber = ({ irSchema = {}, schema, }: { context: Context; irSchema?: IR.SchemaObject; schema: Omit & { type: SchemaType; }; }): IR.SchemaObject => { irSchema.type = schema.type; return irSchema; }; const parseObject = ({ context, irSchema = {}, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; state: SchemaState; }): IR.SchemaObject => { irSchema.type = 'object'; const schemaProperties: Record = {}; for (const name in schema.properties) { const property = schema.properties[name]!; if (typeof property === 'boolean') { // TODO: parser - handle boolean properties } else { const irPropertySchema = schemaToIrSchema({ context, schema: property, state, }); schemaProperties[name] = irPropertySchema; } } if (Object.keys(schemaProperties).length) { irSchema.properties = schemaProperties; } if (schema.additionalProperties === undefined) { if (!irSchema.properties) { irSchema.additionalProperties = { type: 'unknown', }; } } else if (typeof schema.additionalProperties === 'boolean') { // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf // This would override inherited properties from other schemas in the composition const isEmptyObjectInAllOf = state.inAllOf && schema.additionalProperties === false && (!schema.properties || !Object.keys(schema.properties).length) && (!schema.patternProperties || !Object.keys(schema.patternProperties).length); if (!isEmptyObjectInAllOf) { irSchema.additionalProperties = { type: schema.additionalProperties ? 'unknown' : 'never', }; } } else { const irAdditionalPropertiesSchema = schemaToIrSchema({ context, schema: schema.additionalProperties, state, }); irSchema.additionalProperties = irAdditionalPropertiesSchema; } if (schema.patternProperties) { const patternProperties: Record = {}; for (const pattern in schema.patternProperties) { const patternSchema = schema.patternProperties[pattern]!; const irPatternSchema = schemaToIrSchema({ context, schema: patternSchema, state, }); patternProperties[pattern] = irPatternSchema; } if (Object.keys(patternProperties).length) { irSchema.patternProperties = patternProperties; } } if (schema.propertyNames) { irSchema.propertyNames = schemaToIrSchema({ context, schema: schema.propertyNames, state, }); } if (schema.required) { irSchema.required = schema.required; } if (schema.discriminator && state.$ref) { const values = getAllDiscriminatorValues({ discriminator: schema.discriminator, schemaRef: state.$ref, }); if (values.length) { const propertyType = findDiscriminatorPropertyType({ context, propertyName: schema.discriminator.propertyName, schemas: [schema], }); const valueSchemas: ReadonlyArray = values.map((value) => convertDiscriminatorValue(value, propertyType), ); if (!irSchema.properties) { irSchema.properties = {}; } irSchema.properties[schema.discriminator.propertyName] = valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!; } } return irSchema; }; const parseString = ({ irSchema = {}, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; }): IR.SchemaObject => { irSchema.type = 'string'; return irSchema; }; export const parseExtensions = ({ source, target }: { source: object; target: object }) => { for (const key in source) { if (key.startsWith('x-')) { (target as Record)[key] = (source as Record)[key]; } } }; const initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => { const irSchema: IR.SchemaObject = {}; parseSchemaJsDoc({ irSchema, schema, }); parseExtensions({ source: schema, target: irSchema, }); return irSchema; }; const parseAllOf = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); const schemaItems: Array = []; const schemaTypes = getSchemaTypes({ schema }); const compositionSchemas = schema.allOf; // Collect discriminator information to add after all compositions are processed type DiscriminatorInfo = { discriminator: NonNullable; isExplicitMapping: boolean; isRequired: boolean; values: ReadonlyArray; }; const discriminatorsToAdd: Array = []; for (const compositionSchema of compositionSchemas) { const originalInAllOf = state.inAllOf; // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components if (!('$ref' in compositionSchema)) { state.inAllOf = true; } const irCompositionSchema = schemaToIrSchema({ context, schema: compositionSchema, state, }); state.inAllOf = originalInAllOf; if (state.inAllOf === undefined) { delete state.inAllOf; } if (schema.required) { if (irCompositionSchema.required) { irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required]; } else { irCompositionSchema.required = schema.required; } } schemaItems.push(irCompositionSchema); if (compositionSchema.$ref) { const ref = context.resolveRef(compositionSchema.$ref); // `$ref` should be passed from the root `parseSchema()` call if (state.$ref) { // Find all discriminators in the referenced schema, including nested allOf compositions const discriminators = findDiscriminatorsInSchema({ context, schema: ref, }); for (const { discriminator, oneOf } of discriminators) { const values = discriminatorValues( state.$ref, discriminator.mapping, // If the ref has oneOf, we only use the schema name as the value // only if current schema is part of the oneOf. Else it is extending // the ref schema oneOf ? () => oneOf.some((o) => '$ref' in o && o.$ref === state.$ref) : undefined, ); if (values.length === 0) { continue; } // True when state.$ref appears directly in the mapping; false when the // value fell back to the schema name because no mapping entry matched. const isExplicitMapping = discriminator.mapping !== undefined && Object.values(discriminator.mapping).includes(state.$ref); // An explicit mapping always beats a same-property fallback collected // earlier (e.g. from a grandparent discriminator that doesn't list this // schema). Replace it; otherwise skip the duplicate. const existingIndex = discriminatorsToAdd.findIndex( (d) => d.discriminator.propertyName === discriminator.propertyName, ); if (existingIndex !== -1) { if (isExplicitMapping && !discriminatorsToAdd[existingIndex]!.isExplicitMapping) { discriminatorsToAdd.splice(existingIndex, 1); } else { continue; } } const isRequired = discriminators.some( (d) => d.discriminator.propertyName === discriminator.propertyName && (ref.required?.includes(d.discriminator.propertyName) || (ref.allOf && ref.allOf.some((item) => { const resolvedItem = item.$ref ? context.resolveRef(item.$ref) : item; return resolvedItem.required?.includes(d.discriminator.propertyName); }))), ); discriminatorsToAdd.push({ discriminator, isExplicitMapping, isRequired, values, }); } } } } // Now add discriminators after all compositions have been processed for (const { discriminator, isRequired, values } of discriminatorsToAdd) { // Get all discriminator values including children for union types const allValues = getAllDiscriminatorValues({ discriminator, schemaRef: state.$ref!, }); // Use allValues if we found children, otherwise use the original values const finalValues = allValues.length > 0 ? allValues : values; // Detect the actual type of the discriminator property const propertyType = findDiscriminatorPropertyType({ context, propertyName: discriminator.propertyName, schemas: compositionSchemas, }); const valueSchemas: ReadonlyArray = finalValues.map((value) => convertDiscriminatorValue(value, propertyType), ); const discriminatorProperty: IR.SchemaObject = valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!; // Check if any $ref schemas in schemaItems have this discriminator property // If yes, mark them to omit it to avoid conflicts for (const item of schemaItems) { if (item.$ref || item.symbolRef) { // Check if the referenced schema has this property const hasProperty = (() => { if (!item.$ref) return false; try { const refSchema = context.resolveRef(item.$ref); // Check if the discriminator property exists in the ref schema return ( refSchema.properties?.[discriminator.propertyName] !== undefined || (refSchema.allOf && refSchema.allOf.some((allOfItem) => { const resolved = allOfItem.$ref ? context.resolveRef(allOfItem.$ref) : allOfItem; return resolved.properties?.[discriminator.propertyName] !== undefined; })) ); } catch { return false; } })(); if (hasProperty) { // Mark this ref to omit the discriminator property if (!item.omit) { item.omit = [discriminator.propertyName]; } else if (!item.omit.includes(discriminator.propertyName)) { item.omit = [...item.omit, discriminator.propertyName]; } } } } // Find the inline schema (non-$ref) to merge the discriminator property into // The inline schema should be the last non-$ref item in schemaItems let inlineSchema: IR.SchemaObject | undefined; for (let i = schemaItems.length - 1; i >= 0; i--) { const item = schemaItems[i]!; // Check if this is not a $ref schema by looking for properties or checking if it came from an inline schema if (item.type === 'object' || item.properties) { inlineSchema = item; break; } } // If we found an inline schema, add the discriminator property to it if (inlineSchema) { if (!inlineSchema.properties) { inlineSchema.properties = {}; } inlineSchema.properties[discriminator.propertyName] = discriminatorProperty; if (isRequired) { if (!inlineSchema.required) { inlineSchema.required = []; } if (!inlineSchema.required.includes(discriminator.propertyName)) { inlineSchema.required = [...inlineSchema.required, discriminator.propertyName]; } } } else { // Fallback: create a separate discriminator schema if no inline schema found const irDiscriminatorSchema: IR.SchemaObject = { properties: { [discriminator.propertyName]: discriminatorProperty, }, type: 'object', }; if (isRequired) { irDiscriminatorSchema.required = [discriminator.propertyName]; } schemaItems.push(irDiscriminatorSchema); } } if (schemaTypes.includes('object')) { const irObjectSchema = parseOneType({ context, schema: { ...schema, type: 'object', }, state, }); if (irObjectSchema.properties) { for (const requiredProperty of irObjectSchema.required ?? []) { if (!irObjectSchema.properties[requiredProperty]) { for (const compositionSchema of compositionSchemas) { // TODO: parser - this could be probably resolved more accurately const finalCompositionSchema = compositionSchema.$ref ? context.resolveRef(compositionSchema.$ref) : compositionSchema; if (getSchemaTypes({ schema: finalCompositionSchema }).includes('object')) { const irCompositionSchema = parseOneType({ context, schema: { ...finalCompositionSchema, type: 'object', }, state, }); if (irCompositionSchema.properties?.[requiredProperty]) { irObjectSchema.properties[requiredProperty] = irCompositionSchema.properties[requiredProperty]; break; } } } } } schemaItems.push(irObjectSchema); } } irSchema = addItemsToSchema({ items: schemaItems, logicalOperator: 'and', mutateSchemaOneItem: true, schema: irSchema, }); if (schemaTypes.includes('null')) { // nest composition to avoid producing an intersection with null const nestedItems: Array = [ { type: 'null', }, ]; if (schemaItems.length) { nestedItems.unshift(irSchema); } irSchema = { items: nestedItems, logicalOperator: 'or', }; } return irSchema; }; const parseAnyOf = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); const schemaItems: Array = []; const schemaTypes = getSchemaTypes({ schema }); const compositionSchemas = schema.anyOf; const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType({ context, propertyName: schema.discriminator.propertyName, schemas: compositionSchemas, }) : undefined; for (const compositionSchema of compositionSchemas) { let irCompositionSchema = schemaToIrSchema({ context, schema: compositionSchema, state, }); // `$ref` should be defined with discriminators if (schema.discriminator && irCompositionSchema.$ref != null) { const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping); const valueSchemas: ReadonlyArray = values.map((value) => convertDiscriminatorValue(value, discriminatorPropertyType!), ); const irDiscriminatorSchema: IR.SchemaObject = { properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!, }, type: 'object', }; irCompositionSchema = { items: [irDiscriminatorSchema, irCompositionSchema], logicalOperator: 'and', }; } schemaItems.push(irCompositionSchema); } if (schemaTypes.includes('null')) { schemaItems.push({ type: 'null' }); } irSchema = addItemsToSchema({ items: schemaItems, mutateSchemaOneItem: true, schema: irSchema, }); if (schemaTypes.includes('object')) { // nest composition to avoid producing a union with object properties const irObjectSchema = parseOneType({ context, schema: { ...schema, type: 'object', }, state, }); if (irObjectSchema.properties) { irSchema = { items: [irSchema, irObjectSchema], logicalOperator: 'and', }; } } return irSchema; }; const parseEnum = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); irSchema.type = 'enum'; const schemaItems: Array = []; const schemaTypes = getSchemaTypes({ schema }); for (const [index, enumValue] of schema.enum.entries()) { const typeOfEnumValue = typeof enumValue; let enumType: SchemaType | undefined; if ( typeOfEnumValue === 'string' || typeOfEnumValue === 'number' || typeOfEnumValue === 'boolean' ) { enumType = typeOfEnumValue; } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) { enumType = 'array'; } else if (enumValue === null) { // type must contain null if (schemaTypes.includes('null')) { enumType = 'null'; } } else { console.warn( '🚨', `unhandled "${typeOfEnumValue}" typeof value "${enumValue}" for enum`, schema.enum, ); } if (!enumType) { continue; } const irTypeSchema = parseOneType({ context, schema: { const: enumValue, description: schema['x-enum-descriptions']?.[index], title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index], type: enumType, }, state, }); schemaItems.push(irTypeSchema); } irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseOneOf = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { let irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); let schemaItems: Array = []; const schemaTypes = getSchemaTypes({ schema }); const compositionSchemas = schema.oneOf; const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType({ context, propertyName: schema.discriminator.propertyName, schemas: compositionSchemas, }) : undefined; for (const compositionSchema of compositionSchemas) { let irCompositionSchema = schemaToIrSchema({ context, schema: compositionSchema, state, }); // `$ref` should be defined with discriminators if (schema.discriminator && irCompositionSchema.$ref != null) { const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping); const valueSchemas: ReadonlyArray = values.map((value) => convertDiscriminatorValue(value, discriminatorPropertyType!), ); const irDiscriminatorSchema: IR.SchemaObject = { properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? { items: valueSchemas, logicalOperator: 'or', } : valueSchemas[0]!, }, required: [schema.discriminator.propertyName], type: 'object', }; irCompositionSchema = { items: [irDiscriminatorSchema, irCompositionSchema], logicalOperator: 'and', }; } // since we know oneOf will be using "or" logical operator, if the parsed // composition schema also has an "or" operator, we can bring it up // to avoid unnecessary brackets if ( irCompositionSchema.logicalOperator === 'or' && irCompositionSchema.type !== 'array' && irCompositionSchema.items ) { schemaItems = schemaItems.concat(irCompositionSchema.items); } else { schemaItems.push(irCompositionSchema); } } if (schemaTypes.includes('null')) { schemaItems.push({ type: 'null' }); } irSchema = addItemsToSchema({ items: schemaItems, mutateSchemaOneItem: true, schema: irSchema, }); if (schemaTypes.includes('object')) { // nest composition to avoid producing a union with object properties const irObjectSchema = parseOneType({ context, schema: { ...schema, type: 'object', }, state, }); if (irObjectSchema.properties) { irSchema = { items: [irSchema, irObjectSchema], logicalOperator: 'and', }; } } return irSchema; }; const parseRef = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/components/schemas/Foo/properties/bar) // to avoid generating orphaned named types or referencing unregistered symbols const isComponentsRef = isTopLevelComponent(schema.$ref); if (!isComponentsRef) { if (!state.circularReferenceTracker.has(schema.$ref)) { const refSchema = context.resolveRef(schema.$ref); const originalRef = state.$ref; state.$ref = schema.$ref; const irSchema = schemaToIrSchema({ context, schema: refSchema, state, }); state.$ref = originalRef; return irSchema; } // Fallback to preserving the ref if circular } let irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); const irRefSchema: IR.SchemaObject = {}; // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` irRefSchema.$ref = decodeURI(schema.$ref); if (!state.circularReferenceTracker.has(schema.$ref)) { const refSchema = context.resolveRef(schema.$ref); const originalRef = state.$ref; state.$ref = schema.$ref; schemaToIrSchema({ context, schema: refSchema, state, }); state.$ref = originalRef; } const schemaItems: Array = []; schemaItems.push(irRefSchema); if (schema.type && typeof schema.type !== 'string') { if (schema.type.includes('null')) { schemaItems.push({ type: 'null' }); } } irSchema = addItemsToSchema({ items: schemaItems, mutateSchemaOneItem: true, schema: irSchema, }); return irSchema; }; const parseOneType = ({ context, irSchema, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: Omit & { type: SchemaType; }; state: SchemaState; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); } switch (schema.type) { case 'array': return parseArray({ context, irSchema, schema, state, }); case 'boolean': return parseBoolean({ context, irSchema, schema, }); case 'integer': case 'number': return parseNumber({ context, irSchema, schema, }); case 'null': return parseNull({ context, irSchema, schema, }); case 'object': return parseObject({ context, irSchema, schema, state, }); case 'string': return parseString({ context, irSchema, schema, }); default: // gracefully handle invalid type return parseUnknown({ context, irSchema, schema }); } }; const parseManyTypes = ({ context, irSchema, schema, state, }: { context: Context; irSchema?: IR.SchemaObject; schema: Omit & { type: ReadonlyArray>; }; state: SchemaState; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); } const typeIrSchema: IR.SchemaObject = {}; parseSchemaMeta({ irSchema: typeIrSchema, schema }); if (schema.type.includes('null') && typeIrSchema.default === null) { // clear to avoid duplicate default inside the non-null schema. // this would produce incorrect validator output delete typeIrSchema.default; } const schemaItems: Array = []; for (const type of schema.type) { if (type === 'null') { schemaItems.push({ type: 'null' }); } else { const irTypeSchema = parseOneType({ context, irSchema: { ...typeIrSchema }, schema: { ...schema, type, }, state, }); schemaItems.push(irTypeSchema); } } irSchema = addItemsToSchema({ items: schemaItems, schema: irSchema, }); return irSchema; }; const parseType = ({ context, schema, state, }: { context: Context; schema: SchemaWithRequired; state: SchemaState; }): IR.SchemaObject => { const irSchema = initIrSchema({ schema }); parseSchemaMeta({ irSchema, schema }); const schemaTypes = getSchemaTypes({ schema }); if (schemaTypes.length === 1) { return parseOneType({ context, irSchema, schema: { ...schema, type: schemaTypes[0]!, }, state, }); } return parseManyTypes({ context, irSchema, schema: { ...schema, type: schemaTypes, }, state, }); }; const parseUnknown = ({ irSchema, schema, }: { context: Context; irSchema?: IR.SchemaObject; schema: SchemaObject; }): IR.SchemaObject => { if (!irSchema) { irSchema = initIrSchema({ schema }); } irSchema.type = 'unknown'; parseSchemaMeta({ irSchema, schema }); return irSchema; }; export const schemaToIrSchema = ({ context, schema, state, }: { context: Context; schema: SchemaObject; state: SchemaState | undefined; }): IR.SchemaObject => { if (!state) { state = { circularReferenceTracker: new Set(), }; } if (state.$ref) { state.circularReferenceTracker.add(state.$ref); } if (schema.$ref) { return parseRef({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.enum) { return parseEnum({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.allOf) { return parseAllOf({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.anyOf) { return parseAnyOf({ context, schema: schema as SchemaWithRequired, state, }); } if (schema.oneOf) { return parseOneOf({ context, schema: schema as SchemaWithRequired, state, }); } // infer object based on the presence of properties if (schema.type || schema.properties) { return parseType({ context, schema: schema as SchemaWithRequired, state, }); } // infer string with binary format based on contentMediaType if (schema.contentMediaType && isMediaTypeFileLike({ mediaType: schema.contentMediaType })) { return parseType({ context, schema: { ...schema, type: 'string' } as SchemaWithRequired, state, }); } return parseUnknown({ context, schema }); }; export const parseSchema = ({ $ref, context, schema, }: { $ref: string; context: Context; schema: SchemaObject; }) => { if (!context.ir.components) { context.ir.components = {}; } if (!context.ir.components.schemas) { context.ir.components.schemas = {}; } context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({ context, schema, state: { $ref, circularReferenceTracker: new Set(), }, }); }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/server.ts ================================================ import type { Context } from '../../../ir/context'; import { parseUrl } from '../../../utils/url'; export const parseServers = ({ context }: { context: Context }) => { if (context.spec.servers) { context.ir.servers = context.spec.servers; return; } for (const input of context.config.input) { if (typeof input.path === 'string') { const url = parseUrl(input.path); context.ir.servers = [ { url: `${url.protocol ? `${url.protocol}://` : ''}${url.host}${url.port ? `:${url.port}` : ''}`, }, ]; } } if (!context.ir.servers) { context.ir.servers = [ { url: '/', }, ]; } }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/validate.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import { createOperationKey } from '../../../ir/operation'; import { httpMethods } from '../../../openApi/shared/utils/operation'; import type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator'; import type { OpenApiV3_1_X, PathItemObject, PathsObject } from '../types/spec'; export const validateOpenApiSpec = (spec: OpenApiV3_1_X, logger: Logger): ValidatorResult => { const eventValidate = logger.timeEvent('validate'); const issues: Array = []; const operationIds = new Map(); if (spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { const operation = pathItem[method]; if (!operation) { continue; } const operationKey = createOperationKey({ method, path }); if (operation.operationId) { if (!operationIds.has(operation.operationId)) { operationIds.set(operation.operationId, operationKey); } else { issues.push({ code: 'duplicate_key', context: { key: 'operationId', value: operation.operationId, }, message: 'Duplicate `operationId` found. Each `operationId` must be unique.', path: ['paths', path, method, 'operationId'], severity: 'error', }); } } } } } if (spec.servers) { if (typeof spec.servers !== 'object' || !Array.isArray(spec.servers)) { issues.push({ code: 'invalid_type', message: '`servers` must be an array.', path: [], severity: 'error', }); } for (let index = 0; index < spec.servers.length; index++) { const server = spec.servers[index]; if (!server || typeof server !== 'object') { issues.push({ code: 'invalid_type', context: { actual: typeof server, expected: 'object', }, message: 'Each entry in `servers` must be an object.', path: ['servers', index], severity: 'error', }); } else { if (!server.url) { issues.push({ code: 'missing_required_field', context: { field: 'url', }, message: 'Missing required field `url` in server object.', path: ['servers', index], severity: 'error', }); } } } } eventValidate.timeEnd(); return { issues, valid: !issues.some((issue) => issue.severity === 'error'), }; }; ================================================ FILE: packages/shared/src/openApi/3.1.x/parser/webhook.ts ================================================ import type { Context } from '../../../ir/context'; import { mergeParametersObjects } from '../../../openApi/shared/utils/parameter'; import type { OpenApiV3_1_X, PathItemObject } from '../types/spec'; import { parseWebhookOperation } from './operation'; import { parametersArrayToObject } from './parameter'; export const parseWebhooks = ({ context, securitySchemesMap, }: Pick[0], 'securitySchemesMap'> & { context: Context; }) => { const state: Parameters[0]['state'] = { ids: new Map(), }; for (const key in context.spec.webhooks) { const webhook = context.spec.webhooks[key]!; const finalWebhook = '$ref' in webhook ? { ...context.resolveRef(webhook.$ref!), ...webhook, } : webhook; const operationArgs: Omit[0], 'method'> = { context, key, operation: { description: finalWebhook.description, parameters: parametersArrayToObject({ context, parameters: finalWebhook.parameters, }), security: context.spec.security, servers: finalWebhook.servers, summary: finalWebhook.summary, }, securitySchemesMap, state, }; if (finalWebhook.delete) { parseWebhookOperation({ ...operationArgs, method: 'delete', operation: { ...operationArgs.operation, ...finalWebhook.delete, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.delete.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalWebhook.get) { parseWebhookOperation({ ...operationArgs, method: 'get', operation: { ...operationArgs.operation, ...finalWebhook.get, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.get.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalWebhook.head) { parseWebhookOperation({ ...operationArgs, method: 'head', operation: { ...operationArgs.operation, ...finalWebhook.head, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.head.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalWebhook.options) { parseWebhookOperation({ ...operationArgs, method: 'options', operation: { ...operationArgs.operation, ...finalWebhook.options, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.options.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalWebhook.patch) { parseWebhookOperation({ ...operationArgs, method: 'patch', operation: { ...operationArgs.operation, ...finalWebhook.patch, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.patch.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalWebhook.post) { parseWebhookOperation({ ...operationArgs, method: 'post', operation: { ...operationArgs.operation, ...finalWebhook.post, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.post.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalWebhook.put) { parseWebhookOperation({ ...operationArgs, method: 'put', operation: { ...operationArgs.operation, ...finalWebhook.put, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.put.parameters, }), target: operationArgs.operation.parameters, }), }, }); } if (finalWebhook.trace) { parseWebhookOperation({ ...operationArgs, method: 'trace', operation: { ...operationArgs.operation, ...finalWebhook.trace, parameters: mergeParametersObjects({ source: parametersArrayToObject({ context, parameters: finalWebhook.trace.parameters, }), target: operationArgs.operation.parameters, }), }, }); } } }; ================================================ FILE: packages/shared/src/openApi/3.1.x/types/json-schema-draft-2020-12.ts ================================================ import type { AnyString, MaybeArray } from '@hey-api/types'; import type { EnumExtensions } from '../../../openApi/shared/types'; import type { SpecificationExtensions } from './spec'; import type { OpenApiSchemaExtensions } from './spec-extensions'; // TODO: left out some keywords related to structuring a complex schema and declaring a dialect export interface JsonSchemaDraft2020_12 extends ArrayKeywords, NumberKeywords, ObjectKeywords, StringKeywords, EnumExtensions, OpenApiSchemaExtensions, SpecificationExtensions { /** * The `$comment` {@link https://json-schema.org/learn/glossary#keyword keyword} is strictly intended for adding comments to a schema. Its value must always be a string. Unlike the annotations `title`, `description`, and `examples`, JSON schema {@link https://json-schema.org/learn/glossary#implementation implementations} aren't allowed to attach any meaning or behavior to it whatsoever, and may even strip them at any time. Therefore, they are useful for leaving notes to future editors of a JSON schema, but should not be used to communicate to users of the schema. */ $comment?: string; /** * A schema can reference another schema using the `$ref` keyword. The value of `$ref` is a URI-reference that is resolved against the schema's {@link https://json-schema.org/understanding-json-schema/structuring#base-uri Base URI}. When evaluating a `$ref`, an implementation uses the resolved identifier to retrieve the referenced schema and applies that schema to the {@link https://json-schema.org/learn/glossary#instance instance}. * * The `$ref` keyword may be used to create recursive schemas that refer to themselves. */ $ref?: string; /** * `allOf`: (AND) Must be valid against _all_ of the {@link https://json-schema.org/learn/glossary#subschema subschemas} * * To validate against `allOf`, the given data must be valid against all of the given subschemas. * * {@link https://json-schema.org/understanding-json-schema/reference/combining#allof allOf} can not be used to "extend" a schema to add more details to it in the sense of object-oriented inheritance. {@link https://json-schema.org/learn/glossary#instance Instances} must independently be valid against "all of" the schemas in the `allOf`. See the section on {@link https://json-schema.org/understanding-json-schema/reference/object#extending Extending Closed Schemas} for more information. */ allOf?: ReadonlyArray; /** * `anyOf`: (OR) Must be valid against _any_ of the subschemas * * To validate against `anyOf`, the given data must be valid against any (one or more) of the given subschemas. */ anyOf?: ReadonlyArray; /** * The `const` keyword is used to restrict a value to a single value. */ const?: unknown; /** * The `contentEncoding` keyword specifies the encoding used to store the contents, as specified in {@link https://tools.ietf.org/html/rfc2045 RFC 2054, part 6.1} and {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}. * * The acceptable values are `quoted-printable`, `base16`, `base32`, and `base64`. If not specified, the encoding is the same as the containing JSON document. * * Without getting into the low-level details of each of these encodings, there are really only two options useful for modern usage: * - If the content is encoded in the same encoding as the enclosing JSON document (which for practical purposes, is almost always UTF-8), leave `contentEncoding` unspecified, and include the content in a string as-is. This includes text-based content types, such as `text/html` or `application/xml`. * - If the content is binary data, set `contentEncoding` to `base64` and encode the contents using {@link https://tools.ietf.org/html/rfc4648 Base64}. This would include many image types, such as `image/png` or audio types, such as `audio/mpeg`. */ contentEncoding?: 'base16' | 'base32' | 'base64' | 'quoted-printable'; /** * The `contentMediaType` keyword specifies the MIME type of the contents of a string, as described in {@link https://tools.ietf.org/html/rfc2046 RFC 2046}. There is a list of {@link http://www.iana.org/assignments/media-types/media-types.xhtml MIME types officially registered by the IANA}, but the set of types supported will be application and operating system dependent. Mozilla Developer Network also maintains a {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types shorter list of MIME types that are important for the web} */ contentMediaType?: string; /** * The `default` keyword specifies a default value. This value is not used to fill in missing values during the validation process. Non-validation tools such as documentation generators or form generators may use this value to give hints to users about how to use a value. However, `default` is typically used to express that if a value is missing, then the value is semantically the same as if the value was present with the default value. The value of `default` should validate against the schema in which it resides, but that isn't required. */ default?: unknown; /** * The `dependentRequired` {@link https://json-schema.org/learn/glossary#keyword keyword} conditionally requires that certain properties must be present if a given property is present in an object. For example, suppose we have a {@link https://json-schema.org/learn/glossary#schema schema} representing a customer. If you have their credit card number, you also want to ensure you have a billing address. If you don't have their credit card number, a billing address would not be required. We represent this dependency of one property on another using the `dependentRequired` keyword. The value of the `dependentRequired` keyword is an object. Each entry in the object maps from the name of a property, _p_, to an array of strings listing properties that are required if _p_ is present. */ dependentRequired?: Record>; /** * The `dependentSchemas` keyword conditionally applies a {@link https://json-schema.org/learn/glossary#subschema subschema} when a given property is present. This schema is applied in the same way {@link https://json-schema.org/understanding-json-schema/reference/combining#allof allOf} applies schemas. Nothing is merged or extended. Both schemas apply independently. */ dependentSchemas?: Record; /** * The `deprecated` keyword is a boolean that indicates that the {@link https://json-schema.org/learn/glossary#instance instance} value the keyword applies to should not be used and may be removed in the future. */ deprecated?: boolean; /** * The `title` and `description` keywords must be strings. A "title" will preferably be short, whereas a "description" will provide a more lengthy explanation about the purpose of the data described by the schema. */ description?: string; /** * The `if`, `then` and `else` keywords allow the application of a subschema based on the outcome of another schema, much like the `if`/`then`/`else` constructs you've probably seen in traditional programming languages. * * If `if` is valid, `then` must also be valid (and `else` is ignored.) If `if` is invalid, `else` must also be valid (and `then` is ignored). * * If `then` or `else` is not defined, `if` behaves as if they have a value of `true`. * * If `then` and/or `else` appear in a schema without `if`, `then` and `else` are ignored. */ else?: JsonSchemaDraft2020_12; /** * The `enum` {@link https://json-schema.org/learn/glossary#keyword keyword} is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique. * * You can use `enum` even without a type, to accept values of different types. */ enum?: ReadonlyArray; /** * The `examples` keyword is a place to provide an array of examples that validate against the schema. This isn't used for validation, but may help with explaining the effect and purpose of the schema to a reader. Each entry should validate against the schema in which it resides, but that isn't strictly required. There is no need to duplicate the `default` value in the `examples` array, since `default` will be treated as another example. */ examples?: ReadonlyArray; /** * The `format` keyword allows for basic semantic identification of certain kinds of string values that are commonly used. For example, because JSON doesn't have a "DateTime" type, dates need to be encoded as strings. `format` allows the schema author to indicate that the string value should be interpreted as a date. By default, `format` is just an annotation and does not effect validation. * * Optionally, validator {@link https://json-schema.org/learn/glossary#implementation implementations} can provide a configuration option to enable `format` to function as an assertion rather than just an annotation. That means that validation will fail if, for example, a value with a `date` format isn't in a form that can be parsed as a date. This can allow values to be constrained beyond what the other tools in JSON Schema, including {@link https://json-schema.org/understanding-json-schema/reference/regular_expressions Regular Expressions} can do. * * There is a bias toward networking-related formats in the JSON Schema specification, most likely due to its heritage in web technologies. However, custom formats may also be used, as long as the parties exchanging the JSON documents also exchange information about the custom format types. A JSON Schema validator will ignore any format type that it does not understand. */ format?: JsonSchemaFormats; /** * The `if`, `then` and `else` keywords allow the application of a subschema based on the outcome of another schema, much like the `if`/`then`/`else` constructs you've probably seen in traditional programming languages. * * If `if` is valid, `then` must also be valid (and `else` is ignored.) If `if` is invalid, `else` must also be valid (and `then` is ignored). * * If `then` or `else` is not defined, `if` behaves as if they have a value of `true`. * * If `then` and/or `else` appear in a schema without `if`, `then` and `else` are ignored. */ if?: JsonSchemaDraft2020_12; /** * `not`: (NOT) Must _not_ be valid against the given schema * * The `not` keyword declares that an instance validates if it doesn't validate against the given subschema. */ not?: JsonSchemaDraft2020_12; /** * `oneOf`: (XOR) Must be valid against _exactly one_ of the subschemas * * To validate against `oneOf`, the given data must be valid against exactly one of the given subschemas. * * Careful consideration should be taken when using `oneOf` entries as the nature of it requires verification of _every_ sub-schema which can lead to increased processing times. Prefer `anyOf` where possible. */ oneOf?: ReadonlyArray; /** * The boolean keywords `readOnly` and `writeOnly` are typically used in an API context. `readOnly` indicates that a value should not be modified. It could be used to indicate that a `PUT` request that changes a value would result in a `400 Bad Request` response. `writeOnly` indicates that a value may be set, but will remain hidden. In could be used to indicate you can set a value with a `PUT` request, but it would not be included when retrieving that record with a `GET` request. */ readOnly?: boolean; /** * The `if`, `then` and `else` keywords allow the application of a subschema based on the outcome of another schema, much like the `if`/`then`/`else` constructs you've probably seen in traditional programming languages. * * If `if` is valid, `then` must also be valid (and `else` is ignored.) If `if` is invalid, `else` must also be valid (and `then` is ignored). * * If `then` or `else` is not defined, `if` behaves as if they have a value of `true`. * * If `then` and/or `else` appear in a schema without `if`, `then` and `else` are ignored. */ then?: JsonSchemaDraft2020_12; /** * The `title` and `description` keywords must be strings. A "title" will preferably be short, whereas a "description" will provide a more lengthy explanation about the purpose of the data described by the schema. */ title?: string; /** * If it is an array, it must be an array of strings, where each string is the name of one of the basic types, and each element is unique. In this case, the JSON snippet is valid if it matches any of the given types. */ type?: MaybeArray; /** * The boolean keywords `readOnly` and `writeOnly` are typically used in an API context. `readOnly` indicates that a value should not be modified. It could be used to indicate that a `PUT` request that changes a value would result in a `400 Bad Request` response. `writeOnly` indicates that a value may be set, but will remain hidden. In could be used to indicate you can set a value with a `PUT` request, but it would not be included when retrieving that record with a `GET` request. */ writeOnly?: boolean; } interface ArrayKeywords { /** * While the `items` schema must be valid for every item in the array, the `contains` schema only needs to validate against one or more items in the array. */ contains?: JsonSchemaDraft2020_12; /** * List validation is useful for arrays of arbitrary length where each item matches the same schema. For this kind of array, set the `items` {@link https://json-schema.org/learn/glossary#keyword keyword} to a single schema that will be used to validate all of the items in the array. * * The `items` keyword can be used to control whether it's valid to have additional items in a tuple beyond what is defined in `prefixItems`. The value of the `items` keyword is a schema that all additional items must pass in order for the keyword to validate. * * Note that `items` doesn't "see inside" any {@link https://json-schema.org/learn/glossary#instance instances} of `allOf`, `anyOf`, or `oneOf` in the same {@link https://json-schema.org/learn/glossary#subschema subschema}. */ items?: JsonSchemaDraft2020_12 | false; /** * `minContains` and `maxContains` can be used with `contains` to further specify how many times a schema matches a `contains` constraint. These keywords can be any non-negative number including zero. */ maxContains?: number; /** * The length of the array can be specified using the `minItems` and `maxItems` keywords. The value of each keyword must be a non-negative number. These keywords work whether doing {@link https://json-schema.org/understanding-json-schema/reference/array#items list validation} or {@link https://json-schema.org/understanding-json-schema/reference/array#tupleValidation tuple-validation}. */ maxItems?: number; /** * `minContains` and `maxContains` can be used with `contains` to further specify how many times a schema matches a `contains` constraint. These keywords can be any non-negative number including zero. */ minContains?: number; /** * The length of the array can be specified using the `minItems` and `maxItems` keywords. The value of each keyword must be a non-negative number. These keywords work whether doing {@link https://json-schema.org/understanding-json-schema/reference/array#items list validation} or {@link https://json-schema.org/understanding-json-schema/reference/array#tupleValidation tuple-validation}. */ minItems?: number; /** * `prefixItems` is an array, where each item is a schema that corresponds to each index of the document's array. That is, an array where the first element validates the first element of the input array, the second element validates the second element of the input array, etc. */ prefixItems?: ReadonlyArray; /** * The `unevaluatedItems` keyword is useful mainly when you want to add or disallow extra items to an array. * * `unevaluatedItems` applies to any values not evaluated by an `items`, `prefixItems`, or `contains` keyword. Just as `unevaluatedProperties` affects only properties in an object, `unevaluatedItems` affects only items in an array. * * Watch out! The word "unevaluated" _does not mean_ "not evaluated by `items`, `prefixItems`, or `contains`." "Unevaluated" means "not successfully evaluated", or "does not evaluate to true". * * Like with `items`, if you set `unevaluatedItems` to false, you can disallow extra items in the array. */ unevaluatedItems?: JsonSchemaDraft2020_12 | false; /** * A schema can ensure that each of the items in an array is unique. Simply set the `uniqueItems` keyword to `true`. */ uniqueItems?: boolean; } interface NumberKeywords { /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ exclusiveMaximum?: number; /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ exclusiveMinimum?: number; /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ maximum?: number; /** * Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range). * * If _x_ is the value being validated, the following must hold true: * * ``` * x ≥ minimum * x > exclusiveMinimum * x ≤ maximum * x < exclusiveMaximum * ``` * * While you can specify both of `minimum` and `exclusiveMinimum` or both of `maximum` and `exclusiveMaximum`, it doesn't really make sense to do so. */ minimum?: number; /** * Numbers can be restricted to a multiple of a given number, using the `multipleOf` keyword. It may be set to any positive number. The multiple can be a floating point number. */ multipleOf?: number; } interface ObjectKeywords { /** * The `additionalProperties` keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the `properties` keyword or match any of the regular expressions in the `patternProperties` keyword. By default any additional properties are allowed. * * The value of the `additionalProperties` keyword is a schema that will be used to validate any properties in the {@link https://json-schema.org/learn/glossary#instance instance} that are not matched by `properties` or `patternProperties`. Setting the `additionalProperties` schema to `false` means no additional properties will be allowed. * * It's important to note that `additionalProperties` only recognizes properties declared in the same {@link https://json-schema.org/learn/glossary#subschema subschema} as itself. So, `additionalProperties` can restrict you from "extending" a schema using {@link https://json-schema.org/understanding-json-schema/reference/combining combining} keywords such as {@link https://json-schema.org/understanding-json-schema/reference/combining#allof allOf}. */ additionalProperties?: JsonSchemaDraft2020_12 | false; /** * The number of properties on an object can be restricted using the `minProperties` and `maxProperties` keywords. Each of these must be a non-negative integer. */ maxProperties?: number; /** * The number of properties on an object can be restricted using the `minProperties` and `maxProperties` keywords. Each of these must be a non-negative integer. */ minProperties?: number; /** * Sometimes you want to say that, given a particular kind of property name, the value should match a particular schema. That's where `patternProperties` comes in: it maps regular expressions to schemas. If a property name matches the given regular expression, the property value must validate against the corresponding schema. */ patternProperties?: Record; /** * The properties (key-value pairs) on an object are defined using the `properties` {@link https://json-schema.org/learn/glossary#keyword keyword}. The value of `properties` is an object, where each key is the name of a property and each value is a {@link https://json-schema.org/learn/glossary#schema schema} used to validate that property. Any property that doesn't match any of the property names in the `properties` keyword is ignored by this keyword. */ properties?: Record; /** * The names of properties can be validated against a schema, irrespective of their values. This can be useful if you don't want to enforce specific properties, but you want to make sure that the names of those properties follow a specific convention. You might, for example, want to enforce that all names are valid ASCII tokens so they can be used as attributes in a particular programming language. * * Since object keys must always be strings anyway, it is implied that the schema given to `propertyNames` is always at least: * * ```json * { "type": "string" } * ``` */ propertyNames?: JsonSchemaDraft2020_12; /** * By default, the properties defined by the `properties` keyword are not required. However, one can provide a list of required properties using the `required` keyword. * * The `required` keyword takes an array of zero or more strings. Each of these strings must be unique. */ required?: ReadonlyArray; /** * The `unevaluatedProperties` keyword is similar to `additionalProperties` except that it can recognize properties declared in subschemas. So, the example from the previous section can be rewritten without the need to redeclare properties. * * `unevaluatedProperties` works by collecting any properties that are successfully validated when processing the schemas and using those as the allowed list of properties. This allows you to do more complex things like conditionally adding properties. */ unevaluatedProperties?: JsonSchemaDraft2020_12 | false; } interface StringKeywords { /** * The length of a string can be constrained using the `minLength` and `maxLength` {@link https://json-schema.org/learn/glossary#keyword keywords}. For both keywords, the value must be a non-negative number. */ maxLength?: number; /** * The length of a string can be constrained using the `minLength` and `maxLength` {@link https://json-schema.org/learn/glossary#keyword keywords}. For both keywords, the value must be a non-negative number. */ minLength?: number; /** * The `pattern` keyword is used to restrict a string to a particular regular expression. The regular expression syntax is the one defined in JavaScript ({@link https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ ECMA 262} specifically) with Unicode support. See {@link https://json-schema.org/understanding-json-schema/reference/regular_expressions Regular Expressions} for more information. */ pattern?: string; } type JsonSchemaFormats = | 'date' | 'date-time' | 'duration' | 'email' | 'hostname' | 'idn-email' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'iri' | 'iri-reference' | 'json-pointer' | 'regex' | 'relative-json-pointer' | 'time' | 'uri' | 'uri-reference' | 'uri-template' | 'uuid' | AnyString; type JsonSchemaTypes = 'array' | 'boolean' | 'integer' | 'null' | 'number' | 'object' | 'string'; ================================================ FILE: packages/shared/src/openApi/3.1.x/types/spec-extensions.ts ================================================ import type { DiscriminatorObject, ExternalDocumentationObject, XMLObject } from './spec'; export interface OpenApiSchemaExtensions { /** * Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#composition-and-inheritance-polymorphism Composition and Inheritance} for more details. */ discriminator?: DiscriminatorObject; /** * A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. * * **Deprecated**: The `example` property has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it. */ example?: unknown; /** * Additional external documentation for this schema. */ externalDocs?: ExternalDocumentationObject; /** * This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. */ xml?: XMLObject; } ================================================ FILE: packages/shared/src/openApi/3.1.x/types/spec.ts ================================================ import type { CodeSampleObject } from '../../../openApi/shared/types'; import type { JsonSchemaDraft2020_12 } from './json-schema-draft-2020-12'; /** * OpenAPI Specification Extensions. * * See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. */ export interface SpecificationExtensions { [extension: `x-${string}`]: unknown; } /** * This is the root object of the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-document OpenAPI document}. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. */ export interface OpenApiV3_1_X extends SpecificationExtensions { /** * An element to hold various schemas for the document. */ components?: ComponentsObject; /** * Additional external documentation. */ externalDocs?: ExternalDocumentationObject; /** * **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. */ info: InfoObject; /** * The default value for the `$schema` keyword within {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object Schema Objects} contained within this OAS document. This MUST be in the form of a URI. */ jsonSchemaDialect?: string; /** * **REQUIRED**. This string MUST be the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#versions version number} of the OpenAPI Specification that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document. This is _not_ related to the API {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#infoVersion `info.version`} string. */ openapi: '3.1.0' | '3.1.1' | '3.1.2'; /** * The available paths and operations for the API. */ paths?: PathsObject; /** * A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. */ security?: ReadonlyArray; /** * An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-object Server Object} with a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#serverUrl url} value of `/`. */ servers?: ReadonlyArray; /** * A list of tags used by the document with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object Operation Object} must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. */ tags?: ReadonlyArray; /** * The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An {@link https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.1/webhook-example.yaml example} is available. */ webhooks?: Record; } /** * A map of possible out-of band callbacks related to the parent operation. Each value in the map is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object Path Item Object} that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. * * To describe incoming requests from the API provider independent from another API call, use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasWebhooks `webhooks`} field. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * **Key Expression** * * The key that identifies the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object Path Item Object} is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#runtime-expressions runtime expression} that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. A simple example might be $request.body#/url. However, using a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#runtime-expressions runtime expression} the complete HTTP message can be accessed. This includes accessing any part of a body that a JSON Pointer {@link https://tools.ietf.org/html/rfc6901 RFC6901} can reference. * * For example, given the following HTTP request: * * ```http * POST /subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning HTTP/1.1 * Host: example.org * Content-Type: application/json * Content-Length: 187 * * { * "failedUrl" : "https://clientdomain.com/failed", * "successUrls" : [ * "https://clientdomain.com/fast", * "https://clientdomain.com/medium", * "https://clientdomain.com/slow" * ] * } * * 201 Created * Location: https://example.org/subscription/1 * ``` * * The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. * * | Expression | Value | * | -------- | ------- | * | $url | https://example.org/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning | * | $method | POST | * | $request.path.eventType | myevent | * | $request.query.queryUrl | https://clientdomain.com/stillrunning | * | $request.header.content-Type | application/json | * | $request.body#/failedUrl | https://clientdomain.com/failed | * | $request.body#/successUrls/2 | https://clientdomain.com/medium | * | $response.header.Location | https://example.org/subscription/1 | * * **Callback Object Examples** * * The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. * * ```yaml * myCallback: * '{$request.query.queryUrl}': * post: * requestBody: * description: Callback payload * content: * 'application/json': * schema: * $ref: '#/components/schemas/SomePayload' * responses: * '200': * description: callback successfully processed * ``` * * The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. * * ```yaml * transactionCallback: * 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': * post: * requestBody: * description: Callback payload * content: * 'application/json': * schema: * $ref: '#/components/schemas/SomePayload' * responses: * '200': * description: callback successfully processed * ``` */ export interface CallbackObject extends SpecificationExtensions { /** * A Path Item Object, or a reference to one, used to define a callback request and expected responses. A {@link https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.0/callback-example.yaml complete example} is available. */ [expression: string]: PathItemObject | ReferenceObject | unknown; } /** * Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. * * Field Name Examples: * * ``` * User * User_1 * User_Name * user-name * my.org.User * ``` * * **Components Object Example** * * ```yaml * components: * schemas: * GeneralError: * type: object * properties: * code: * type: integer * format: int32 * message: * type: string * Category: * type: object * properties: * id: * type: integer * format: int64 * name: * type: string * Tag: * type: object * properties: * id: * type: integer * format: int64 * name: * type: string * parameters: * skipParam: * name: skip * in: query * description: number of items to skip * required: true * schema: * type: integer * format: int32 * limitParam: * name: limit * in: query * description: max records to return * required: true * schema: * type: integer * format: int32 * responses: * NotFound: * description: Entity not found. * IllegalInput: * description: Illegal input for operation. * GeneralError: * description: General Error * content: * application/json: * schema: * $ref: '#/components/schemas/GeneralError' * securitySchemes: * api_key: * type: apiKey * name: api_key * in: header * petstore_auth: * type: oauth2 * flows: * implicit: * authorizationUrl: https://example.org/api/oauth/dialog * scopes: * write:pets: modify pets in your account * read:pets: read your pets * ``` */ export interface ComponentsObject extends SpecificationExtensions { /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object Callback Objects}. */ callbacks?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object Example Objects}. */ examples?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#header-object Header Objects}. */ headers?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object Link Objects}. */ links?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object Parameter Objects}. */ parameters?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object Path Item Object}. */ pathItems?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#request-body-object Request Body Objects}. */ requestBodies?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#response-object Response Objects}. */ responses?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object Schema Objects}. */ schemas?: Record; /** * An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-scheme-object Security Scheme Objects}. */ securitySchemes?: Record; } /** * Contact information for the exposed API. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * name: API Support * url: https://www.example.com/support * email: support@example.com * ``` */ export interface ContactObject extends SpecificationExtensions { /** * The email address of the contact person/organization. This MUST be in the form of an email address. */ email?: string; /** * The identifying name of the contact person/organization. */ name?: string; /** * The URL pointing to the contact information. This MUST be in the form of a URL. */ url?: string; } /** * When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the document of an alternative schema based on the value associated with it. * * When using the discriminator, _inline_ schemas will not be considered. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. * * In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: * * ```yaml * MyResponseType: * oneOf: * - $ref: '#/components/schemas/Cat' * - $ref: '#/components/schemas/Dog' * - $ref: '#/components/schemas/Lizard' * ``` * * which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: * * ```yaml * MyResponseType: * oneOf: * - $ref: '#/components/schemas/Cat' * - $ref: '#/components/schemas/Dog' * - $ref: '#/components/schemas/Lizard' * discriminator: * propertyName: petType * ``` * * The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: * * ```json * { * "id": 12345, * "petType": "Cat" * } * ``` * * Will indicate that the `Cat` schema be used in conjunction with this payload. * * In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: * * ```yaml * MyResponseType: * oneOf: * - $ref: '#/components/schemas/Cat' * - $ref: '#/components/schemas/Dog' * - $ref: '#/components/schemas/Lizard' * - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' * discriminator: * propertyName: petType * mapping: * dog: '#/components/schemas/Dog' * monster: 'https://gigantic-server.com/schemas/Monster/schema.json' * ``` * * Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. * * When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. * * In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. * * For example: * * ```yaml * components: * schemas: * Pet: * type: object * required: * - petType * properties: * petType: * type: string * discriminator: * propertyName: petType * mapping: * dog: Dog * Cat: * allOf: * - $ref: '#/components/schemas/Pet' * - type: object * # all other properties specific to a `Cat` * properties: * name: * type: string * Dog: * allOf: * - $ref: '#/components/schemas/Pet' * - type: object * # all other properties specific to a `Dog` * properties: * bark: * type: string * Lizard: * allOf: * - $ref: '#/components/schemas/Pet' * - type: object * # all other properties specific to a `Lizard` * properties: * lovesRocks: * type: boolean * ``` * * a payload like this: * * ```json * { * "petType": "Cat", * "name": "misty" * } * ``` * * will indicate that the `Cat` schema be used. Likewise this schema: * * ```json * { * "petType": "dog", * "bark": "soft" * } * ``` * * will map to `Dog` because of the definition in the `mapping` element. */ export interface DiscriminatorObject extends SpecificationExtensions { /** * An object to hold mappings between payload values and schema names or references. */ mapping?: Record; /** * **REQUIRED**. The name of the property in the payload that will hold the discriminator value. */ propertyName: string; } /** * A single encoding definition applied to a single schema property. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * requestBody: * content: * multipart/form-data: * schema: * type: object * properties: * id: * # default is text/plain * type: string * format: uuid * address: * # default is application/json * type: object * properties: {} * historyMetadata: * # need to declare XML format! * description: metadata in XML format * type: object * properties: {} * profileImage: {} * encoding: * historyMetadata: * # require XML Content-Type in utf-8 encoding * contentType: application/xml; charset=utf-8 * profileImage: * # only accept png/jpeg * contentType: image/png, image/jpeg * headers: * X-Rate-Limit-Limit: * description: The number of allowed requests in the current period * schema: * type: integer * ``` */ export interface EncodingObject extends SpecificationExtensions { /** * Determines whether the parameter value SHOULD allow reserved characters, as defined by {@link https://tools.ietf.org/html/rfc3986#section-2.2 RFC3986} `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingContentType `contentType`} (implicit or explicit) SHALL be ignored. */ allowReserved?: boolean; /** * The Content-Type for encoding a specific property. Default value depends on the property type: for `object` - `application/json`; for `array` – the default is defined based on the inner type; for all other cases the default is `application/octet-stream`. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. */ contentType?: string; /** * When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingStyle `style`} is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingContentType `contentType`} (implicit or explicit) SHALL be ignored. */ explode?: boolean; /** * A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. */ headers?: Record; /** * Describes how a specific property value will be serialized depending on its type. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object Parameter Object} for details on the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle `style`} property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingContentType `contentType`} (implicit or explicit) SHALL be ignored. */ style?: | 'deepObject' | 'form' | 'label' | 'matrix' | 'pipeDelimited' | 'simple' | 'spaceDelimited'; } /** * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible. * * Example Object Examples * * In a request body: * * @example * ```yaml * requestBody: * content: * 'application/json': * schema: * $ref: '#/components/schemas/Address' * examples: * foo: * summary: A foo example * value: {"foo": "bar"} * bar: * summary: A bar example * value: {"bar": "baz"} * 'application/xml': * examples: * xmlExample: * summary: This is an example in XML * externalValue: 'https://example.org/examples/address-example.xml' * 'text/plain': * examples: * textExample: * summary: This is a text example * externalValue: 'https://foo.bar/examples/address-example.txt' * ``` * * In a parameter: * * @example * ```yaml * parameters: * - name: 'zipCode' * in: 'query' * schema: * type: 'string' * format: 'zip-code' * examples: * zip-example: * $ref: '#/components/examples/zip-example' * ``` * * In a response: * * @example * ```yaml * responses: * '200': * description: your car appointment has been booked * content: * application/json: * schema: * $ref: '#/components/schemas/SuccessResponse' * examples: * confirmation-success: * $ref: '#/components/examples/confirmation-success' * ``` */ export interface ExampleObject extends SpecificationExtensions { /** * Long description for the example. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * A URI that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#relative-references-in-uris Relative References}. */ externalValue?: string; /** * Short description for the example. */ summary?: string; /** * Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. */ value?: unknown; } /** * Allows referencing an external resource for extended documentation. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * description: Find more info here * url: https://example.com * ``` */ export interface ExternalDocumentationObject extends SpecificationExtensions { /** * A description of the target documentation. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * **REQUIRED**. The URL for the target documentation. This MUST be in the form of a URL. */ url: string; } /** * The Header Object follows the structure of the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object Parameter Object} with the following changes: * * 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. * 1. `in` MUST NOT be specified, it is implicitly in `header`. * 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle `style`}). * * @example * ```yaml * description: The number of allowed requests in the current period * schema: * type: integer * ``` */ export type HeaderObject = Omit; /** * The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * title: Sample Pet Store App * summary: A pet store manager. * description: This is a sample server for a pet store. * termsOfService: https://example.com/terms/ * contact: * name: API Support * url: https://www.example.com/support * email: support@example.com * license: * name: Apache 2.0 * url: https://www.apache.org/licenses/LICENSE-2.0.html * version: 1.0.1 * ``` */ export interface InfoObject extends SpecificationExtensions { /** * The contact information for the exposed API. */ contact?: ContactObject; /** * A description of the API. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * The license information for the exposed API. */ license?: LicenseObject; /** * A short summary of the API. */ summary?: string; /** * A URL to the Terms of Service for the API. This MUST be in the form of a URL. */ termsOfService?: string; /** * **REQUIRED**. The title of the API. */ title: string; /** * **REQUIRED**. The version of the OpenAPI document (which is distinct from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasVersion OpenAPI Specification version} or the API implementation version). */ version: string; } /** * License information for the exposed API. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * name: Apache 2.0 * identifier: Apache-2.0 * ``` */ export interface LicenseObject extends SpecificationExtensions { /** * An {@link https://spdx.org/licenses/ SPDX} license expression for the API. The `identifier` field is mutually exclusive of the `url` field. */ identifier?: string; /** * **REQUIRED**. The license name used for the API. */ name: string; /** * A URL to the license used for the API. This MUST be in the form of a URL. The `url` field is mutually exclusive of the `identifier` field. */ url?: string; } /** * The `Link object` represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. * * Unlike _dynamic_ links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response. * * For computing links, and providing instructions to execute them, a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#runtime-expressions runtime expression} is used for accessing values in an operation and using them as parameters while invoking the linked operation. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * A linked operation MUST be identified using either an `operationRef` or `operationId`. In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. Because of the potential for name clashes, the `operationRef` syntax is preferred for OpenAPI documents with external references. * * **Examples** * * Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. * * ```yaml * paths: * /users/{id}: * parameters: * - name: id * in: path * required: true * description: the user identifier, as userId * schema: * type: string * get: * responses: * '200': * description: the user being returned * content: * application/json: * schema: * type: object * properties: * uuid: # the unique user id * type: string * format: uuid * links: * address: * # the target link operationId * operationId: getUserAddress * parameters: * # get the `id` field from the request path parameter named `id` * userId: $request.path.id * # the path item of the linked operation * /users/{userid}/address: * parameters: * - name: userid * in: path * required: true * description: the user identifier, as userId * schema: * type: string * # linked operation * get: * operationId: getUserAddress * responses: * '200': * description: the user's address * ``` * * When a runtime expression fails to evaluate, no parameter value is passed to the target operation. * * Values from the response body can be used to drive a linked operation. * * ```yaml * links: * address: * operationId: getUserAddressByUUID * parameters: * # get the `uuid` field from the `uuid` field in the response body * userUuid: $response.body#/uuid * ``` * * Clients follow all links at their discretion. Neither permissions, nor the capability to make a successful call to that link, is guaranteed solely by the existence of a relationship. * * **OperationRef Examples** * * As references to `operationId` MAY NOT be possible (the `operationId` is an optional field in an {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object Operation Object}), references MAY also be made through a relative `operationRef`: * * ```yaml * links: * UserRepositories: * # returns array of '#/components/schemas/repository' * operationRef: '#/paths/~12.0~1repositories~1{username}/get' * parameters: * username: $response.body#/username * ``` * * or an absolute `operationRef`: * * ```yaml * links: * UserRepositories: * # returns array of '#/components/schemas/repository' * operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' * parameters: * username: $response.body#/username * ``` * * Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when using JSON references. * * **Runtime Expressions** * * Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. This mechanism is used by {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object Link Objects} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object Callback Objects}. * * The runtime expression is defined by the following {@link https://tools.ietf.org/html/rfc5234 ABNF} syntax * * ```abnf * expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) * source = ( header-reference / query-reference / path-reference / body-reference ) * header-reference = "header." token * query-reference = "query." name * path-reference = "path." name * body-reference = "body" ["#" json-pointer ] * json-pointer = *( "/" reference-token ) * reference-token = *( unescaped / escaped ) * unescaped = %x00-2E / %x30-7D / %x7F-10FFFF * ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' * escaped = "~" ( "0" / "1" ) * ; representing '~' and '/', respectively * name = *( CHAR ) * token = 1*tchar * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / * "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA * ``` * * Here, `json-pointer` is taken from {@link https://tools.ietf.org/html/rfc6901 RFC6901}, `char` from {@link https://tools.ietf.org/html/rfc7159#section-7 RFC7159} and `token` from {@link https://tools.ietf.org/html/rfc7230#section-3.2.6 RFC7230}. * * The `name` identifier is case-sensitive, whereas `token` is not. * * The table below provides examples of runtime expressions and examples of their use in a value: * * **Examples** * * | Source Location | example expression | notes | * | -------- | ------- | ------- | * | HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. | * | Requested media type | `$request.header.accept` | | * | Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. | * | Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. | * | Request URL | `$url` | | * | Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. | * | Response header | `$response.header.Server` | Single header values only are available | * * Runtime expressions preserve the type of the referenced value. Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. */ export interface LinkObject extends SpecificationExtensions { /** * A description of the link. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. */ operationId?: string; /** * A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object Operation Object}. Relative `operationRef` values MAY be used to locate an existing {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object Operation Object} in the OpenAPI definition. See the rules for resolving {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#relative-references-in-uris Relative References}. */ operationRef?: string; /** * A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn parameter location} `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). */ parameters?: Record; /** * A literal value or {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#runtime-expressions {expression}} to use as a request body when calling the target operation. */ requestBody?: unknown | string; /** * A server object to be used by the target operation. */ server?: ServerObject; } /** * Each Media Type Object provides schema and examples for the media type identified by its key. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * **Media Type Examples** * * @example * ```yaml * application/json: * schema: * $ref: "#/components/schemas/Pet" * examples: * cat: * summary: An example of a cat * value: * name: Fluffy * petType: Cat * color: White * gender: male * breed: Persian * dog: * summary: An example of a dog with a cat's name * value: * name: Puma * petType: Dog * color: Black * gender: Female * breed: Mixed * frog: * $ref: "#/components/examples/frog-example" * ``` */ export interface MediaTypeObject extends SpecificationExtensions { /** * A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. */ encoding?: Record; /** * Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. */ example?: unknown; /** * Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. */ examples?: Record; /** * The schema defining the content of the request, response, or parameter. */ schema?: SchemaObject; } /** * Configuration details for a supported OAuth Flow * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * **OAuth Flow Object Examples** * * ```yaml * type: oauth2 * flows: * implicit: * authorizationUrl: https://example.com/api/oauth/dialog * scopes: * write:pets: modify pets in your account * read:pets: read your pets * authorizationCode: * authorizationUrl: https://example.com/api/oauth/dialog * tokenUrl: https://example.com/api/oauth/token * scopes: * write:pets: modify pets in your account * read:pets: read your pets * ``` */ export interface OAuthFlowObject extends SpecificationExtensions { /** * **REQUIRED (`"implicit"`, `"authorizationCode"`)**. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. */ authorizationUrl?: string; /** * The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. */ refreshUrl?: string; /** * **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. */ scopes: Record; /** * **REQUIRED (`"password"`, `"clientCredentials"`, `"authorizationCode"`)**. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. */ tokenUrl?: string; } /** * Allows configuration of the supported OAuth Flows. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. */ export interface OAuthFlowsObject extends SpecificationExtensions { /** * Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. */ authorizationCode?: OAuthFlowObject; /** * Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. */ clientCredentials?: OAuthFlowObject; /** * Configuration for the OAuth Implicit flow */ implicit?: OAuthFlowObject; /** * Configuration for the OAuth Resource Owner Password flow */ password?: OAuthFlowObject; } /** * Describes a single API operation on a path. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * tags: * - pet * summary: Updates a pet in the store with form data * operationId: updatePetWithForm * parameters: * - name: petId * in: path * description: ID of pet that needs to be updated * required: true * schema: * type: string * requestBody: * content: * 'application/x-www-form-urlencoded': * schema: * type: object * properties: * name: * description: Updated name of the pet * type: string * status: * description: Updated status of the pet * type: string * required: * - status * responses: * '200': * description: Pet updated. * content: * 'application/json': {} * 'application/xml': {} * '405': * description: Method Not Allowed * content: * 'application/json': {} * 'application/xml': {} * security: * - petstore_auth: * - write:pets * - read:pets * ``` */ export interface OperationObject extends SpecificationExtensions { /** * A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object Callback Object} that describes a request that may be initiated by the API provider and the expected responses. */ callbacks?: Record; /** * Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. */ deprecated?: boolean; /** * A verbose explanation of the operation behavior. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Additional external documentation for this operation. */ externalDocs?: ExternalDocumentationObject; /** * Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. */ operationId?: string; /** * A list of parameters that are applicable for this operation. If a parameter is already defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathItemParameters Path Item}, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterName name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn location}. The list can use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#reference-object Reference Object} to link to parameters that are defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#componentsParameters OpenAPI Object's components/parameters}. */ parameters?: ReadonlyArray; /** * The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP 1.1 specification {@link https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.1 RFC7231} has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as {@link https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.1 GET}, {@link https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.2 HEAD} and {@link https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.5 DELETE}), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible. */ requestBody?: RequestBodyObject | ReferenceObject; /** * The list of possible responses as they are returned from executing this operation. */ responses?: ResponsesObject; /** * A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasSecurity `security`}. To remove a top-level security declaration, an empty array can be used. */ security?: ReadonlyArray; /** * An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. */ servers?: ReadonlyArray; /** * A short summary of what the operation does. */ summary?: string; /** * A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. */ tags?: ReadonlyArray; /** * A list of code samples associated with an operation. */ 'x-codeSamples'?: ReadonlyArray; } /** * Describes a single operation parameter. * * A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterName name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn location}. * * **Parameter Locations** * * There are four possible parameter locations specified by the `in` field: * * - path - Used together with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-templating Path Templating}, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. * - query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. * - header - Custom headers that are expected as part of the request. Note that {@link https://datatracker.ietf.org/doc/html/rfc7230#page-22 RFC7230} states header names are case insensitive. * - cookie - Used to pass a specific cookie value to the API. * * The rules for serialization of the parameter are specified in one of two ways. For simpler scenarios, a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterSchema `schema`} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle `style`} can describe the structure and syntax of the parameter. * * For more complex scenarios, the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterContent `content`} property can define the media type and schema of the parameter. A parameter MUST contain either a `schema` property, or a `content` property, but not both. When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * A header parameter with an array of 64 bit integer numbers: * * @example * ```yaml * name: token * in: header * description: token to be passed as a header * required: true * schema: * type: array * items: * type: integer * format: int64 * style: simple * ``` * * A path parameter of a string value: * * @example * ```yaml * name: username * in: path * description: username to fetch * required: true * schema: * type: string * ``` * * An optional query parameter of a string value, allowing multiple values by repeating the query parameter: * * @example * ```yaml * name: id * in: query * description: ID of the object to fetch * required: false * schema: * type: array * items: * type: string * style: form * explode: true * ``` * * A free-form query parameter, allowing undefined parameters of a specific type: * * @example * ```yaml * in: query * name: freeForm * schema: * type: object * additionalProperties: * type: integer * style: form * ``` * * A complex parameter using `content` to define serialization: * * @example * ```yaml * in: query * name: coordinates * content: * application/json: * schema: * type: object * required: * - lat * - long * properties: * lat: * type: number * long: * type: number * ``` */ export interface ParameterObject extends SpecificationExtensions { /** * Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle `style`} is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. */ allowEmptyValue?: boolean; /** * Determines whether the parameter value SHOULD allow reserved characters, as defined by {@link https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 RFC3986} `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. */ allowReserved?: boolean; /** * A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. */ content?: Record; /** * Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. */ deprecated?: boolean; /** * A brief description of the parameter. This could contain examples of use. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. */ example?: unknown; /** * Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. */ examples?: Record; /** * When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle `style`} is `form`, the default value is `true`. For all other styles, the default value is `false`. */ explode?: boolean; /** * **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. */ in: 'cookie' | 'header' | 'path' | 'query'; /** * **REQUIRED**. The name of the parameter. Parameter names are _case sensitive_. * - If {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn `in`} is `"path"`, the `name` field MUST correspond to a template expression occurring within the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsPath path} field in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#paths-object Paths Object}. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-templating Path Templating} for further information. * - If {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn `in`} is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored. * - For all other cases, the `name` corresponds to the parameter name used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn `in`} property. */ name: string; /** * Determines whether this parameter is mandatory. If the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn parameter location} is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. */ required?: boolean; /** * The schema defining the type used for the parameter. */ schema?: SchemaObject; /** * Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. */ style?: | 'deepObject' | 'form' | 'label' | 'matrix' | 'pipeDelimited' | 'simple' | 'spaceDelimited'; } /** * Describes the operations available on a single path. A Path Item MAY be empty, due to {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-filtering ACL constraints}. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * get: * description: Returns pets based on ID * summary: Find pets by ID * operationId: getPetsById * responses: * '200': * description: pet response * content: * '*\/*': * schema: * type: array * items: * $ref: '#/components/schemas/Pet' * default: * description: error payload * content: * 'text/html': * schema: * $ref: '#/components/schemas/ErrorModel' * parameters: * - name: id * in: path * description: ID of pet to use * required: true * schema: * type: array * items: * type: string * style: simple * ``` */ export interface PathItemObject extends SpecificationExtensions { /** * Allows for a referenced definition of this path item. The referenced structure MUST be in the form of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object Path Item Object}. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#relative-references-in-uris Relative References}. */ $ref?: string; /** * A definition of a DELETE operation on this path. */ delete?: OperationObject; /** * An optional, string description, intended to apply to all operations in this path. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * A definition of a GET operation on this path. */ get?: OperationObject; /** * A definition of a HEAD operation on this path. */ head?: OperationObject; /** * A definition of a OPTIONS operation on this path. */ options?: OperationObject; /** * A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterName name} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn location}. The list can use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#reference-object Reference Object} to link to parameters that are defined at the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#componentsParameters OpenAPI Object's components/parameters}. */ parameters?: ReadonlyArray; /** * A definition of a PATCH operation on this path. */ patch?: OperationObject; /** * A definition of a POST operation on this path. */ post?: OperationObject; /** * A definition of a PUT operation on this path. */ put?: OperationObject; /** * An alternative `server` array to service all operations in this path. */ servers?: ReadonlyArray; /** * An optional, string summary, intended to apply to all operations in this path. */ summary?: string; /** * A definition of a TRACE operation on this path. */ trace?: OperationObject; } /** * Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-object `Server Object`} in order to construct the full URL. The Paths MAY be empty, due to {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-filtering Access Control List (ACL) constraints}. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * **Path Templating Matching** * * Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: * * ``` * /pets/{petId} * /pets/mine * ``` * * The following paths are considered identical and invalid: * * ``` * /pets/{petId} * /pets/{name} * ``` * * The following may lead to ambiguous resolution: * * ``` * /{entity}/me * /books/{id} * ``` * * **Paths Object Example** * * ```yaml * /pets: * get: * description: Returns all pets from the system that the user has access to * responses: * '200': * description: A list of pets. * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/pet' * ``` */ export interface PathsObject extends SpecificationExtensions { /** * A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-object `Server Object`}'s `url` field in order to construct the full URL. {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-templating Path templating} is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. */ [path: `/${string}`]: PathItemObject; } /** * A simple object to allow referencing other components in the OpenAPI document, internally and externally. * * The `$ref` string value contains a URI {@link https://datatracker.ietf.org/doc/html/rfc3986 RFC3986}, which identifies the location of the value being referenced. * * See the rules for resolving {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#relative-references-in-uris Relative References}. * * This object cannot be extended with additional properties and any properties added SHALL be ignored. * * Note that this restriction on additional properties is a difference between Reference Objects and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object `Schema Objects`} that contain a `$ref` keyword. * * Reference Object Example * * @example * ```yaml * $ref: '#/components/schemas/Pet' * ``` * * Relative Schema Document Example * * @example * ```yaml * $ref: Pet.yaml * ``` * * Relative Documents With Embedded Schema Example * * @example * ```yaml * $ref: definitions.yaml#/Pet * ``` */ export interface ReferenceObject { /** * **REQUIRED**. The reference identifier. This MUST be in the form of a URI. */ $ref: string; /** * A description which by default SHOULD override that of the referenced component. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect. */ description?: string; /** * A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect. */ summary?: string; } /** * Describes a single request body. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * **Request Body Examples** * * A request body with a referenced model definition. * * ```yaml * description: user to add to the system * content: * 'application/json': * schema: * $ref: '#/components/schemas/User' * examples: * user: * summary: User Example * externalValue: 'https://foo.bar/examples/user-example.json' * 'application/xml': * schema: * $ref: '#/components/schemas/User' * examples: * user: * summary: User example in XML * externalValue: 'https://foo.bar/examples/user-example.xml' * 'text/plain': * examples: * user: * summary: User example in Plain text * externalValue: 'https://foo.bar/examples/user-example.txt' * '*\/*': * examples: * user: * summary: User example in other format * externalValue: 'https://foo.bar/examples/user-example.whatever' * ``` * * A body parameter that is an array of string values: * * ```yaml * description: user to add to the system * required: true * content: * text/plain: * schema: * type: array * items: * type: string * ``` */ export interface RequestBodyObject extends SpecificationExtensions { /** * **REQUIRED**. The content of the request body. The key is a media type or {@link https://tools.ietf.org/html/rfc7231#appendix-D media type range} and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* */ content: Record; /** * A brief description of the request body. This could contain examples of use. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Determines if the request body is required in the request. Defaults to `false`. */ required?: boolean; } /** * Describes a single response from an API Operation, including design-time, static `links` to operations based on the response. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * Response of an array of a complex type: * * @example * ```yaml * description: A complex object array response * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/VeryComplexType' * ``` * * Response with a string type: * * @example * ```yaml * description: A simple string response * content: * text/plain: * schema: * type: string * ``` * * Plain text response with headers: * * @example * ```yaml * description: A simple string response * content: * text/plain: * schema: * type: string * example: 'whoa!' * headers: * X-Rate-Limit-Limit: * description: The number of allowed requests in the current period * schema: * type: integer * X-Rate-Limit-Remaining: * description: The number of remaining requests in the current period * schema: * type: integer * X-Rate-Limit-Reset: * description: The number of seconds left in the current period * schema: * type: integer * ``` * * Response with no return value: * * @example * ```yaml * description: object created * ``` */ export interface ResponseObject extends SpecificationExtensions { /** * A map containing descriptions of potential response payloads. The key is a media type or {@link https://datatracker.ietf.org/doc/html/rfc7231#appendix-D media type range} and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* */ content?: Record; /** * **REQUIRED**. A description of the response. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description: string; /** * Maps a header name to its definition. {@link https://datatracker.ietf.org/doc/html/rfc7230#page-22 RFC7230} states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. */ headers?: Record; /** * A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#components-object Component Objects}. */ links?: Record; } /** * A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. * * The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors. * * The `default` MAY be used as a default response object for all HTTP codes that are not covered individually by the `Responses Object`. * * The `Responses Object` MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * A 200 response for a successful operation and a default response for others (implying an error): * * @example * ```yaml * '200': * description: a pet to be returned * content: * application/json: * schema: * $ref: '#/components/schemas/Pet' * default: * description: Unexpected error * content: * application/json: * schema: * $ref: '#/components/schemas/ErrorModel' * ``` */ export interface ResponsesObject extends SpecificationExtensions { /** * Any {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#http-status-codes HTTP status code} can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. */ [httpStatusCode: string]: ResponseObject | ReferenceObject | undefined | unknown; /** * The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. */ default?: ResponseObject | ReferenceObject; } /** * The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is a superset of the {@link https://tools.ietf.org/html/draft-bhutton-json-schema-00 JSON Schema Specification Draft 2020-12}. * * For more information about the properties, see {@link https://tools.ietf.org/html/draft-bhutton-json-schema-00 JSON Schema Core} and {@link https://tools.ietf.org/html/draft-bhutton-json-schema-validation-00 JSON Schema Validation}. * * Unless stated otherwise, the property definitions follow those of JSON Schema and do not add any additional semantics. Where JSON Schema indicates that behavior is defined by the application (e.g. for annotations), OAS also defers the definition of semantics to the application consuming the OpenAPI document. * * **Properties** * * The OpenAPI Schema Object {@link https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.3.3 dialect} is defined as requiring the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-20 OAS base vocabulary}, in addition to the vocabularies as specified in the JSON Schema draft 2020-12 {@link https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8 general purpose meta-schema}. * * The OpenAPI Schema Object dialect for this version of the specification is identified by the URI `https://spec.openapis.org/oas/3.1/dialect/base` (the "OAS dialect schema id"). * * The following properties are taken from the JSON Schema specification but their definitions have been extended by the OAS: * * - description - {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. * - format - See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#dataTypeFormat Data Type Formats} for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. * * In addition to the JSON Schema properties comprising the OAS dialect, the Schema Object supports keywords from any other vocabularies, or entirely arbitrary properties. * * The OpenAPI Specification's base vocabulary is comprised of the following keywords: * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}, though as noted, additional properties MAY omit the `x-` prefix within this object. */ export type SchemaObject = JsonSchemaDraft2020_12 & SpecificationExtensions; /** * Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#componentsSecuritySchemes Security Schemes} under the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#components-object Components Object}. * * Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. * * When a list of Security Requirement Objects is defined on the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object OpenAPI Object} or {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object Operation Object}, only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. * * Non-OAuth2 Security Requirement * * @example * ```yaml * api_key: [] * ``` * * OAuth2 Security Requirement * * @example * ```yaml * petstore_auth: * - write:pets * - read:pets * ``` * * Optional OAuth2 Security * * @example * ```yaml * security: * - {} * - petstore_auth: * - write:pets * - read:pets * ``` */ export interface SecurityRequirementObject { /** * Each name MUST correspond to a security scheme which is declared in the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#componentsSecuritySchemes Security Schemes} under the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#components-object Components Object}. If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band. */ [name: string]: ReadonlyArray; } /** * Defines a security scheme that can be used by the operations. * * Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in {@link https://tools.ietf.org/html/rfc6749 RFC6749}, and {@link https://tools.ietf.org/html/draft-ietf-oauth-discovery-06 OpenID Connect Discovery}. Please note that as of 2020, the implicit flow is about to be deprecated by {@link https://tools.ietf.org/html/draft-ietf-oauth-security-topics OAuth 2.0 Security Best Current Practice}. Recommended for most use case is Authorization Code Grant flow with PKCE. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * **Security Scheme Object Example** * * **Basic Authentication Sample** * * ```yaml * type: http * scheme: basic * ``` * * **API Key Sample** * * ```yaml * type: apiKey * name: api_key * in: header * ``` * * **JWT Bearer Sample** * * ```yaml * type: http * scheme: bearer * bearerFormat: JWT * ``` * * **Implicit OAuth2 Sample** * * ```yaml * type: oauth2 * flows: * implicit: * authorizationUrl: https://example.com/api/oauth/dialog * scopes: * write:pets: modify pets in your account * read:pets: read your pets * ``` */ export type SecuritySchemeObject = SpecificationExtensions & { /** * A description for security scheme. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; } & ( | { /** * **REQUIRED**. The location of the API key. Valid values are "query", "header" or "cookie". */ in: 'cookie' | 'header' | 'query'; /** * **REQUIRED**. The name of the header, query or cookie parameter to be used. */ name: string; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. */ type: 'apiKey'; } | { /** * A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. */ bearerFormat?: string; /** * **REQUIRED**. The name of the HTTP Authorization scheme to be used in the {@link https://tools.ietf.org/html/rfc7235#section-5.1 Authorization header as defined in RFC7235}. The values used SHOULD be registered in the {@link https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml IANA Authentication Scheme registry}. */ scheme: string; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. */ type: 'http'; } | { /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. */ type: 'mutualTLS'; } | { /** * **REQUIRED**. An object containing configuration information for the flow types supported. */ flows: OAuthFlowsObject; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. */ type: 'oauth2'; } | { /** * **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. The OpenID Connect standard requires the use of TLS. */ openIdConnectUrl: string; /** * **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. */ type: 'openIdConnect'; } ); /** * An object representing a Server. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * url: https://development.gigantic-server.com/v1 * description: Development server * ``` */ export interface ServerObject extends SpecificationExtensions { /** * An optional string describing the host designated by the URL. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. */ url: string; /** * A map between a variable name and its value. The value is used for substitution in the server's URL template. */ variables?: Record; } /** * An object representing a Server Variable for server URL template substitution. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. */ export interface ServerVariableObject extends SpecificationExtensions { /** * **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object Schema Object's} treatment of default values, because in those cases parameter values are optional. If the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#serverVariableEnum `enum`} is defined, the value MUST exist in the enum's values. */ default: string; /** * An optional description for the server variable. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty. */ enum?: ReadonlyArray; } /** * Adds metadata to a single tag that is used by the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object Operation Object}. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * @example * ```yaml * name: pet * description: Pets operations * ``` */ export interface TagObject extends SpecificationExtensions { /** * A description for the tag. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation. */ description?: string; /** * Additional external documentation for this tag. */ externalDocs?: ExternalDocumentationObject; /** * **REQUIRED**. The name of the tag. */ name: string; } /** * A metadata object that allows for more fine-tuned XML model definitions. * * When using arrays, XML element names are _not_ inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. See examples for expected behavior. * * This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}. * * **XML Object Examples** * * The examples of the XML object definitions are included inside a property definition of a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object Schema Object} with a sample of the XML representation of it. * * **No XML Element** * * Basic string property: * * ```yaml * animals: * type: string * ``` * * ```xml * ... * ``` * * Basic string array property ({@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xmlWrapped `wrapped`} is `false` by default): * * ```yaml * animals: * type: array * items: * type: string * ``` * * ```xml * ... * ... * ... * ``` * * **XML Name Replacement** * * ```yaml * animals: * type: string * xml: * name: animal * ``` * * ```xml * ... * ``` * * **XML Attribute, Prefix and Namespace** * * In this example, a full model definition is shown. * * ```yaml * Person: * type: object * properties: * id: * type: integer * format: int32 * xml: * attribute: true * name: * type: string * xml: * namespace: https://example.com/schema/sample * prefix: sample * ``` * * ```xml * * example * * ``` * * **XML Arrays** * * Changing the element names: * * ```yaml * animals: * type: array * items: * type: string * xml: * name: animal * ``` * * ```xml * value * value * ``` * * The external `name` property has no effect on the XML: * * ```yaml * animals: * type: array * items: * type: string * xml: * name: animal * xml: * name: aliens * ``` * * ```xml * value * value * ``` * * Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: * * ```yaml * animals: * type: array * items: * type: string * xml: * wrapped: true * ``` * * ```xml * * value * value * * ``` * * To overcome the naming problem in the example above, the following definition can be used: * * ```yaml * animals: * type: array * items: * type: string * xml: * name: animal * xml: * wrapped: true * ``` * * ```xml * * value * value * * ``` * * Affecting both internal and external names: * * ```yaml * animals: * type: array * items: * type: string * xml: * name: animal * xml: * name: aliens * wrapped: true * ``` * * ```xml * * value * value * * ``` * * If we change the external element but not the internal ones: * * ```yaml * animals: * type: array * items: * type: string * xml: * name: aliens * wrapped: true * ``` * * ```xml * * value * value * * ``` */ export interface XMLObject extends SpecificationExtensions { /** * Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. */ attribute?: boolean; /** * Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. */ name?: string; /** * The URI of the namespace definition. This MUST be in the form of an absolute URI. */ namespace?: string; /** * The prefix to be used for the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xmlName name}. */ prefix?: string; /** * MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). */ wrapped?: boolean; } ================================================ FILE: packages/shared/src/openApi/__tests__/index.test.ts ================================================ import { Logger } from '@hey-api/codegen-core'; import type { AnyConfig } from '../../config/shared'; import { Context } from '../../ir/context'; import { parseOpenApiSpec } from '..'; import { type OpenApiV3_0_X, parseV3_0_X } from '../3.0.x'; import { type OpenApiV3_1_X, parseV3_1_X } from '../3.1.x'; vi.mock('../3.0.x', () => ({ parseV3_0_X: vi.fn(), })); vi.mock('../3.1.x', () => ({ parseV3_1_X: vi.fn(), })); vi.mock('../../utils/config', () => { const config: Partial = { logs: { file: false, level: 'silent', path: '', }, pluginOrder: [], }; return { getConfig: () => config, }; }); describe('OpenAPI parser', () => { afterEach(() => { vi.restoreAllMocks(); }); it('handles OpenAPI 3.0.0', () => { const spec: OpenApiV3_0_X = { info: { title: '', version: '1', }, openapi: '3.0.0', paths: {}, }; const context = new Context({ config: { input: [], logs: {}, // @ts-expect-error output: { case: undefined, entryFile: false, path: '', }, // @ts-expect-error parser: {}, pluginOrder: [], plugins: {}, }, dependencies: {}, logger: new Logger(), spec, }); parseOpenApiSpec(context); expect(parseV3_0_X).toHaveBeenCalled(); }); it('handles OpenAPI 3.0.1', () => { const spec: OpenApiV3_0_X = { info: { title: '', version: '1', }, openapi: '3.0.1', paths: {}, }; const context = new Context({ config: { input: [], logs: {}, // @ts-expect-error output: { case: undefined, entryFile: false, path: '', }, // @ts-expect-error parser: {}, pluginOrder: [], plugins: {}, }, dependencies: {}, logger: new Logger(), spec, }); parseOpenApiSpec(context); expect(parseV3_0_X).toHaveBeenCalled(); }); it('handles OpenAPI 3.0.2', () => { const spec: OpenApiV3_0_X = { info: { title: '', version: '1', }, openapi: '3.0.2', paths: {}, }; const context = new Context({ config: { input: [], logs: {}, // @ts-expect-error output: { case: undefined, entryFile: false, path: '', }, // @ts-expect-error parser: {}, pluginOrder: [], plugins: {}, }, dependencies: {}, logger: new Logger(), spec, }); parseOpenApiSpec(context); expect(parseV3_0_X).toHaveBeenCalled(); }); it('handles OpenAPI 3.0.3', () => { const spec: OpenApiV3_0_X = { info: { title: '', version: '1', }, openapi: '3.0.3', paths: {}, }; const context = new Context({ config: { input: [], logs: {}, // @ts-expect-error output: { case: undefined, entryFile: false, path: '', }, // @ts-expect-error parser: {}, pluginOrder: [], plugins: {}, }, dependencies: {}, logger: new Logger(), spec, }); parseOpenApiSpec(context); expect(parseV3_0_X).toHaveBeenCalled(); }); it('handles OpenAPI 3.0.4', () => { const spec: OpenApiV3_0_X = { info: { title: '', version: '1', }, openapi: '3.0.4', paths: {}, }; const context = new Context({ config: { input: [], logs: {}, // @ts-expect-error output: { case: undefined, entryFile: false, path: '', }, // @ts-expect-error parser: {}, pluginOrder: [], plugins: {}, }, dependencies: {}, logger: new Logger(), spec, }); parseOpenApiSpec(context); expect(parseV3_0_X).toHaveBeenCalled(); }); it('handles OpenAPI 3.1.0', () => { const spec: OpenApiV3_1_X = { info: { title: '', version: '1', }, openapi: '3.1.0', }; const context = new Context({ config: { input: [], logs: {}, // @ts-expect-error output: { case: undefined, entryFile: false, path: '', }, // @ts-expect-error parser: {}, pluginOrder: [], plugins: {}, }, dependencies: {}, logger: new Logger(), spec, }); parseOpenApiSpec(context); expect(parseV3_1_X).toHaveBeenCalled(); }); it('handles OpenAPI 3.1.1', () => { const spec: OpenApiV3_1_X = { info: { title: '', version: '1', }, openapi: '3.1.1', }; const context = new Context({ config: { input: [], logs: {}, // @ts-expect-error output: { case: undefined, entryFile: false, path: '', }, // @ts-expect-error parser: {}, pluginOrder: [], plugins: {}, }, dependencies: {}, logger: new Logger(), spec, }); parseOpenApiSpec(context); expect(parseV3_1_X).toHaveBeenCalled(); }); }); ================================================ FILE: packages/shared/src/openApi/__tests__/utils.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import yaml from 'yaml'; export const getSpecsPath = (): string => path.join(__dirname, '..', '..', '..', '..', '..', 'specs'); export const specFileToJson = (file: string) => { const raw = fs.readFileSync(file, 'utf8'); const ext = path.extname(file).toLowerCase(); return ext === '.json' ? JSON.parse(raw) : yaml.parse(raw); }; ================================================ FILE: packages/shared/src/openApi/index.ts ================================================ import { satisfies } from '../config/utils/dependencies'; import type { Context } from '../ir/context'; import { parseV2_0_X } from './2.0.x'; import { parseV3_0_X } from './3.0.x'; import { parseV3_1_X } from './3.1.x'; import type { OpenApi } from './types'; /** * @internal * Parse the resolved OpenAPI specification. This will populate and return * `context` with intermediate representation obtained from the parsed spec. */ export function parseOpenApiSpec(context: Context): Context { if ('swagger' in context.spec) { parseV2_0_X(context as Context); return context; } if (satisfies(context.spec.openapi, '>=3.0.0 <3.1.0')) { parseV3_0_X(context as Context); return context; } if (satisfies(context.spec.openapi, '>=3.1.0')) { parseV3_1_X(context as Context); return context; } throw new Error('Unsupported OpenAPI specification'); } ================================================ FILE: packages/shared/src/openApi/shared/graph/meta.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import type { Graph } from '../../../graph'; import { createOperationKey } from '../../../ir/operation'; import { jsonPointerToPath } from '../../../utils/ref'; import { addNamespace, stringToNamespace } from '../utils/filter'; import { httpMethods } from '../utils/operation'; export type ResourceMetadata = { operations: Map< string, { dependencies: Set; deprecated: boolean; tags: Set; } >; parameters: Map< string, { dependencies: Set; deprecated: boolean; } >; requestBodies: Map< string, { dependencies: Set; deprecated: boolean; } >; responses: Map< string, { dependencies: Set; deprecated: boolean; } >; schemas: Map< string, { dependencies: Set; deprecated: boolean; } >; }; /** * Builds a resource metadata map from a Graph, matching the old Graph interface * for compatibility with filtering code. */ export const buildResourceMetadata = ( graph: Graph, logger: Logger, ): { resourceMetadata: ResourceMetadata; } => { const eventBuildResourceMetadata = logger.timeEvent('build-resource-metadata'); const resourceMetadata: ResourceMetadata = { operations: new Map(), parameters: new Map(), requestBodies: new Map(), responses: new Map(), schemas: new Map(), }; const getDependencies = (pointer: string): Set => { const dependencies = new Set(); const nodeDependencies = graph.transitiveDependencies.get(pointer); if (nodeDependencies?.size) { for (const dependency of nodeDependencies) { const path = jsonPointerToPath(dependency); const type = path[path.length - 2]; const name = path[path.length - 1]; if (type && name) { const namespace = stringToNamespace(type); if (namespace === 'unknown') { console.warn(`unsupported type: ${type}`); } dependencies.add(addNamespace(namespace, name)); } } } return dependencies; }; // Process each node to find top-level resources for (const [pointer, nodeInfo] of graph.nodes) { // const node = nodeInfo.node as Record; const path = jsonPointerToPath(pointer); // OpenAPI 3.x if (path[0] === 'components') { if (path.length === 3) { if (path[1] === 'schemas') { // Schema: #/components/schemas/{name} const name = path[path.length - 1]!; resourceMetadata.schemas.set(addNamespace('schema', name), { dependencies: getDependencies(pointer), deprecated: nodeInfo.deprecated ?? false, }); } else if (path[1] === 'parameters') { // Parameter: #/components/parameters/{name} const name = path[path.length - 1]!; resourceMetadata.parameters.set(addNamespace('parameter', name), { dependencies: getDependencies(pointer), deprecated: nodeInfo.deprecated ?? false, }); } else if (path[1] === 'requestBodies') { // RequestBody: #/components/requestBodies/{name} const name = path[path.length - 1]!; resourceMetadata.requestBodies.set(addNamespace('body', name), { dependencies: getDependencies(pointer), deprecated: nodeInfo.deprecated ?? false, }); } else if (path[1] === 'responses') { // Response: #/components/responses/{name} const name = path[path.length - 1]!; resourceMetadata.responses.set(addNamespace('response', name), { dependencies: getDependencies(pointer), deprecated: nodeInfo.deprecated ?? false, }); } } continue; } if (path[0] === 'paths') { if (path.length === 3 && httpMethods.includes(path[2] as (typeof httpMethods)[number])) { // Operation: #/paths/{path}/{method} const method = path[path.length - 1]!; const operationPath = path.slice(1, -1).join('/'); const operationKey = createOperationKey({ method, path: operationPath, }); resourceMetadata.operations.set(addNamespace('operation', operationKey), { dependencies: getDependencies(pointer), deprecated: nodeInfo.deprecated ?? false, tags: nodeInfo.tags ?? new Set(), }); } continue; } // OpenAPI 2.0 if (path[0] === 'definitions') { if (path.length === 2) { // Schema: #/definitions/{name} const name = path[path.length - 1]!; resourceMetadata.schemas.set(addNamespace('schema', name), { dependencies: getDependencies(pointer), deprecated: nodeInfo.deprecated ?? false, }); } continue; } } eventBuildResourceMetadata.timeEnd(); return { resourceMetadata }; }; ================================================ FILE: packages/shared/src/openApi/shared/locations/index.ts ================================================ export type { OperationPathStrategy, OperationsStrategy, OperationStructureStrategy, } from './operation'; export { OperationPath, OperationStrategy } from './operation'; ================================================ FILE: packages/shared/src/openApi/shared/locations/operation.ts ================================================ import type { StructureLocation } from '@hey-api/codegen-core'; import type { IR } from '../../../ir/types'; /** * A function that derives path segments from an operation. * * Used by location strategies to build paths within containers. */ export type OperationPathStrategy = (operation: IR.OperationObject) => ReadonlyArray; /** * A function that determines where an operation appears in the structure. * * Returns one or more locations, each with a full path. */ export type OperationStructureStrategy = ( operation: IR.OperationObject, ) => ReadonlyArray; export type OperationsStrategy = 'byTags' | 'flat' | 'single' | OperationStructureStrategy; /** * Built-in strategies for operations. */ export const OperationStrategy = { /** * Creates one root container per operation tag. * * Operations with multiple tags appear in multiple root containers. * Operations without tags use the fallback root container. * * @example * // Operation with tags: ['users', 'admin'] * // Path function returns: ['list'] * // Result: [{ path: ['users', 'list'], shell }, { path: ['admin', 'list'], shell }] */ byTags: (config: { /** * Root name for operations without tags. */ fallback: string; /** * Derives path segments from the operation. * * @default OperationPath.id() */ path?: OperationPathStrategy; }): OperationStructureStrategy => (operation) => { const tags = operation.tags && operation.tags.length > 0 ? operation.tags : [config.fallback]; const path = config.path ?? OperationPath.id(); const pathSegments = path(operation); return tags.map((tag) => [tag, ...pathSegments]); }, /** * Creates flat functions without any container. * * Each operation becomes a standalone function at the root level. * No shell is applied. * * @example * // Operation id: 'getUsers' * // Result: [{ path: ['getUsers'] }] */ flat: (config?: { /** * Derives path segments within the root from the operation. * * @default OperationPath.id() */ path?: OperationPathStrategy; }): OperationStructureStrategy => (operation) => { const path = config?.path ?? OperationPath.id(); const pathSegments = path(operation); return [[pathSegments[pathSegments.length - 1]!]]; }, /** * Places all operations under a single root container. * * @example * // Root: 'Sdk', path function returns: ['users', 'list'] * // Result: [{ path: ['Sdk', 'users', 'list'], shell }] */ single: (config: { /** * Derives path segments within the root from the operation. * * @default OperationPath.id() */ path?: OperationPathStrategy; /** * Name of the container. */ root: string; }): OperationStructureStrategy => (operation) => { const path = config.path ?? OperationPath.id(); const pathSegments = path(operation); return [[config.root, ...pathSegments]]; }, }; /** * Built-in path derivation helpers for operations. */ export const OperationPath = { /** * Splits operationId by delimiters to create nested paths. * * @example * // operationId: 'users.accounts.list' * // Result: ['users', 'accounts', 'list'] * * @example * // operationId: 'users/accounts/getAll' * // Result: ['users', 'accounts', 'getAll'] */ fromOperationId: (config?: { /** * Pattern to split operationId. * * @default /[./]/ */ delimiters?: RegExp; /** * Fallback strategy if operationId is missing. * * @default OperationPath.id() */ fallback?: OperationPathStrategy; }): OperationPathStrategy => (operation) => { const fallback = config?.fallback ?? OperationPath.id(); if (!operation.operationId) return fallback(operation); const delimiters = config?.delimiters ?? /[./]/; const segments = operation.operationId.split(delimiters).filter(Boolean); return segments.length === 0 ? fallback(operation) : segments; }, /** * Splits path by delimiters to create nested paths. * * Can include the method as a prefix or suffix segment. * * @example * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\/{}]+/, methodPosition: 'none' * // Result: ['users', 'id', 'accounts'] * * @example * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\/{}]+/, methodPosition: 'prefix' * // Result: ['get', 'users', 'id', 'accounts'] * * @example * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\/{}]+/, methodPosition: 'suffix' * // Result: ['users', 'id', 'accounts', 'get'] */ fromPath: (config?: { /** * Pattern to split the path. * * @default /[./]/ */ delimiters?: RegExp; /** * Position of the method segment. * * @default 'none' */ methodPosition?: 'prefix' | 'suffix'; }): OperationPathStrategy => (operation) => { const delimiters = config?.delimiters ?? /[./]/; const segments = operation.path.split(delimiters).filter(Boolean); switch (config?.methodPosition) { case 'prefix': segments.unshift(operation.method.toLowerCase()); break; case 'suffix': segments.push(operation.method.toLowerCase()); break; default: break; } return segments; }, /** * Uses operation.id as a single path segment. * * @example * // operation.id: 'getUserById' * // Result: ['getUserById'] */ id: (): OperationPathStrategy => (operation) => [operation.id], }; ================================================ FILE: packages/shared/src/openApi/shared/transforms/enums.ts ================================================ import type { Parser } from '../../../config/parser/types'; import { applyNaming } from '../../../utils/naming/naming'; import { jsonPointerToPath } from '../../../utils/ref'; import { deepClone } from '../utils/schema'; import { childSchemaRelationships } from '../utils/schemaChildRelationships'; import { getSchemasObject } from '../utils/transforms'; import { getUniqueComponentName, isPathRootSchema, specToSchemasPointerNamespace } from './utils'; type EnumsConfig = Parser['transforms']['enums']; /** * Generate a unique, structural signature for an enum schema for deduplication. * Only considers 'type' and sorted 'enum' values, ignoring other fields. * * @param schema - The schema object to analyze * @returns A string signature if the schema is an enum, otherwise undefined */ const getEnumSignature = (schema: unknown): string | undefined => { if ( !schema || typeof schema !== 'object' || !('enum' in schema) || !(schema.enum instanceof Array) ) { return; } // Use type + sorted enum values for signature const type = ('type' in schema ? schema.type : undefined) || ''; const values = [...schema.enum].sort(); return JSON.stringify({ type, values }); }; type NodeInfo = { key: string | number | null; node: unknown; parent: unknown; path: ReadonlyArray; }; /** * Recursively walk all schemas in the OpenAPI spec, visiting every object/array * that could contain an enum. Calls the visitor with node info for each. * * @param key - The key of the current node * @param node - The current node * @param parent - The parent node * @param path - The path to the current node * @param visitor - Function to call for each visited node */ const walkSchemas = ({ key, node, parent, path, visitor, }: NodeInfo & { visitor: (nodeInfo: NodeInfo) => void; }) => { if (!node || typeof node !== 'object' || node instanceof Array) return; const value = node as Record; if ( 'type' in value || 'enum' in value || childSchemaRelationships.some(([keyword]) => keyword in value) ) { visitor({ key, node, parent, path }); } for (const [k, v] of Object.entries(value)) { if (typeof v === 'object' && v !== null) { if (v instanceof Array) { v.forEach((item, index) => walkSchemas({ key: index, node: item, parent: v, path: [...path, k, index], visitor, }), ); } else { walkSchemas({ key: k, node: v, parent: node, path: [...path, k], visitor, }); } } } }; /** * Inlines all root/top-level enums by replacing $refs to them with the actual enum schema, * and then removes the now-unreferenced root enums from the schemas object. * * @param spec - The OpenAPI spec object to transform */ const inlineMode = ({ spec }: { spec: unknown }) => { const schemasObj = getSchemasObject(spec); if (!schemasObj) { return; } const schemasPointerNamespace = specToSchemasPointerNamespace(spec); // Collect all root enums const rootEnums: Record = {}; for (const [name, schema] of Object.entries(schemasObj)) { const signature = getEnumSignature(schema); if (signature) { rootEnums[`${schemasPointerNamespace}${name}`] = schema; } } // Walk the spec and replace $refs to root enums with inline enum schemas const replaceEnumRefs = (node: unknown) => { if (node instanceof Array) { node.forEach(replaceEnumRefs); } else if (node && typeof node === 'object') { for (const [k, v] of Object.entries(node)) { if (k === '$ref' && typeof v === 'string' && v in rootEnums) { // Replace $ref with a deep clone of the enum schema Object.assign(node, deepClone(rootEnums[v])); delete (node as Record)['$ref']; } else { replaceEnumRefs(v); } } } }; replaceEnumRefs(spec); // Remove unreferenced root enums for (const pointer of Object.keys(rootEnums)) { const path = jsonPointerToPath(pointer); const name = path[path.length - 1]!; if (name) { delete schemasObj[name]; } } }; /** * Promotes all inline enums to reusable root components (if mode is 'root'), * deduplicates by signature, and replaces inline enums with $refs. * * Naming, casing, and deduplication are controlled by the enums transform config. * Existing root enums are reused if structurally identical. * * @param spec - The OpenAPI spec object to transform * @param config - The enums transform config */ const rootMode = ({ config, spec }: { config: EnumsConfig; spec: unknown }) => { const schemasObj = getSchemasObject(spec); if (!schemasObj) { return; } // Build a map of existing root enum signatures to their names for deduplication const rootEnumSignatures: Record = {}; for (const [name, schema] of Object.entries(schemasObj)) { const signature = getEnumSignature(schema); if (signature) { rootEnumSignatures[signature] = name; } } // Collect all inline enums (not at root schemas) const inlineEnums: Array<{ key: string | number | null; node: unknown; parent: unknown; path: ReadonlyArray; signature: string; }> = []; walkSchemas({ key: null, node: spec, parent: null, path: [], visitor: (nodeInfo) => { if (!isPathRootSchema(nodeInfo.path)) { const signature = getEnumSignature(nodeInfo.node); if (signature) { inlineEnums.push({ ...nodeInfo, signature }); } } }, }); // Deduplicate and assign unique names for promoted enums const signatureToName: Record = {}; const signatureToSchema: Record = {}; for (const { key, node, signature } of inlineEnums) { if (signature in signatureToName) { // Already handled continue; } // Use existing root enum if available if (signature in rootEnumSignatures) { signatureToName[signature] = rootEnumSignatures[signature]; continue; } // Generate a unique name for the new root enum using config const base = applyNaming( typeof node === 'object' && node && 'title' in node && typeof node.title === 'string' ? node.title : String(key), config, ); const name = getUniqueComponentName({ base, components: schemasObj, extraComponents: Object.values(signatureToName), }); signatureToName[signature] = name; signatureToSchema[signature] = node; } // Add new root enums to the schemas object for (const [signature, name] of Object.entries(signatureToName)) { // Only add if not already present const schema = signatureToSchema[signature]; if (name && !(name in schemasObj) && schema && typeof schema === 'object') { schemasObj[name] = schema; } } // Replace inline enums with $ref to the new root enum const schemasPointerNamespace = specToSchemasPointerNamespace(spec); for (const { key, parent, signature } of inlineEnums) { const name = signatureToName[signature]; if (name && key != null && parent && typeof parent === 'object') { (parent as Record)[key] = { $ref: `${schemasPointerNamespace}${name}`, }; } } }; /** * Applies the enums transform according to the configured mode ('inline' or 'root'). * * - In 'inline' mode, all root enums are inlined and removed. * - In 'root' mode, all inline enums are promoted to root components and deduplicated. * * @param config - The enums transform config * @param spec - The OpenAPI spec object to transform */ export const enumsTransform = ({ config, spec }: { config: EnumsConfig; spec: unknown }) => { if (config.mode === 'inline') { inlineMode({ spec }); return; } if (config.mode === 'root') { rootMode({ config, spec }); return; } }; ================================================ FILE: packages/shared/src/openApi/shared/transforms/index.ts ================================================ import type { Context } from '../../../ir/context'; import { enumsTransform } from './enums'; import { propertiesRequiredByDefaultTransform } from './propertiesRequiredByDefault'; import { readWriteTransform } from './readWrite'; import { schemaNameTransform } from './schemas'; export const transformOpenApiSpec = ({ context }: { context: Context }) => { const { logger } = context; const eventTransformOpenApiSpec = logger.timeEvent('transform-openapi-spec'); if (context.config.parser.transforms.schemaName) { schemaNameTransform({ config: context.config.parser.transforms.schemaName, spec: context.spec, }); } if (context.config.parser.transforms.enums.enabled) { enumsTransform({ config: context.config.parser.transforms.enums, spec: context.spec, }); } if (context.config.parser.transforms.propertiesRequiredByDefault) { propertiesRequiredByDefaultTransform({ spec: context.spec }); } if (context.config.parser.transforms.readWrite.enabled) { readWriteTransform({ config: context.config.parser.transforms.readWrite, logger, spec: context.spec, }); } eventTransformOpenApiSpec.timeEnd(); }; ================================================ FILE: packages/shared/src/openApi/shared/transforms/propertiesRequiredByDefault.ts ================================================ import { childSchemaRelationships } from '../utils/schemaChildRelationships'; type NodeInfo = { key: string | number | null; node: unknown; parent: unknown; path: ReadonlyArray; }; /** * Recursively walk all schemas in the OpenAPI spec, visiting every object. * Calls the visitor with node info for each. * * @param key - The key of the current node * @param node - The current node * @param parent - The parent node * @param path - The path to the current node * @param visitor - Function to call for each visited node */ const walkSchemas = ({ key, node, parent, path, visitor, }: NodeInfo & { visitor: (nodeInfo: NodeInfo) => void; }) => { if (!node || typeof node !== 'object' || node instanceof Array) return; const value = node as Record; if ('type' in value || childSchemaRelationships.some(([keyword]) => keyword in value)) { visitor({ key, node, parent, path }); } for (const [k, v] of Object.entries(value)) { if (typeof v === 'object' && v !== null) { if (v instanceof Array) { v.forEach((item, index) => walkSchemas({ key: index, node: item, parent: v, path: [...path, k, index], visitor, }), ); } else { walkSchemas({ key: k, node: v, parent: node, path: [...path, k], visitor, }); } } } }; /** * Applies the properties required by default transform * * @param spec - The OpenAPI spec object to transform */ export const propertiesRequiredByDefaultTransform = ({ spec }: { spec: unknown }) => { walkSchemas({ key: null, node: spec, parent: null, path: [], visitor: (nodeInfo) => { if ( nodeInfo.node && typeof nodeInfo.node === 'object' && 'type' in nodeInfo.node && nodeInfo.node.type === 'object' && 'properties' in nodeInfo.node && nodeInfo.node.properties && typeof nodeInfo.node.properties === 'object' && !('required' in nodeInfo.node) ) { const propKeys = Object.keys(nodeInfo.node.properties as Record); if (propKeys.length > 0) { (nodeInfo.node as Record).required = propKeys; } } }, }); }; ================================================ FILE: packages/shared/src/openApi/shared/transforms/readWrite.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import type { Parser } from '../../../config/parser/types'; import type { Graph } from '../../../graph'; import { applyNaming } from '../../../utils/naming/naming'; import { jsonPointerToPath } from '../../../utils/ref'; import deepEqual from '../utils/deepEqual'; import { buildGraph, type Scope } from '../utils/graph'; import { deepClone } from '../utils/schema'; import { childSchemaRelationships } from '../utils/schemaChildRelationships'; import { getSchemasObject, hasComponentsSchemasObject, hasDefinitionsObject, } from '../utils/transforms'; import { getUniqueComponentName, isPathRootSchema, specToSchemasPointerNamespace } from './utils'; type OriginalSchemas = Record; type SplitMapping = Record< string, { read?: string; write?: string; } >; type SplitSchemas = { /** Key is the original schema pointer. */ mapping: SplitMapping; /** splitPointer -> originalPointer */ reverseMapping: Record; /** name -> schema object */ schemas: Record; }; type ReadWriteConfig = Parser['transforms']['readWrite']; const schemaKeys = new Set([ 'additionalProperties', 'allOf', 'anyOf', 'items', 'not', 'oneOf', 'patternProperties', 'properties', 'schema', 'unevaluatedProperties', ]); const getComponentContext = (path: ReadonlyArray): Scope | undefined => { // OpenAPI 3.x: #/components/{type}/{name} if (path.length === 3 && path[0] === 'components') { const type = path[1]; if (type === 'parameters') return 'write'; if (type === 'requestBodies') return 'write'; if (type === 'responses') return 'read'; if (type === 'headers') return 'read'; } // OpenAPI 2.x: #/parameters/{name}, #/responses/{name} if (path.length === 2) { const type = path[0]; if (type === 'parameters') return 'write'; if (type === 'responses') return 'read'; } return; }; /** * Capture the original schema objects by pointer before splitting. * This is used to safely remove only the true originals after splitting, * even if names are swapped or overwritten by split variants. */ const captureOriginalSchemas = (spec: unknown, logger: Logger): OriginalSchemas => { const event = logger.timeEvent('capture-original-schemas'); const originals: OriginalSchemas = {}; if (hasComponentsSchemasObject(spec)) { for (const [name, obj] of Object.entries((spec as any).components.schemas)) { originals[`#/components/schemas/${name}`] = obj; } } else if (hasDefinitionsObject(spec)) { for (const [name, obj] of Object.entries((spec as any).definitions)) { originals[`#/definitions/${name}`] = obj; } } event.timeEnd(); return originals; }; /** * Inserts split schemas into the spec at the correct location (OpenAPI 3.x or 2.0). * This function is robust to spec version and will assign all split schemas * to either components.schemas (OAS3) or definitions (OAS2). * * @param spec - The OpenAPI spec object * @param split - The split schemas (from splitSchemas) */ const insertSplitSchemasIntoSpec = ({ logger, spec, split, }: { logger: Logger; spec: unknown; split: Pick; }) => { const event = logger.timeEvent('insert-split-schemas-into-spec'); if (hasComponentsSchemasObject(spec)) { Object.assign((spec as any).components.schemas, split.schemas); } else if (hasDefinitionsObject(spec)) { Object.assign((spec as any).definitions, split.schemas); } event.timeEnd(); }; /** * Prunes a schema by removing all child schemas (in any structural keyword) * that are marked with the given scope (readOnly/writeOnly), or that are $ref to a schema * that is exclusively the excluded scope (according to the graph). * * Uses childSchemaRelationships for parity with graph traversal. * Returns true if the schema itself should be removed from its parent. * * @param graph - The Graph containing all nodes and their scopes * @param schema - The schema object to prune * @param scope - The scope to exclude ('readOnly' or 'writeOnly') * @returns boolean - Whether the schema should be removed from its parent */ const pruneSchemaByScope = ( graph: Graph, schema: unknown, scope: 'readOnly' | 'writeOnly', ): boolean => { if (schema && typeof schema === 'object') { // Handle $ref schemas if ('$ref' in schema && typeof schema.$ref === 'string') { const nodeInfo = graph.nodes.get(schema.$ref); if (nodeInfo?.scopes) { // Only remove $ref if the referenced schema is *exclusively* the excluded scope. // This ensures 'normal' or multi-scope schemas are always kept. if ( (scope === 'writeOnly' && nodeInfo.scopes.size === 1 && nodeInfo.scopes.has('write')) || (scope === 'readOnly' && nodeInfo.scopes.size === 1 && nodeInfo.scopes.has('read')) ) { delete (schema as Record)['$ref']; // If the schema is now empty, remove it if (!childSchemaRelationships.some(([keyword]) => keyword in schema)) { return true; } } } } // Recursively prune all child schemas according to childSchemaRelationships for (const [keyword, type] of childSchemaRelationships) { if (!(keyword in schema)) { continue; } const value = (schema as Record)[keyword]; if (type === 'array' && value instanceof Array) { for (let index = value.length - 1; index >= 0; index--) { const item = value[index]; if ( item && typeof item === 'object' && (item as Record)[scope] === true ) { value.splice(index, 1); } else { const shouldRemove = pruneSchemaByScope(graph, item, scope); if (shouldRemove) value.splice(index, 1); } } if (!value.length) { delete (schema as Record)[keyword]; } } else if ( type === 'objectMap' && typeof value === 'object' && value !== null && !(value instanceof Array) ) { const objMap = value as Record; // Track removed properties for object schemas to update required array const removedProperties = new Set(); for (const key of Object.keys(objMap)) { const prop = objMap[key]; if ( prop && typeof prop === 'object' && (prop as Record)[scope] === true ) { delete objMap[key]; // Track removed properties for object schemas if (keyword === 'properties') { removedProperties.add(key); } } else { const shouldRemove = pruneSchemaByScope(graph, prop, scope); if (shouldRemove) { delete objMap[key]; // Track removed properties for object schemas if (keyword === 'properties') { removedProperties.add(key); } } } } // Update required array if properties were removed if ( removedProperties.size > 0 && keyword === 'properties' && 'required' in schema && Array.isArray((schema as Record).required) ) { const required = (schema as Record).required as string[]; const filteredRequired = required.filter((prop) => !removedProperties.has(prop)); if (!filteredRequired.length) { delete (schema as Record).required; } else { (schema as Record).required = filteredRequired; } } if (!Object.keys(objMap).length) { delete (schema as Record)[keyword]; } } else if (type === 'single' && typeof value === 'object' && value !== null) { if ((value as Record)[scope] === true) { delete (schema as Record)[keyword]; } else { const shouldRemove = pruneSchemaByScope(graph, value, scope); if (shouldRemove) { delete (schema as Record)[keyword]; } } } else if (type === 'singleOrArray') { if (value instanceof Array) { for (let index = value.length - 1; index >= 0; index--) { const item = value[index]; if ( item && typeof item === 'object' && (item as Record)[scope] === true ) { value.splice(index, 1); } else { const shouldRemove = pruneSchemaByScope(graph, item, scope); if (shouldRemove) value.splice(index, 1); } } if (!value.length) { delete (schema as Record)[keyword]; } } else if (typeof value === 'object' && value !== null) { if ((value as Record)[scope] === true) { delete (schema as Record)[keyword]; } else { const shouldRemove = pruneSchemaByScope(graph, value, scope); if (shouldRemove) { delete (schema as Record)[keyword]; } } } } } // After all removals, if this is type: object and has no structural fields, remove it if ( (schema as Record).type === 'object' && !childSchemaRelationships.some(([keyword]) => keyword in schema) ) { return true; } } return false; }; /** * Remove only the true original schemas that were split, by object identity. * This is robust to swaps, overwrites, and name collisions. * * @param originalSchemas - Map of original pointers to their schema objects (captured before splitting) * @param spec - The OpenAPI spec object * @param split - The split mapping (from splitSchemas) */ const removeOriginalSplitSchemas = ({ logger, originalSchemas, spec, split, }: { logger: Logger; originalSchemas: OriginalSchemas; spec: unknown; split: Pick; }) => { const event = logger.timeEvent('remove-original-split-schemas'); const schemasObj = getSchemasObject(spec); for (const originalPointer of Object.keys(split.mapping)) { const path = jsonPointerToPath(originalPointer); const name = path[path.length - 1]!; if ( typeof name === 'string' && schemasObj && Object.prototype.hasOwnProperty.call(schemasObj, name) && schemasObj[name] === originalSchemas[originalPointer] ) { delete schemasObj[name]; } } event.timeEnd(); }; /** * Create writable variants of parent schemas that have discriminators * and are referenced by split schemas. */ function splitDiscriminatorSchemas({ config, existingNames, schemasPointerNamespace, spec, split, }: { config: ReadWriteConfig; existingNames: Set; schemasPointerNamespace: string; spec: unknown; split: SplitSchemas; }) { const schemasObj = getSchemasObject(spec); if (!schemasObj) return; const parentSchemasToSplit = new Map>(); // First pass: identify parent schemas that need writable variants for (const [name, schema] of Object.entries(split.schemas)) { const pointer = `${schemasPointerNamespace}${name}`; const originalPointer = split.reverseMapping[pointer]; if (originalPointer) { const mapping = split.mapping[originalPointer]; if (mapping) { const contextVariant: Scope | null = mapping.read === pointer ? 'read' : mapping.write === pointer ? 'write' : null; // Check allOf for $refs to schemas with discriminators if ( contextVariant && schema && typeof schema === 'object' && 'allOf' in schema && schema.allOf instanceof Array ) { for (const comp of schema.allOf) { if ( comp && typeof comp === 'object' && '$ref' in comp && typeof comp.$ref === 'string' ) { const refPath = jsonPointerToPath(comp.$ref); const schemaName = refPath[refPath.length - 1]; if (typeof schemaName === 'string' && schemaName in schemasObj) { const resolvedSchema = schemasObj[schemaName]; // Check if this schema has a discriminator with mapping if ( resolvedSchema && typeof resolvedSchema === 'object' && 'discriminator' in resolvedSchema && resolvedSchema.discriminator && typeof resolvedSchema.discriminator === 'object' && 'mapping' in resolvedSchema.discriminator && resolvedSchema.discriminator.mapping && typeof resolvedSchema.discriminator.mapping === 'object' ) { // This parent schema needs a variant for this context if (!parentSchemasToSplit.has(comp.$ref)) { parentSchemasToSplit.set(comp.$ref, new Set()); } parentSchemasToSplit.get(comp.$ref)!.add(contextVariant); } } } } } } } } // Second pass: create writable variants of parent schemas and update their discriminator mappings const parentSchemaVariants = new Map(); for (const [parentRef, contexts] of parentSchemasToSplit) { const refPath = jsonPointerToPath(parentRef); const parentName = refPath[refPath.length - 1]; if (typeof parentName !== 'string' || !(parentName in schemasObj)) continue; const parentSchema = schemasObj[parentName]; if (!parentSchema || typeof parentSchema !== 'object') continue; const variants: SplitMapping[keyof SplitMapping] = {}; // Create variants for each context for (const context of contexts) { const variantSchema = deepClone(parentSchema); // Update discriminator mapping in the variant if ( 'discriminator' in variantSchema && variantSchema.discriminator && typeof variantSchema.discriminator === 'object' && 'mapping' in variantSchema.discriminator && variantSchema.discriminator.mapping && typeof variantSchema.discriminator.mapping === 'object' ) { const mapping = variantSchema.discriminator.mapping; const updatedMapping: Record = {}; for (const [discriminatorValue, originalRef] of Object.entries(mapping)) { const map = split.mapping[originalRef]; if (map) { if (context === 'read' && map.read) { updatedMapping[discriminatorValue] = map.read; } else if (context === 'write' && map.write) { updatedMapping[discriminatorValue] = map.write; } else { updatedMapping[discriminatorValue] = originalRef; } } else { updatedMapping[discriminatorValue] = originalRef; } } variantSchema.discriminator.mapping = updatedMapping; } // Add the variant to split.schemas with an appropriate name if (context === 'write') { const writeBase = applyNaming(parentName, config.requests); const writeName = getUniqueComponentName({ base: writeBase, components: existingNames, }); existingNames.add(writeName); split.schemas[writeName] = variantSchema; variants.write = `${schemasPointerNamespace}${writeName}`; } // We could create read variants too, but typically they're not needed // since the original schema serves as the read variant } parentSchemaVariants.set(parentRef, variants); } // Third pass: update $refs in split schemas to point to the parent variants for (const [name, schema] of Object.entries(split.schemas)) { const pointer = `${schemasPointerNamespace}${name}`; const originalPointer = split.reverseMapping[pointer]; if (!originalPointer) continue; const mapping = split.mapping[originalPointer]; if (!mapping) continue; const contextVariant: Scope | null = mapping.read === pointer ? 'read' : mapping.write === pointer ? 'write' : null; if (contextVariant && schema && typeof schema === 'object') { // Update $refs in allOf if ('allOf' in schema && schema.allOf instanceof Array) { for (let i = 0; i < schema.allOf.length; i++) { const comp = schema.allOf[i]; if (comp && typeof comp === 'object' && '$ref' in comp && typeof comp.$ref === 'string') { const variants = parentSchemaVariants.get(comp.$ref); if (variants) { if (contextVariant === 'write' && variants.write) { comp.$ref = variants.write; } else if (contextVariant === 'read' && variants.read) { comp.$ref = variants.read; } } } } } } } } /** * Splits schemas with both 'read' and 'write' scopes into read/write variants. * Returns the new schemas and a mapping from original pointer to new variant pointers. * * @param config - The readWrite transform config * @param graph - The Graph containing all nodes and their scopes * @param spec - The OpenAPI spec object * @returns SplitSchemas - The split schemas and pointer mappings */ export const splitSchemas = ({ config, graph, logger, spec, }: { config: ReadWriteConfig; graph: Graph; logger: Logger; spec: unknown; }): SplitSchemas => { const event = logger.timeEvent('split-schemas'); const existingNames = new Set(); const split: SplitSchemas = { mapping: {}, reverseMapping: {}, schemas: {}, }; const schemasPointerNamespace = specToSchemasPointerNamespace(spec); const schemasNamespaceSegments = schemasPointerNamespace.split('/').length - 1; /** * Extracts the schema name from pointer, but only if it's a top-level schema * pointer. Returns an empty string if it's a nested pointer. * @param pointer * @returns Schema's base name. */ const pointerToSchema = (pointer: string): string => { if (pointer.startsWith(schemasPointerNamespace)) { const path = jsonPointerToPath(pointer); if (path.length === schemasNamespaceSegments) { return path[schemasNamespaceSegments - 1] || ''; } } return ''; }; // Collect all existing schema names for (const pointer of graph.nodes.keys()) { const name = pointerToSchema(pointer); if (name) existingNames.add(name); } for (const [pointer, nodeInfo] of graph.nodes) { const name = pointerToSchema(pointer); // Only split top-level schemas, with either read-only or write-only scopes (or both). if ( !name || !(nodeInfo.scopes?.has('read') || nodeInfo.scopes?.has('write')) || !nodeInfo.scopes?.has('normal') ) { continue; } // read variant const readSchema = deepClone(nodeInfo.node); pruneSchemaByScope(graph, readSchema, 'writeOnly'); const readBase = applyNaming(name, config.responses); const readName = readBase === name ? readBase : getUniqueComponentName({ base: readBase, components: existingNames, }); existingNames.add(readName); split.schemas[readName] = readSchema; const readPointer = `${schemasPointerNamespace}${readName}`; // write variant const writeSchema = deepClone(nodeInfo.node); pruneSchemaByScope(graph, writeSchema, 'readOnly'); // Check if this schema (or any of its descendants) references any schema that // will need read/write variants. This is determined by checking transitive // dependencies for schemas with both 'normal' and ('read' or 'write') scopes. const transitiveDeps = graph.transitiveDependencies.get(pointer) || new Set(); const referencesReadWriteSchemas = Array.from(transitiveDeps).some((depPointer) => { const depNodeInfo = graph.nodes.get(depPointer); return ( depNodeInfo?.scopes?.has('normal') && (depNodeInfo.scopes.has('read') || depNodeInfo.scopes.has('write')) ); }); // If pruning did not change anything (both variants equal and equal to original), // and the schema doesn't reference any schemas that will have read/write variants, // skip splitting and keep the original single schema. if ( !referencesReadWriteSchemas && deepEqual(readSchema, writeSchema) && deepEqual(readSchema, nodeInfo.node) ) { continue; } const writeBase = applyNaming(name, config.requests); const writeName = writeBase === name && writeBase !== readName ? writeBase : getUniqueComponentName({ base: writeBase, components: existingNames, }); existingNames.add(writeName); split.schemas[writeName] = writeSchema; const writePointer = `${schemasPointerNamespace}${writeName}`; split.mapping[pointer] = { read: readPointer, write: writePointer, }; split.reverseMapping[readPointer] = pointer; split.reverseMapping[writePointer] = pointer; } splitDiscriminatorSchemas({ config, existingNames, schemasPointerNamespace, spec, split, }); event.timeEnd(); return split; }; type WalkArgs = { context: Scope | null; currentPointer: string | null; inSchema: boolean; node: unknown; path: ReadonlyArray; visited?: Set; }; /** * Recursively updates $ref fields in the spec to point to the correct read/write variant * according to the current context (read/write), using the split mapping. * * @param spec - The OpenAPI spec object * @param split - The split mapping (from splitSchemas) */ export const updateRefsInSpec = ({ logger, spec, split, }: { logger: Logger; spec: unknown; split: Omit; }): void => { const event = logger.timeEvent('update-refs-in-spec'); const schemasPointerNamespace = specToSchemasPointerNamespace(spec); const walk = ({ context, currentPointer, inSchema, node, path, visited = new Set(), }: WalkArgs): void => { if (node instanceof Array) { node.forEach((item, index) => walk({ context, currentPointer, inSchema, node: item, path: [...path, index], visited, }), ); } else if (node && typeof node === 'object') { // Detect if we're entering a split schema variant let nextPointer = currentPointer; let nextContext = context; if (isPathRootSchema(path)) { // Use the last path segment instead of a fixed index (path[2]) because // path depth varies across OAS2/OAS3 and contexts; fixed indexing is brittle. const nameSegment = path[path.length - 1] as string; nextPointer = `${schemasPointerNamespace}${nameSegment}`; const originalPointer = split.reverseMapping[nextPointer]; if (originalPointer) { const mapping = split.mapping[originalPointer]; if (mapping?.read === nextPointer) { nextContext = 'read'; } else if (mapping?.write === nextPointer) { nextContext = 'write'; } } // For schemas that are not split variants, keep the inherited context. // This ensures that $refs inside these schemas are resolved based on // where the schema is actually used (requestBody vs responses), not // based on the schema's own scopes which track readOnly/writeOnly fields. } const compContext = getComponentContext(path); if (compContext !== undefined) { // For each component, walk with the correct context for (const key in node) { if (!Object.prototype.hasOwnProperty.call(node, key)) { continue; } walk({ context: compContext, currentPointer: nextPointer, inSchema: false, node: (node as Record)[key], path: [...path, key], visited, }); } return; } for (const key in node) { if (!Object.prototype.hasOwnProperty.call(node, key)) { continue; } const value = (node as Record)[key]; // Only treat context switches at the OpenAPI structure level (not inside schemas) if (!inSchema) { if (key === 'requestBody') { walk({ context: 'write', currentPointer: nextPointer, inSchema: false, node: value, path: [...path, key], visited, }); continue; } if (key === 'responses') { walk({ context: 'read', currentPointer: nextPointer, inSchema: false, node: value, path: [...path, key], visited, }); continue; } if (key === 'parameters' && Array.isArray(value)) { value.forEach((param, index) => { if (param && typeof param === 'object' && 'schema' in param) { walk({ context: 'write', currentPointer: nextPointer, inSchema: true, node: param.schema, path: [...path, key, index, 'schema'], visited, }); } // Also handle content (OpenAPI 3.x) if (param && typeof param === 'object' && 'content' in param) { walk({ context: 'write', currentPointer: nextPointer, inSchema: false, node: param.content, path: [...path, key, index, 'content'], visited, }); } }); continue; } // OpenAPI 3.x: headers in responses if (key === 'headers' && typeof value === 'object' && value !== null) { for (const headerKey in value) { if (!Object.prototype.hasOwnProperty.call(value, headerKey)) { continue; } walk({ context: 'read', currentPointer: nextPointer, inSchema: false, node: (value as Record)[headerKey], path: [...path, key, headerKey], visited, }); } continue; } } // Entering a schema context if (schemaKeys.has(key)) { walk({ context: nextContext, currentPointer: nextPointer, inSchema: true, node: value, path: [...path, key], visited, }); } else if (key === '$ref' && typeof value === 'string') { // Prefer exact match first const map = split.mapping[value]; if (map) { if (nextContext === 'read' && map.read) { (node as Record)[key] = map.read; } else if (nextContext === 'write' && map.write) { (node as Record)[key] = map.write; } else if (!nextContext && map.read) { // For schemas with no context (unused in operations), default to read variant // This ensures $refs in unused schemas don't point to removed originals (node as Record)[key] = map.read; } } } else if (key === 'discriminator' && typeof value === 'object' && value !== null) { // Update discriminator mappings to point to the correct read/write variants if ('mapping' in value && value.mapping && typeof value.mapping === 'object') { const updatedMapping: Record = {}; for (const [discriminatorValue, originalRef] of Object.entries(value.mapping)) { const map = split.mapping[originalRef]; if (map) { if (nextContext === 'read' && map.read) { updatedMapping[discriminatorValue] = map.read; } else if (nextContext === 'write' && map.write) { updatedMapping[discriminatorValue] = map.write; } else { // For schemas with no context, don't update the mapping. // This preserves the original mapping for base schemas. updatedMapping[discriminatorValue] = originalRef; } } else { updatedMapping[discriminatorValue] = originalRef; } } value.mapping = updatedMapping; } // Continue walking the discriminator object for other properties walk({ context: nextContext, currentPointer: nextPointer, inSchema, node: value, path: [...path, key], visited, }); } else { walk({ context: nextContext, currentPointer: nextPointer, inSchema, node: value, path: [...path, key], visited, }); } } } }; walk({ context: null, currentPointer: null, inSchema: false, node: spec, path: [], }); event.timeEnd(); }; /** * Orchestrates the full read/write transform: * - Captures original schemas * - Splits schemas into read/write variants * - Inserts split schemas into the spec * - Updates $refs throughout the spec * - Removes original schemas that were split * * @param config - The readWrite transform config * @param spec - The OpenAPI spec object */ export const readWriteTransform = ({ config, logger, spec, }: { config: ReadWriteConfig; logger: Logger; spec: unknown; }) => { const { graph } = buildGraph(spec, logger); const originalSchemas = captureOriginalSchemas(spec, logger); const split = splitSchemas({ config, graph, logger, spec }); insertSplitSchemasIntoSpec({ logger, spec, split }); updateRefsInSpec({ logger, spec, split }); removeOriginalSplitSchemas({ logger, originalSchemas, spec, split }); }; ================================================ FILE: packages/shared/src/openApi/shared/transforms/schemas.ts ================================================ import type { Parser } from '../../../config/parser/types'; import { applyNaming } from '../../../utils/naming/naming'; import { getSchemasObject } from '../utils/transforms'; import { specToSchemasPointerNamespace } from './utils'; type SchemaNameConfig = Parser['transforms']['schemaName']; /** * Recursively walks the entire spec object and replaces all $ref strings * according to the provided rename mapping. */ const rewriteRefs = (node: unknown, renameMap: Record) => { if (node instanceof Array) { node.forEach((item) => rewriteRefs(item, renameMap)); } else if (node && typeof node === 'object') { for (const [key, value] of Object.entries(node)) { if (key === '$ref' && typeof value === 'string' && value in renameMap) { (node as Record)[key] = renameMap[value]; } else { rewriteRefs(value, renameMap); } } } }; /** * Renames schema component keys and updates all $ref pointers throughout * the spec. Handles collisions by skipping renames when the target name * already exists or conflicts with another rename. */ export const schemaNameTransform = ({ config, spec, }: { config: SchemaNameConfig; spec: unknown; }) => { if (!config) { return; } const schemasObj = getSchemasObject(spec); if (!schemasObj) { return; } const schemasPointerNamespace = specToSchemasPointerNamespace(spec); if (!schemasPointerNamespace) { return; } const renameMap: Record = {}; const newNames = new Set(); const namingConfig = { name: config }; for (const oldName of Object.keys(schemasObj)) { const newName = applyNaming(oldName, namingConfig); if (newName === oldName || newName in schemasObj || newNames.has(newName)) { continue; } renameMap[`${schemasPointerNamespace}${oldName}`] = `${schemasPointerNamespace}${newName}`; newNames.add(newName); } for (const [oldPointer, newPointer] of Object.entries(renameMap)) { const oldName = oldPointer.slice(schemasPointerNamespace.length); const newName = newPointer.slice(schemasPointerNamespace.length); const schema = schemasObj[oldName]; delete schemasObj[oldName]; schemasObj[newName] = schema; } if (Object.keys(renameMap).length > 0) { rewriteRefs(spec, renameMap); } }; ================================================ FILE: packages/shared/src/openApi/shared/transforms/utils.ts ================================================ type Obj = Record | Set | ReadonlyArray; const hasName = (obj: Obj, value: string): boolean => { if (obj instanceof Set) { return obj.has(value); } if (obj instanceof Array) { return obj.includes(value); } return value in obj; }; export const getUniqueComponentName = ({ base, components, extraComponents, }: { base: string; /** * Input components. */ components: Obj; /** * Temporary input components, waiting to be inserted for example. */ extraComponents?: Obj; }): string => { let index = 2; let name = base; while (hasName(components, name) || (extraComponents && hasName(extraComponents, name))) { name = `${base}${index}`; index += 1; } return name; }; export const isPathRootSchema = (path: ReadonlyArray) => (path.length === 3 && path[0] === 'components' && path[1] === 'schemas') || (path.length === 2 && path[0] === 'definitions'); export const specToSchemasPointerNamespace = (spec: unknown): string => { if (spec && typeof spec === 'object') { if ('swagger' in spec) { // #/definitions/SchemaName return '#/definitions/'; } if ('openapi' in spec) { // #/components/schemas/SchemaName return '#/components/schemas/'; } } return ''; }; ================================================ FILE: packages/shared/src/openApi/shared/types/index.ts ================================================ export type { CodeSampleObject, EnumExtensions, LinguistLanguages, } from './openapi-spec-extensions'; ================================================ FILE: packages/shared/src/openApi/shared/types/openapi-spec-extensions.ts ================================================ export type LinguistLanguages = | 'C' | 'C#' | 'C++' | 'CoffeeScript' | 'CSS' | 'Dart' | 'DM' | 'Elixir' | 'Go' | 'Groovy' | 'HTML' | 'Java' | 'JavaScript' | 'Kotlin' | 'Objective-C' | 'Perl' | 'PHP' | 'PowerShell' | 'Python' | 'Ruby' | 'Rust' | 'Scala' | 'Shell' | 'Swift' | 'TypeScript'; export interface CodeSampleObject { /** * Code sample label, for example `Node` or `Python2.7`. * * @default `lang` value */ label?: string; /** * **REQUIRED**. Code sample language. Can be one of the automatically supported languages or any other language identifier of your choice (for custom code samples). */ lang: LinguistLanguages; /** * **REQUIRED**. Code sample source code, or a `$ref` to the file containing the code sample. */ source: string; } export interface EnumExtensions { /** * `x-enum-descriptions` are {@link https://stackoverflow.com/a/66471626 supported} by OpenAPI Generator. */ 'x-enum-descriptions'?: ReadonlyArray; /** * `x-enum-varnames` are {@link https://stackoverflow.com/a/66471626 supported} by OpenAPI Generator. */ 'x-enum-varnames'?: ReadonlyArray; /** * {@link https://github.com/RicoSuter/NSwag NSwag} generates `x-enumNames` field containing custom enum names. */ 'x-enumNames'?: ReadonlyArray; } ================================================ FILE: packages/shared/src/openApi/shared/types/schema.ts ================================================ export interface SchemaState { /** * Optional schema $ref. This will be only defined for reusable components * from the OpenAPI specification. */ $ref?: string; /** * Set of $refs currently being resolved that are circular. This is used to * avoid infinite loops when resolving schemas with circular references. */ circularReferenceTracker: Set; /** * True if current schema is part of an allOf composition. This is used to * avoid emitting [key: string]: never for empty objects with * additionalProperties: false inside allOf, which would override inherited * properties from other schemas in the composition. */ inAllOf?: boolean; } export type SchemaWithRequired< S extends { type?: unknown; }, K extends keyof S, > = { [P in keyof S as P extends K ? never : P]: S[P]; } & { [P in K]-?: S[P]; }; export type SchemaType< S extends { type?: unknown; }, > = Extract['type'], string>; ================================================ FILE: packages/shared/src/openApi/shared/types/state.ts ================================================ export interface State { ids: Map; } ================================================ FILE: packages/shared/src/openApi/shared/utils/__tests__/deepEqual.test.ts ================================================ import deepEqual from '../deepEqual'; describe('deepEqual', () => { const scenarios: Array<{ a: unknown; b: unknown; equal: boolean; name: string; }> = [ // Primitives { a: 1, b: 1, equal: true, name: 'numbers equal' }, { a: 1, b: 2, equal: false, name: 'numbers not equal' }, { a: 'a', b: 'a', equal: true, name: 'strings equal' }, { a: 'a', b: 'b', equal: false, name: 'strings not equal' }, { a: true, b: true, equal: true, name: 'booleans equal' }, { a: true, b: false, equal: false, name: 'booleans not equal' }, { a: null, b: null, equal: true, name: 'null equal' }, { a: null, b: {}, equal: false, name: 'null vs object' }, { a: undefined, b: undefined, equal: true, name: 'undefined equal' }, { a: 1, b: '1', equal: false, name: 'number vs string' }, { a: Number.NaN, b: Number.NaN, equal: false, name: 'NaN vs NaN (not equal)', }, // Arrays { a: [1, 2], b: [1, 2], equal: true, name: 'arrays equal' }, { a: [1, 2], b: [2, 1], equal: false, name: 'arrays different order' }, { a: [1], b: [1, 2], equal: false, name: 'arrays different length' }, { a: [{ a: 1 }, 2, [3, 4]], b: [{ a: 1 }, 2, [3, 4]], equal: true, name: 'nested arrays and objects equal', }, // Objects { a: { a: 1, b: 2 }, b: { a: 1, b: 2 }, equal: true, name: 'objects equal different key order', }, { a: { a: 1 }, b: { a: 1, b: 2 }, equal: false, name: 'objects different keys', }, { a: { a: { b: 2 } }, b: { a: { b: 2 } }, equal: true, name: 'objects nested equal', }, { a: { a: { b: 2 } }, b: { a: { b: 3 } }, equal: false, name: 'objects nested not equal', }, { a: { a: undefined }, b: { a: undefined }, equal: true, name: 'object with undefined values equal', }, // Mismatched types { a: [], b: {}, equal: false, name: 'array vs object' }, ]; it.each(scenarios)('compares $name', async ({ a, b, equal }) => { expect(deepEqual(a, b)).toBe(equal); }); }); ================================================ FILE: packages/shared/src/openApi/shared/utils/__tests__/graph.test.ts ================================================ import { buildGraph } from '../graph'; // simple logger stub for buildGraph const loggerStub = { timeEvent: () => ({ timeEnd: () => {} }), } as any; describe('buildGraph', () => { it('computes referenced and transitive dependencies for validators-circular-ref.json', async () => { const mod = await import('../../../../../../../specs/3.1.x/validators-circular-ref.json'); const spec = (mod as any).default ?? mod; const { graph } = buildGraph(spec, loggerStub); const foo = '#/components/schemas/Foo'; const bar = '#/components/schemas/Bar'; const baz = '#/components/schemas/Baz'; const qux = '#/components/schemas/Qux'; // Foo has a child property that $ref's Bar, so Foo should have Bar in subtreeDependencies expect(graph.subtreeDependencies.get(foo)).toBeDefined(); expect(Array.from(graph.subtreeDependencies.get(foo)!).sort()).toEqual([bar].sort()); // Foo transitively depends on Bar (via the child), so transitiveDependencies should include Bar expect(graph.transitiveDependencies.get(foo)).toBeDefined(); expect(Array.from(graph.transitiveDependencies.get(foo)!).sort()).toEqual([bar].sort()); // Bar references itself via an array item; Bar should reference Bar expect(Array.from(graph.subtreeDependencies.get(bar)!).sort()).toEqual([bar].sort()); // Baz and Qux form a mutual $ref cycle; each should reference the other in subtreeDependencies expect(Array.from(graph.subtreeDependencies.get(baz)!).sort()).toEqual([qux].sort()); expect(Array.from(graph.subtreeDependencies.get(qux)!).sort()).toEqual([baz].sort()); // Qux node should exist and have a direct dependency to Baz (node-level $ref) expect(graph.nodes.has(qux)).toBe(true); expect(graph.nodeDependencies.get(qux)).toBeDefined(); expect(Array.from(graph.nodeDependencies.get(qux)!).sort()).toEqual([baz].sort()); // Qux transitive deps should include Baz (and vice-versa because of the cycle) expect(graph.transitiveDependencies.get(qux)).toBeDefined(); expect(Array.from(graph.transitiveDependencies.get(qux)!).sort()).toEqual([baz].sort()); // Reverse dependencies should reflect the mutual references expect(graph.reverseNodeDependencies.get(qux)).toBeDefined(); expect(Array.from(graph.reverseNodeDependencies.get(qux)!).sort()).toEqual([baz].sort()); expect(Array.from(graph.reverseNodeDependencies.get(baz)!).sort()).toEqual([qux].sort()); }); it('handles a small hand-constructed tree with child-level $ref', () => { const spec = { components: { schemas: { A: { properties: { p: { $ref: '#/components/schemas/B' } }, type: 'object', }, B: { type: 'object' }, }, }, }; const { graph } = buildGraph(spec, loggerStub); const a = '#/components/schemas/A'; const b = '#/components/schemas/B'; expect(Array.from(graph.subtreeDependencies.get(a)!).sort()).toEqual([b].sort()); expect(Array.from(graph.transitiveDependencies.get(a)!).sort()).toEqual([b].sort()); // reverseNodeDependencies should record that b is referenced by the property child as well expect(graph.reverseNodeDependencies.get(b)).toBeDefined(); expect(Array.from(graph.reverseNodeDependencies.get(b)!).some((p) => p.startsWith(a))).toBe( true, ); }); }); ================================================ FILE: packages/shared/src/openApi/shared/utils/__tests__/operation.test.ts ================================================ import type { Context } from '../../../../ir/context'; import { operationToId } from '../operation'; describe('operationToId', () => { const scenarios: Array<{ id?: string; method: string; output: string; path: string; }> = [ { method: 'post', output: 'postFoo', path: '/foo', }, { id: 'Post-foo', method: 'post', output: 'postFoo', path: '/foo', }, { method: 'post', output: 'postFooByFooId', path: '/foo/{foo_id}', }, { method: 'post', output: 'postFooByFooIdBarBazQux', path: '/foo/{foo_id}/bar+baz:qux', }, ]; it.each(scenarios)( 'transforms $method $path ($id) -> $output', async ({ id, method, output, path }) => { const context: Partial = { config: { plugins: { '@hey-api/sdk': { config: { // @ts-expect-error operationId: true, }, name: '@hey-api/sdk', }, }, }, }; expect( operationToId({ context: context as Context, id, method, path, state: { ids: new Map(), }, }), ).toEqual(output); }, ); }); ================================================ FILE: packages/shared/src/openApi/shared/utils/__tests__/patch.test.ts ================================================ import type { OpenApi } from '../../../types'; import { patchOpenApiSpec } from '../patch'; const specMetadataV2: Pick = { info: { title: 'Test API', version: '1.0.0', }, paths: {}, swagger: '2.0', }; const specMetadataV3: Pick = { info: { title: 'Test API', version: '1.0.0', }, openapi: '3.1.0', }; describe('patchOpenApiSpec', () => { describe('patch.input', () => { describe('OpenAPI v3', () => { it('calls patch.input function before other patches', async () => { const inputFn = vi.fn(); const metaFn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; await patchOpenApiSpec({ patchOptions: { input: inputFn, meta: metaFn, }, spec, }); // Both should be called expect(inputFn).toHaveBeenCalledOnce(); expect(inputFn).toHaveBeenCalledWith(spec); expect(metaFn).toHaveBeenCalledOnce(); }); it('allows bulk creation of component parameters', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: {}, }; await patchOpenApiSpec({ patchOptions: { input: (spec) => { if ('openapi' in spec) { if (!spec.components) spec.components = {}; if (!spec.components.parameters) spec.components.parameters = {}; spec.components.parameters.MyParam = { in: 'query', name: 'myParam', schema: { type: 'string' }, } as any; } }, }, spec, }); expect(spec.components?.parameters?.MyParam).toEqual({ in: 'query', name: 'myParam', schema: { type: 'string' }, }); }); it('allows injecting parameters into multiple operations', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { parameters: { SharedParam: { in: 'query', name: 'shared', schema: { type: 'string' }, } as any, }, }, paths: { '/bar': { get: { responses: {}, }, }, '/baz': { post: { responses: {}, }, }, '/foo': { get: { responses: {}, }, }, } as any, }; await patchOpenApiSpec({ patchOptions: { input: (spec) => { // Inject parameter into all GET operations for (const [, pathItem] of Object.entries(spec.paths ?? {})) { if (pathItem?.get) { if (!Array.isArray(pathItem.get.parameters)) { pathItem.get.parameters = []; } (pathItem.get.parameters as any[]).push({ $ref: '#/components/parameters/SharedParam', }); } } }, }, spec, }); expect((spec.paths as any)['/foo'].get.parameters).toEqual([ { $ref: '#/components/parameters/SharedParam' }, ]); expect((spec.paths as any)['/bar'].get.parameters).toEqual([ { $ref: '#/components/parameters/SharedParam' }, ]); expect((spec.paths as any)['/baz'].post.parameters).toBeUndefined(); }); it('allows complex Redfish-like transformations', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/other/path': { get: { responses: {}, }, }, '/redfish/v1/Chassis': { get: { responses: {}, }, }, '/redfish/v1/Systems': { get: { responses: {}, }, }, } as any, }; const QUERY_PARAMS = [ { description: 'Expand related resources.', key: '$expand' }, { description: 'Select subset.', key: '$select' }, ]; await patchOpenApiSpec({ patchOptions: { input: (spec) => { if (!('openapi' in spec)) return; // 1. Create component parameters if (!spec.components) spec.components = {}; if (!spec.components.parameters) spec.components.parameters = {}; for (const param of QUERY_PARAMS) { (spec.components.parameters as any)[`Redfish_${param.key}`] = { description: param.description, in: 'query', name: param.key, required: false, schema: { type: 'string' }, }; } // 2. Inject into Redfish paths for (const [path, pathItem] of Object.entries(spec.paths ?? {})) { if (!path.startsWith('/redfish/v1')) continue; const getOp = pathItem?.get; if (!getOp) continue; if (!Array.isArray(getOp.parameters)) getOp.parameters = []; for (const param of QUERY_PARAMS) { (getOp.parameters as any[]).push({ $ref: `#/components/parameters/Redfish_${param.key}`, }); } } }, }, spec, }); // Verify component parameters were created expect(spec.components?.parameters).toHaveProperty('Redfish_$expand'); expect(spec.components?.parameters).toHaveProperty('Redfish_$select'); // Verify they were injected into Redfish paths expect((spec.paths as any)['/redfish/v1/Systems'].get.parameters).toHaveLength(2); expect((spec.paths as any)['/redfish/v1/Chassis'].get.parameters).toHaveLength(2); // Verify they were NOT injected into non-Redfish paths expect((spec.paths as any)['/other/path'].get.parameters).toBeUndefined(); }); }); describe('OpenAPI v2', () => { it('calls patch.input function for v2 specs', async () => { const inputFn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, }; await patchOpenApiSpec({ patchOptions: { input: inputFn, }, spec, }); expect(inputFn).toHaveBeenCalledOnce(); expect(inputFn).toHaveBeenCalledWith(spec); }); it('allows adding definitions in v2 specs', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, }; await patchOpenApiSpec({ patchOptions: { input: (spec) => { if ('swagger' in spec) { if (!spec.definitions) spec.definitions = {}; spec.definitions.NewSchema = { properties: { id: { type: 'string' }, }, type: 'object', } as any; } }, }, spec, }); expect(spec.definitions?.NewSchema).toEqual({ properties: { id: { type: 'string' }, }, type: 'object', }); }); }); }); describe('async patch support', () => { describe('patch.input async', () => { it('supports async patch.input function', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; let asyncExecuted = false; await patchOpenApiSpec({ patchOptions: { input: async (spec) => { await new Promise((resolve) => setTimeout(resolve, 10)); spec.info.title = 'Async Modified'; asyncExecuted = true; }, }, spec, }); expect(asyncExecuted).toBe(true); expect(spec.info.title).toBe('Async Modified'); }); it('supports async operations in patch.input', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: {}, }; await patchOpenApiSpec({ patchOptions: { input: async (spec) => { // Simulate async operation like fetching data await new Promise((resolve) => setTimeout(resolve, 5)); if ('openapi' in spec) { if (!spec.components) spec.components = {}; if (!spec.components.parameters) spec.components.parameters = {}; spec.components.parameters.AsyncParam = { in: 'query', name: 'asyncParam', schema: { type: 'string' }, } as any; } }, }, spec, }); expect(spec.components?.parameters?.AsyncParam).toEqual({ in: 'query', name: 'asyncParam', schema: { type: 'string' }, }); }); }); describe('shorthand async', () => { it('supports async shorthand patch function', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; let asyncExecuted = false; await patchOpenApiSpec({ patchOptions: async (spec) => { await new Promise((resolve) => setTimeout(resolve, 10)); spec.info.title = 'Async Shorthand Modified'; asyncExecuted = true; }, spec, }); expect(asyncExecuted).toBe(true); expect(spec.info.title).toBe('Async Shorthand Modified'); }); it('supports async operations in shorthand function', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Foo: { type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: async (spec) => { // Simulate async operation await new Promise((resolve) => setTimeout(resolve, 5)); spec.info.description = 'Added via async shorthand'; if ('openapi' in spec && spec.components?.schemas) { (spec.components.schemas as any).Bar = { type: 'number', }; } }, spec, }); expect(spec.info.description).toBe('Added via async shorthand'); expect((spec.components?.schemas as any)?.Bar).toEqual({ type: 'number', }); }); }); }); describe('shorthand patch function', () => { describe('OpenAPI v3', () => { it('calls shorthand patch function', async () => { const patchFn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; await patchOpenApiSpec({ patchOptions: patchFn, spec, }); expect(patchFn).toHaveBeenCalledOnce(); expect(patchFn).toHaveBeenCalledWith(spec); }); it('allows modifications through shorthand function', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; await patchOpenApiSpec({ patchOptions: (spec) => { spec.info.title = 'Modified Title'; }, spec, }); expect(spec.info.title).toBe('Modified Title'); }); it('shorthand function replaces object-based patch configuration', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Foo: { type: 'string', }, }, }, }; // When using shorthand syntax, only the function is called // Object properties like meta or schemas would be ignored await patchOpenApiSpec({ patchOptions: (spec) => { spec.info.title = 'Shorthand Title'; // This is the only code that runs }, spec, }); expect(spec.info.title).toBe('Shorthand Title'); // Schemas remain untouched since no schema patch was applied expect(spec.components?.schemas?.Foo).toEqual({ type: 'string' }); }); }); describe('OpenAPI v2', () => { it('calls shorthand patch function for v2 specs', async () => { const patchFn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, }; await patchOpenApiSpec({ patchOptions: patchFn, spec, }); expect(patchFn).toHaveBeenCalledOnce(); expect(patchFn).toHaveBeenCalledWith(spec); }); it('allows modifications through shorthand function in v2', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, }; await patchOpenApiSpec({ patchOptions: (spec) => { spec.info.title = 'Modified V2 Title'; }, spec, }); expect(spec.info.title).toBe('Modified V2 Title'); }); }); }); describe('edge cases', () => { it('does not modify spec', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Foo: { type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: undefined, spec, }); expect(spec).toEqual({ ...specMetadataV3, components: { schemas: { Foo: { type: 'string', }, }, }, }); }); it('does not modify spec', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Foo: { type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: {}, spec, }); expect(spec).toEqual({ ...specMetadataV3, components: { schemas: { Foo: { type: 'string', }, }, }, }); }); }); describe('OpenAPI v3', () => { it('calls patch function', async () => { const fnBar = vi.fn(); const fnFoo = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Bar: { type: 'object', }, Foo: { type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Bar: fnBar, Foo: fnFoo, }, }, spec, }); expect(fnBar).toHaveBeenCalledOnce(); expect(fnBar).toHaveBeenCalledWith({ type: 'object', }); expect(fnFoo).toHaveBeenCalledOnce(); expect(fnFoo).toHaveBeenCalledWith({ type: 'string', }); }); it('patch function mutates spec', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { parameters: { Foo: { in: 'path', name: 'foo', schema: { type: 'string', }, }, }, requestBodies: { Foo: { content: { 'application/json': { schema: { type: 'string', }, }, }, }, }, responses: { Foo: { $ref: 'foo', content: { 'application/json': { schema: { type: 'string', }, }, }, }, }, schemas: { Foo: { type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: { parameters: { Foo: (schema) => { if ('in' in schema) { schema.in = 'query'; if (schema.schema && 'type' in schema.schema) { schema.schema.type = 'number'; } } }, }, requestBodies: { Foo: (schema) => { if ('content' in schema) { if ( schema.content['application/json'] && schema.content['application/json'].schema ) { if ('type' in schema.content['application/json'].schema) { schema.content['application/json'].schema.type = 'number'; } } } }, }, responses: { Foo: (schema) => { if ('content' in schema) { if ( schema.content && schema.content['application/json'] && schema.content['application/json'].schema ) { if ('type' in schema.content['application/json'].schema) { schema.content['application/json'].schema.type = 'number'; } } } }, }, schemas: { Foo: (schema) => { schema.type = 'number'; }, }, }, spec, }); expect(spec).toEqual({ ...specMetadataV3, components: { parameters: { Foo: { in: 'query', name: 'foo', schema: { type: 'number', }, }, }, requestBodies: { Foo: { content: { 'application/json': { schema: { type: 'number', }, }, }, }, }, responses: { Foo: { $ref: 'foo', content: { 'application/json': { schema: { type: 'number', }, }, }, }, }, schemas: { Foo: { type: 'number', }, }, }, }); }); it('handles spec without components', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; await patchOpenApiSpec({ patchOptions: { parameters: { Foo: fn, }, requestBodies: { Foo: fn, }, responses: { Foo: fn, }, schemas: { Foo: fn, }, }, spec, }); expect(fn).not.toHaveBeenCalled(); }); it('handles spec without component namespaces', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: {}, }; await patchOpenApiSpec({ patchOptions: { parameters: { Foo: fn, }, requestBodies: { Foo: fn, }, responses: { Foo: fn, }, schemas: { Foo: fn, }, }, spec, }); expect(fn).not.toHaveBeenCalled(); }); it('handles spec without matching components', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { parameters: {}, requestBodies: {}, responses: {}, schemas: {}, }, }; await patchOpenApiSpec({ patchOptions: { parameters: { Foo: fn, }, requestBodies: { Foo: fn, }, responses: { Foo: fn, }, schemas: { Foo: fn, }, }, spec, }); expect(fn).not.toHaveBeenCalled(); }); it('skips invalid schemas', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Bar: 123 as any, Baz: 'invalid' as any, Foo: null as any, Qux: { type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Bar: fn, Baz: fn, Foo: fn, Qux: fn, }, }, spec, }); expect(fn).toHaveBeenCalledOnce(); expect(fn).toHaveBeenCalledWith({ type: 'string', }); }); it('applies meta patch function', async () => { const metaFn = vi.fn((meta) => { meta.title = 'Changed Title'; }); const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; await patchOpenApiSpec({ patchOptions: { meta: metaFn, }, spec, }); expect(metaFn).toHaveBeenCalledOnce(); expect(spec.info.title).toBe('Changed Title'); }); it('applies version patch function', async () => { const versionFn = vi.fn((version) => `patched-${version}`); const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; await patchOpenApiSpec({ patchOptions: { version: versionFn, }, spec, }); expect(versionFn).toHaveBeenCalledOnce(); expect(spec.openapi).toBe('patched-3.1.0'); }); it('calls bulk callback function for all schemas', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Bar: { type: 'object', }, Foo: { type: 'string', }, Qux: { type: 'number', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: fn, }, spec, }); expect(fn).toHaveBeenCalledTimes(3); expect(fn).toHaveBeenCalledWith('Bar', { type: 'object' }); expect(fn).toHaveBeenCalledWith('Foo', { type: 'string' }); expect(fn).toHaveBeenCalledWith('Qux', { type: 'number' }); }); it('bulk callback mutates all schemas', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Bar: { description: 'Bar schema', type: 'object', }, Foo: { description: 'Foo schema', type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: (name, schema) => { schema.description = `${schema.description} - patched`; }, }, spec, }); expect(spec.components?.schemas?.Bar!.description).toBe('Bar schema - patched'); expect(spec.components?.schemas?.Foo!.description).toBe('Foo schema - patched'); }); it('bulk callback can extract version from schema name', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { OtherSchema: { type: 'string', }, ServiceRoot_v1_20_0_ServiceRoot: { description: 'Service root', type: 'object', }, User_v2_3_1_User: { description: 'User object', type: 'object', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: (name, schema) => { const match = name.match(/_v(\d+)_(\d+)_(\d+)_/); if (match) { schema.description = `${schema.description || ''}\n@version ${match[1]}.${match[2]}.${match[3]}`; } }, }, spec, }); expect(spec.components?.schemas?.ServiceRoot_v1_20_0_ServiceRoot!.description).toBe( 'Service root\n@version 1.20.0', ); expect(spec.components?.schemas?.User_v2_3_1_User!.description).toBe( 'User object\n@version 2.3.1', ); expect(spec.components?.schemas?.OtherSchema!.description).toBeUndefined(); }); it('bulk callback skips invalid schemas', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Bar: 123 as any, Baz: 'invalid' as any, Foo: null as any, Qux: { type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: fn, }, spec, }); expect(fn).toHaveBeenCalledOnce(); expect(fn).toHaveBeenCalledWith('Qux', { type: 'string' }); }); it('supports async bulk callback', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Bar: { description: 'Bar schema', type: 'object', }, Foo: { description: 'Foo schema', type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: async (name, schema) => { // Simulate async operation await Promise.resolve(); schema.description = `${schema.description} - async patched`; }, }, spec, }); expect(spec.components?.schemas?.Bar!.description).toBe('Bar schema - async patched'); expect(spec.components?.schemas?.Foo!.description).toBe('Foo schema - async patched'); }); it('supports async Record-based callbacks', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Bar: { description: 'Bar schema', type: 'object', }, Foo: { description: 'Foo schema', type: 'string', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Bar: async (schema) => { await Promise.resolve(); schema.description = `${schema.description} - async`; }, Foo: async (schema) => { await Promise.resolve(); schema.description = `${schema.description} - async`; }, }, }, spec, }); expect(spec.components?.schemas?.Bar!.description).toBe('Bar schema - async'); expect(spec.components?.schemas?.Foo!.description).toBe('Foo schema - async'); }); }); describe('OpenAPI v2', () => { it('calls patch function', async () => { const fnBar = vi.fn(); const fnFoo = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Bar: { type: 'object', }, Foo: { type: 'string', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Bar: fnBar, Foo: fnFoo, }, }, spec, }); expect(fnBar).toHaveBeenCalledOnce(); expect(fnBar).toHaveBeenCalledWith({ type: 'object', }); expect(fnFoo).toHaveBeenCalledOnce(); expect(fnFoo).toHaveBeenCalledWith({ type: 'string', }); }); it('patch function mutates schema', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Foo: { type: 'string', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Foo: (schema) => { schema.type = 'number'; }, }, }, spec, }); expect(spec).toEqual({ ...specMetadataV2, definitions: { Foo: { type: 'number', }, }, }); }); it('handles spec without definitions', async () => { const fn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, }; await patchOpenApiSpec({ patchOptions: { parameters: { Foo: fn, }, requestBodies: { Foo: fn, }, responses: { Foo: fn, }, schemas: { Foo: fn, }, }, spec, }); expect(fn).not.toHaveBeenCalled(); }); it('handles spec without matching definitions', async () => { const fn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: {}, }; await patchOpenApiSpec({ patchOptions: { parameters: { Foo: fn, }, requestBodies: { Foo: fn, }, responses: { Foo: fn, }, schemas: { Foo: fn, }, }, spec, }); expect(fn).not.toHaveBeenCalled(); }); it('skips invalid schemas', async () => { const fn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Bar: 123 as any, Baz: 'invalid' as any, Foo: null as any, Qux: { type: 'string', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Bar: fn, Baz: fn, Foo: fn, Qux: fn, }, }, spec, }); expect(fn).toHaveBeenCalledOnce(); expect(fn).toHaveBeenCalledWith({ type: 'string', }); }); it('applies meta patch function', async () => { const metaFn = vi.fn((meta) => { meta.title = 'Changed Title'; }); const spec: OpenApi.V2_0_X = { ...specMetadataV2, }; await patchOpenApiSpec({ patchOptions: { meta: metaFn, }, spec, }); expect(metaFn).toHaveBeenCalledOnce(); expect(spec.info.title).toBe('Changed Title'); }); it('applies version patch function', async () => { const versionFn = vi.fn((version) => `patched-${version}`); const spec: OpenApi.V2_0_X = { ...specMetadataV2, }; await patchOpenApiSpec({ patchOptions: { version: versionFn, }, spec, }); expect(versionFn).toHaveBeenCalledOnce(); expect(spec.swagger).toBe('patched-2.0'); }); it('calls bulk callback function for all schemas', async () => { const fn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Bar: { type: 'object', }, Foo: { type: 'string', }, Qux: { type: 'number', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: fn, }, spec, }); expect(fn).toHaveBeenCalledTimes(3); expect(fn).toHaveBeenCalledWith('Bar', { type: 'object' }); expect(fn).toHaveBeenCalledWith('Foo', { type: 'string' }); expect(fn).toHaveBeenCalledWith('Qux', { type: 'number' }); }); it('bulk callback mutates all schemas', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Bar: { description: 'Bar schema', type: 'object', }, Foo: { description: 'Foo schema', type: 'string', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: (name, schema) => { schema.description = `${schema.description} - patched`; }, }, spec, }); expect(spec.definitions?.Bar!.description).toBe('Bar schema - patched'); expect(spec.definitions?.Foo!.description).toBe('Foo schema - patched'); }); it('bulk callback can extract version from schema name', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { OtherSchema: { type: 'string', }, ServiceRoot_v1_20_0_ServiceRoot: { description: 'Service root', type: 'object', }, User_v2_3_1_User: { description: 'User object', type: 'object', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: (name, schema) => { const match = name.match(/_v(\d+)_(\d+)_(\d+)_/); if (match) { schema.description = `${schema.description || ''}\n@version ${match[1]}.${match[2]}.${match[3]}`; } }, }, spec, }); expect(spec.definitions?.ServiceRoot_v1_20_0_ServiceRoot!.description).toBe( 'Service root\n@version 1.20.0', ); expect(spec.definitions?.User_v2_3_1_User!.description).toBe('User object\n@version 2.3.1'); expect(spec.definitions?.OtherSchema!.description).toBeUndefined(); }); it('bulk callback skips invalid schemas', async () => { const fn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Bar: 123 as any, Baz: 'invalid' as any, Foo: null as any, Qux: { type: 'string', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: fn, }, spec, }); expect(fn).toHaveBeenCalledOnce(); expect(fn).toHaveBeenCalledWith('Qux', { type: 'string' }); }); it('supports async bulk callback', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Bar: { description: 'Bar schema', type: 'object', }, Foo: { description: 'Foo schema', type: 'string', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: async (name, schema) => { // Simulate async operation await Promise.resolve(); schema.description = `${schema.description} - async patched`; }, }, spec, }); expect(spec.definitions?.Bar!.description).toBe('Bar schema - async patched'); expect(spec.definitions?.Foo!.description).toBe('Foo schema - async patched'); }); it('supports async Record-based callbacks', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, definitions: { Bar: { description: 'Bar schema', type: 'object', }, Foo: { description: 'Foo schema', type: 'string', }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Bar: async (schema) => { await Promise.resolve(); schema.description = `${schema.description} - async`; }, Foo: async (schema) => { await Promise.resolve(); schema.description = `${schema.description} - async`; }, }, }, spec, }); expect(spec.definitions?.Bar!.description).toBe('Bar schema - async'); expect(spec.definitions?.Foo!.description).toBe('Foo schema - async'); }); }); describe('real-world usage', () => { it('handles complex schema example from docs', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Foo: { properties: { id: { type: 'string' }, name: { type: 'string' }, updatedAt: { format: 'date-time', type: 'string', }, }, type: 'object', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Foo: (schema: any) => { if (typeof schema.properties?.updatedAt === 'object') { delete schema.properties.updatedAt.format; schema.properties.updatedAt.type = 'number'; } }, }, }, spec, }); expect(spec).toEqual({ ...specMetadataV3, components: { schemas: { Foo: { properties: { id: { type: 'string' }, name: { type: 'string' }, updatedAt: { type: 'number', }, }, type: 'object', }, }, }, }); }); it('handles adding new schema properties', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Foo: { properties: { id: { type: 'string' }, }, type: 'object', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Foo: (schema: any) => { schema.properties.meta = { additionalProperties: true, type: 'object', }; schema.required = ['meta']; }, }, }, spec, }); expect(spec).toEqual({ ...specMetadataV3, components: { schemas: { Foo: { properties: { id: { type: 'string' }, meta: { additionalProperties: true, type: 'object', }, }, required: ['meta'], type: 'object', }, }, }, }); }); it('handles removing schema properties', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, components: { schemas: { Foo: { properties: { id: { type: 'string' }, internalField: { type: 'string' }, publicField: { type: 'string' }, }, type: 'object', }, }, }, }; await patchOpenApiSpec({ patchOptions: { schemas: { Foo: (schema: any) => { delete schema.properties.internalField; }, }, }, spec, }); expect(spec).toEqual({ ...specMetadataV3, components: { schemas: { Foo: { properties: { id: { type: 'string' }, publicField: { type: 'string' }, }, type: 'object', }, }, }, }); }); }); describe('patch.operations', () => { describe('OpenAPI v3', () => { it('bulk callback mutates all operations', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, put: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: (method, path, operation) => { operation.operationId = `${method}_${path.replace(/\//g, '_')}`; }, }, spec, }); expect(spec.paths!['/foo']?.get?.operationId).toBe('get__foo'); expect(spec.paths!['/foo']?.put?.operationId).toBe('put__foo'); expect(spec.paths!['/bar']?.post?.operationId).toBe('post__bar'); }); it('bulk callback receives correct parameters', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: fn, }, spec, }); expect(fn).toHaveBeenCalledTimes(2); expect(fn).toHaveBeenCalledWith('get', '/foo', spec.paths!['/foo']?.get); expect(fn).toHaveBeenCalledWith('post', '/bar', spec.paths!['/bar']?.post); }); it('bulk callback can inject operationId based on path patterns', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/users': { get: { responses: {}, } as any, post: { responses: {}, } as any, }, '/users/{id}': { delete: { responses: {}, } as any, get: { operationId: 'existingId', responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: (method, path, operation) => { if (operation.operationId) return; // don't override existing const segments = path.split('/').filter(Boolean); const parts = segments.map((seg) => (seg.startsWith('{') ? 'ById' : seg)).join(''); operation.operationId = method + parts; }, }, spec, }); expect(spec.paths!['/users']?.get?.operationId).toBe('getusers'); expect(spec.paths!['/users']?.post?.operationId).toBe('postusers'); expect(spec.paths!['/users/{id}']?.get?.operationId).toBe('existingId'); // not overridden expect(spec.paths!['/users/{id}']?.delete?.operationId).toBe('deleteusersById'); }); it('bulk callback skips invalid operations', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/bar': { get: null as any, post: 'invalid' as any, }, '/baz': 123 as any, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: fn, }, spec, }); expect(fn).toHaveBeenCalledOnce(); expect(fn).toHaveBeenCalledWith('get', '/foo', spec.paths!['/foo']?.get); }); it('supports async bulk callback', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: async (method, path, operation) => { // Simulate async operation await Promise.resolve(); operation.operationId = `async_${method}_${path}`; }, }, spec, }); expect(spec.paths!['/foo']?.get?.operationId).toBe('async_get_/foo'); expect(spec.paths!['/bar']?.post?.operationId).toBe('async_post_/bar'); }); it('supports async Record-based callbacks', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: { 'GET /foo': async (operation) => { await Promise.resolve(); operation.operationId = 'asyncGetFoo'; }, 'POST /bar': async (operation) => { await Promise.resolve(); operation.operationId = 'asyncPostBar'; }, }, }, spec, }); expect(spec.paths!['/foo']?.get?.operationId).toBe('asyncGetFoo'); expect(spec.paths!['/bar']?.post?.operationId).toBe('asyncPostBar'); }); it('Record-based operations still work as before', async () => { const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: { 'GET /foo': (operation) => { operation.operationId = 'getFoo'; }, 'POST /bar': (operation) => { operation.operationId = 'postBar'; }, }, }, spec, }); expect(spec.paths!['/foo']?.get?.operationId).toBe('getFoo'); expect(spec.paths!['/bar']?.post?.operationId).toBe('postBar'); }); it('handles spec without paths', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, }; await patchOpenApiSpec({ patchOptions: { operations: fn, }, spec, }); expect(fn).not.toHaveBeenCalled(); }); it('handles all HTTP methods', async () => { const fn = vi.fn(); const spec: OpenApi.V3_1_X = { ...specMetadataV3, paths: { '/test': { delete: { responses: {} } as any, get: { responses: {} } as any, head: { responses: {} } as any, options: { responses: {} } as any, patch: { responses: {} } as any, post: { responses: {} } as any, put: { responses: {} } as any, trace: { responses: {} } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: fn, }, spec, }); expect(fn).toHaveBeenCalledTimes(8); expect(fn).toHaveBeenCalledWith('get', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('put', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('post', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('delete', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('options', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('head', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('patch', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('trace', '/test', expect.any(Object)); }); }); describe('OpenAPI v2', () => { it('bulk callback mutates all operations', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, put: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: (method, path, operation) => { operation.operationId = `${method}_${path.replace(/\//g, '_')}`; }, }, spec, }); expect(spec.paths!['/foo']?.get?.operationId).toBe('get__foo'); expect(spec.paths!['/foo']?.put?.operationId).toBe('put__foo'); expect(spec.paths!['/bar']?.post?.operationId).toBe('post__bar'); }); it('bulk callback receives correct parameters', async () => { const fn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: fn, }, spec, }); expect(fn).toHaveBeenCalledTimes(2); expect(fn).toHaveBeenCalledWith('get', '/foo', spec.paths!['/foo']?.get); expect(fn).toHaveBeenCalledWith('post', '/bar', spec.paths!['/bar']?.post); }); it('supports async bulk callback', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: async (method, path, operation) => { await Promise.resolve(); operation.operationId = `async_${method}_${path}`; }, }, spec, }); expect(spec.paths!['/foo']?.get?.operationId).toBe('async_get_/foo'); expect(spec.paths!['/bar']?.post?.operationId).toBe('async_post_/bar'); }); it('Record-based operations still work as before', async () => { const spec: OpenApi.V2_0_X = { ...specMetadataV2, paths: { '/bar': { post: { responses: {}, } as any, }, '/foo': { get: { responses: {}, } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: { 'GET /foo': (operation) => { operation.operationId = 'getFoo'; }, 'POST /bar': (operation) => { operation.operationId = 'postBar'; }, }, }, spec, }); expect(spec.paths!['/foo']?.get?.operationId).toBe('getFoo'); expect(spec.paths!['/bar']?.post?.operationId).toBe('postBar'); }); it('handles all HTTP methods', async () => { const fn = vi.fn(); const spec: OpenApi.V2_0_X = { ...specMetadataV2, paths: { '/test': { delete: { responses: {} } as any, get: { responses: {} } as any, head: { responses: {} } as any, options: { responses: {} } as any, patch: { responses: {} } as any, post: { responses: {} } as any, put: { responses: {} } as any, }, }, }; await patchOpenApiSpec({ patchOptions: { operations: fn, }, spec, }); expect(fn).toHaveBeenCalledTimes(7); expect(fn).toHaveBeenCalledWith('get', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('put', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('post', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('delete', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('options', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('head', '/test', expect.any(Object)); expect(fn).toHaveBeenCalledWith('patch', '/test', expect.any(Object)); }); }); }); }); ================================================ FILE: packages/shared/src/openApi/shared/utils/__tests__/sanitize.test.ts ================================================ import { sanitizeNamespaceIdentifier } from '../operation'; describe('sanitizeNamespaceIdentifier', () => { it.each([ { expected: 'abc', input: 'abc' }, { expected: 'æbc', input: 'æbc' }, { expected: 'æb-c', input: 'æb.c' }, { expected: 'æb-c', input: '1æb.c' }, { expected: 'a-b-c--d---e', input: 'a/b{c}/d/$+e' }, ])('sanitizeNamespaceIdentifier($input) -> $expected', ({ expected, input }) => { expect(sanitizeNamespaceIdentifier(input)).toEqual(expected); }); }); ================================================ FILE: packages/shared/src/openApi/shared/utils/deepEqual.ts ================================================ /** * Deep equality for JSON-compatible values (objects, arrays, primitives). * Used to determine whether read/write pruned variants actually differ. */ const deepEqual = (a: unknown, b: unknown): boolean => { if (a === b) return true; if (a === null || b === null) return a === b; const typeA = typeof a; const typeB = typeof b; if (typeA !== typeB) return false; if (typeA !== 'object') return false; // Arrays if (Array.isArray(a) || Array.isArray(b)) { if (!Array.isArray(a) || !Array.isArray(b)) return false; if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (!deepEqual(a[i], b[i])) return false; } return true; } // Plain objects const objA = a as Record; const objB = b as Record; const keysA = Object.keys(objA).sort(); const keysB = Object.keys(objB).sort(); if (keysA.length !== keysB.length) return false; for (let i = 0; i < keysA.length; i++) { if (keysA[i] !== keysB[i]) return false; } for (const key of keysA) { if (!deepEqual(objA[key], objB[key])) return false; } return true; }; export default deepEqual; ================================================ FILE: packages/shared/src/openApi/shared/utils/discriminator.ts ================================================ import type { IR } from '../../../ir/types'; import { refToName } from '../../../utils/ref'; /** * Supported types for discriminator properties. */ export type DiscriminatorPropertyType = 'boolean' | 'integer' | 'number' | 'string'; /** * Converts a string discriminator mapping value to the appropriate type based on * the actual property type in the schema. * * OpenAPI discriminator mappings always use string keys, but the actual discriminator * property may be a boolean, number, or integer. This function converts the string * key to the correct runtime value and IR type. */ export const convertDiscriminatorValue = ( value: string, propertyType: DiscriminatorPropertyType, ): { const: IR.SchemaObject['const']; type: IR.SchemaObject['type'] } => { switch (propertyType) { case 'boolean': { const lowerValue = value.toLowerCase(); if (lowerValue !== 'true' && lowerValue !== 'false') { console.warn( '🚨', `non-boolean discriminator mapping value "${value}" for boolean property, falling back to string`, ); return { const: value, type: 'string', }; } return { const: lowerValue === 'true', type: 'boolean', }; } case 'integer': { const parsed = parseInt(value, 10); if (Number.isNaN(parsed)) { console.warn( '🚨', `non-numeric discriminator mapping value "${value}" for integer property, falling back to string`, ); return { const: value, type: 'string', }; } return { const: parsed, type: 'integer', }; } case 'number': { const parsed = parseFloat(value); if (Number.isNaN(parsed)) { console.warn( '🚨', `non-numeric discriminator mapping value "${value}" for number property, falling back to string`, ); return { const: value, type: 'string', }; } return { const: parsed, type: 'number', }; } default: return { const: value, type: 'string', }; } }; export const discriminatorValues = ( $ref: string, mapping?: Record, shouldUseRefAsValue?: () => boolean, ): ReadonlyArray => { const values: Array = []; for (const name in mapping) { if (mapping[name] === $ref) { values.push(name); } } if (!values.length && (!shouldUseRefAsValue || shouldUseRefAsValue())) { return [refToName($ref)]; } return values; }; ================================================ FILE: packages/shared/src/openApi/shared/utils/filter.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import type { Parser } from '../../../config/parser/types'; import { createOperationKey } from '../../../ir/operation'; import type { PathItemObject, PathsObject } from '../../../openApi/3.1.x/types/spec'; import type { OpenApi } from '../../../openApi/types'; import type { ResourceMetadata } from '../graph/meta'; import { httpMethods } from './operation'; type FilterNamespace = 'body' | 'operation' | 'parameter' | 'response' | 'schema' | 'unknown'; const namespaceNeedle = '/'; export const addNamespace = (namespace: FilterNamespace, value: string = ''): string => `${namespace}${namespaceNeedle}${value}`; export const removeNamespace = ( key: string, ): { name: string; namespace: FilterNamespace; } => { const index = key.indexOf(namespaceNeedle); const name = key.slice(index + 1); return { name, namespace: key.slice(0, index)! as FilterNamespace, }; }; /** * Converts reference strings from OpenAPI $ref keywords into namespaces. * * @example '#/components/schemas/Foo' -> 'schema' */ export const stringToNamespace = (value: string): FilterNamespace => { switch (value) { case 'parameters': return 'parameter'; case 'requestBodies': return 'body'; case 'responses': return 'response'; case 'definitions': case 'schemas': return 'schema'; default: return 'unknown'; } }; type FiltersConfigToState = { [K in keyof T]-?: NonNullable extends ReadonlyArray ? Set : NonNullable extends object ? FiltersConfigToState> : T[K]; }; export type Filters = FiltersConfigToState>; interface SetAndRegExps { regexps: Array; set: Set; } const createFiltersSetAndRegExps = ( type: FilterNamespace, filters: ReadonlyArray | undefined, ): SetAndRegExps => { const keys: Array = []; const regexps: Array = []; if (filters) { for (const value of filters) { if (value.startsWith('/') && value.endsWith('/')) { regexps.push(new RegExp(value.slice(1, value.length - 1))); } else { keys.push(addNamespace(type, value)); } } } return { regexps, set: new Set(keys), }; }; interface CollectFiltersSetFromRegExps { excludeOperations: SetAndRegExps; excludeParameters: SetAndRegExps; excludeRequestBodies: SetAndRegExps; excludeResponses: SetAndRegExps; excludeSchemas: SetAndRegExps; includeOperations: SetAndRegExps; includeParameters: SetAndRegExps; includeRequestBodies: SetAndRegExps; includeResponses: SetAndRegExps; includeSchemas: SetAndRegExps; } const collectFiltersSetFromRegExpsOpenApiV2 = ({ excludeOperations, excludeSchemas, includeOperations, includeSchemas, spec, }: CollectFiltersSetFromRegExps & { spec: OpenApi.V2_0_X; }) => { if ((excludeOperations.regexps.length || includeOperations.regexps.length) && spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { const operation = pathItem[method]; if (!operation) { continue; } const key = createOperationKey({ method, path }); if (excludeOperations.regexps.some((regexp) => regexp.test(key))) { excludeOperations.set.add(addNamespace('operation', key)); } if (includeOperations.regexps.some((regexp) => regexp.test(key))) { includeOperations.set.add(addNamespace('operation', key)); } } } } if (spec.definitions) { // TODO: add parameters if (excludeSchemas.regexps.length || includeSchemas.regexps.length) { for (const key of Object.keys(spec.definitions)) { if (excludeSchemas.regexps.some((regexp) => regexp.test(key))) { excludeSchemas.set.add(addNamespace('schema', key)); } if (includeSchemas.regexps.some((regexp) => regexp.test(key))) { includeSchemas.set.add(addNamespace('schema', key)); } } } } }; const collectFiltersSetFromRegExpsOpenApiV3 = ({ excludeOperations, excludeParameters, excludeRequestBodies, excludeResponses, excludeSchemas, includeOperations, includeParameters, includeRequestBodies, includeResponses, includeSchemas, spec, }: CollectFiltersSetFromRegExps & { spec: OpenApi.V3_0_X | OpenApi.V3_1_X; }) => { if ((excludeOperations.regexps.length || includeOperations.regexps.length) && spec.paths) { for (const entry of Object.entries(spec.paths)) { const path = entry[0] as keyof PathsObject; const pathItem = entry[1] as PathItemObject; for (const method of httpMethods) { const operation = pathItem[method]; if (!operation) { continue; } const key = createOperationKey({ method, path }); if (excludeOperations.regexps.some((regexp) => regexp.test(key))) { excludeOperations.set.add(addNamespace('operation', key)); } if (includeOperations.regexps.some((regexp) => regexp.test(key))) { includeOperations.set.add(addNamespace('operation', key)); } } } } if (spec.components) { if ( (excludeParameters.regexps.length || includeParameters.regexps.length) && spec.components.parameters ) { for (const key of Object.keys(spec.components.parameters)) { if (excludeParameters.regexps.some((regexp) => regexp.test(key))) { excludeParameters.set.add(addNamespace('parameter', key)); } if (includeParameters.regexps.some((regexp) => regexp.test(key))) { includeParameters.set.add(addNamespace('parameter', key)); } } } if ( (excludeRequestBodies.regexps.length || includeRequestBodies.regexps.length) && spec.components.requestBodies ) { for (const key of Object.keys(spec.components.requestBodies)) { if (excludeRequestBodies.regexps.some((regexp) => regexp.test(key))) { excludeRequestBodies.set.add(addNamespace('body', key)); } if (includeRequestBodies.regexps.some((regexp) => regexp.test(key))) { includeRequestBodies.set.add(addNamespace('body', key)); } } } if ( (excludeResponses.regexps.length || includeResponses.regexps.length) && spec.components.responses ) { for (const key of Object.keys(spec.components.responses)) { if (excludeResponses.regexps.some((regexp) => regexp.test(key))) { excludeResponses.set.add(addNamespace('response', key)); } if (includeResponses.regexps.some((regexp) => regexp.test(key))) { includeResponses.set.add(addNamespace('response', key)); } } } if ( (excludeSchemas.regexps.length || includeSchemas.regexps.length) && spec.components.schemas ) { for (const key of Object.keys(spec.components.schemas)) { if (excludeSchemas.regexps.some((regexp) => regexp.test(key))) { excludeSchemas.set.add(addNamespace('schema', key)); } if (includeSchemas.regexps.some((regexp) => regexp.test(key))) { includeSchemas.set.add(addNamespace('schema', key)); } } } } }; const collectFiltersSetFromRegExps = ({ spec, ...filters }: CollectFiltersSetFromRegExps & { spec: OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X; }): void => { if ('swagger' in spec) { collectFiltersSetFromRegExpsOpenApiV2({ ...filters, spec }); } else { collectFiltersSetFromRegExpsOpenApiV3({ ...filters, spec }); } }; export const createFilters = ( config: Parser['filters'], spec: OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X, logger: Logger, ): Filters => { const eventCreateFilters = logger.timeEvent('create-filters'); const excludeOperations = createFiltersSetAndRegExps('operation', config?.operations?.exclude); const includeOperations = createFiltersSetAndRegExps('operation', config?.operations?.include); const excludeParameters = createFiltersSetAndRegExps('parameter', config?.parameters?.exclude); const includeParameters = createFiltersSetAndRegExps('parameter', config?.parameters?.include); const excludeRequestBodies = createFiltersSetAndRegExps('body', config?.requestBodies?.exclude); const includeRequestBodies = createFiltersSetAndRegExps('body', config?.requestBodies?.include); const excludeResponses = createFiltersSetAndRegExps('response', config?.responses?.exclude); const includeResponses = createFiltersSetAndRegExps('response', config?.responses?.include); const excludeSchemas = createFiltersSetAndRegExps('schema', config?.schemas?.exclude); const includeSchemas = createFiltersSetAndRegExps('schema', config?.schemas?.include); collectFiltersSetFromRegExps({ excludeOperations, excludeParameters, excludeRequestBodies, excludeResponses, excludeSchemas, includeOperations, includeParameters, includeRequestBodies, includeResponses, includeSchemas, spec, }); const filters: Filters = { deprecated: config?.deprecated ?? true, operations: { exclude: excludeOperations.set, include: includeOperations.set, }, orphans: config?.orphans ?? false, parameters: { exclude: excludeParameters.set, include: includeParameters.set, }, preserveOrder: config?.preserveOrder ?? false, requestBodies: { exclude: excludeRequestBodies.set, include: includeRequestBodies.set, }, responses: { exclude: excludeResponses.set, include: includeResponses.set, }, schemas: { exclude: excludeSchemas.set, include: includeSchemas.set, }, tags: { exclude: new Set(config?.tags?.exclude), include: new Set(config?.tags?.include), }, }; eventCreateFilters.timeEnd(); return filters; }; export const hasFilters = (config: Parser['filters']): boolean => { if (!config) { return false; } // we explicitly want to strip orphans or deprecated if (config.orphans === false || config.deprecated === false) { return true; } return Boolean( config.operations?.exclude?.length || config.operations?.include?.length || config.parameters?.exclude?.length || config.parameters?.include?.length || config.requestBodies?.exclude?.length || config.requestBodies?.include?.length || config.responses?.exclude?.length || config.responses?.include?.length || config.schemas?.exclude?.length || config.schemas?.include?.length || config.tags?.exclude?.length || config.tags?.include?.length, ); }; /** * Collect operations that satisfy the include/exclude filters and schema dependencies. */ const collectOperations = ({ filters, parameters, requestBodies, resourceMetadata, responses, schemas, }: { filters: Filters; parameters: Set; requestBodies: Set; resourceMetadata: ResourceMetadata; responses: Set; schemas: Set; }): { operations: Set; } => { const finalSet = new Set(); const initialSet = filters.operations.include.size ? filters.operations.include : new Set(resourceMetadata.operations.keys()); const stack = [...initialSet]; while (stack.length) { const key = stack.pop()!; if (filters.operations.exclude.has(key) || finalSet.has(key)) { continue; } const node = resourceMetadata.operations.get(key); if (!node) { continue; } if (!filters.deprecated && node.deprecated) { continue; } if ( filters.tags.exclude.size && node.tags.size && [...filters.tags.exclude].some((tag) => node.tags.has(tag)) ) { continue; } if ( filters.tags.include.size && !new Set([...filters.tags.include].filter((tag) => node.tags.has(tag))).size ) { continue; } // skip operation if it references any component not included if ( [...node.dependencies].some((dependency) => { const { namespace } = removeNamespace(dependency); switch (namespace) { case 'body': return !requestBodies.has(dependency); case 'parameter': return !parameters.has(dependency); case 'response': return !responses.has(dependency); case 'schema': return !schemas.has(dependency); default: return false; } }) ) { continue; } finalSet.add(key); } return { operations: finalSet }; }; /** * Collect parameters that satisfy the include/exclude filters and schema dependencies. */ const collectParameters = ({ filters, resourceMetadata, schemas, }: { filters: Filters; resourceMetadata: ResourceMetadata; schemas: Set; }): { parameters: Set; } => { const finalSet = new Set(); const initialSet = filters.parameters.include.size ? filters.parameters.include : new Set(resourceMetadata.parameters.keys()); const stack = [...initialSet]; while (stack.length) { const key = stack.pop()!; if (filters.parameters.exclude.has(key) || finalSet.has(key)) { continue; } const node = resourceMetadata.parameters.get(key); if (!node) { continue; } if (!filters.deprecated && node.deprecated) { continue; } finalSet.add(key); if (!node.dependencies.size) { continue; } for (const dependency of node.dependencies) { const { namespace } = removeNamespace(dependency); switch (namespace) { case 'body': { if (filters.requestBodies.exclude.has(dependency)) { finalSet.delete(key); } else if (!finalSet.has(dependency)) { stack.push(dependency); } break; } case 'schema': { if (filters.schemas.exclude.has(dependency)) { finalSet.delete(key); } else if (!schemas.has(dependency)) { schemas.add(dependency); } break; } } } } return { parameters: finalSet }; }; /** * Collect request bodies that satisfy the include/exclude filters and schema dependencies. */ const collectRequestBodies = ({ filters, resourceMetadata, schemas, }: { filters: Filters; resourceMetadata: ResourceMetadata; schemas: Set; }): { requestBodies: Set; } => { const finalSet = new Set(); const initialSet = filters.requestBodies.include.size ? filters.requestBodies.include : new Set(resourceMetadata.requestBodies.keys()); const stack = [...initialSet]; while (stack.length) { const key = stack.pop()!; if (filters.requestBodies.exclude.has(key) || finalSet.has(key)) { continue; } const node = resourceMetadata.requestBodies.get(key); if (!node) { continue; } if (!filters.deprecated && node.deprecated) { continue; } finalSet.add(key); if (!node.dependencies.size) { continue; } for (const dependency of node.dependencies) { const { namespace } = removeNamespace(dependency); switch (namespace) { case 'body': { if (filters.requestBodies.exclude.has(dependency)) { finalSet.delete(key); } else if (!finalSet.has(dependency)) { stack.push(dependency); } break; } case 'schema': { if (filters.schemas.exclude.has(dependency)) { finalSet.delete(key); } else if (!schemas.has(dependency)) { schemas.add(dependency); } break; } } } } return { requestBodies: finalSet }; }; /** * Collect responses that satisfy the include/exclude filters and schema dependencies. */ const collectResponses = ({ filters, resourceMetadata, schemas, }: { filters: Filters; resourceMetadata: ResourceMetadata; schemas: Set; }): { responses: Set; } => { const finalSet = new Set(); const initialSet = filters.responses.include.size ? filters.responses.include : new Set(resourceMetadata.responses.keys()); const stack = [...initialSet]; while (stack.length) { const key = stack.pop()!; if (filters.responses.exclude.has(key) || finalSet.has(key)) { continue; } const node = resourceMetadata.responses.get(key); if (!node) { continue; } if (!filters.deprecated && node.deprecated) { continue; } finalSet.add(key); if (!node.dependencies.size) { continue; } for (const dependency of node.dependencies) { const { namespace } = removeNamespace(dependency); switch (namespace) { case 'body': { if (filters.requestBodies.exclude.has(dependency)) { finalSet.delete(key); } else if (!finalSet.has(dependency)) { stack.push(dependency); } break; } case 'schema': { if (filters.schemas.exclude.has(dependency)) { finalSet.delete(key); } else if (!schemas.has(dependency)) { schemas.add(dependency); } break; } } } } return { responses: finalSet }; }; /** * Collect schemas that satisfy the include/exclude filters. */ const collectSchemas = ({ filters, resourceMetadata, }: { filters: Filters; resourceMetadata: ResourceMetadata; }): { schemas: Set; } => { const finalSet = new Set(); const initialSet = filters.schemas.include.size ? filters.schemas.include : new Set(resourceMetadata.schemas.keys()); const stack = [...initialSet]; while (stack.length) { const key = stack.pop()!; if (filters.schemas.exclude.has(key) || finalSet.has(key)) { continue; } const node = resourceMetadata.schemas.get(key); if (!node) { continue; } if (!filters.deprecated && node.deprecated) { continue; } finalSet.add(key); if (!node.dependencies.size) { continue; } for (const dependency of node.dependencies) { const { namespace } = removeNamespace(dependency); switch (namespace) { case 'schema': { if (!finalSet.has(dependency) && !filters.schemas.exclude.has(dependency)) { stack.push(dependency); } break; } } } } return { schemas: finalSet }; }; /** * Drop parameters that depend on already excluded parameters. */ const dropExcludedParameters = ({ filters, parameters, resourceMetadata, }: { filters: Filters; parameters: Set; resourceMetadata: ResourceMetadata; }): void => { if (!filters.parameters.exclude.size) { return; } for (const key of parameters) { const node = resourceMetadata.parameters.get(key); if (!node?.dependencies.size) { continue; } for (const excludedKey of filters.parameters.exclude) { if (node.dependencies.has(excludedKey)) { parameters.delete(key); break; } } } }; /** * Drop request bodies that depend on already excluded request bodies. */ const dropExcludedRequestBodies = ({ filters, requestBodies, resourceMetadata, }: { filters: Filters; requestBodies: Set; resourceMetadata: ResourceMetadata; }): void => { if (!filters.requestBodies.exclude.size) { return; } for (const key of requestBodies) { const node = resourceMetadata.requestBodies.get(key); if (!node?.dependencies.size) { continue; } for (const excludedKey of filters.requestBodies.exclude) { if (node.dependencies.has(excludedKey)) { requestBodies.delete(key); break; } } } }; /** * Drop responses that depend on already excluded responses. */ const dropExcludedResponses = ({ filters, resourceMetadata, responses, }: { filters: Filters; resourceMetadata: ResourceMetadata; responses: Set; }): void => { if (!filters.responses.exclude.size) { return; } for (const key of responses) { const node = resourceMetadata.responses.get(key); if (!node?.dependencies.size) { continue; } for (const excludedKey of filters.responses.exclude) { if (node.dependencies.has(excludedKey)) { responses.delete(key); break; } } } }; /** * Drop schemas that depend on already excluded schemas. */ const dropExcludedSchemas = ({ filters, resourceMetadata, schemas, }: { filters: Filters; resourceMetadata: ResourceMetadata; schemas: Set; }): void => { if (!filters.schemas.exclude.size) { return; } for (const key of schemas) { const node = resourceMetadata.schemas.get(key); if (!node?.dependencies.size) { continue; } for (const excludedKey of filters.schemas.exclude) { if (node.dependencies.has(excludedKey)) { schemas.delete(key); break; } } } }; const dropOrphans = ({ operationDependencies, parameters, requestBodies, responses, schemas, }: { operationDependencies: Set; parameters: Set; requestBodies: Set; responses: Set; schemas: Set; }) => { for (const key of schemas) { if (!operationDependencies.has(key)) { schemas.delete(key); } } for (const key of parameters) { if (!operationDependencies.has(key)) { parameters.delete(key); } } for (const key of requestBodies) { if (!operationDependencies.has(key)) { requestBodies.delete(key); } } for (const key of responses) { if (!operationDependencies.has(key)) { responses.delete(key); } } }; const collectOperationDependencies = ({ operations, resourceMetadata, }: { operations: Set; resourceMetadata: ResourceMetadata; }): { operationDependencies: Set; } => { const finalSet = new Set(); const initialSet = new Set( [...operations].flatMap((key) => [ ...(resourceMetadata.operations.get(key)?.dependencies ?? []), ]), ); const stack = [...initialSet]; while (stack.length) { const key = stack.pop()!; if (finalSet.has(key)) { continue; } finalSet.add(key); const { namespace } = removeNamespace(key); let dependencies: Set | undefined; if (namespace === 'body') { dependencies = resourceMetadata.requestBodies.get(key)?.dependencies; } else if (namespace === 'operation') { dependencies = resourceMetadata.operations.get(key)?.dependencies; } else if (namespace === 'parameter') { dependencies = resourceMetadata.parameters.get(key)?.dependencies; } else if (namespace === 'response') { dependencies = resourceMetadata.responses.get(key)?.dependencies; } else if (namespace === 'schema') { dependencies = resourceMetadata.schemas.get(key)?.dependencies; } if (!dependencies?.size) { continue; } for (const dependency of dependencies) { if (!finalSet.has(dependency)) { stack.push(dependency); } } } return { operationDependencies: finalSet }; }; export const createFilteredDependencies = ({ filters, logger, resourceMetadata, }: { filters: Filters; logger: Logger; resourceMetadata: ResourceMetadata; }): { operations: Set; parameters: Set; requestBodies: Set; responses: Set; schemas: Set; } => { const eventCreateFilteredDependencies = logger.timeEvent('create-filtered-dependencies'); const { schemas } = collectSchemas({ filters, resourceMetadata }); const { parameters } = collectParameters({ filters, resourceMetadata, schemas, }); const { requestBodies } = collectRequestBodies({ filters, resourceMetadata, schemas, }); const { responses } = collectResponses({ filters, resourceMetadata, schemas, }); dropExcludedSchemas({ filters, resourceMetadata, schemas }); dropExcludedParameters({ filters, parameters, resourceMetadata }); dropExcludedRequestBodies({ filters, requestBodies, resourceMetadata }); dropExcludedResponses({ filters, resourceMetadata, responses }); // collect operations after dropping components const { operations } = collectOperations({ filters, parameters, requestBodies, resourceMetadata, responses, schemas, }); if (!filters.orphans && operations.size) { const { operationDependencies } = collectOperationDependencies({ operations, resourceMetadata, }); dropOrphans({ operationDependencies, parameters, requestBodies, responses, schemas, }); } eventCreateFilteredDependencies.timeEnd(); return { operations, parameters, requestBodies, responses, schemas, }; }; ================================================ FILE: packages/shared/src/openApi/shared/utils/graph.ts ================================================ import type { Logger } from '@hey-api/codegen-core'; import type { Graph, NodeInfo } from '../../../graph'; import { normalizeJsonPointer, pathToJsonPointer } from '../../../utils/ref'; import { childSchemaRelationships } from './schemaChildRelationships'; /** * Represents the possible access scopes for OpenAPI nodes. * - 'normal': Default scope for regular nodes. * - 'read': Node is read-only (e.g., readOnly: true). * - 'write': Node is write-only (e.g., writeOnly: true). */ export type Scope = 'normal' | 'read' | 'write'; /** * Ensures every relevant child node (e.g., properties, items) in the graph has a `scopes` property. * If a node does not have its own scopes, it inherits from its parent if available. * * @param nodes - Map of JSON Pointer to NodeInfo. */ export const annotateChildScopes = (nodes: Graph['nodes']): void => { for (const [, nodeInfo] of nodes) { if (nodeInfo.scopes) continue; if (nodeInfo.parentPointer) { const parentInfo = nodes.get(nodeInfo.parentPointer); if (parentInfo?.scopes) { nodeInfo.scopes = new Set(parentInfo.scopes); } } } }; interface Cache { parentToChildren: Map>; subtreeDependencies: Map>; transitiveDependencies: Map>; } type PointerDependenciesResult = { subtreeDependencies: Set; transitiveDependencies: Set; }; /** * Recursively collects all $ref dependencies in the subtree rooted at `pointer`. */ const collectPointerDependencies = ({ cache, graph, pointer, visited, }: { cache: Cache; graph: Graph; pointer: string; visited: Set; }): PointerDependenciesResult => { const cached = cache.transitiveDependencies.get(pointer); if (cached) { return { subtreeDependencies: cache.subtreeDependencies.get(pointer)!, transitiveDependencies: cached, }; } if (visited.has(pointer)) { return { subtreeDependencies: new Set(), transitiveDependencies: new Set(), }; } visited.add(pointer); const nodeInfo = graph.nodes.get(pointer); if (!nodeInfo) { return { subtreeDependencies: new Set(), transitiveDependencies: new Set(), }; } const transitiveDependencies = new Set(); const subtreeDependencies = new Set(); // Add direct $ref dependencies for this node // (from the dependencies map, or by checking nodeInfo.node directly) // We'll use the dependencies map for consistency: const nodeDependencies = graph.nodeDependencies.get(pointer); if (nodeDependencies) { for (const depPointer of nodeDependencies) { transitiveDependencies.add(depPointer); subtreeDependencies.add(depPointer); // Recursively collect dependencies of the referenced node const depResult = collectPointerDependencies({ cache, graph, pointer: depPointer, visited, }); for (const dependency of depResult.transitiveDependencies) { transitiveDependencies.add(dependency); } } } const children = cache.parentToChildren.get(pointer) ?? []; for (const childPointer of children) { let childResult: Partial = { subtreeDependencies: cache.subtreeDependencies.get(childPointer), transitiveDependencies: cache.transitiveDependencies.get(childPointer), }; if (!childResult.subtreeDependencies || !childResult.transitiveDependencies) { childResult = collectPointerDependencies({ cache, graph, pointer: childPointer, visited, }); cache.transitiveDependencies.set(childPointer, childResult.transitiveDependencies!); cache.subtreeDependencies.set(childPointer, childResult.subtreeDependencies!); } for (const dependency of childResult.transitiveDependencies!) { transitiveDependencies.add(dependency); } for (const dependency of childResult.subtreeDependencies!) { subtreeDependencies.add(dependency); } } cache.transitiveDependencies.set(pointer, transitiveDependencies); cache.subtreeDependencies.set(pointer, subtreeDependencies); return { subtreeDependencies, transitiveDependencies, }; }; /** * Propagates scopes through the graph using a worklist algorithm. * Each node's scopes will be updated to include any scopes inherited via $ref dependencies, combinator/child relationships, and parent relationships. * Handles cycles and deep chains efficiently. * * Whenever a node's scopes change, all dependents are notified: * - Its parent (if any) * - All nodes that reference it via $ref (reverse dependencies) * - Combinator parents (allOf/anyOf/oneOf) if applicable * * @param graph - The Graph structure containing nodes, dependencies, and reverseNodeDependencies. */ export const propagateScopes = (graph: Graph): void => { const worklist: Set = new Set( Array.from(graph.nodes.entries()) .filter(([, nodeInfo]) => nodeInfo.scopes && nodeInfo.scopes.size > 0) .map(([pointer]) => pointer), ); /** * Notifies all dependents of a node that its scopes may have changed. * Dependents include: * - The parent node (if any) * - All nodes that reference this node via $ref (reverse dependencies) * - Combinator parents (allOf/anyOf/oneOf) if this node is a combinator child * * @param pointer - The JSON pointer of the node whose dependents to notify * @param nodeInfo - The NodeInfo of the node * @param childPointer - (Optional) The pointer of the child, used to detect combinator parents */ const notifyAllDependents = (pointer: string, nodeInfo: NodeInfo, childPointer?: string) => { if (nodeInfo.parentPointer) { worklist.add(nodeInfo.parentPointer); } const reverseNodeDependencies = graph.reverseNodeDependencies.get(pointer); if (reverseNodeDependencies) { for (const dependentPointer of reverseNodeDependencies) { worklist.add(dependentPointer); } } if (childPointer) { // If this is a combinator child, notify the combinator parent const combinatorChildMatch = childPointer.match(/(.*)\/(allOf|anyOf|oneOf)\/\d+$/); if (combinatorChildMatch) { const combinatorParentPointer = combinatorChildMatch[1]; if (combinatorParentPointer) { worklist.add(combinatorParentPointer); } } } }; /** * Propagates scopes from a child node to its parent node. * If the parent's scopes change, notifies all dependents. * * @param pointer - The parent node's pointer * @param nodeInfo - The parent node's NodeInfo * @param childPointer - The child node's pointer */ const propagateChildScopes = ( pointer: string, nodeInfo: NodeInfo, childPointer: string, ): void => { if (!nodeInfo?.scopes) return; const childInfo = graph.nodes.get(childPointer); if (!childInfo?.scopes) return; const changed = propagateScopesToNode(childInfo, nodeInfo); if (changed) { notifyAllDependents(pointer, nodeInfo, childPointer); } }; while (worklist.size > 0) { const pointer = worklist.values().next().value!; worklist.delete(pointer); const nodeInfo = graph.nodes.get(pointer); if (!nodeInfo) continue; if (!nodeInfo.scopes) { nodeInfo.scopes = new Set(); } const node = nodeInfo.node as Record; // Propagate scopes from all child schema relationships (combinators, properties, etc.) for (const [keyword, type] of childSchemaRelationships) { if (!node || typeof node !== 'object' || !(keyword in node)) continue; const value = node[keyword]; if (type === 'array' && value instanceof Array) { for (let index = 0; index < value.length; index++) { const childPointer = `${pointer}/${keyword}/${index}`; propagateChildScopes(pointer, nodeInfo, childPointer); } } else if ( type === 'objectMap' && typeof value === 'object' && value !== null && !(value instanceof Array) ) { for (const key of Object.keys(value)) { const childPointer = `${pointer}/${keyword}/${key}`; propagateChildScopes(pointer, nodeInfo, childPointer); } } else if (type === 'single' && typeof value === 'object' && value !== null) { const childPointer = `${pointer}/${keyword}`; propagateChildScopes(pointer, nodeInfo, childPointer); } else if (type === 'singleOrArray') { if (value instanceof Array) { for (let index = 0; index < value.length; index++) { const childPointer = `${pointer}/${keyword}/${index}`; propagateChildScopes(pointer, nodeInfo, childPointer); } } else if (typeof value === 'object' && value !== null) { const childPointer = `${pointer}/${keyword}`; propagateChildScopes(pointer, nodeInfo, childPointer); } } } // Propagate scopes from $ref dependencies const nodeDependencies = graph.nodeDependencies.get(pointer); if (nodeDependencies) { for (const depPointer of nodeDependencies) { const depNode = graph.nodes.get(depPointer); if (depNode?.scopes) { const changed = propagateScopesToNode(depNode, nodeInfo); if (changed) { notifyAllDependents(pointer, nodeInfo); } } } } // Propagate scopes up the parent chain if (nodeInfo.parentPointer) { const parentInfo = graph.nodes.get(nodeInfo.parentPointer); if (parentInfo) { const changed = propagateScopesToNode(nodeInfo, parentInfo); if (changed) { notifyAllDependents(nodeInfo.parentPointer, parentInfo); } } } } }; /** * Propagates scopes from one node to another. * Adds any scopes from fromNodeInfo to toNodeInfo that are not already present. * Returns true if any scopes were added, false otherwise. * * @param fromNodeInfo - The node to propagate scopes from * @param toNodeInfo - The node to propagate scopes to * @returns boolean - Whether any scopes were added */ const propagateScopesToNode = (fromNodeInfo: NodeInfo, toNodeInfo: NodeInfo): boolean => { if (!fromNodeInfo.scopes) { return false; } if (!toNodeInfo.scopes) { toNodeInfo.scopes = new Set(); } let changed = false; for (const scope of fromNodeInfo.scopes) { if (!toNodeInfo.scopes.has(scope)) { toNodeInfo.scopes.add(scope); changed = true; } } return changed; }; /** * Seeds each node in the graph with its local access scope(s) based on its own properties. * - 'read' if readOnly: true * - 'write' if writeOnly: true * - 'normal' if node is an object property * * Only non-array objects are considered for scope seeding. * * @param nodes - Map of JSON Pointer to NodeInfo. */ export const seedLocalScopes = (nodes: Graph['nodes']): void => { for (const [pointer, nodeInfo] of nodes) { const { node } = nodeInfo; if (typeof node !== 'object' || node === null || node instanceof Array) { continue; } if ('readOnly' in node && node.readOnly === true) { nodeInfo.scopes = new Set(['read']); } else if ('writeOnly' in node && node.writeOnly === true) { nodeInfo.scopes = new Set(['write']); } else if (pointer.match(/\/properties\/[^/]+$/)) { nodeInfo.scopes = new Set(['normal']); } } }; /** * Builds a graph of all nodes in an OpenAPI spec, indexed by normalized JSON Pointer, * and tracks all $ref dependencies and reverse dependencies between nodes. * * - All keys in the returned maps are normalized JSON Pointers (RFC 6901, always starting with '#'). * - The `nodes` map allows fast lookup of any node and its parent/key context. * - The `dependencies` map records, for each node, the set of normalized pointers it references via $ref. * - The `reverseNodeDependencies` map records, for each node, the set of nodes that reference it via $ref. * - After construction, all nodes will have their local and propagated scopes annotated. * * @param root The root object (e.g., the OpenAPI spec) * @returns An object with: * - nodes: Map from normalized JSON Pointer string to NodeInfo * - dependencies: Map from normalized JSON Pointer string to Set of referenced normalized JSON Pointers * - reverseNodeDependencies: Map from normalized JSON Pointer string to Set of referencing normalized JSON Pointers */ export function buildGraph( root: unknown, logger: Logger, ): { graph: Graph; } { const eventBuildGraph = logger.timeEvent('build-graph'); const graph: Graph = { nodeDependencies: new Map(), nodes: new Map(), reverseNodeDependencies: new Map(), subtreeDependencies: new Map(), transitiveDependencies: new Map(), }; const walk = ({ key, node, parentPointer, path, }: NodeInfo & { path: ReadonlyArray; }) => { if (typeof node !== 'object' || node === null) { return; } const pointer = pathToJsonPointer(path); let deprecated: boolean | undefined; let tags: Set | undefined; if (typeof node === 'object' && node !== null) { // Check for deprecated property if ('deprecated' in node && typeof node.deprecated === 'boolean') { deprecated = Boolean(node.deprecated); } // If this node has a $ref, record the dependency if ('$ref' in node && typeof node.$ref === 'string') { const refPointer = normalizeJsonPointer(node.$ref); if (!graph.nodeDependencies.has(pointer)) { graph.nodeDependencies.set(pointer, new Set()); } graph.nodeDependencies.get(pointer)!.add(refPointer); } // Check for tags property (should be an array of strings) if ('tags' in node && node.tags instanceof Array) { tags = new Set(node.tags.filter((tag) => typeof tag === 'string')); } } graph.nodes.set(pointer, { deprecated, key, node, parentPointer, tags }); if (node instanceof Array) { node.forEach((item, index) => walk({ key: index, node: item, parentPointer: pointer, path: [...path, index], }), ); } else { for (const [childKey, value] of Object.entries(node)) { walk({ key: childKey, node: value, parentPointer: pointer, path: [...path, childKey], }); } } }; walk({ key: null, node: root, parentPointer: null, path: [], }); const cache: Cache = { parentToChildren: new Map(), subtreeDependencies: new Map(), transitiveDependencies: new Map(), }; for (const [pointer, nodeInfo] of graph.nodes) { const parent = nodeInfo.parentPointer; if (!parent) continue; if (!cache.parentToChildren.has(parent)) { cache.parentToChildren.set(parent, []); } cache.parentToChildren.get(parent)!.push(pointer); } for (const [pointerFrom, pointers] of graph.nodeDependencies) { for (const pointerTo of pointers) { if (!graph.reverseNodeDependencies.has(pointerTo)) { graph.reverseNodeDependencies.set(pointerTo, new Set()); } graph.reverseNodeDependencies.get(pointerTo)!.add(pointerFrom); } } seedLocalScopes(graph.nodes); propagateScopes(graph); annotateChildScopes(graph.nodes); for (const pointer of graph.nodes.keys()) { const result = collectPointerDependencies({ cache, graph, pointer, visited: new Set(), }); graph.transitiveDependencies.set(pointer, result.transitiveDependencies); graph.subtreeDependencies.set(pointer, result.subtreeDependencies); } eventBuildGraph.timeEnd(); // functions creating data for debug scripts located in `dev/` // const { maxChildren, maxDepth, totalNodes } = debugTools.graph.analyzeStructure(graph); // const nodesForViz = debugTools.graph.exportForVisualization(graph); // fs.writeFileSync('dev/graph.json', JSON.stringify(nodesForViz, null, 2)); return { graph }; } ================================================ FILE: packages/shared/src/openApi/shared/utils/operation.ts ================================================ import type { Context } from '../../../ir/context'; import { createOperationKey } from '../../../ir/operation'; import { toCase } from '../../../utils/naming/naming'; import type { State } from '../types/state'; export const httpMethods = [ 'delete', 'get', 'head', 'options', 'patch', 'post', 'put', 'trace', ] as const; /** * Sanitizes namespace identifiers so they are valid TypeScript identifiers of a certain form. * * 1: Remove any leading characters that are illegal as starting character of a typescript identifier. * 2: Replace illegal characters in remaining part of type name with hyphen (-). * * Step 1 should perhaps instead also replace illegal characters with underscore, or prefix with it, like sanitizeEnumName * does. The way this is now one could perhaps end up removing all characters, if all are illegal start characters. It * would be sort of a breaking change to do so, though, previously generated code might change then. * * JavaScript identifier regexp pattern retrieved from https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers * * The output of this is expected to be converted to PascalCase * * @deprecated */ export const sanitizeNamespaceIdentifier = (name: string) => name .replace(/^[^\p{ID_Start}]+/u, '') .replace(/[^$\u200c\u200d\p{ID_Continue}]/gu, '-') .replace(/[$+]/g, '-'); /** * Returns an operation ID to use across the application. By default, we try * to use the provided ID. If it's not provided or the SDK is configured * to exclude it, we generate operation ID from its location. * * @deprecated */ export function operationToId({ context, count = 1, id, method, path, state, }: { context: Context; count?: number; id: string | undefined; method: string; path: string; state: Pick; }): string { let result: string; const { output } = context.config; const targetCase = (output !== undefined && typeof output === 'object' && 'case' in output ? output.case : undefined) ?? 'camelCase'; if ( id && (!context.config.plugins['@hey-api/sdk'] || // TODO: needs to be refactored... // @ts-expect-error (context.config.plugins['@hey-api/sdk'].config.operations && // @ts-expect-error typeof context.config.plugins['@hey-api/sdk'].config.operations !== 'function' && // @ts-expect-error typeof context.config.plugins['@hey-api/sdk'].config.operations === 'object' && // @ts-expect-error context.config.plugins['@hey-api/sdk'].config.operations.nesting === 'operationId')) ) { result = toCase(sanitizeNamespaceIdentifier(id), targetCase); } else { const pathWithoutPlaceholders = path .replace(/{(.*?)}/g, 'by-$1') // replace slashes with hyphens for camelcase method at the end .replace(/[/:+]/g, '-'); result = toCase(`${method}-${pathWithoutPlaceholders}`, targetCase); } if (count > 1) { result = `${result}${count}`; } if (state.ids.has(result)) { return operationToId({ context, count: count + 1, id, method, path, state, }); } state.ids.set(result, createOperationKey({ method, path })); return result; } ================================================ FILE: packages/shared/src/openApi/shared/utils/parameter.ts ================================================ import type { IR } from '../../../ir/types'; export const mergeParametersObjects = ({ source, target, }: { source: IR.ParametersObject | undefined; target: IR.ParametersObject | undefined; }): IR.ParametersObject | undefined => { const result = { ...target }; if (source) { if (source.cookie) { if (result.cookie) { result.cookie = { ...result.cookie, ...source.cookie, }; } else { result.cookie = source.cookie; } } if (source.header) { if (result.header) { result.header = { ...result.header, ...source.header, }; } else { result.header = source.header; } } if (source.path) { if (result.path) { result.path = { ...result.path, ...source.path, }; } else { result.path = source.path; } } if (source.query) { if (result.query) { result.query = { ...result.query, ...source.query, }; } else { result.query = source.query; } } } if (!Object.keys(result).length) { return; } return result; }; ================================================ FILE: packages/shared/src/openApi/shared/utils/patch.ts ================================================ import type { Patch } from '../../../config/parser/patch'; import type { OpenApi } from '../../../openApi/types'; export async function patchOpenApiSpec({ patchOptions, spec: _spec, }: { patchOptions: Patch | undefined; spec: unknown; }) { if (!patchOptions) { return; } const spec = _spec as OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X; if (typeof patchOptions === 'function') { await patchOptions(spec); return; } if (patchOptions.input) { await patchOptions.input(spec); } if ('swagger' in spec) { if (patchOptions.version && spec.swagger) { spec.swagger = ( typeof patchOptions.version === 'string' ? patchOptions.version : patchOptions.version(spec.swagger) ) as typeof spec.swagger; } if (patchOptions.meta && spec.info) { patchOptions.meta(spec.info); } if (patchOptions.schemas && spec.definitions) { if (typeof patchOptions.schemas === 'function') { for (const [key, schema] of Object.entries(spec.definitions)) { if (schema && typeof schema === 'object') { await patchOptions.schemas(key, schema); } } } else { for (const key in patchOptions.schemas) { const schema = spec.definitions[key]; if (!schema || typeof schema !== 'object') continue; const patchFn = patchOptions.schemas[key]!; await patchFn(schema); } } } if (patchOptions.operations && spec.paths) { if (typeof patchOptions.operations === 'function') { // Bulk callback: iterate all operations for (const [path, pathItem] of Object.entries(spec.paths)) { if (!pathItem || typeof pathItem !== 'object') continue; for (const method of [ 'get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace', ]) { const operation = pathItem[method as keyof typeof pathItem]; if (!operation || typeof operation !== 'object') continue; await patchOptions.operations(method, path, operation as any); } } } else { // Record-based: iterate named operations for (const key in patchOptions.operations) { const [method, path] = key.split(' '); if (!method || !path) continue; const pathItem = spec.paths[path as keyof typeof spec.paths]; if (!pathItem) continue; const operation = pathItem[method.toLocaleLowerCase() as keyof typeof pathItem] || pathItem[method.toLocaleUpperCase() as keyof typeof pathItem]; if (!operation || typeof operation !== 'object') continue; const patchFn = patchOptions.operations[key]!; await patchFn(operation as any); } } } return; } if (patchOptions.version && spec.openapi) { spec.openapi = ( typeof patchOptions.version === 'string' ? patchOptions.version : patchOptions.version(spec.openapi) ) as typeof spec.openapi; } if (patchOptions.meta && spec.info) { patchOptions.meta(spec.info); } if (spec.components) { if (patchOptions.schemas && spec.components.schemas) { if (typeof patchOptions.schemas === 'function') { for (const [key, schema] of Object.entries(spec.components.schemas)) { if (schema && typeof schema === 'object') { await patchOptions.schemas(key, schema as Parameters[1]); } } } else { for (const key in patchOptions.schemas) { const schema = spec.components.schemas[key]; if (!schema || typeof schema !== 'object') continue; const patchFn = patchOptions.schemas[key]!; await patchFn(schema as Parameters[0]); } } } if (patchOptions.parameters && spec.components.parameters) { for (const key in patchOptions.parameters) { const schema = spec.components.parameters[key]; if (!schema || typeof schema !== 'object') continue; const patchFn = patchOptions.parameters[key]!; patchFn(schema); } } if (patchOptions.requestBodies && spec.components.requestBodies) { for (const key in patchOptions.requestBodies) { const schema = spec.components.requestBodies[key]; if (!schema || typeof schema !== 'object') continue; const patchFn = patchOptions.requestBodies[key]!; patchFn(schema); } } if (patchOptions.responses && spec.components.responses) { for (const key in patchOptions.responses) { const schema = spec.components.responses[key]; if (!schema || typeof schema !== 'object') continue; const patchFn = patchOptions.responses[key]!; patchFn(schema); } } } if (patchOptions.operations && spec.paths) { if (typeof patchOptions.operations === 'function') { // Bulk callback: iterate all operations for (const [path, pathItem] of Object.entries(spec.paths)) { if (!pathItem || typeof pathItem !== 'object') continue; for (const method of [ 'get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace', ]) { const operation = pathItem[method as keyof typeof pathItem]; if (!operation || typeof operation !== 'object') continue; await patchOptions.operations(method, path, operation as any); } } } else { // Record-based: iterate named operations for (const key in patchOptions.operations) { const [method, path] = key.split(' '); if (!method || !path) continue; const pathItem = spec.paths[path as keyof typeof spec.paths]; if (!pathItem) continue; const operation = pathItem[method.toLocaleLowerCase() as keyof typeof pathItem] || pathItem[method.toLocaleUpperCase() as keyof typeof pathItem]; if (!operation || typeof operation !== 'object') continue; const patchFn = patchOptions.operations[key]!; await patchFn(operation as any); } } } } ================================================ FILE: packages/shared/src/openApi/shared/utils/schema.ts ================================================ export const deepClone = (obj: T): T => JSON.parse(JSON.stringify(obj)); ================================================ FILE: packages/shared/src/openApi/shared/utils/schemaChildRelationships.ts ================================================ export const childSchemaRelationships = [ ['additionalProperties', 'single'], ['allOf', 'array'], ['anyOf', 'array'], ['contains', 'single'], ['dependentSchemas', 'objectMap'], ['else', 'single'], ['if', 'single'], ['items', 'singleOrArray'], ['oneOf', 'array'], ['patternProperties', 'objectMap'], ['properties', 'objectMap'], ['propertyNames', 'single'], ['then', 'single'], ['unevaluatedProperties', 'single'], ] as const; ================================================ FILE: packages/shared/src/openApi/shared/utils/transforms.ts ================================================ export const getSchemasObject = (spec: unknown): Record | undefined => { if (hasComponentsSchemasObject(spec)) { return (spec as any).components.schemas; } if (hasDefinitionsObject(spec)) { return (spec as any).definitions; } return; }; /** * Checks if the given spec has a valid OpenAPI 3.x components.schemas object. * Returns true if present, false otherwise. */ export const hasComponentsSchemasObject = (spec: unknown): boolean => typeof spec === 'object' && spec !== null && 'components' in spec && typeof (spec as any).components === 'object' && (spec as any).components !== null && 'schemas' in (spec as any).components && typeof (spec as any).components.schemas === 'object' && (spec as any).components.schemas !== null; /** * Checks if the given spec has a valid OpenAPI 2.0 definitions object. * Returns true if present, false otherwise. */ export const hasDefinitionsObject = (spec: unknown): boolean => typeof spec === 'object' && spec !== null && 'definitions' in spec && typeof (spec as any).definitions === 'object' && (spec as any).definitions !== null; ================================================ FILE: packages/shared/src/openApi/shared/utils/validator.ts ================================================ import colors from 'ansi-colors'; import type { Context } from '../../../ir/context'; export interface ValidatorIssue { /** * Machine-readable issue code * * @example * 'invalid_type' */ code: 'duplicate_key' | 'invalid_type' | 'missing_required_field'; /** * Optional additional data. * * @example * 'expectedType' */ context?: Record; /** * Human-readable issue summary. */ message: string; /** * JSONPath-like array to issue location. */ path: ReadonlyArray; /** * Error severity. */ severity: 'error' | 'warning'; } export interface ValidatorResult { issues: ReadonlyArray; valid: boolean; } const isSimpleKey = (key: string) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key); const formatPath = (path: ReadonlyArray): string => path .map((segment, i) => { if (typeof segment === 'number') { return `[${segment}]`; } if (i === 0) { // first segment no dot or brackets return segment; } return isSimpleKey(segment) ? `.${segment}` : `['${segment.replace(/"/g, "\\'")}']`; }) .join(''); const formatValidatorIssue = (issue: ValidatorIssue): string => { const pathStr = formatPath(issue.path); const level = issue.severity === 'error' ? colors.bold.red : colors.bold.yellow; const highlightedMessage = issue.message.replace(/`([^`]+)`/g, (_, code) => colors.yellow(`\`${code}\``), ); return `${level(`[${issue.severity.toUpperCase()}]`)} ${colors.cyan(pathStr)}: ${highlightedMessage}`; }; const shouldPrint = ({ context, issue }: { context: Context; issue: ValidatorIssue }) => { if (context.config.logs.level === 'silent') { return false; } if (issue.severity === 'error') { return context.config.logs.level !== 'warn'; } return true; }; export const handleValidatorResult = ({ context, result, }: { context: Context; result: ValidatorResult; }) => { for (const issue of result.issues) { if (shouldPrint({ context, issue })) { console.log(formatValidatorIssue(issue)); } } if (!result.valid) { process.exit(1); } }; ================================================ FILE: packages/shared/src/openApi/types.ts ================================================ /* eslint-disable @typescript-eslint/no-namespace */ import type { OpenApiV2_0_X, OpenApiV2_0_XTypes } from './2.0.x'; import type { OpenApiV3_0_X, OpenApiV3_0_XTypes } from './3.0.x'; import type { OpenApiV3_1_X, OpenApiV3_1_XTypes } from './3.1.x'; export namespace OpenApi { export type V2_0_X = OpenApiV2_0_X; export type V3_0_X = OpenApiV3_0_X; export type V3_1_X = OpenApiV3_1_X; } export namespace OpenApiMetaObject { export type V2_0_X = OpenApiV2_0_XTypes['InfoObject']; export type V3_0_X = OpenApiV3_0_XTypes['InfoObject']; export type V3_1_X = OpenApiV3_1_XTypes['InfoObject']; } export namespace OpenApiOperationObject { export type V2_0_X = OpenApiV2_0_XTypes['OperationObject']; export type V3_0_X = OpenApiV3_0_XTypes['OperationObject']; export type V3_1_X = OpenApiV3_1_XTypes['OperationObject']; } export namespace OpenApiParameterObject { export type V3_0_X = | OpenApiV3_0_XTypes['ParameterObject'] | OpenApiV3_0_XTypes['ReferenceObject']; export type V3_1_X = | OpenApiV3_1_XTypes['ParameterObject'] | OpenApiV3_1_XTypes['ReferenceObject']; } export namespace OpenApiRequestBodyObject { export type V3_0_X = | OpenApiV3_0_XTypes['RequestBodyObject'] | OpenApiV3_0_XTypes['ReferenceObject']; export type V3_1_X = | OpenApiV3_1_XTypes['RequestBodyObject'] | OpenApiV3_1_XTypes['ReferenceObject']; } export namespace OpenApiResponseObject { export type V3_0_X = OpenApiV3_0_XTypes['ResponseObject'] | OpenApiV3_0_XTypes['ReferenceObject']; export type V3_1_X = OpenApiV3_1_XTypes['ResponseObject'] | OpenApiV3_1_XTypes['ReferenceObject']; } export namespace OpenApiSchemaObject { export type V2_0_X = OpenApiV2_0_XTypes['SchemaObject']; export type V3_0_X = OpenApiV3_0_XTypes['SchemaObject']; export type V3_1_X = OpenApiV3_1_XTypes['SchemaObject']; } ================================================ FILE: packages/shared/src/parser/hooks.ts ================================================ import type { Node, Symbol, SymbolIn, SymbolMeta } from '@hey-api/codegen-core'; import type { MaybeFunc } from '@hey-api/types'; import type { SchemaProcessorContext } from '../ir/schema-processor'; import type { IROperationObject, IRSchemaObject } from '../ir/types'; import type { PluginInstance } from '../plugins/shared/utils/instance'; import type { NamingConfig } from '../utils/naming/types'; export type Hooks = { /** * Event hooks. */ events?: { /** * Triggered after adding or updating a node. * * You can use this to perform actions after a node is added or updated. * * @param args Arguments object. * @returns void */ 'node:set:after'?: (args: { /** The node added or updated. */ node: Node | null; /** Plugin that added or updated the node. */ plugin: PluginInstance; }) => void; /** * Triggered before adding or updating a node. * * You can use this to modify the node before it's added or updated. * * @param args Arguments object. * @returns void */ 'node:set:before'?: (args: { /** The node to be added or updated. */ node: Node | null; /** Plugin adding or updating the node. */ plugin: PluginInstance; }) => void; /** * Triggered after executing a plugin handler. * * @param args Arguments object. * @returns void */ 'plugin:handler:after'?: (args: { /** Plugin that just executed. */ plugin: PluginInstance; }) => void; /** * Triggered before executing a plugin handler. * * @param args Arguments object. * @returns void */ 'plugin:handler:before'?: (args: { /** Plugin about to execute. */ plugin: PluginInstance; }) => void; /** * Triggered after registering a symbol. * * You can use this to perform actions after a symbol is registered. * * @param args Arguments object. * @returns void */ 'symbol:register:after'?: (args: { /** Plugin that registered the symbol. */ plugin: PluginInstance; /** The registered symbol. */ symbol: Symbol; }) => void; /** * Triggered before registering a symbol. * * You can use this to modify the symbol before it's registered. * * @param args Arguments object. * @returns void */ 'symbol:register:before'?: (args: { /** Plugin registering the symbol. */ plugin: PluginInstance; /** Symbol to register. */ symbol: SymbolIn; }) => void; }; /** * Hooks specifically for overriding operations behavior. * * Use these to classify operations, decide which outputs to generate, * or apply custom behavior to individual operations. */ operations?: { /** * Classify the given operation into one or more kinds. * * Each kind determines how we treat the operation (e.g., generating queries or mutations). * * **Default behavior:** * - GET → 'query' * - DELETE, PATCH, POST, PUT → 'mutation' * * **Resolution order:** * 1. If `isQuery` or `isMutation` returns `true` or `false`, that overrides `getKind`. * 2. If `isQuery` or `isMutation` returns `undefined`, the result of `getKind` is used. * * @param operation - The operation object to classify. * @returns An array containing one or more of 'query' or 'mutation', or undefined to fallback to default behavior. * @example * ```ts * getKind: (operation) => { * if (operation.method === 'get' && operation.path === '/search') { * return ['query', 'mutation']; * } * return; // fallback to default behavior * } * ``` */ getKind?: (operation: IROperationObject) => ReadonlyArray<'mutation' | 'query'> | undefined; /** * Check if the given operation should be treated as a mutation. * * This affects which outputs are generated for the operation. * * **Default behavior:** DELETE, PATCH, POST, and PUT operations are treated as mutations. * * **Resolution order:** If this returns `true` or `false`, it overrides `getKind`. * If it returns `undefined`, `getKind` is used instead. * * @param operation - The operation object to check. * @returns true if the operation is a mutation, false otherwise, or undefined to fallback to `getKind`. * @example * ```ts * isMutation: (operation) => { * if (operation.method === 'post' && operation.path === '/search') { * return true; * } * return; // fallback to default behavior * } * ``` */ isMutation?: (operation: IROperationObject) => boolean | undefined; /** * Check if the given operation should be treated as a query. * * This affects which outputs are generated for the operation. * * **Default behavior:** GET operations are treated as queries. * * **Resolution order:** If this returns `true` or `false`, it overrides `getKind`. * If it returns `undefined`, `getKind` is used instead. * * @param operation - The operation object to check. * @returns true if the operation is a query, false otherwise, or undefined to fallback to `getKind`. * @example * ```ts * isQuery: (operation) => { * if (operation.method === 'post' && operation.path === '/search') { * return true; * } * return; // fallback to default behavior * } * ``` */ isQuery?: (operation: IROperationObject) => boolean | undefined; }; schemas?: { /** * Whether to extract the given schema into a separate symbol. * * This affects how schemas are processed and output. * * **Default behavior:** No schemas are extracted. * * @param ctx - The processing context for the schema. * @returns true to extract the schema, false to keep it inline, or undefined to fallback to default behavior. * @example * ```ts * shouldExtract: (ctx) => { * if (ctx.meta.resource === 'requestBody') { * return true; * } * return; // fallback to default behavior * } * ``` */ shouldExtract?: (ctx: SchemaProcessorContext) => boolean; }; /** * Hooks specifically for overriding symbols behavior. * * Use these to customize file placement. */ symbols?: { /** * Optional output strategy to override default plugin behavior. * * Use this to re-export symbols from specific files. * * @returns The file path(s) that re-export this symbol, or undefined to fallback to default behavior. */ getExportFromFilePath?: (symbol: Symbol) => ReadonlyArray | undefined; /** * Optional output strategy to override default plugin behavior. * * Use this to route symbols to specific files. * * @returns The file path to output the symbol to, or undefined to fallback to default behavior. */ getFilePath?: (symbol: Symbol) => string | undefined; /** * Optional output strategy to override default plugin behavior. * * Use this to customize symbol names. * * @returns The name to register the symbol with, or undefined to fallback to default behavior. */ getName?: (ctx: GetNameContext) => MaybeFunc<(ctx: GetNameContext) => string | undefined>; }; }; export interface GetNameContext { /** Arbitrary metadata about the symbol. */ meta: SymbolMeta; /** The proposed name for the symbol. */ name: string; /** The naming configuration for the symbol. */ naming?: NamingConfig; /** The operation object associated with the symbol. */ operation?: IROperationObject; /** The schema object associated with the symbol. */ schema?: IRSchemaObject; } ================================================ FILE: packages/shared/src/plugins/shared/types/instance.ts ================================================ import type { IrTopLevelKind } from '../../../ir/graph'; import type { IR } from '../../../ir/types'; export type BaseEvent = { /** * Path to the node, derived from the pointer. */ _path: ReadonlyArray; /** * Pointer to the node in the graph. */ pointer: string; /** * Tags associated with the node. */ tags?: ReadonlyArray; }; type WalkEvents = BaseEvent & ( | { method: keyof IR.PathItemObject; operation: IR.OperationObject; path: string; type: Extract; } | { /** Name of the parameter (e.g., "id" for a parameter defined as "#/components/parameters/id"). */ name: string; parameter: IR.ParameterObject; type: Extract; } | { /** Name of the request body (e.g., "CreateUserRequest" for a request body defined as "#/components/requestBodies/CreateUserRequest"). */ name: string; requestBody: IR.RequestBodyObject; type: Extract; } | { /** Name of the schema (e.g., "User" for a schema defined as "#/components/schemas/User"). */ name: string; schema: IR.SchemaObject; type: Extract; } | { server: IR.ServerObject; type: Extract; } | { key: string; method: keyof IR.PathItemObject; operation: IR.OperationObject; type: Extract; } ); export type WalkEvent = Extract; ================================================ FILE: packages/shared/src/plugins/shared/types/schema.ts ================================================ import type { IR } from '../../../ir/types'; export type SchemaWithType< T extends Required['type'] = Required['type'], > = Omit & { type: Extract['type'], T>; }; ================================================ FILE: packages/shared/src/plugins/shared/utils/config.ts ================================================ import type { Plugin } from '../../types'; export const definePluginConfig = (defaultConfig: Plugin.Config) => ( userConfig?: Omit, ): Omit, 'name'> & { /** * Cast name to `any` so it doesn't throw type error in `plugins` array. * We could allow any `string` as plugin `name` in the object syntax, but * that TypeScript trick would cause all string methods to appear as * suggested auto completions, which is undesirable. */ name: any; } => ({ ...defaultConfig, config: { ...defaultConfig.config, ...userConfig, }, }); /** * Reusable mappers for `enabled` and `name` fields. */ export const mappers = { boolean: (enabled: boolean) => ({ enabled }), function: (name: (...args: Array) => any) => ({ name }), string: (name: string) => ({ name }), } as const; ================================================ FILE: packages/shared/src/plugins/shared/utils/instance.ts ================================================ import path from 'node:path'; import type { IProject, Node, Symbol, SymbolIdentifier, SymbolIn, SymbolMeta, } from '@hey-api/codegen-core'; import type { Dependency } from '../../../config/utils/dependencies'; import { HeyApiError } from '../../../error'; import type { MatchPointerToGroupFn, WalkOptions } from '../../../graph'; import { walk } from '../../../graph'; import type { Context } from '../../../ir/context'; import type { IrTopLevelKind } from '../../../ir/graph'; import { getIrPointerPriority, irTopLevelKinds, matchIrPointerToGroup, preferGroups, } from '../../../ir/graph'; import type { ExampleIntent } from '../../../ir/intents'; import type { IR } from '../../../ir/types'; import type { Hooks } from '../../../parser/hooks'; import { jsonPointerToPath } from '../../../utils/ref'; import type { Plugin, PluginConfigMap } from '../../types'; import type { BaseEvent, WalkEvent } from '../types/instance'; // eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface PluginInstanceTypes {} /** * Resolves the Node type, falling back to base Node if not augmented. */ type ResolvedNode = 'Node' extends keyof PluginInstanceTypes ? // @ts-expect-error ts cannot resolve conditional types properly here PluginInstanceTypes['Node'] : Node; // TODO: abstract const defaultGetFilePath = (symbol: Symbol): string | undefined => { if (!symbol.meta?.pluginName || typeof symbol.meta.pluginName !== 'string') { return; } if (symbol.meta.pluginName.startsWith('@hey-api/client-')) { return 'client'; } if (symbol.meta.pluginName === '@hey-api/typescript') { return 'types'; } if (symbol.meta.pluginName === '@hey-api/python-sdk') { return 'sdk'; } if (symbol.meta.pluginName.startsWith('@hey-api/')) { return symbol.meta.pluginName.split('/')[1]; } return symbol.meta.pluginName; }; const defaultGetKind: Required['operations']>['getKind'] = (operation) => { switch (operation.method) { case 'delete': case 'patch': case 'post': case 'put': return ['mutation']; case 'get': return ['query']; default: return; } }; type EventHooks = { [K in keyof Required>]: Array< NonNullable[K]> >; }; export class PluginInstance { api: T['api']; config: Omit; context: Context; dependencies: Required>['dependencies'] = []; private eventHooks: EventHooks; gen: IProject; private handler: Plugin.Config['handler']; name: T['resolvedConfig']['name']; /** * The package metadata and utilities for the current context, constructed * from the provided dependencies. Used for managing package-related * information such as name, version, and dependency resolution during * code generation. */ package: Dependency; constructor( props: Pick>, 'config' | 'dependencies' | 'handler'> & { api?: T['api']; context: Context; gen: IProject; name: string; }, ) { this.api = props.api ?? {}; this.config = props.config; this.context = props.context; this.dependencies = props.dependencies; this.eventHooks = this.buildEventHooks(); this.gen = props.gen; this.handler = props.handler; this.name = props.name; this.package = props.context.package; } external( resource: Required['resource'], meta?: Omit, ): Symbol { return this.gen.symbols.reference({ ...meta, category: 'external', resource, }); } /** * Iterates over various input elements as specified by the event types, in * a specific order: servers, schemas, parameters, request bodies, then * operations. * * This ensures, for example, that schemas are always processed before * operations, which may reference them. * * @template TKind - The event type(s) to yield. Defaults to all event types. * @param events - The event types to walk over. If none are provided, all event types are included. * @param callback - Function to execute for each event. * * @example * // Iterate over all operations and schemas * plugin.forEach('operation', 'schema', (event) => { * if (event.type === 'operation') { * // handle operation * } else if (event.type === 'schema') { * // handle schema * } * }); */ forEach( ...args: [...events: ReadonlyArray, callback: (event: WalkEvent) => void] ): void; forEach( ...args: [ ...events: ReadonlyArray, callback: (event: WalkEvent) => void, options: WalkOptions, ] ): void; forEach( ...args: [ ...events: ReadonlyArray, callback: (event: WalkEvent) => void, options: any, ] ): void { if (!this.context.graph) { throw new Error('No graph available in context'); } let callback: (event: WalkEvent) => void; let events: ReadonlyArray; let options: WalkOptions = { getPointerPriority: getIrPointerPriority, // default functions operate on the full union of kinds; cast them // to the WalkOptions generic to keep strict typing for callers. matchPointerToGroup: matchIrPointerToGroup as unknown as MatchPointerToGroupFn, order: 'topological', preferGroups: preferGroups as unknown as ReadonlyArray, }; if (typeof args[args.length - 1] === 'function') { events = args.slice(0, -1); callback = args[args.length - 1]; } else { events = args.slice(0, -2); callback = args[args.length - 2]; options = { ...options, ...args[args.length - 1], }; } const eventSet = new Set(events.length ? events : irTopLevelKinds); walk( this.context.graph, (pointer, nodeInfo) => { const result = matchIrPointerToGroup(pointer); if (!result.matched || !eventSet.has(result.kind)) return; let event: WalkEvent | undefined; const baseEvent: BaseEvent = { _path: jsonPointerToPath(pointer), pointer, tags: nodeInfo.tags ? Array.from(nodeInfo.tags) : undefined, }; switch (result.kind) { case 'operation': event = { ...baseEvent, method: nodeInfo.key as keyof IR.PathItemObject, operation: nodeInfo.node as IR.OperationObject, path: baseEvent._path[1] as string, type: result.kind, } satisfies WalkEvent<'operation'>; break; case 'parameter': event = { ...baseEvent, name: nodeInfo.key as string, parameter: nodeInfo.node as IR.ParameterObject, type: result.kind, } satisfies WalkEvent<'parameter'>; break; case 'requestBody': event = { ...baseEvent, name: nodeInfo.key as string, requestBody: nodeInfo.node as IR.RequestBodyObject, type: result.kind, } satisfies WalkEvent<'requestBody'>; break; case 'schema': event = { ...baseEvent, name: nodeInfo.key as string, schema: nodeInfo.node as IR.SchemaObject, type: result.kind, } satisfies WalkEvent<'schema'>; break; case 'server': event = { ...baseEvent, server: nodeInfo.node as IR.ServerObject, type: result.kind, } satisfies WalkEvent<'server'>; break; case 'webhook': event = { ...baseEvent, key: baseEvent._path[1] as string, method: nodeInfo.key as keyof IR.PathItemObject, operation: nodeInfo.node as IR.OperationObject, type: result.kind, } satisfies WalkEvent<'webhook'>; break; } if (event) { try { callback(event as WalkEvent); } catch (error) { this.forEachError(error, event); } } }, options, ); } /** * Retrieves a registered plugin instance by its name from the context. This * allows plugins to access other plugins that have been registered in the * same context, enabling cross-plugin communication and dependencies. * * @param name Plugin name as defined in the configuration. * @returns The plugin instance if found, undefined otherwise. */ getPlugin( name: TName, ): TName extends any ? PluginInstance | undefined : never { return this.context.plugins[name] as any; } /** * Retrieves a registered plugin instance by its name from the context. This * allows plugins to access other plugins that have been registered in the * same context, enabling cross-plugin communication and dependencies. * * @param name Plugin name as defined in the configuration. * @returns The plugin instance if found, throw otherwise. */ getPluginOrThrow( name: TName, ): TName extends any ? PluginInstance : never { const plugin = this.getPlugin(name); if (!plugin) throw new Error(`plugin not found ${name}`); return plugin as any; } getSymbol(identifier: SymbolIdentifier): Symbol | undefined { return this.gen.symbols.get(identifier); } hooks = { operation: { isMutation: (operation: IR.OperationObject): boolean => this.isOperationKind(operation, 'mutation'), isQuery: (operation: IR.OperationObject): boolean => this.isOperationKind(operation, 'query'), }, }; /** * Registers an intent in the context's intent list. * * @param intent The intent to be registered. * @returns void */ intent(intent: ExampleIntent): void { this.context.intents.push(intent); } isSymbolRegistered(identifier: SymbolIdentifier): boolean { return this.gen.symbols.isRegistered(identifier); } /** * Sets or adds a node to the project graph. * * @param node The node to be added or updated in the project graph. * @param index The index at which to update the node. If undefined, the node will be added. * @returns The index of the added node or void if updated. */ node( node: Node | null, index?: T, ): T extends number ? void : number { for (const hook of this.eventHooks['node:set:before']) { hook({ node, plugin: this as any }); } const result = index !== undefined ? this.gen.nodes.update(index, node) : this.gen.nodes.add(node); for (const hook of this.eventHooks['node:set:after']) { hook({ node, plugin: this as any }); } return result as T extends number ? void : number; } querySymbol(filter: SymbolMeta): Symbol | undefined { return this.gen.symbols.query(filter)[0] as Symbol | undefined; } referenceSymbol(meta: SymbolMeta): Symbol { return this.gen.symbols.reference(meta) as Symbol; } /** * Alias for `symbol()` method with single argument. */ registerSymbol(symbol: SymbolIn): Symbol { return this.symbol(symbol.name, symbol) as Symbol; } /** * Executes plugin's handler function. */ async run(): Promise { for (const hook of this.eventHooks['plugin:handler:before']) { hook({ plugin: this as any }); } await this.handler({ plugin: this }); for (const hook of this.eventHooks['plugin:handler:after']) { hook({ plugin: this as any }); } } symbol(name: SymbolIn['name'], symbol?: Omit): Symbol { const symbolIn: SymbolIn = { ...symbol, meta: { pluginName: path.isAbsolute(this.name) ? 'custom' : this.name, ...symbol?.meta, }, name, }; if (symbolIn.getExportFromFilePath === undefined) { symbolIn.getExportFromFilePath = this.getSymbolExportFromFilePath.bind(this); } if (symbolIn.getFilePath === undefined) { symbolIn.getFilePath = this.getSymbolFilePath.bind(this); } for (const hook of this.eventHooks['symbol:register:before']) { hook({ plugin: this as any, symbol: symbolIn }); } const symbolOut = this.gen.symbols.register(symbolIn); for (const hook of this.eventHooks['symbol:register:after']) { hook({ plugin: this as any, symbol: symbolOut }); } return symbolOut as Symbol; } /** * Registers a symbol only if it does not already exist based on the provided * metadata. This prevents duplicate symbols from being created in the project. */ symbolOnce(name: SymbolIn['name'], symbol?: Omit): Symbol { const meta = { ...symbol?.meta, }; if (symbol?.external) { meta.category = 'external'; meta.resource = symbol.external; } const existing = this.querySymbol(meta); if (existing) return existing; return this.symbol(name, { ...symbol, meta }); } private buildEventHooks(): EventHooks { const result: EventHooks = { 'node:set:after': [], 'node:set:before': [], 'plugin:handler:after': [], 'plugin:handler:before': [], 'symbol:register:after': [], 'symbol:register:before': [], }; const scopes = [this.config['~hooks']?.events, this.context.config.parser.hooks.events]; for (const scope of scopes) { if (!scope) continue; for (const [key, value] of Object.entries(scope)) { if (value) { result[key as keyof typeof result].push(value.bind(scope) as any); } } } return result; } private forEachError(error: unknown, event: WalkEvent) { const originalError = error instanceof Error ? error : new Error(String(error)); throw new HeyApiError({ args: [event], error: originalError, event: event.type, name: 'Error', pluginName: this.name, }); } private getSymbolExportFromFilePath(symbol: Symbol): ReadonlyArray | undefined { const hooks = [this.config['~hooks']?.symbols, this.context.config.parser.hooks.symbols]; for (const hook of hooks) { const result = hook?.getExportFromFilePath?.(symbol); if (result !== undefined) return result; } // default logic below const entryFile = this.context.config.output.indexFile ?? this.context.config.output.entryFile; if (symbol.external || !entryFile) return; const includeInEntry = this.config.exportFromIndex ?? this.config.includeInEntry; if ( (typeof includeInEntry === 'boolean' && !includeInEntry) || (typeof includeInEntry === 'function' && !includeInEntry(symbol)) ) { return; } const language = symbol.node?.language; if (!language) return; const moduleEntryName = this.gen.moduleEntryNames[language]; if (!moduleEntryName) return; return [moduleEntryName]; } private getSymbolFilePath(symbol: Symbol): string | undefined { const hooks = [this.config['~hooks']?.symbols, this.context.config.parser.hooks.symbols]; for (const hook of hooks) { const result = hook?.getFilePath?.(symbol); if (result !== undefined) return result; } return defaultGetFilePath(symbol); } private isOperationKind(operation: IR.OperationObject, kind: 'mutation' | 'query'): boolean { const method = kind === 'query' ? 'isQuery' : 'isMutation'; const hooks = [ this.config['~hooks']?.operations?.[method], this.config['~hooks']?.operations?.getKind, this.context.config.parser.hooks.operations?.[method], this.context.config.parser.hooks.operations?.getKind, defaultGetKind, ]; for (const hook of hooks) { if (hook) { const result = hook(operation); if (result !== undefined) { return typeof result === 'boolean' ? result : result.includes(kind); } } } return false; } } ================================================ FILE: packages/shared/src/plugins/symbol.ts ================================================ import type { SymbolIn } from '@hey-api/codegen-core'; import type { GetNameContext } from '../parser/hooks'; import { applyNaming } from '../utils/naming/naming'; import type { PluginInstance } from './shared/utils/instance'; /** * Helper function to build the input for symbol registration, applying naming hooks if provided. */ export function buildSymbolIn({ plugin, ...ctx }: GetNameContext & { plugin: { config: Pick; context: { config: { parser: Pick; }; }; }; }): SymbolIn { const hooks = [ plugin.config['~hooks']?.symbols?.getName, plugin.context.config.parser.hooks.symbols?.getName, ]; for (const hook of hooks) { if (!hook) continue; const result = hook(ctx); if (typeof result === 'function') { const name = result(ctx); if (name) { return { meta: ctx.meta, name, }; } } else if (typeof result === 'string') { return { meta: ctx.meta, name: ctx.naming ? applyNaming(result, ctx.naming) : result, }; } } return { meta: ctx.meta, name: ctx.naming ? applyNaming(ctx.name, ctx.naming) : ctx.name, }; } ================================================ FILE: packages/shared/src/plugins/types.ts ================================================ /* eslint-disable @typescript-eslint/no-namespace */ import type { AnyString } from '@hey-api/types'; import type { CommentsOption, IndexExportOption, UserCommentsOption, UserIndexExportOption, } from '../config/shared'; import type { ValueToObject } from '../config/utils/config'; import type { Dependency } from '../config/utils/dependencies'; import type { Hooks as ParserHooks } from '../parser/hooks'; import type { PluginInstance } from './shared/utils/instance'; // eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface PluginConfigMap {} export type PluginNames = keyof PluginConfigMap extends never ? string : keyof PluginConfigMap; export type AnyPluginName = PluginNames | AnyString; type PluginTag = 'client' | 'mocker' | 'sdk' | 'transformer' | 'validator'; export type PluginContext = { package: Dependency; pluginByTag: ( tag: PluginTag, props?: { defaultPlugin?: Exclude; errorMessage?: string; }, ) => Exclude | undefined; valueToObject: ValueToObject; }; type BaseApi = Record; type PluginBaseConfig = UserIndexExportOption & { name: AnyPluginName; /** * Optional hooks to override default plugin behavior. * * Use these to classify resources, control which outputs are generated, * or provide custom behavior for specific resources. */ '~hooks'?: ParserHooks; }; /** * Public Plugin API. */ export namespace Plugin { export type Config = Pick & { config: Omit; /** * Dependency plugins will be always processed, regardless of whether user * explicitly defines them in their `plugins` config. */ dependencies?: ReadonlyArray; handler: (args: { plugin: PluginInstance }) => void; name: T['config']['name']; /** * Resolves static configuration values into their runtime equivalents. For * example, when `validator` is set to `true`, it figures out which plugin * should be used for validation. */ resolveConfig?: ( plugin: Omit, 'dependencies'> & { dependencies: Set; }, context: PluginContext, ) => void; /** * Tags can be used to help with deciding plugin order and resolving * plugin configuration options. */ tags?: ReadonlyArray; }; export type Comments = CommentsOption; export type UserComments = UserCommentsOption; export type Exports = IndexExportOption; export type UserExports = UserIndexExportOption; /** * Generic wrapper for plugin hooks. */ export type Hooks = Pick; export interface Name { name: Name; } /** * Generic wrapper for plugin resolvers. * * Provides a namespaced configuration entry (`~resolvers`) * where plugins can define how specific schema constructs * should be resolved or overridden. */ export type Resolvers = Record> = { /** * Custom behavior resolvers for a plugin. * * Used to define how specific schema constructs are * resolved into AST or runtime logic. */ '~resolvers'?: T; }; export type Types< Config extends PluginBaseConfig = PluginBaseConfig, ResolvedConfig extends PluginBaseConfig = Config, Api extends BaseApi = never, > = ([Api] extends [never] ? { api?: BaseApi } : { api: Api }) & { config: Config; resolvedConfig: ResolvedConfig; }; } export type DefinePlugin< Config extends PluginBaseConfig = PluginBaseConfig, ResolvedConfig extends PluginBaseConfig = Config, Api extends BaseApi = never, > = { Config: Plugin.Config>; Handler: (args: { plugin: PluginInstance> }) => void; /** The plugin instance. */ Instance: PluginInstance>; Types: Plugin.Types; }; ================================================ FILE: packages/shared/src/tsConfig.ts ================================================ import fs from 'node:fs'; import path from 'node:path'; import type { AnyString } from '@hey-api/types'; export function findPackageJson(initialDir: string): unknown | undefined { let dir = initialDir; while (dir !== path.dirname(dir)) { const files = fs.readdirSync(dir); const candidates = files.filter((file) => file === 'package.json'); if (candidates[0]) { const packageJsonPath = path.join(dir, candidates[0]); return JSON.parse( fs.readFileSync(packageJsonPath, { encoding: 'utf8', }), ); } dir = path.dirname(dir); } return; } type PackageJson = { bugs: { url: string; }; name: string; version: string; }; export function loadPackageJson(initialDir: string): PackageJson | undefined { const packageJson = findPackageJson(initialDir); const safePackage: PackageJson = { bugs: { url: '', }, name: '', version: '', }; if (packageJson && typeof packageJson === 'object') { if ('name' in packageJson && typeof packageJson.name === 'string') { safePackage.name = packageJson.name; } if ('version' in packageJson && typeof packageJson.version === 'string') { safePackage.version = packageJson.version; } if ('bugs' in packageJson && packageJson.bugs && typeof packageJson.bugs === 'object') { if ('url' in packageJson.bugs && typeof packageJson.bugs.url === 'string') { safePackage.bugs.url = packageJson.bugs.url; if (safePackage.bugs.url && !safePackage.bugs.url.endsWith('/')) { safePackage.bugs.url += '/'; } } } } if (!safePackage.name) return; return safePackage; } export function findTsConfigPath(baseDir: string, tsConfigPath?: AnyString | null): string | null { if (tsConfigPath === null) { return null; } if (tsConfigPath) { const resolved = path.isAbsolute(tsConfigPath) ? tsConfigPath : path.resolve(baseDir, tsConfigPath); return fs.existsSync(resolved) ? resolved : null; } let dir = baseDir; while (dir !== path.dirname(dir)) { const files = fs.readdirSync(dir); const candidates = files .filter((file) => file.startsWith('tsconfig') && file.endsWith('.json')) .sort((file) => (file === 'tsconfig.json' ? -1 : 1)); if (candidates[0]) { return path.join(dir, candidates[0]); } dir = path.dirname(dir); } return null; } ================================================ FILE: packages/shared/src/types/logs.ts ================================================ export type Logs = { /** * Whether or not error logs should be written to a file or not * * @default true * */ file?: boolean; /** * The logging level to control the verbosity of log output. * Determines which messages are logged based on their severity. * * Available levels (in increasing order of severity): * - `trace`: Detailed debug information, primarily for development. * - `debug`: Diagnostic information useful during debugging. * - `info`: General operational messages that indicate normal application behavior. * - `warn`: Potentially problematic situations that require attention. * - `error`: Errors that prevent some functionality but do not crash the application. * - `fatal`: Critical errors that cause the application to terminate. * - `silent`: Disables all logging. * * Messages with a severity equal to or higher than the specified level will be logged. * * @default 'info' */ level?: 'debug' | 'error' | 'fatal' | 'info' | 'silent' | 'trace' | 'warn'; /** * The relative location of the logs folder * * @default process.cwd() */ path?: string; }; ================================================ FILE: packages/shared/src/types/watch.ts ================================================ export type WatchValues = { /** * Headers to be sent with each HEAD and/or GET request. This effectively * serves as a mechanism resolver because setting certain headers will opt * into comparing the specifications using that method. */ headers: Headers; /** * Can we send a HEAD request instead of fetching the whole specification? * This value will be set after the first successful fetch. */ isHeadMethodSupported?: boolean; /** * String content of the last successfully fetched specification. */ lastValue?: string; }; ================================================ FILE: packages/shared/src/utils/__tests__/minHeap.test.ts ================================================ import { MinHeap } from '../minHeap'; describe('MinHeap', () => { it('pops items in increasing declIndex order', () => { const idx = new Map([ ['a', 10], ['b', 5], ['c', 20], ]); const h = new MinHeap(idx); h.push('a'); h.push('b'); h.push('c'); expect(h.pop()).toBe('b'); expect(h.pop()).toBe('a'); expect(h.pop()).toBe('c'); expect(h.pop()).toBeUndefined(); }); it('supports interleaved push/pop and maintains order', () => { const idx = new Map([ ['x', 0], ['y', 1], ['z', 2], ]); const h = new MinHeap(idx); h.push('y'); expect(h.pop()).toBe('y'); h.push('z'); h.push('x'); expect(h.pop()).toBe('x'); expect(h.pop()).toBe('z'); }); it('handles duplicates (same id pushed multiple times)', () => { const idx = new Map([['dup', 1]]); const h = new MinHeap(idx); h.push('dup'); h.push('dup'); expect(h.pop()).toBe('dup'); // second duplicate still present expect(h.pop()).toBe('dup'); expect(h.pop()).toBeUndefined(); }); it('isEmpty returns true when empty and false when not', () => { const idx = new Map([['a', 0]]); const h = new MinHeap(idx); expect(h.isEmpty()).toBe(true); h.push('a'); expect(h.isEmpty()).toBe(false); h.pop(); expect(h.isEmpty()).toBe(true); }); }); ================================================ FILE: packages/shared/src/utils/__tests__/path.test.ts ================================================ import { pathToName } from '../path'; describe('pathToName', () => { // ── OpenAPI 3.x component schemas ── it('handles top-level schema', () => { expect(pathToName(['components', 'schemas', 'User'])).toBe('User'); }); it('handles nested property', () => { expect(pathToName(['components', 'schemas', 'User', 'properties', 'address'])).toBe( 'User-address', ); }); it('handles deeply nested properties', () => { expect( pathToName(['components', 'schemas', 'User', 'properties', 'address', 'properties', 'city']), ).toBe('User-address-city'); }); it('handles property literally named "properties"', () => { expect(pathToName(['components', 'schemas', 'Foo', 'properties', 'properties'])).toBe( 'Foo-properties', ); }); it('handles property named "properties" with children', () => { expect( pathToName([ 'components', 'schemas', 'Foo', 'properties', 'properties', 'properties', 'items', ]), ).toBe('Foo-properties-items'); }); it('handles property named "items"', () => { expect(pathToName(['components', 'schemas', 'Foo', 'properties', 'items'])).toBe('Foo-items'); }); // ── additionalProperties ── it('handles additionalProperties', () => { expect(pathToName(['components', 'schemas', 'Pet', 'additionalProperties'])).toBe('Pet-Value'); }); it('handles nested additionalProperties', () => { expect( pathToName([ 'components', 'schemas', 'Pet', 'properties', 'metadata', 'additionalProperties', ]), ).toBe('Pet-metadata-Value'); }); // ── Array items ── it('handles array items (skips index)', () => { expect( pathToName(['components', 'schemas', 'Order', 'properties', 'line_items', 'items', 0]), ).toBe('Order-line_items'); }); it('handles items without numeric index', () => { expect(pathToName(['components', 'schemas', 'Result', 'items', 0])).toBe('Result'); }); // ── Tuple items ── it('handles tuple items at different indices', () => { expect(pathToName(['components', 'schemas', 'Pair', 'items', 0])).toBe('Pair'); expect(pathToName(['components', 'schemas', 'Pair', 'items', 1])).toBe('Pair'); }); // ── patternProperties ── it('handles patternProperties', () => { expect(pathToName(['components', 'schemas', 'Config', 'patternProperties', '^x-'])).toBe( 'Config-^x-', ); }); // ── OpenAPI 2.0 ── it('handles definitions (OpenAPI 2.0)', () => { expect(pathToName(['definitions', 'User'])).toBe('User'); }); it('handles definitions with nested properties', () => { expect(pathToName(['definitions', 'User', 'properties', 'address'])).toBe('User-address'); }); // ── Paths (operations) ── it('handles simple path', () => { expect(pathToName(['paths', '/event', 'get', 'properties', 'query'])).toBe('Event-get-query'); }); it('handles path with multiple segments', () => { expect(pathToName(['paths', '/api/v1/users', 'post', 'properties', 'body'])).toBe( 'ApiV1Users-post-body', ); }); it('handles path with parameter', () => { expect(pathToName(['paths', '/users/{id}/posts', 'get', 'properties', 'query'])).toBe( 'UsersIdPosts-get-query', ); }); it('handles path without properties', () => { expect(pathToName(['paths', '/event', 'get'])).toBe('Event-get'); }); // ── Webhooks ── it('handles webhooks', () => { expect(pathToName(['webhooks', 'onEvent', 'post', 'properties', 'body'])).toBe( 'onEvent-post-body', ); }); // ── Component types beyond schemas ── it('handles component parameters', () => { expect(pathToName(['components', 'parameters', 'UserId'])).toBe('UserId'); }); it('handles component requestBodies', () => { expect(pathToName(['components', 'requestBodies', 'CreateUser', 'properties', 'name'])).toBe( 'CreateUser-name', ); }); // ── Encoded characters ── it('handles URI-encoded names', () => { expect(pathToName(['components', 'schemas', 'My%20Schema'])).toBe('My Schema'); }); // ── Anchor option ── it('uses anchor for component schema', () => { expect( pathToName(['components', 'schemas', 'User', 'properties', 'address'], { anchor: 'UserDTO', }), ).toBe('UserDTO-address'); }); it('uses anchor for paths', () => { expect( pathToName(['paths', '/event', 'get', 'properties', 'query'], { anchor: 'event.subscribe', }), ).toBe('event.subscribe-query'); }); it('uses anchor and preserves structural suffix', () => { expect( pathToName(['components', 'schemas', 'Pet', 'additionalProperties'], { anchor: 'PetMap', }), ).toBe('PetMap-Value'); }); it('uses anchor with deeply nested properties', () => { expect( pathToName(['components', 'schemas', 'User', 'properties', 'address', 'properties', 'city'], { anchor: 'UserInput', }), ).toBe('UserInput-address-city'); }); it('uses anchor for unknown root', () => { expect(pathToName(['foo', 'bar', 'baz'], { anchor: 'Root' })).toBe('Root'); }); }); ================================================ FILE: packages/shared/src/utils/__tests__/ref.test.ts ================================================ import { isTopLevelComponent, jsonPointerToPath, pathToJsonPointer } from '../ref'; describe('jsonPointerToPath', () => { it('parses root pointer', () => { expect(jsonPointerToPath('#')).toEqual([]); expect(jsonPointerToPath('')).toEqual([]); }); it('parses component ref', () => { expect(jsonPointerToPath('#/components/schemas/Foo')).toEqual(['components', 'schemas', 'Foo']); }); it('parses deep path ref', () => { expect(jsonPointerToPath('#/components/schemas/Foo/properties/bar/items')).toEqual([ 'components', 'schemas', 'Foo', 'properties', 'bar', 'items', ]); }); }); describe('pathToJsonPointer', () => { it('converts empty path to root pointer', () => { expect(pathToJsonPointer([])).toBe('#'); }); it('converts path to pointer', () => { expect(pathToJsonPointer(['components', 'schemas', 'Foo'])).toBe('#/components/schemas/Foo'); }); }); describe('isTopLevelComponent', () => { describe('OpenAPI 3.x refs', () => { it('returns true for top-level component refs', () => { expect(isTopLevelComponent('#/components/schemas/Foo')).toBe(true); expect(isTopLevelComponent('#/components/parameters/Bar')).toBe(true); expect(isTopLevelComponent('#/components/responses/Error')).toBe(true); expect(isTopLevelComponent('#/components/requestBodies/Body')).toBe(true); }); it('returns false for deep path refs', () => { expect(isTopLevelComponent('#/components/schemas/Foo/properties/bar')).toBe(false); expect(isTopLevelComponent('#/components/schemas/Foo/properties/bar/items')).toBe(false); expect(isTopLevelComponent('#/components/schemas/Foo/allOf/0')).toBe(false); }); }); describe('OpenAPI 2.0 refs', () => { it('returns true for top-level definitions refs', () => { expect(isTopLevelComponent('#/definitions/Foo')).toBe(true); expect(isTopLevelComponent('#/definitions/Bar')).toBe(true); }); it('returns false for deep path refs', () => { expect(isTopLevelComponent('#/definitions/Foo/properties/bar')).toBe(false); expect(isTopLevelComponent('#/definitions/Foo/properties/bar/items')).toBe(false); }); }); describe('non-component refs', () => { it('returns false for path refs', () => { expect(isTopLevelComponent('#/paths/~1users/get')).toBe(false); }); it('returns false for other refs', () => { expect(isTopLevelComponent('#/info/title')).toBe(false); }); }); }); ================================================ FILE: packages/shared/src/utils/__tests__/url.test.ts ================================================ import { parseUrl } from '../url'; describe('parseUrl', () => { it.each([ { host: '', path: '', port: '', protocol: '', value: '' }, { host: '', path: '', port: '', protocol: '', value: '/' }, { host: 'foo.com', path: '', port: '', protocol: '', value: 'foo.com' }, { host: 'foo.com', path: '', port: '', protocol: '', value: 'foo.com/' }, { host: 'foo.com', path: '/bar', port: '', protocol: '', value: 'foo.com/bar', }, { host: 'www.foo.com', path: '/bar', port: '', protocol: '', value: 'www.foo.com/bar', }, { host: 'www.foo.com', path: '/bar', port: '', protocol: 'https', value: 'https://www.foo.com/bar', }, { host: 'www.foo.com', path: '/bar', port: '', protocol: 'custom', value: 'custom://www.foo.com/bar', }, { host: 'foo.com', path: '/bar', port: '', protocol: 'ws', value: 'ws://foo.com/bar', }, { host: 'foo.com', path: '/bar', port: '', protocol: '', value: '//foo.com/bar?ignore', }, { host: 'foo.com', path: '', port: '', protocol: '', value: '//foo.com' }, { host: '', path: '', port: '', protocol: 'https', value: 'https://' }, { host: '', path: '/bar', port: '', protocol: '', value: '/bar' }, { host: 'localhost', path: '', port: '3025', protocol: 'http', value: 'http://localhost:3025', }, { host: 'localhost', path: '', port: '', protocol: 'https', value: 'https://localhost', }, { host: '', path: '/v1/foo', port: '', protocol: '', value: '/v1/foo' }, { host: '10.0.81.36', path: '/v1', port: '', protocol: 'http', value: 'http://10.0.81.36/v1', }, { host: '{id}.foo.com', path: '/v1', port: '{port}', protocol: 'https', value: 'https://{id}.foo.com:{port}/v1', }, { host: '', path: '', port: '', protocol: '', value: './foo.json' }, { host: '', path: '', port: '', protocol: '', value: '../../foo.json' }, { host: '', path: '', port: '', protocol: '', value: 'D://\\foo.json' }, ])('$value', ({ host, path, port, protocol, value }) => { expect(parseUrl(value)).toEqual({ host, path, port, protocol, }); }); }); ================================================ FILE: packages/shared/src/utils/escape.ts ================================================ import { EOL } from 'node:os'; export function escapeComment(value: string) { return value .replace(/\*\//g, '*') .replace(/\/\*/g, '*') .replace(/\r?\n(.*)/g, (_l, w) => EOL + w.trim()); } ================================================ FILE: packages/shared/src/utils/exports.ts ================================================ import { toCase } from './naming/naming'; import type { Casing } from './naming/types'; /** * Utilities shared across the package. */ export const utils = { /** * @deprecated use `toCase` instead */ stringCase({ case: casing, stripLeadingSeparators, value, }: { readonly case: Casing | undefined; /** * If leading separators have a semantic meaning, we might not want to * remove them. */ stripLeadingSeparators?: boolean; value: string; }) { return toCase(value, casing, { stripLeadingSeparators }); }, /** * Converts the given string to the specified casing. */ toCase, }; ================================================ FILE: packages/shared/src/utils/header.ts ================================================ import type { IProject } from '@hey-api/codegen-core'; import type { OutputHeader } from '../config/output/types'; /** * Converts an {@link OutputHeader} value to a string prefix for file content. */ export function outputHeaderToPrefix(ctx: { defaultValue: ReadonlyArray; header: OutputHeader; project: IProject; }): string { const { defaultValue, header, project } = ctx; let lines = typeof header === 'function' ? header({ defaultValue, project }) : header; if (lines === undefined) lines = defaultValue; if (lines === null) return ''; lines = typeof lines === 'string' ? lines.split(/\r?\n/) : lines.flatMap((line) => line.split(/\r?\n/)); const content = lines.join('\n'); return content ? `${content}\n\n` : ''; } ================================================ FILE: packages/shared/src/utils/input/__tests__/readme.test.ts ================================================ import { getRegistryUrl, inputToReadmePath, type Parsed, parseShorthand } from '../readme'; describe('readme utils', () => { describe('parseShorthand', () => { it('should parse simple UUID format', () => { const result = parseShorthand('abc123'); expect(result).toEqual({ uuid: 'abc123' }); }); it('should parse UUID with hyphens', () => { const result = parseShorthand('test-uuid-123'); expect(result).toEqual({ uuid: 'test-uuid-123' }); }); it('should parse full format with organization and project', () => { const result = parseShorthand('@myorg/myproject#uuid123'); expect(result).toEqual({ organization: 'myorg', project: 'myproject', uuid: 'uuid123', }); }); it('should parse organization and project with hyphens', () => { const result = parseShorthand('@my-org/my-project#test-uuid'); expect(result).toEqual({ organization: 'my-org', project: 'my-project', uuid: 'test-uuid', }); }); it('should throw error for invalid formats', () => { expect(() => parseShorthand('')).toThrow('Invalid ReadMe shorthand format'); expect(() => parseShorthand('@org')).toThrow('Invalid ReadMe shorthand format'); expect(() => parseShorthand('@org/project')).toThrow('Invalid ReadMe shorthand format'); expect(() => parseShorthand('@org/project#')).toThrow('Invalid ReadMe shorthand format'); expect(() => parseShorthand('https://example.com')).toThrow( 'Invalid ReadMe shorthand format', ); }); it('should throw error for invalid UUID characters', () => { expect(() => parseShorthand('abc@123')).toThrow('Invalid ReadMe shorthand format'); expect(() => parseShorthand('abc/123')).toThrow('Invalid ReadMe shorthand format'); expect(() => parseShorthand('abc#123')).toThrow('Invalid ReadMe shorthand format'); expect(() => parseShorthand('abc 123')).toThrow('Invalid ReadMe shorthand format'); }); it('should handle empty UUID', () => { expect(() => parseShorthand('@org/project#')).toThrow('Invalid ReadMe shorthand format'); }); }); describe('getRegistryUrl', () => { it('should generate correct URL', () => { expect(getRegistryUrl('abc123')).toBe('https://dash.readme.com/api/v1/api-registry/abc123'); expect(getRegistryUrl('test-uuid-with-hyphens')).toBe( 'https://dash.readme.com/api/v1/api-registry/test-uuid-with-hyphens', ); }); }); describe('inputToReadmePath', () => { it('should transform simple UUID format to API URL', () => { const result = inputToReadmePath('readme:abc123'); expect(result).toEqual({ path: 'https://dash.readme.com/api/v1/api-registry/abc123', registry: 'readme', uuid: 'abc123', }); }); it('should transform full format to API URL', () => { const result = inputToReadmePath('readme:@myorg/myproject#uuid123'); expect(result).toEqual({ organization: 'myorg', path: 'https://dash.readme.com/api/v1/api-registry/uuid123', project: 'myproject', registry: 'readme', uuid: 'uuid123', }); }); it('should throw error for invalid inputs', () => { expect(() => inputToReadmePath('invalid')).toThrow('Invalid ReadMe shorthand format'); expect(() => inputToReadmePath('')).toThrow('Invalid ReadMe shorthand format'); }); }); describe('integration scenarios', () => { const validInputs: ReadonlyArray<{ expected: Parsed; input: string }> = [ { expected: { uuid: 'simple123' }, input: 'simple123' }, { expected: { uuid: 'uuid-with-hyphens' }, input: 'uuid-with-hyphens', }, { expected: { uuid: 'UUID123' }, input: 'UUID123' }, { expected: { organization: 'org', project: 'proj', uuid: 'uuid' }, input: '@org/proj#uuid', }, { expected: { organization: 'my-org', project: 'my-project', uuid: 'my-uuid', }, input: '@my-org/my-project#my-uuid', }, ]; it.each(validInputs)('should handle $input correctly', ({ expected, input }) => { expect(parseShorthand(input)).toEqual(expected); expect(inputToReadmePath(`readme:${input}`)).toEqual({ organization: expected.organization, path: `https://dash.readme.com/api/v1/api-registry/${expected.uuid}`, project: expected.project, registry: 'readme', uuid: expected.uuid, }); }); const invalidInputs = [ '', '@', '@org', '@org/', '@org/proj', '@org/proj#', 'uuid with spaces', 'uuid@invalid', 'uuid/invalid', 'uuid#invalid', 'https://example.com', './local-file.yaml', ]; it.each(invalidInputs)('should reject invalid input: %s', (input) => { expect(() => parseShorthand(input)).toThrow(); }); }); }); ================================================ FILE: packages/shared/src/utils/input/__tests__/scalar.test.ts ================================================ import { getRegistryUrl, inputToScalarPath, type Parsed, parseShorthand } from '../scalar'; describe('readme utils', () => { describe('parseShorthand', () => { it('should parse full format with organization and project', () => { const result = parseShorthand('@myorg/myproject'); expect(result).toEqual({ organization: '@myorg', project: 'myproject', }); }); it('should parse organization and project with hyphens', () => { const result = parseShorthand('@my-org/my-project'); expect(result).toEqual({ organization: '@my-org', project: 'my-project', }); }); it('should throw error for invalid formats', () => { expect(() => parseShorthand('')).toThrow('Invalid Scalar shorthand format'); expect(() => parseShorthand('@org')).toThrow('Invalid Scalar shorthand format'); expect(() => parseShorthand('@org/project#')).toThrow('Invalid Scalar shorthand format'); expect(() => parseShorthand('https://example.com')).toThrow( 'Invalid Scalar shorthand format', ); }); it('should throw error for invalid UUID characters', () => { expect(() => parseShorthand('abc@123')).toThrow('Invalid Scalar shorthand format'); expect(() => parseShorthand('abc/123')).toThrow('Invalid Scalar shorthand format'); expect(() => parseShorthand('abc#123')).toThrow('Invalid Scalar shorthand format'); expect(() => parseShorthand('abc 123')).toThrow('Invalid Scalar shorthand format'); }); it('should handle empty UUID', () => { expect(() => parseShorthand('@org/project#')).toThrow('Invalid Scalar shorthand format'); }); }); describe('getRegistryUrl', () => { it('should generate correct URL', () => { expect(getRegistryUrl('@foo', 'bar')).toBe( 'https://registry.scalar.com/@foo/apis/bar/latest?format=json', ); expect(getRegistryUrl('@foo-with-hyphens', 'bar')).toBe( 'https://registry.scalar.com/@foo-with-hyphens/apis/bar/latest?format=json', ); }); }); describe('inputToScalarPath', () => { it('should transform full format to API URL', () => { const result = inputToScalarPath('scalar:@foo/bar'); expect(result).toEqual({ organization: '@foo', path: 'https://registry.scalar.com/@foo/apis/bar/latest?format=json', project: 'bar', registry: 'scalar', }); }); it('should throw error for invalid inputs', () => { expect(() => inputToScalarPath('invalid')).toThrow('Invalid Scalar shorthand format'); expect(() => inputToScalarPath('')).toThrow('Invalid Scalar shorthand format'); }); }); describe('integration scenarios', () => { const validInputs: ReadonlyArray<{ expected: Parsed; input: string }> = [ { expected: { organization: '@org', project: 'proj' }, input: '@org/proj', }, { expected: { organization: '@my-org', project: 'my-project', }, input: '@my-org/my-project', }, ]; it.each(validInputs)('should handle $input correctly', ({ expected, input }) => { expect(parseShorthand(input)).toEqual(expected); expect(inputToScalarPath(`scalar:${input}`)).toEqual({ organization: expected.organization, path: `https://registry.scalar.com/${expected.organization}/apis/${expected.project}/latest?format=json`, project: expected.project, registry: 'scalar', }); }); const invalidInputs = [ '', '@', '@org', '@org/', 'uuid with spaces', 'uuid@invalid', 'uuid/invalid', 'uuid#invalid', 'https://example.com', './local-file.yaml', ]; it.each(invalidInputs)('should reject invalid input: %s', (input) => { expect(() => parseShorthand(input)).toThrow(); }); }); }); ================================================ FILE: packages/shared/src/utils/input/heyApi.ts ================================================ import type { Input } from '../../config/input/types'; // Regular expression to match Hey API Registry input formats: // - {organization}/{project}?{queryParams} const registryRegExp = /^([\w-]+)\/([\w-]+)(?:\?([\w=&.-]*))?$/; export const heyApiRegistryBaseUrl = 'https://get.heyapi.dev'; /** * Creates a full Hey API Registry URL. * * @param organization - Hey API organization slug * @param project - Hey API project slug * @param queryParams - Optional query parameters * @returns The full Hey API registry URL. */ export function getRegistryUrl( organization: string, project: string, queryParams?: string, ): string { return `${heyApiRegistryBaseUrl}/${organization}/${project}${queryParams ? `?${queryParams}` : ''}`; } export type Parsed = { organization: string; project: string; queryParams?: string; }; /** * Parses a Hey API input string and extracts components. * * @param input - Hey API configuration input * @returns Parsed Hey API input components * @throws Error if the input format is invalid */ export function parseShorthand( input: Input & { path: string; }, ): Parsed { let organization = input.organization; let project = input.project; let queryParams: string | undefined; if (input.path) { const match = input.path.match(registryRegExp); if (!match) { throw new Error( `Invalid Hey API shorthand format. Expected "organization/project?queryParams" or "organization/project", received: ${input.path}`, ); } organization = match[1]; project = match[2]; queryParams = match[3]; } if (!organization) { throw new Error('The Hey API organization cannot be empty.'); } if (!project) { throw new Error('The Hey API project cannot be empty.'); } const result: Parsed = { organization, project, queryParams, }; return result; } /** * Transforms a Hey API shorthand string to the corresponding API URL. * * @param input - Hey API configuration input * @returns The Hey API Registry URL */ export function inputToHeyApiPath( input: Input & { path: string; }, ): Partial { const parsed = parseShorthand(input); return { path: getRegistryUrl(parsed.organization, parsed.project, parsed.queryParams), registry: 'hey-api', }; } ================================================ FILE: packages/shared/src/utils/input/index.ts ================================================ import type { Input } from '../../config/input/types'; import { heyApiRegistryBaseUrl, inputToHeyApiPath } from './heyApi'; import { inputToReadmePath } from './readme'; import { inputToScalarPath } from './scalar'; export function inputToApiRegistry( input: Input & { path: string; }, ) { if (input.path.startsWith('readme:')) { Object.assign(input, inputToReadmePath(input.path)); return; } if (input.path.startsWith('scalar:')) { Object.assign(input, inputToScalarPath(input.path)); return; } if (input.path.startsWith('.')) { return; } if (input.path.startsWith(heyApiRegistryBaseUrl)) { input.path = input.path.slice(heyApiRegistryBaseUrl.length + 1); Object.assign(input, inputToHeyApiPath(input as Input & { path: string })); return; } const parts = input.path.split('/'); if (parts.length === 2 && parts.filter(Boolean).length === 2) { Object.assign(input, inputToHeyApiPath(input as Input & { path: string })); return; } } ================================================ FILE: packages/shared/src/utils/input/readme.ts ================================================ import type { Input } from '../../config/input/types'; // Regular expression to match ReadMe API Registry input formats: // - @{organization}/{project}#{uuid} // - {uuid} const registryRegExp = /^(@([\w-]+)\/([\w\-.]+)#)?([\w-]+)$/; /** * Creates a full ReadMe API Registry URL. * * @param uuid - ReadMe UUID * @returns The full ReadMe API registry URL. */ export function getRegistryUrl(uuid: string): string { return `https://dash.readme.com/api/v1/api-registry/${uuid}`; } export type Parsed = { organization?: string; project?: string; uuid: string; }; const namespace = 'readme'; /** * Parses a ReadMe input string and extracts components. * * @param shorthand - ReadMe format string (@org/project#uuid or uuid) * @returns Parsed ReadMe input components * @throws Error if the input format is invalid */ export function parseShorthand(shorthand: string): Parsed { const match = shorthand.match(registryRegExp); if (!match) { throw new Error( `Invalid ReadMe shorthand format. Expected "${namespace}:@organization/project#uuid" or "${namespace}:uuid", received: ${namespace}:${shorthand}`, ); } const [, , organization, project, uuid] = match; if (!uuid) { throw new Error('The ReadMe UUID cannot be empty.'); } const result: Parsed = { organization, project, uuid, }; return result; } /** * Transforms a ReadMe shorthand string to the corresponding API URL. * * @param input - ReadMe format string * @returns The ReadMe API Registry URL */ export function inputToReadmePath(input: string): Partial { const shorthand = input.slice(`${namespace}:`.length); const parsed = parseShorthand(shorthand); return { ...parsed, path: getRegistryUrl(parsed.uuid), registry: 'readme', }; } ================================================ FILE: packages/shared/src/utils/input/scalar.ts ================================================ import type { Input } from '../../config/input/types'; // Regular expression to match Scalar API Registry input formats: // - @{organization}/{project} const registryRegExp = /^(@[\w-]+)\/([\w.-]+)$/; /** * Creates a full Scalar API Registry URL. * * @param organization - Scalar organization slug * @param project - Scalar project slug * @returns The full Scalar API registry URL. */ export function getRegistryUrl(organization: string, project: string): string { return `https://registry.scalar.com/${organization}/apis/${project}/latest?format=json`; } export type Parsed = { organization: string; project: string; }; const namespace = 'scalar'; /** * Parses a Scalar input string and extracts components. * * @param shorthand - Scalar format string (@org/project) * @returns Parsed Scalar input components * @throws Error if the input format is invalid */ export function parseShorthand(shorthand: string): Parsed { const match = shorthand.match(registryRegExp); if (!match) { throw new Error( `Invalid Scalar shorthand format. Expected "${namespace}:@organization/project", received: ${namespace}:${shorthand}`, ); } const [, organization, project] = match; if (!organization) { throw new Error('The Scalar organization cannot be empty.'); } if (!project) { throw new Error('The Scalar project cannot be empty.'); } const result: Parsed = { organization, project, }; return result; } /** * Transforms a Scalar shorthand string to the corresponding API URL. * * @param input - Scalar format string * @returns The Scalar API Registry URL */ export function inputToScalarPath(input: string): Partial { const shorthand = input.slice(`${namespace}:`.length); const parsed = parseShorthand(shorthand); return { ...parsed, path: getRegistryUrl(parsed.organization, parsed.project), registry: 'scalar', }; } ================================================ FILE: packages/shared/src/utils/minHeap.ts ================================================ export class MinHeap { private heap: Array = []; constructor(public declIndex: Map) {} isEmpty(): boolean { return !this.heap.length; } pop(): string | undefined { const [top] = this.heap; if (!this.heap.length) return; const last = this.heap.pop()!; if (!this.heap.length) return top; this.heap[0] = last; this.sinkDown(0); return top; } push(item: string): void { this.heap.push(item); this.bubbleUp(this.heap.length - 1); } private bubbleUp(index: number): void { const heap = this.heap; while (index > 0) { const parent = Math.floor((index - 1) / 2); const parentVal = heap[parent]!; const curVal = heap[index]!; if (this.declIndex.get(parentVal)! <= this.declIndex.get(curVal)!) break; heap[parent] = curVal; heap[index] = parentVal; index = parent; } } private sinkDown(index: number): void { const heap = this.heap; const len = heap.length; while (true) { const left = 2 * index + 1; const right = 2 * index + 2; let smallest = index; if (left < len) { const leftVal = heap[left]!; const smallestVal = heap[smallest]!; if (this.declIndex.get(leftVal)! < this.declIndex.get(smallestVal)!) smallest = left; } if (right < len) { const rightVal = heap[right]!; const smallestVal = heap[smallest]!; if (this.declIndex.get(rightVal)! < this.declIndex.get(smallestVal)!) smallest = right; } if (smallest === index) break; const tmp = heap[smallest]!; heap[smallest] = heap[index]!; heap[index] = tmp; index = smallest; } } } ================================================ FILE: packages/shared/src/utils/naming/__tests__/naming.test.ts ================================================ import { toCase } from '../naming'; import type { Casing } from '../types'; const cases: ReadonlyArray = [ 'camelCase', 'PascalCase', 'SCREAMING_SNAKE_CASE', 'snake_case', ]; const scenarios: ReadonlyArray<{ PascalCase: string; SCREAMING_SNAKE_CASE: string; camelCase: string; snake_case: string; stripLeadingSeparators?: boolean; value: string; }> = [ { PascalCase: 'FooDtoById', SCREAMING_SNAKE_CASE: 'FOO_DTO_BY_ID', camelCase: 'fooDtoById', snake_case: 'foo_dto_by_id', value: 'fooDTOById', }, { PascalCase: 'FooDtos', SCREAMING_SNAKE_CASE: 'FOO_DTOS', camelCase: 'fooDtos', snake_case: 'foo_dtos', value: 'fooDTOs', }, { PascalCase: 'FooDtosById', SCREAMING_SNAKE_CASE: 'FOO_DTOS_BY_ID', camelCase: 'fooDtosById', snake_case: 'foo_dtos_by_id', value: 'fooDTOsById', }, { PascalCase: 'DtoById', SCREAMING_SNAKE_CASE: 'DTO_BY_ID', camelCase: 'dtoById', snake_case: 'dto_by_id', value: 'DTOById', }, { PascalCase: 'Dtos', SCREAMING_SNAKE_CASE: 'DTOS', camelCase: 'dtos', snake_case: 'dtos', value: 'DTOs', }, { PascalCase: 'DtosById', SCREAMING_SNAKE_CASE: 'DTOS_BY_ID', camelCase: 'dtosById', snake_case: 'dtos_by_id', value: 'DTOsById', }, { PascalCase: 'SomeJsonFile', SCREAMING_SNAKE_CASE: 'SOME_JSON_FILE', camelCase: 'someJsonFile', snake_case: 'some_json_file', value: 'SOME_JSON_FILE', }, { PascalCase: 'SomeJsonsFile', SCREAMING_SNAKE_CASE: 'SOME_JSONS_FILE', camelCase: 'someJsonsFile', snake_case: 'some_jsons_file', value: 'SOME_JSONs_FILE', }, { PascalCase: 'PostHtmlGuide', SCREAMING_SNAKE_CASE: 'POST_HTML_GUIDE', camelCase: 'postHtmlGuide', snake_case: 'post_html_guide', value: 'postHTMLGuide', }, { PascalCase: 'PostHtmlScale', SCREAMING_SNAKE_CASE: 'POST_HTML_SCALE', camelCase: 'postHtmlScale', snake_case: 'post_html_scale', value: 'postHTMLScale', }, { PascalCase: 'SnakeCase', SCREAMING_SNAKE_CASE: 'SNAKE_CASE', camelCase: 'snakeCase', snake_case: 'snake_case', value: 'snake_case', }, { PascalCase: 'CamelCase', SCREAMING_SNAKE_CASE: 'CAMEL_CASE', camelCase: 'camelCase', snake_case: 'camel_case', value: 'camelCase', }, { PascalCase: 'PascalCase', SCREAMING_SNAKE_CASE: 'PASCAL_CASE', camelCase: 'pascalCase', snake_case: 'pascal_case', value: 'PascalCase', }, { PascalCase: 'IsXRated', SCREAMING_SNAKE_CASE: 'IS_X_RATED', camelCase: 'isXRated', snake_case: 'is_x_rated', value: 'isXRated', }, { PascalCase: 'IsHtmlSafe', SCREAMING_SNAKE_CASE: 'IS_HTML_SAFE', camelCase: 'isHtmlSafe', snake_case: 'is_html_safe', value: 'isHTMLSafe', }, { PascalCase: 'MyAspirations', SCREAMING_SNAKE_CASE: 'MY_ASPIRATIONS', camelCase: 'myAspirations', snake_case: 'my_aspirations', value: 'MyAspirations', }, { PascalCase: 'IoK8sApimachineryPkgApisMetaV1DeleteOptions', SCREAMING_SNAKE_CASE: 'IO_K8S_APIMACHINERY_PKG_APIS_META_V1_DELETE_OPTIONS', camelCase: 'ioK8sApimachineryPkgApisMetaV1DeleteOptions', snake_case: 'io_k8s_apimachinery_pkg_apis_meta_v1_delete_options', value: 'io.k8sApimachinery.pkg.apis.meta:v1.DeleteOptions', }, { PascalCase: 'GenericSchemaDuplicateIssue1SystemBoolean', SCREAMING_SNAKE_CASE: 'GENERIC_SCHEMA_DUPLICATE_ISSUE_1_SYSTEM_BOOLEAN', camelCase: 'genericSchemaDuplicateIssue1SystemBoolean', snake_case: 'generic_schema_duplicate_issue_1_system_boolean', value: 'Generic.Schema.Duplicate.Issue`1[System.Boolean]', }, { PascalCase: 'GetApiVApiVersionUsersUserIdLocationLocationId', SCREAMING_SNAKE_CASE: 'GET_API_V_API_VERSION_USERS_USER_ID_LOCATION_LOCATION_ID', camelCase: 'getApiVApiVersionUsersUserIdLocationLocationId', snake_case: 'get_api_v_api_version_users_user_id_location_location_id', value: 'GET /api/v{api-version}/users/{userId}/location/{locationId}', }, { PascalCase: 'IPhoneS', SCREAMING_SNAKE_CASE: 'I_PHONE_S', camelCase: 'iPhoneS', snake_case: 'i_phone_s', value: 'iPhone S', }, { PascalCase: '-100', SCREAMING_SNAKE_CASE: '-100', camelCase: '-100', snake_case: '-100', stripLeadingSeparators: false, value: '-100', }, { PascalCase: 'MyFoo', SCREAMING_SNAKE_CASE: 'MY_FOO', camelCase: 'myFoo', snake_case: 'my_foo', stripLeadingSeparators: false, value: 'MyFoo', }, ]; describe('toCase', () => { describe.each(cases)('%s', (casing) => { switch (casing) { case 'PascalCase': it.each(scenarios)( '$value -> $PascalCase', ({ PascalCase, stripLeadingSeparators, value }) => { expect(toCase(value, casing, { stripLeadingSeparators })).toBe(PascalCase); }, ); break; case 'camelCase': it.each(scenarios)( '$value -> $camelCase', ({ camelCase, stripLeadingSeparators, value }) => { expect(toCase(value, casing, { stripLeadingSeparators })).toBe(camelCase); }, ); break; case 'SCREAMING_SNAKE_CASE': it.each(scenarios)( '$value -> $SCREAMING_SNAKE_CASE', ({ SCREAMING_SNAKE_CASE, stripLeadingSeparators, value }) => { expect(toCase(value, casing, { stripLeadingSeparators })).toBe(SCREAMING_SNAKE_CASE); }, ); break; case 'snake_case': it.each(scenarios)( '$value -> $snake_case', ({ snake_case, stripLeadingSeparators, value }) => { expect(toCase(value, casing, { stripLeadingSeparators })).toBe(snake_case); }, ); break; } }); }); ================================================ FILE: packages/shared/src/utils/naming/naming.ts ================================================ import type { Casing, NamingConfig, NamingRule } from './types'; const uppercaseRegExp = /[\p{Lu}]/u; const lowercaseRegExp = /[\p{Ll}]/u; const identifierRegExp = /([\p{Alpha}\p{N}_]|$)/u; const separatorsRegExp = /[_.$+:\- `\\[\](){}\\/]+/; const leadingSeparatorsRegExp = new RegExp(`^${separatorsRegExp.source}`); const separatorsAndIdentifierRegExp = new RegExp( `${separatorsRegExp.source}${identifierRegExp.source}`, 'gu', ); const numbersAndIdentifierRegExp = new RegExp(`\\d+${identifierRegExp.source}`, 'gu'); const preserveCase = (value: string, casing: Casing) => { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; let isLastLastCharPreserved = false; const separator = casing === 'snake_case' || casing === 'SCREAMING_SNAKE_CASE' ? '_' : '-'; for (let index = 0; index < value.length; index++) { const character = value[index]!; isLastLastCharPreserved = index > 2 ? value[index - 3] === separator : true; let nextIndex = index + 1; let nextCharacter = value[nextIndex]; separatorsRegExp.lastIndex = 0; while (nextCharacter && separatorsRegExp.test(nextCharacter)) { nextIndex += 1; nextCharacter = value[nextIndex]; } const isSeparatorBeforeNextCharacter = nextIndex !== index + 1; lowercaseRegExp.lastIndex = 0; uppercaseRegExp.lastIndex = 0; if ( uppercaseRegExp.test(character) && (isLastCharLower || (nextCharacter && !isSeparatorBeforeNextCharacter && nextCharacter !== 's' && lowercaseRegExp.test(nextCharacter))) ) { // insert separator behind character value = `${value.slice(0, index)}${separator}${value.slice(index)}`; index++; isLastLastCharUpper = isLastCharUpper; isLastCharLower = false; isLastCharUpper = true; } else if ( isLastCharUpper && isLastLastCharUpper && lowercaseRegExp.test(character) && !isLastLastCharPreserved && // naive detection of plurals !( character === 's' && (!nextCharacter || nextCharacter.toLocaleLowerCase() !== nextCharacter) ) ) { // insert separator 2 characters behind value = `${value.slice(0, index - 1)}${separator}${value.slice(index - 1)}`; isLastLastCharUpper = isLastCharUpper; isLastCharLower = true; isLastCharUpper = false; } else { const characterLower = character.toLocaleLowerCase(); const characterUpper = character.toLocaleUpperCase(); isLastLastCharUpper = isLastCharUpper; isLastCharLower = characterLower === character && characterUpper !== character; isLastCharUpper = characterUpper === character && characterLower !== character; } } return value; }; /** * Convert a string to the specified casing. * * @param value - The string to convert * @param casing - The target casing * @param options - Additional options * @returns The converted string */ export function toCase( value: string, casing: Casing | undefined, options: { /** * If leading separators have a semantic meaning, we might not want to * remove them. */ stripLeadingSeparators?: boolean; } = {}, ): string { const stripLeadingSeparators = options.stripLeadingSeparators ?? true; let result = value.trim(); if (!result.length || !casing || casing === 'preserve') { return result; } if (result.length === 1) { separatorsRegExp.lastIndex = 0; if (separatorsRegExp.test(result)) { return ''; } return casing === 'PascalCase' || casing === 'SCREAMING_SNAKE_CASE' ? result.toLocaleUpperCase() : result.toLocaleLowerCase(); } const hasUpperCase = result !== result.toLocaleLowerCase(); if (hasUpperCase) { result = preserveCase(result, casing); } if (stripLeadingSeparators || result[0] !== value[0]) { result = result.replace(leadingSeparatorsRegExp, ''); } result = casing === 'SCREAMING_SNAKE_CASE' ? result.toLocaleUpperCase() : result.toLocaleLowerCase(); if (casing === 'PascalCase') { result = `${result.charAt(0).toLocaleUpperCase()}${result.slice(1)}`; } if (casing === 'snake_case' || casing === 'SCREAMING_SNAKE_CASE') { result = result.replaceAll(separatorsAndIdentifierRegExp, (match, identifier, offset) => { if (offset === 0 && !stripLeadingSeparators) { return match; } return `_${identifier}`; }); if (result[result.length - 1] === '_') { // strip trailing underscore result = result.slice(0, result.length - 1); } } else { separatorsAndIdentifierRegExp.lastIndex = 0; numbersAndIdentifierRegExp.lastIndex = 0; result = result.replaceAll(numbersAndIdentifierRegExp, (match, _, offset) => { if (['_', '-', '.'].includes(result.charAt(offset + match.length))) { return match; } return match.toLocaleUpperCase(); }); result = result.replaceAll(separatorsAndIdentifierRegExp, (match, identifier, offset) => { if (offset === 0 && !stripLeadingSeparators && match[0] && value.startsWith(match[0])) { return match; } return identifier.toLocaleUpperCase(); }); } return result; } /** * Normalize a NamingRule to NamingConfig. */ export function resolveNaming(rule: NamingRule | undefined): NamingConfig { if (!rule) { return {}; } if (typeof rule === 'string' || typeof rule === 'function') { return { name: rule }; } return rule; } /** * Apply naming configuration to a value. * * Casing is applied first, then transformation. */ export function applyNaming(value: string, config: NamingConfig): string { let result = value; const casing = config.casing ?? config.case; if (config.name) { if (typeof config.name === 'function') { result = config.name(result); } else { // TODO: refactor so there's no need for separators? const separator = !casing || casing === 'preserve' ? '' : '-'; result = config.name.replace('{{name}}', `${separator}${result}${separator}`); } } // TODO: apply case before name? return toCase(result, casing); } ================================================ FILE: packages/shared/src/utils/naming/types.ts ================================================ import type { MaybeFunc } from '@hey-api/types'; /** * Available casing strategies. */ export type Casing = | 'camelCase' | 'PascalCase' | 'preserve' | 'snake_case' | 'SCREAMING_SNAKE_CASE'; /** * Name transformer: template string or function. * * Template supports `{{name}}` variable. */ export type NameTransformer = MaybeFunc<(name: string) => string>; /** * Full naming configuration. */ export interface NamingConfig { /** * Casing strategy applied after transformation. * * @deprecated Use `casing` instead. */ case?: Casing; /** * Casing strategy applied after transformation. */ casing?: Casing; /** * Name template or transformer function. * * Applied before `casing` transformation. */ name?: NameTransformer; } /** * Name customization: shorthand or full configuration. */ export type NamingRule = NameTransformer | NamingConfig; ================================================ FILE: packages/shared/src/utils/path.ts ================================================ /** * After these structural segments, the next segment has a known role. * This is what makes a property literally named "properties" safe — * it occupies the name position, never the structural position. */ const STRUCTURAL_ROLE: Record = { items: 'index', patternProperties: 'name', properties: 'name', }; /** * These structural segments have no following name/index — * they are the terminal structural node. Append a suffix * to disambiguate from the parent. */ const STRUCTURAL_SUFFIX: Record = { additionalProperties: 'Value', }; type RootContextConfig = { /** How many consecutive semantic segments follow before structural walking begins */ names: number; /** How many leading segments to skip (the root keyword + any category segment) */ skip: number; }; /** * Root context configuration. */ const ROOT_CONTEXT: Record = { components: { names: 1, skip: 2 }, // components/schemas/{name} definitions: { names: 1, skip: 1 }, // definitions/{name} paths: { names: 2, skip: 1 }, // paths/{path}/{method} webhooks: { names: 2, skip: 1 }, // webhooks/{name}/{method} }; /** * Sanitizes a path segment for use in a derived name. * * Handles API path segments like `/api/v1/users/{id}` → `ApiV1UsersId`. */ function sanitizeSegment(segment: string | number): string { const str = String(segment); if (str.startsWith('/')) { return str .split('/') .filter(Boolean) .map((part) => { const clean = part.replace(/[{}]/g, ''); return clean.charAt(0).toUpperCase() + clean.slice(1); }) .join(''); } return str; } export interface PathToNameOptions { /** * When provided, replaces the root semantic segments with this anchor. * Structural suffixes are still derived from path. */ anchor?: string; } /** * Derives a composite name from a path. * * Examples: * .../User → 'User' * .../User/properties/address → 'UserAddress' * .../User/properties/properties → 'UserProperties' * .../User/properties/address/properties/city → 'UserAddressCity' * .../Pet/additionalProperties → 'PetValue' * .../Order/properties/items/items/0 → 'OrderItems' * paths//event/get/properties/query → 'EventGetQuery' * * With anchor: * paths//event/get/properties/query, { anchor: 'event.subscribe' } * → 'event.subscribe-Query' */ export function pathToName( path: ReadonlyArray, options?: PathToNameOptions, ): string { const names: Array = []; let index = 0; const rootContext = ROOT_CONTEXT[path[0]!]; if (rootContext) { index = rootContext.skip; if (options?.anchor) { // Use anchor as base name, skip past root semantic segments names.push(options.anchor); index += rootContext.names; } else { // Collect consecutive semantic name segments for (let n = 0; n < rootContext.names && index < path.length; n++) { names.push(sanitizeSegment(path[index]!)); index++; } } } else { // Unknown root if (options?.anchor) { names.push(options.anchor); index++; } else if (index < path.length) { names.push(sanitizeSegment(path[index]!)); index++; } } while (index < path.length) { const segment = String(path[index]); const role = STRUCTURAL_ROLE[segment]; if (role === 'name') { // Next segment is a semantic name — collect it index++; if (index < path.length) { names.push(sanitizeSegment(path[index]!)); } } else if (role === 'index') { // Next segment is a numeric index — skip it index++; if (index < path.length && typeof path[index] === 'number') { index++; } continue; } else if (STRUCTURAL_SUFFIX[segment]) { names.push(STRUCTURAL_SUFFIX[segment]); } index++; } // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` return decodeURI(names.join('-')); } ================================================ FILE: packages/shared/src/utils/ref.ts ================================================ const jsonPointerSlash = /~1/g; const jsonPointerTilde = /~0/g; /** * Returns the reusable component name from `$ref`. */ export function refToName($ref: string): string { const path = jsonPointerToPath($ref); const name = path[path.length - 1]!; // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` return decodeURI(name); } /** * Encodes a path segment for use in a JSON Pointer (RFC 6901). * * - Replaces all '~' with '~0'. * - Replaces all '/' with '~1'. * * This ensures that path segments containing these characters are safely * represented in JSON Pointer strings. * * @param segment - The path segment (string or number) to encode. * @returns The encoded segment as a string. */ export function encodeJsonPointerSegment(segment: string | number): string { return String(segment).replace(/~/g, '~0').replace(/\//g, '~1'); } /** * Converts a JSON Pointer string (RFC 6901) to an array of path segments. * * - Removes the leading '#' if present. * - Splits the pointer on '/'. * - Decodes '~1' to '/' and '~0' to '~' in each segment. * - Returns an empty array for the root pointer ('#' or ''). * * @param pointer - The JSON Pointer string to convert (e.g., '#/components/schemas/Foo'). * @returns An array of decoded path segments. */ export function jsonPointerToPath(pointer: string): ReadonlyArray { let clean = pointer.trim(); if (clean.startsWith('#')) { clean = clean.slice(1); } if (clean.startsWith('/')) { clean = clean.slice(1); } if (!clean) { return []; } return clean .split('/') .map((part) => part.replace(jsonPointerSlash, '/').replace(jsonPointerTilde, '~')); } /** * Normalizes a JSON Pointer string to a canonical form. * * - Ensures the pointer starts with '#'. * - Removes trailing slashes (except for root). * - Collapses multiple consecutive slashes into one. * - Trims whitespace from the input. * * @param pointer - The JSON Pointer string to normalize. * @returns The normalized JSON Pointer string. */ export function normalizeJsonPointer(pointer: string): string { let normalized = pointer.trim(); if (!normalized.startsWith('#')) { normalized = `#${normalized}`; } // Remove trailing slashes (except for root) if (normalized.length > 1 && normalized.endsWith('/')) { normalized = normalized.slice(0, -1); } // Collapse multiple slashes normalized = normalized.replace(/\/+/g, '/'); return normalized; } /** * Encode path as JSON Pointer (RFC 6901). * * @param path * @returns */ export function pathToJsonPointer(path: ReadonlyArray): string { const segments = path.map(encodeJsonPointerSegment).join('/'); return '#' + (segments ? `/${segments}` : ''); } /** * Checks if a $ref or path points to a top-level component (not a deep path reference). * * Top-level component references: * - OpenAPI 3.x: #/components/{type}/{name} (3 segments) * - OpenAPI 2.0: #/definitions/{name} (2 segments) * * Deep path references (4+ segments for 3.x, 3+ for 2.0) should be inlined * because they don't have corresponding registered symbols. * * @param refOrPath - The $ref string or path array to check * @returns true if the ref points to a top-level component, false otherwise */ export function isTopLevelComponent(refOrPath: string | ReadonlyArray): boolean { const path = refOrPath instanceof Array ? refOrPath : jsonPointerToPath(refOrPath); // OpenAPI 3.x: #/components/{type}/{name} = 3 segments if (path[0] === 'components') { return path.length === 3; } // OpenAPI 2.0: #/definitions/{name} = 2 segments if (path[0] === 'definitions') { return path.length === 2; } return false; } export function resolveRef({ $ref, spec }: { $ref: string; spec: Record }): T { // refs using unicode characters become encoded, didn't investigate why // but the suspicion is this comes from `@hey-api/json-schema-ref-parser` const path = jsonPointerToPath(decodeURI($ref)); let current = spec; for (const part of path) { const segment = part as keyof typeof current; if (current[segment] === undefined) { throw new Error(`Reference not found: ${$ref}`); } current = current[segment]; } return current as T; } ================================================ FILE: packages/shared/src/utils/url.ts ================================================ const parseUrlRegExp = /^(([^:/?#]+):)?((\/\/)?([^:/?#]*)(:?([^/?#]*)))?([^?#]*)(\?([^#]*))?(#(.*))?/; interface Url { host: string; path: string; port: string; protocol: string; } export function parseUrl(value: string): Url { const errorResponse: Url = { host: '', path: '', port: '', protocol: '', }; parseUrlRegExp.lastIndex = 0; const match = value.match(parseUrlRegExp); if (!match) { return errorResponse; } const host = match[5] || ''; // value is a relative file system path if (host === '.' || host === '..') { return errorResponse; } const path = match[8] || ''; const protocol = match[2] || ''; // value is probably a Windows file system path if (protocol.length === 1) { return errorResponse; } return { host, path: path === '/' ? '' : path, port: match[7] || '', protocol, }; } ================================================ FILE: packages/shared/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "composite": true, "outDir": "dist", "rootDir": "src", "types": ["bun", "vitest/globals"] }, "include": ["src"], "references": [ { "path": "../types" }, { "path": "../codegen-core" }, { "path": "../json-schema-ref-parser" } ] } ================================================ FILE: packages/shared/tsdown.config.ts ================================================ import { defineConfig } from 'tsdown'; export default defineConfig({ clean: true, dts: true, entry: ['src/index.ts'], format: ['esm'], minify: false, sourcemap: true, treeshake: true, }); ================================================ FILE: packages/shared/turbo.json ================================================ { "$schema": "../../node_modules/turbo/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": [], "outputs": ["dist/**"] } } } ================================================ FILE: packages/types/CHANGELOG.md ================================================ # @hey-api/types ## 0.1.4 ### Patch Changes - **internal**: remove TypeScript from peer dependencies ([#3566](https://github.com/hey-api/openapi-ts/pull/3566)) ([`b5f1e4b`](https://github.com/hey-api/openapi-ts/commit/b5f1e4b5f64cbf0bad2eff888177ac9c1881ba3e)) by [@mrlubos](https://github.com/mrlubos) ## 0.1.3 ### Patch Changes - **types**: add `AnyString` utility type ([#3251](https://github.com/hey-api/openapi-ts/pull/3251)) ([`7f19d59`](https://github.com/hey-api/openapi-ts/commit/7f19d5921dadfa96ecae84a5298b7aee1daee56d)) by [@mrlubos](https://github.com/mrlubos) ## 0.1.2 ### Patch Changes - feat: add `ToArray`, `ToReadonlyArray`, and `AnyObject` types ([#3244](https://github.com/hey-api/openapi-ts/pull/3244)) ([`4f52bce`](https://github.com/hey-api/openapi-ts/commit/4f52bce79d8ac6573472f32a05b7f70913b90605)) by [@mrlubos](https://github.com/mrlubos) ## 0.1.1 ### Patch Changes - Publish `@hey-api/types` so workspace packages can resolve it from npm. ([#3224](https://github.com/hey-api/openapi-ts/pull/3224)) ([`1f381b7`](https://github.com/hey-api/openapi-ts/commit/1f381b7cea64d38dc0ebec2a18323829cf322f07)) by [@mrlubos](https://github.com/mrlubos) ================================================ FILE: packages/types/package.json ================================================ { "name": "@hey-api/types", "version": "0.1.4", "description": "Shared utility types.", "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "files": [ "dist" ], "type": "module", "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts" }, "./package.json": "./package.json" }, "scripts": { "build": "tsc --build", "dev": "tsc --build --watch", "prepublishOnly": "pnpm build", "typecheck": "tsgo --noEmit" }, "devDependencies": { "typescript": "5.9.3" } } ================================================ FILE: packages/types/src/index.ts ================================================ /** * An object with string keys and unknown values. */ export type AnyObject = Record; /** * An arbitrary string type. */ export type AnyString = string & {}; /** * Converts all top-level ReadonlyArray properties to Array (shallow). */ export type ArrayOnly = { [K in keyof T]: ToArray; }; /** * Recursively makes all non-function properties optional. */ export type DeepPartial = { [K in keyof T]?: T[K] extends (...args: Array) => any ? T[K] : T[K] extends object ? DeepPartial : T[K]; }; /** * Accepts a value, a function returning a value, or a function returning a promise of a value. */ export type LazyOrAsync = T | (() => MaybePromise); /** * Accepts a value or a readonly array of values of type T. */ export type MaybeArray = T | ReadonlyArray; /** * Accepts a value or a function returning a value. */ export type MaybeFunc) => any> = T | ReturnType; /** * Accepts a value or a promise of a value. */ export type MaybePromise = T | Promise; /** * Converts all top-level Array properties to ReadonlyArray (shallow). */ export type ReadonlyArrayOnly = { [K in keyof T]: ToReadonlyArray; }; /** * Converts ReadonlyArray to Array, preserving unions. */ export type ToArray = T extends ReadonlyArray ? Array : T; /** * Converts Array to ReadonlyArray, preserving unions. */ export type ToReadonlyArray = T extends ReadonlyArray ? ReadonlyArray : T; ================================================ FILE: packages/types/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "composite": true, "emitDeclarationOnly": true, "outDir": "dist", "rootDir": "src" }, "include": ["src"] } ================================================ FILE: packages/vite-plugin/.gitignore ================================================ .DS_Store .idea .tmp .tsdown logs node_modules temp .env coverage dist # test files .gen # test files test/generated test/e2e/generated generated/ ================================================ FILE: packages/vite-plugin/CHANGELOG.md ================================================ # @hey-api/vite-plugin ## 0.2.1 ### Patch Changes - **build**: do not minify bundles for better code readability and debugging ([#3186](https://github.com/hey-api/openapi-ts/pull/3186)) ([`4d46130`](https://github.com/hey-api/openapi-ts/commit/4d46130b53d9d8d5d3c178343a1b4fc3645b2628)) by [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent) ## 0.2.0 ### Minor Changes - [#1838](https://github.com/hey-api/openapi-ts/pull/1838) [`cee4508`](https://github.com/hey-api/openapi-ts/commit/cee4508fe2a58f4bbc79955176c9e930f941ba94) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: initial release ## 0.1.2 ### Patch Changes - [#1836](https://github.com/hey-api/openapi-ts/pull/1836) [`f22dc53`](https://github.com/hey-api/openapi-ts/commit/f22dc533bb822d90b2be835217367ae9e6bbc559) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: use enforce pre ## 0.1.1 ### Patch Changes - [#1826](https://github.com/hey-api/openapi-ts/pull/1826) [`90886c1`](https://github.com/hey-api/openapi-ts/commit/90886c1372a999e8cb59d5da218762f6ee6cd459) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: allow config to be a function - [#1825](https://github.com/hey-api/openapi-ts/pull/1825) [`0670a38`](https://github.com/hey-api/openapi-ts/commit/0670a38c66dffc1431a7d4b48ec06b72d4f6868f) Thanks [@mrlubos](https://github.com/mrlubos)! - fix: move @hey-api/openapi-ts to peerDependencies - Updated dependencies [[`c73b0d4`](https://github.com/hey-api/openapi-ts/commit/c73b0d401c2bfa6f0b0d89d844a6aa09f2685a69), [`90886c1`](https://github.com/hey-api/openapi-ts/commit/90886c1372a999e8cb59d5da218762f6ee6cd459)]: - @hey-api/openapi-ts@0.64.13 ## 0.1.0 ### Minor Changes - [#1813](https://github.com/hey-api/openapi-ts/pull/1813) [`c737e05`](https://github.com/hey-api/openapi-ts/commit/c737e055591376e9351cd07533779023f773cff0) Thanks [@mrlubos](https://github.com/mrlubos)! - feat: initial release ================================================ FILE: packages/vite-plugin/LICENSE.md ================================================ MIT License Copyright (c) Hey API Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/vite-plugin/README.md ================================================
    Hey API logo

    Vite Plugin

    🚀 Vite plugin for @hey-api/openapi-ts codegen.

    ## Dashboard Access your projects and OpenAPI specifications in the [Hey API Platform](https://app.heyapi.dev/). ## Contributing Want to see your code in products used by millions? Start with our [Contributing](https://heyapi.dev/openapi-ts/community/contributing) guide and release your first feature. ## Documentation Please visit our [website](https://heyapi.dev) for documentation, guides, migrating, and more. ## Sponsors Help Hey API stay around for the long haul by becoming a [sponsor](https://github.com/sponsors/hey-api).

    Gold

    Stainless logo
    Best-in-class developer interfaces for your API.
    stainless.com

    Opencode logo
    The open source coding agent.
    opencode.ai

    Mintlify logo
    The intelligent knowledge platform.
    mintlify.com

    Silver

    Scalar logo
    scalar.com
    FastAPI logo
    fastapi.tiangolo.com

    Bronze

    Kinde logo Cella logo
    ## Usage Add to `plugins` inside your Vite configuration. ```ts import { heyApiPlugin } from '@hey-api/vite-plugin'; export default defineConfig({ plugins: [ heyApiPlugin({ config: { // optional configuration instead of using the configuration file }, }), ], }); ``` ================================================ FILE: packages/vite-plugin/package.json ================================================ { "name": "@hey-api/vite-plugin", "version": "0.2.1", "description": "🚀 Vite plugin for `@hey-api/openapi-ts` codegen.", "keywords": [ "codegen", "openapi", "plugin", "swagger", "vite", "vite-plugin" ], "homepage": "https://heyapi.dev/", "bugs": { "url": "https://github.com/hey-api/openapi-ts/issues" }, "license": "MIT", "author": { "name": "Hey API", "email": "lubos@heyapi.dev", "url": "https://heyapi.dev" }, "repository": { "type": "git", "url": "git+https://github.com/hey-api/openapi-ts.git" }, "funding": "https://github.com/sponsors/hey-api", "files": [ "dist", "LICENSE.md", "README.md" ], "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "import": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" }, "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } }, "./package.json": "./package.json" }, "scripts": { "build": "tsdown && pnpm check-exports", "check-exports": "attw --pack .", "dev": "tsdown --watch", "prepublishOnly": "pnpm build" }, "devDependencies": { "@hey-api/openapi-ts": "workspace:*", "typescript": "5.9.3", "vite": "7.3.1" }, "peerDependencies": { "@hey-api/openapi-ts": "<2" } } ================================================ FILE: packages/vite-plugin/src/index.ts ================================================ import { createClient } from '@hey-api/openapi-ts'; export function heyApiPlugin(options?: { /** * `@hey-api/openapi-ts` configuration options. */ config?: Parameters[0]; }) { return { configResolved: async () => { await createClient(options?.config); }, enforce: 'pre', name: 'hey-api-plugin', }; } ================================================ FILE: packages/vite-plugin/tsconfig.base.json ================================================ { "compilerOptions": { "declaration": true, "esModuleInterop": true, "module": "ESNext", "moduleResolution": "Bundler", "noImplicitOverride": true, "noUncheckedIndexedAccess": true, "noUnusedLocals": true, "strict": true, "target": "ES2022", "useUnknownInCatchVariables": false } } ================================================ FILE: packages/vite-plugin/tsconfig.json ================================================ { "extends": "./tsconfig.base.json", "compilerOptions": { "declaration": false, "esModuleInterop": true, "resolveJsonModule": true, "skipLibCheck": true } } ================================================ FILE: packages/vite-plugin/tsdown.config.ts ================================================ import { defineConfig } from 'tsdown'; export default defineConfig({ banner(ctx) { /** * fix dynamic require in ESM * @link https://github.com/hey-api/openapi-ts/issues/1079 */ if (ctx.format === 'esm') { return { js: `import { createRequire } from 'module'; const require = createRequire(import.${'meta'}.url);`, }; } }, clean: true, dts: true, entry: ['src/index.ts'], format: ['cjs', 'esm'], minify: false, shims: false, sourcemap: true, treeshake: true, }); ================================================ FILE: patches/vitepress.patch ================================================ diff --git a/dist/client/shared.js b/dist/client/shared.js index f65eb22fe2b0dfeb9bd823c00c737f5035f2c891..16a45edcf11b71881b31f1203add291a2c447d22 100644 --- a/dist/client/shared.js +++ b/dist/client/shared.js @@ -16,6 +16,7 @@ export const notFoundPageData = { lastUpdated: 0, isNotFound: true }; +const versionedPaths = ['clients', 'plugins']; export function isActive(currentPath, matchPath, asRegex = false) { if (matchPath === undefined) { return false; @@ -24,8 +25,19 @@ export function isActive(currentPath, matchPath, asRegex = false) { if (asRegex) { return new RegExp(matchPath).test(currentPath); } - if (normalize(matchPath) !== currentPath) { - return false; + const normalizedMatchPath = normalize(matchPath); + if (normalizedMatchPath !== currentPath) { + const currentPathParts = currentPath.split('/'); + if (currentPathParts.length > 3 && + versionedPaths.some((entry) => entry === currentPathParts[2])) { + currentPath = currentPathParts.slice(0, 4).join('/'); + if (normalizedMatchPath !== currentPath) { + return false; + } + } + else { + return false; + } } const hashMatch = matchPath.match(HASH_RE); if (hashMatch) { diff --git a/dist/node/chunk-CwUP9ZhX.js b/dist/node/chunk-CwUP9ZhX.js index e8b4954d00f247fb852096bb1f8f077fcfc1f93f..8db594d1bdaac76359656a95ac96cd98161b1062 100644 --- a/dist/node/chunk-CwUP9ZhX.js +++ b/dist/node/chunk-CwUP9ZhX.js @@ -2053,7 +2053,7 @@ function requireBrowser () { } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } - }; + }; } (browser, browser.exports)); return browser.exports; } @@ -2328,7 +2328,7 @@ function requireNode () { formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); - }; + }; } (node, node.exports)); return node.exports; } @@ -3522,7 +3522,7 @@ function requireFs () { 'fs.realpath.native is not a function. Is fs being monkey-patched?', 'Warning', 'fs-extra-WARN0003' ); - } + } } (fs$1)); return fs$1; } @@ -6185,7 +6185,7 @@ class AST { const aps = addPatternStart; // check if we have a possibility of matching . or .., // and prevent that. - const needNoTrav = + const needNoTrav = // dots are allowed, and the pattern starts with [ or . (dot && aps.has(src.charAt(0))) || // the pattern starts with \., and then [ or . @@ -8616,11 +8616,11 @@ class LRUCache { b.__abortController instanceof AC); } async fetch(k, fetchOptions = {}) { - const { + const { // get options - allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, + allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, // set options - ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, + ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, // fetch exclusive options noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; if (!this.#hasFetchMethod) { @@ -14468,7 +14468,7 @@ function requireUtils$4 () { } return last; - }; + }; } (utils$5)); return utils$5; } @@ -17226,7 +17226,7 @@ function requireDist$1 () { exports.fdir = void 0; const builder_1 = requireBuilder(); Object.defineProperty(exports, "fdir", { enumerable: true, get: function () { return builder_1.Builder; } }); - __exportStar(requireTypes$1(), exports); + __exportStar(requireTypes$1(), exports); } (dist$1)); return dist$1; } @@ -18267,6 +18267,7 @@ const notFoundPageData = { lastUpdated: 0, isNotFound: true }; +const versionedPaths = ["clients", "plugins"]; function isActive(currentPath, matchPath, asRegex = false) { if (matchPath === void 0) { return false; @@ -18275,8 +18276,17 @@ function isActive(currentPath, matchPath, asRegex = false) { if (asRegex) { return new RegExp(matchPath).test(currentPath); } - if (normalize$1(matchPath) !== currentPath) { - return false; + const normalizedMatchPath = normalize$1(matchPath); + if (normalizedMatchPath !== currentPath) { + const currentPathParts = currentPath.split("/"); + if (currentPathParts.length > 3 && versionedPaths.some((entry) => entry === currentPathParts[2])) { + currentPath = currentPathParts.slice(0, 4).join("/"); + if (normalizedMatchPath !== currentPath) { + return false; + } + } else { + return false; + } } const hashMatch = matchPath.match(HASH_RE); if (hashMatch) { @@ -23631,7 +23641,7 @@ function requireEngines () { stringify: function() { throw new Error('stringifying JavaScript is not supported'); } - }; + }; } (engines)); return engines.exports; } @@ -23731,7 +23741,7 @@ function requireUtils$2 () { exports.startsWith = function(str, substr, len) { if (typeof len !== 'number') len = substr.length; return str.slice(0, len) === substr; - }; + }; } (utils$3)); return utils$3; } @@ -25043,7 +25053,7 @@ const decodeMap = new Map([ /** * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. */ -const fromCodePoint$1 = +const fromCodePoint$1 = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins (_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) { let output = ""; @@ -25135,7 +25145,7 @@ var DecodingMode; class EntityDecoder { constructor( /** The tree used to decode entities. */ - decodeTree, + decodeTree, /** * The function that is called when a codepoint is decoded. * @@ -25145,7 +25155,7 @@ class EntityDecoder { * @param codepoint The decoded codepoint. * @param consumed The number of bytes consumed by the decoder. */ - emitCodePoint, + emitCodePoint, /** An object that is used to produce errors. */ errors) { this.decodeTree = decodeTree; @@ -25458,7 +25468,7 @@ function getDecoder(decodeTree) { while ((offset = str.indexOf("&", offset)) >= 0) { ret += str.slice(lastIndex, offset); decoder.startEntity(decodeMode); - const len = decoder.write(str, + const len = decoder.write(str, // Skip the "&" offset + 1); if (len < 0) { @@ -38931,7 +38941,7 @@ class SignalExit extends SignalExitBase { const process$1 = globalThis.process; // wrap so that we call the method on the actual handler, without // exporting it directly. -const { +const { /** * Called when the process is exiting, whether via signal, explicit * exit, or running out of stuff to do. @@ -41070,7 +41080,7 @@ function requireEastasianwidth () { eawLen += charLen; } return result; - }; + }; } (eastasianwidth)); return eastasianwidth.exports; } @@ -42826,7 +42836,7 @@ function requireTypes () { IndexTagNames["sitemapindex"] = "sitemapindex"; IndexTagNames["loc"] = "loc"; IndexTagNames["lastmod"] = "lastmod"; - })(exports.IndexTagNames || (exports.IndexTagNames = {})); + })(exports.IndexTagNames || (exports.IndexTagNames = {})); } (types)); return types; } @@ -42840,7 +42850,7 @@ function requireSitemapXml () { hasRequiredSitemapXml = 1; Object.defineProperty(sitemapXml, "__esModule", { value: true }); sitemapXml.element = sitemapXml.ctag = sitemapXml.otag = sitemapXml.text = void 0; - const invalidXMLUnicodeRegex = + const invalidXMLUnicodeRegex = // eslint-disable-next-line no-control-regex /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F\uD800-\uDFFF\uFDD0-\uFDDF\u{1FFFE}-\u{1FFFF}\u{2FFFE}-\u{2FFFF}\u{3FFFE}-\u{3FFFF}\u{4FFFE}-\u{4FFFF}\u{5FFFE}-\u{5FFFF}\u{6FFFE}-\u{6FFFF}\u{7FFFE}-\u{7FFFF}\u{8FFFE}-\u{8FFFF}\u{9FFFE}-\u{9FFFF}\u{AFFFE}-\u{AFFFF}\u{BFFFE}-\u{BFFFF}\u{CFFFE}-\u{CFFFF}\u{DFFFE}-\u{DFFFF}\u{EFFFE}-\u{EFFFF}\u{FFFFE}-\u{FFFFF}\u{10FFFE}-\u{10FFFF}]/gu; const amp = /&/g; @@ -43586,7 +43596,7 @@ function requireSitemapStream () { }); }); } - exports.streamToPromise = streamToPromise; + exports.streamToPromise = streamToPromise; } (sitemapStream)); return sitemapStream; } @@ -43809,7 +43819,7 @@ function requireSitemapIndexStream () { }); } } - exports.SitemapAndIndexStream = SitemapAndIndexStream; + exports.SitemapAndIndexStream = SitemapAndIndexStream; } (sitemapIndexStream)); return sitemapIndexStream; } @@ -45470,7 +45480,7 @@ function requireSax () { } }()); } - })(exports); + })(exports); } (sax)); return sax; } @@ -46277,7 +46287,7 @@ function requireSitemapSimple () { } }; exports.simpleSitemapAndIndex = simpleSitemapAndIndex; - exports.default = exports.simpleSitemapAndIndex; + exports.default = exports.simpleSitemapAndIndex; } (sitemapSimple)); return sitemapSimple; } @@ -46333,7 +46343,7 @@ function requireDist () { Object.defineProperty(exports, "XMLToSitemapIndexStream", { enumerable: true, get: function () { return sitemap_index_parser_1.XMLToSitemapIndexStream; } }); Object.defineProperty(exports, "IndexObjectStreamToJSON", { enumerable: true, get: function () { return sitemap_index_parser_1.IndexObjectStreamToJSON; } }); var sitemap_simple_1 = requireSitemapSimple(); - Object.defineProperty(exports, "simpleSitemapAndIndex", { enumerable: true, get: function () { return sitemap_simple_1.simpleSitemapAndIndex; } }); + Object.defineProperty(exports, "simpleSitemapAndIndex", { enumerable: true, get: function () { return sitemap_simple_1.simpleSitemapAndIndex; } }); } (dist)); return dist; } @@ -48930,7 +48940,7 @@ function requireLodash_template () { return false; } - module.exports = template; + module.exports = template; } (lodash_template, lodash_template.exports)); return lodash_template.exports; } @@ -49165,7 +49175,7 @@ function requirePostcssPrefixSelector () { return { postcssPlugin: 'postcss-prefix-selector', - prepare(result) { + prepare(result) { const root = result.root; const file = root.source.input.file; ================================================ FILE: pnpm-workspace.yaml ================================================ packages: - docs - dev/** - examples/**/* - packages/**/* - '!examples/*/.output' patchedDependencies: vitepress: patches/vitepress.patch ================================================ FILE: pyproject.toml ================================================ [project] name = "hey-api-dev" version = "0.0.0" requires-python = ">=3.9" [dependency-groups] dev = ["httpx>=0.27", "mypy>=1.15", "pydantic>=2.0", "ruff>=0.11"] [tool.mypy] python_version = "3.9" strict = false warn_return_any = true warn_unused_configs = true [tool.ruff] line-length = 120 target-version = "py310" [tool.ruff.format] exclude = ["**/__snapshots__/**"] [tool.ruff.lint] select = ["E", "F", "W", "I"] ================================================ FILE: renovate.json ================================================ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "dependencyDashboardTitle": "Dependencies 📦", "extends": ["config:recommended"], "ignorePaths": ["**/node_modules/**"], "minimumReleaseAge": "3 days", "packageRules": [ { "matchPackageNames": ["zod"], "matchFileNames": ["packages/openapi-ts-tests/zod/v3/**"], "allowedVersions": "<4.0.0" }, { "matchFileNames": ["examples/**"], "groupName": "examples", "prPriority": -1 }, { "matchFileNames": ["packages/**"], "groupName": "core packages", "prPriority": 10 } ], "prConcurrentLimit": 4, "schedule": ["before 3am on Monday"], "updatePinnedDependencies": true } ================================================ FILE: scripts/examples-check.sh ================================================ #!/usr/bin/env bash # Check if generated client code for all examples is up-to-date # This script is used in CI to ensure examples are kept in sync with the codebase set -e # Get the directory of this script SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" echo "Checking if generated code is up-to-date..." # Generate fresh code "$SCRIPT_DIR/examples-generate.sh" # Check if there are any changes if ! git diff --quiet; then echo "" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "❌ ERROR: Generated code is out of sync!" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "" echo "The following files have changed:" git diff --name-only echo "" echo "To fix this, run:" echo " pnpm examples:generate" echo "" echo "Then commit the changes." exit 1 fi echo "" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "✅ All generated code is up-to-date!" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" ================================================ FILE: scripts/examples-generate.sh ================================================ #!/usr/bin/env bash # Generate client code for all examples that have openapi-ts script # This script is used to ensure examples are up-to-date with the latest code set -e # Get the directory of this script SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" echo "⏳ Generating client code for all examples..." # Find all examples with openapi-ts script and generate code in parallel # Concurrency control: adjust this number depending on CI machine resources CONCURRENCY=${CONCURRENCY:-4} tmpdir=$(mktemp -d) # Use a simple space-separated list of pids and per-pid files for metadata PIDS="" wait_for_slot() { # Wait until number of background jobs is less than CONCURRENCY while [ "$(jobs -rp | wc -l)" -ge "$CONCURRENCY" ]; do sleep 0.2 done } for dir in "$ROOT_DIR"/examples/*/; do package_json="$dir/package.json" if [ ! -f "$package_json" ]; then continue fi if ! grep -q "\"openapi-ts\":" "$package_json"; then continue fi example_name=$(basename "$dir") echo "📦 Scheduling: $example_name" wait_for_slot log="$tmpdir/${example_name}.log" ( echo "Generating: $example_name" set -e cd "$dir" echo "-> Running openapi-ts" pnpm run openapi-ts # Format generated files in this example only to keep the step fast if command -v pnpm >/dev/null 2>&1 && pnpm -w -s --version >/dev/null 2>&1; then pnpm -s exec oxfmt "src/**/*.{ts,tsx,js,jsx}" || true pnpm -s exec eslint --fix "src/**/*.{ts,tsx,js,jsx}" || true else if [ -x "node_modules/.bin/oxfmt" ]; then ./node_modules/.bin/oxfmt "src/**/*.{ts,tsx,js,jsx}" || true fi if [ -x "node_modules/.bin/eslint" ]; then ./node_modules/.bin/eslint --fix "src/**/*.{ts,tsx,js,jsx}" || true fi fi echo "Completed: $example_name" ) >"$log" 2>&1 & pid=$! PIDS="$PIDS $pid" printf '%s' "$example_name" >"$tmpdir/$pid.name" printf '%s' "$log" >"$tmpdir/$pid.log" done failed=0 for pid in $PIDS; do if wait "$pid"; then name=$(cat "$tmpdir/$pid.name" 2>/dev/null || echo "$pid") echo "✅ $name succeeded" else name=$(cat "$tmpdir/$pid.name" 2>/dev/null || echo "$pid") # Read the metadata file which contains the path to the real log logpath=$(cat "$tmpdir/$pid.log" 2>/dev/null || echo "") if [ -n "$logpath" ] && [ -f "$logpath" ]; then echo "❌ $name failed — showing full log ($logpath):" echo "---- full log start ----" cat "$logpath" || true echo "---- full log end ----" else echo "❌ $name failed — no log found (metadata: $tmpdir/$pid.log)" fi failed=1 fi done if [ "$failed" -ne 0 ]; then echo "One or more examples failed to generate. Logs are in: $tmpdir" exit 1 fi echo "✨ All examples generated successfully!" ================================================ FILE: scripts/publish-preview-packages.sh ================================================ #!/usr/bin/env bash result=$(pnpm turbo run build --affected --dry-run=json 2>&1) json=$(printf '%s\n' "$result" | awk '/^{/ {flag=1} flag {print}') if [ -z "$json" ]; then echo "Error: no JSON output from turbo; aborting." >&2 echo "Raw result was:" echo "$result" exit 1 fi echo "Affected tasks:" echo "$json" | jq -r '.tasks[].directory' packages=$(echo "$json" | jq -r '.tasks[].directory' | grep '^packages/' | while read -r dir; do if [ "$(jq -r '.private' "$dir/package.json")" != "true" ]; then echo "./$dir" fi done) echo "Packages to publish:" echo "$packages" if [ -n "$packages" ]; then pnpx pkg-pr-new publish --pnpm $packages else echo "No packages to publish" fi ================================================ FILE: scripts/update-contributors.sh ================================================ #!/usr/bin/env bash REPO="hey-api/openapi-ts" PER_PAGE=100 PAGE=1 USERS=() TMP_LOGINS="tmp_logins.txt" TMP_USERS="tmp_users.txt" CACHE_DIR=".cache/github-users" mkdir -p "$CACHE_DIR" AUTH_HEADER=() if [[ -n "${GITHUB_TOKEN:-}" ]]; then AUTH_HEADER=(-H "Authorization: token $GITHUB_TOKEN") fi EXCLUDED_FILE="./docs/.contributorsignore" SINCE_FILE="./docs/.contributorssince" # disabled for now, we'd need to append to the list instead of write # if [[ -f "$SINCE_FILE" ]]; then # SINCE=$(cat "$SINCE_FILE") # else # SINCE="2024-01-27T00:00:00Z" # fi SINCE="2024-01-27T00:00:00Z" MAX_COMMIT_EPOCH=0 > "$TMP_USERS" while :; do TMP_JSON=$(mktemp) HTTP_STATUS=$(curl -s -w "%{http_code}" -o "$TMP_JSON" \ "${AUTH_HEADER[@]}" \ "https://api.github.com/repos/$REPO/commits?sha=main&since=$SINCE&per_page=$PER_PAGE&page=$PAGE") if [ "$HTTP_STATUS" != "200" ]; then echo "GitHub API error: $HTTP_STATUS" cat "$TMP_JSON" rm "$TMP_JSON" break fi if ! jq empty "$TMP_JSON" >/dev/null 2>&1; then echo "Invalid JSON, stopping." cat "$TMP_JSON" > debug_response.json rm "$TMP_JSON" break fi COUNT=$(jq 'length' "$TMP_JSON") if [ "$COUNT" -eq 0 ]; then rm "$TMP_JSON" break fi # Track max commit date epoch for the whole run LATEST_COMMIT_DATE=$(jq -r '.[].commit.committer.date' "$TMP_JSON" | sort -r | head -n1) if [[ -n "$LATEST_COMMIT_DATE" ]]; then EPOCH=$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "$LATEST_COMMIT_DATE" "+%s") if [ "$EPOCH" -gt "$MAX_COMMIT_EPOCH" ]; then MAX_COMMIT_EPOCH=$EPOCH fi fi jq -r '.[].author | select(.login != null) | .login' "$TMP_JSON" | sort -u > "$TMP_LOGINS" while read -r login; do if ! grep -Fxq "$login" "$EXCLUDED_FILE"; then if ! printf '%s\n' "${USERS[@]}" | grep -qx "$login"; then USERS+=("$login") CACHE_FILE="$CACHE_DIR/$login.json" if [ -f "$CACHE_FILE" ]; then USER_JSON=$(<"$CACHE_FILE") else echo "Fetching user $login" USER_JSON=$(curl -s "${AUTH_HEADER[@]}" "https://api.github.com/users/$login") echo "$USER_JSON" > "$CACHE_FILE" fi SANITIZED_JSON=$(echo "$USER_JSON" | tr -d '\000-\037') NAME=$(jq -r '.name // empty' <<< "$SANITIZED_JSON") echo "$login|$NAME" >> "$TMP_USERS" fi fi done < "$TMP_LOGINS" rm "$TMP_JSON" "$TMP_LOGINS" PAGE=$((PAGE + 1)) done # Update SINCE_FILE once after all pages if [ "$MAX_COMMIT_EPOCH" -gt 0 ]; then BUFFER_DAYS=90 BUFFER_SECONDS=$((BUFFER_DAYS * 86400)) BUFFERED_EPOCH=$((MAX_COMMIT_EPOCH - BUFFER_SECONDS)) BUFFERED_DATE=$(date -u -r "$BUFFERED_EPOCH" "+%Y-%m-%dT%H:%M:%SZ") echo "$BUFFERED_DATE" > "$SINCE_FILE" echo "Updated SINCE to $BUFFERED_DATE" fi NAMES_SORTED=$(awk -F'|' '$2 != ""' "$TMP_USERS" | sort -t'|' -k2,2) NO_NAMES_SORTED=$(awk -F'|' '$2 == ""' "$TMP_USERS" | sort -t'|' -k1,1) { echo "$NAMES_SORTED" echo "$NO_NAMES_SORTED" } | while IFS='|' read -r login name; do if [ -n "$name" ]; then echo "- [$name](https://github.com/$login)" else echo "- [$login](https://github.com/$login)" fi done > ./docs/partials/contributors-list.md if [[ -f "$TMP_USERS" ]]; then rm "$TMP_USERS" fi echo "Done. Total contributors: ${#USERS[@]}" ================================================ FILE: specs/2.0.x/additional-properties-false.json ================================================ { "swagger": "2.0", "info": { "title": "OpenAPI 2.0 additional properties false example", "version": "1" }, "definitions": { "Foo": { "required": ["foo"], "type": "object", "properties": { "foo": { "type": "string" } }, "additionalProperties": false }, "Bar": { "allOf": [ { "$ref": "#/definitions/Foo" }, { "type": "object", "additionalProperties": false } ] }, "Baz": { "allOf": [ { "$ref": "#/definitions/Foo" }, { "required": ["bar"], "type": "object", "properties": { "bar": { "type": "string" } }, "additionalProperties": false } ] } } } ================================================ FILE: specs/2.0.x/additional-properties-true.json ================================================ { "swagger": "2.0", "info": { "title": "OpenAPI 2.0 additional properties true example", "version": "1" }, "definitions": { "Foo": { "required": ["foo"], "type": "object", "properties": { "foo": { "type": "string" } }, "additionalProperties": true }, "Bar": { "allOf": [ { "$ref": "#/definitions/Foo" }, { "type": "object", "additionalProperties": true } ] }, "Baz": { "allOf": [ { "$ref": "#/definitions/Foo" }, { "required": ["bar"], "type": "object", "properties": { "bar": { "type": "string" } }, "additionalProperties": true } ] }, "Qux": { "type": "object", "additionalProperties": {} } } } ================================================ FILE: specs/2.0.x/array-items-all-of.yaml ================================================ swagger: '2.0' info: title: OpenAPI 2.0 array items allOf example version: '1' definitions: ArrayWithAllOfObjects: type: array items: allOf: - type: object properties: id: type: integer - type: object properties: name: type: string ArrayWithAllOfPrimitives: type: array items: allOf: - type: number - type: string ArrayWithAllOfRefs: type: array items: allOf: - $ref: '#/definitions/BaseModel' - type: object properties: extra: type: string BaseModel: type: object properties: id: type: integer createdAt: type: string format: date-time ================================================ FILE: specs/2.0.x/body-response-text-plain.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 body response text plain example version: 1 paths: /foo: post: consumes: - text/plain produces: - text/plain parameters: - name: body in: body required: true schema: type: string responses: '200': description: OK schema: type: string ================================================ FILE: specs/2.0.x/enum-names-values.json ================================================ { "swagger": "2.0", "info": { "title": "OpenAPI 2.0 enum names values example", "version": "1" }, "definitions": { "1-10": { "enum": ["1-10", "11-20"], "type": "string" }, "myFoo": { "enum": ["myFoo", "myBar"], "type": "string" }, "MyFoo": { "enum": ["MyFoo", "MyBar"], "type": "string" }, "Foo": { "enum": ["foo", "bar", "", true, false], "type": "string" }, "Numbers": { "enum": [100, 200, 300, -100, -200, -300], "type": "number" }, "Arrays": { "enum": [["foo"], ["bar"], ["baz"]], "type": "array" } } } ================================================ FILE: specs/2.0.x/exclude-deprecated.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 exclude deprecated example version: 1 produces: - application/json consumes: - application/json paths: /foo: post: parameters: - name: body in: body required: true schema: $ref: '#/definitions/Foo' responses: '200': description: OK /bar: post: deprecated: true parameters: - name: body in: body required: true schema: $ref: '#/definitions/Bar' responses: '200': description: OK definitions: Foo: type: string Bar: deprecated: true type: string ================================================ FILE: specs/2.0.x/external-shared.json ================================================ { "definitions": { "ExternalSharedModel": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" } }, "required": ["id"] }, "ExternalSharedModelWithUuid": { "type": "string", "format": "uuid" }, "ExternalNested": { "type": "object", "properties": { "inner": { "type": "object", "properties": { "deep": { "type": "string" } } } } }, "ExternalNestedNumeric": { "type": "object", "properties": { "0": { "type": "object", "properties": { "1": { "type": "string" } } } } } } } ================================================ FILE: specs/2.0.x/external.yaml ================================================ swagger: '2.0' info: title: Swagger 2.0 external example version: 1 # Paths using external references paths: /external-model: get: summary: Get external model parameters: - $ref: '#/parameters/ExternalIdParam' - $ref: '#/parameters/ExternalUuidParam' responses: '200': $ref: '#/responses/ExternalModelResponse' '400': $ref: '#/responses/ExternalUuidResponse' post: summary: Create external model parameters: - $ref: '#/parameters/ExternalModelBody' responses: '201': $ref: '#/responses/ExternalModelResponse' '422': $ref: '#/responses/ExternalUnionResponse' /external-uuid: get: summary: Get external UUID parameters: - $ref: '#/parameters/ExternalUuidParam' responses: '200': $ref: '#/responses/ExternalUuidResponse' put: summary: Update external UUID parameters: - $ref: '#/parameters/ExternalUuidBody' responses: '200': $ref: '#/responses/ExternalUuidResponse' /external-nested: get: summary: Get external nested object parameters: - $ref: '#/parameters/ExternalDeepParam' responses: '200': $ref: '#/responses/ExternalNestedResponse' post: summary: Create external nested object parameters: - $ref: '#/parameters/ExternalNestedBody' responses: '201': $ref: '#/responses/ExternalNestedResponse' /external-mixed: get: summary: Get mixed external data parameters: - $ref: '#/parameters/ExternalIdParam' - $ref: '#/parameters/ExternalUuidParam' - $ref: '#/parameters/ExternalDeepParam' - $ref: '#/parameters/ExternalNumericParam' responses: '200': $ref: '#/responses/ExternalArrayResponse' post: summary: Create mixed external data parameters: - $ref: '#/parameters/ExternalMixedBody' responses: '201': $ref: '#/responses/ExternalModelResponse' /external-array: get: summary: Get array of external models responses: '200': $ref: '#/responses/ExternalArrayResponse' post: summary: Create array of external models parameters: - name: body in: body required: true schema: type: array items: $ref: './external-shared.json#/definitions/ExternalSharedModel' responses: '201': $ref: '#/responses/ExternalArrayResponse' /external-union: get: summary: Get union of external types responses: '200': $ref: '#/responses/ExternalUnionResponse' post: summary: Create union of external types parameters: - name: body in: body required: true schema: oneOf: - $ref: './external-shared.json#/definitions/ExternalSharedModel' - $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/definitions/ExternalNested' responses: '201': $ref: '#/responses/ExternalUnionResponse' /external-properties/{id}: get: summary: Get external properties parameters: - name: id in: path required: true schema: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/id' - name: uuid in: query schema: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' - name: deep in: header schema: $ref: './external-shared.json#/definitions/ExternalNested/properties/inner/properties/deep' responses: '200': schema: type: object properties: id: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/id' name: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/name' uuid: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' deep: $ref: './external-shared.json#/definitions/ExternalNested/properties/inner/properties/deep' numeric: $ref: './external-shared.json#/definitions/ExternalNestedNumeric/properties/0/properties/1' # Definitions (equivalent to components/schemas in OpenAPI 3.0) definitions: # Basic external schema references (multiple uses of each type) ExternalSchemaA: description: External schema (A) $ref: './external-shared.json#/definitions/ExternalSharedModel' ExternalSchemaB: description: External schema (B) - second use of ExternalSharedModel $ref: './external-shared.json#/definitions/ExternalSharedModel' ExternalSchemaC: description: External schema (C) - third use of ExternalSharedModel $ref: './external-shared.json#/definitions/ExternalSharedModel' # Path-based references using /path syntax ExternalSchemaPathA: description: External schema via path reference (A) $ref: './external-shared.json#/definitions/ExternalSharedModel' ExternalSchemaPathB: description: External schema via path reference (B) - second use $ref: './external-shared.json#/definitions/ExternalSharedModel' # UUID type references (multiple uses) ExternalSchemaPropertyA: description: External schema property (A) type: object properties: uuid1: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' ExternalSchemaPropertyB: description: External schema property (B) - second use of UUID type: object properties: uuid2: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' ExternalSchemaPropertyC: description: External schema property (C) - third use of UUID type: object properties: uuid3: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' # Duplicate refs in same schema ExternalSchemaPropertyD: description: External schema property with duplicate refs (D) type: object properties: uuid4: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' uuid5: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' # External property references ExternalSchemaExternalProp: description: External schema property via external property ref (id) type: object properties: id3: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/id' id4: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/id' # Alias references ExternalSchemaExternalPropAlias: description: Alias to external property via component property ref type: object properties: id5: $ref: '#/definitions/ExternalSchemaExternalProp/properties/id3' id6: $ref: '#/definitions/ExternalSchemaExternalProp/properties/id4' # Nested property references (multiple uses) ExternalDoubleNestedProp: description: External double nested prop via property ref type: object properties: deep1: $ref: './external-shared.json#/definitions/ExternalNested/properties/inner/properties/deep' deep2: $ref: './external-shared.json#/definitions/ExternalNested/properties/inner/properties/deep' # Numeric property references (multiple uses) ExternalDoubleNestedNumeric: description: External double nested numeric properties type: object properties: numeric1: $ref: './external-shared.json#/definitions/ExternalNestedNumeric/properties/0/properties/1' numeric2: $ref: './external-shared.json#/definitions/ExternalNestedNumeric/properties/0/properties/1' # Complex nested object references ExternalNestedObjectA: description: External nested object reference (A) $ref: './external-shared.json#/definitions/ExternalNested' ExternalNestedObjectB: description: External nested object reference (B) - second use $ref: './external-shared.json#/definitions/ExternalNested' # Numeric nested object references ExternalNestedNumericObjectA: description: External numeric nested object reference (A) $ref: './external-shared.json#/definitions/ExternalNestedNumeric' ExternalNestedNumericObjectB: description: External numeric nested object reference (B) - second use $ref: './external-shared.json#/definitions/ExternalNestedNumeric' # Mixed property references ExternalMixedProperties: description: Mixed external property references type: object properties: id7: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/id' name1: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/name' uuid6: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' deep3: $ref: './external-shared.json#/definitions/ExternalNested/properties/inner/properties/deep' numeric3: $ref: './external-shared.json#/definitions/ExternalNestedNumeric/properties/0/properties/1' # Array of external references ExternalArraySchema: description: Array containing external references type: object properties: items: type: array items: $ref: './external-shared.json#/definitions/ExternalSharedModel' uuidItems: type: array items: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' # Union types with external references ExternalUnionSchema: description: Union type with external references oneOf: - $ref: './external-shared.json#/definitions/ExternalSharedModel' - $ref: './external-shared.json#/definitions/ExternalSharedModel' - $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' # AllOf with external references ExternalAllOfSchema: description: AllOf with external references allOf: - $ref: './external-shared.json#/definitions/ExternalSharedModel' - $ref: './external-shared.json#/definitions/ExternalSharedModel' - type: object properties: additional: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' # AnyOf with external references ExternalAnyOfSchema: description: AnyOf with external references anyOf: - $ref: './external-shared.json#/definitions/ExternalNested' - $ref: './external-shared.json#/definitions/ExternalNested' - $ref: './external-shared.json#/definitions/ExternalNestedNumeric' - $ref: './external-shared.json#/definitions/ExternalNestedNumeric' # Parameters using external references parameters: ExternalIdParam: name: id in: path required: true schema: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/id' ExternalUuidParam: name: uuid in: query schema: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' ExternalDeepParam: name: deep in: header schema: $ref: './external-shared.json#/definitions/ExternalNested/properties/inner/properties/deep' ExternalNumericParam: name: numeric in: query schema: $ref: './external-shared.json#/definitions/ExternalNestedNumeric/properties/0/properties/1' # Request bodies using external references ExternalModelBody: name: body in: body description: Request body using external model required: true schema: $ref: './external-shared.json#/definitions/ExternalSharedModel' ExternalUuidBody: name: body in: body description: Request body using external UUID schema: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' ExternalNestedBody: name: body in: body description: Request body using external nested object schema: $ref: './external-shared.json#/definitions/ExternalNested' ExternalMixedBody: name: body in: body description: Request body with mixed external properties schema: type: object properties: id: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/id' name: $ref: './external-shared.json#/definitions/ExternalSharedModel/properties/name' uuid: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' deep: $ref: './external-shared.json#/definitions/ExternalNested/properties/inner/properties/deep' # Responses using external references responses: ExternalModelResponse: description: Response using external model schema: $ref: './external-shared.json#/definitions/ExternalSharedModel' ExternalUuidResponse: description: Response using external UUID schema: $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' ExternalNestedResponse: description: Response using external nested object schema: $ref: './external-shared.json#/definitions/ExternalNested' ExternalArrayResponse: description: Response with array of external models schema: type: array items: $ref: './external-shared.json#/definitions/ExternalSharedModel' ExternalUnionResponse: description: Response with union of external types schema: oneOf: - $ref: './external-shared.json#/definitions/ExternalSharedModel' - $ref: './external-shared.json#/definitions/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/definitions/ExternalNested' ================================================ FILE: specs/2.0.x/form-data.json ================================================ { "swagger": "2.0", "info": { "title": "OpenAPI 2.0 form data example", "version": "1" }, "paths": { "/v1/foo": { "post": { "consumes": ["multipart/form-data"], "parameters": [ { "in": "formData", "name": "file", "required": true, "type": "file" }, { "in": "formData", "name": "info", "required": true, "type": "string" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/Foo" } } } } } }, "definitions": { "Foo": { "type": "object", "properties": { "status": { "type": "integer" } } } } } ================================================ FILE: specs/2.0.x/full.yaml ================================================ swagger: '2.0' info: title: swagger version: v1.0 host: localhost:3000 basePath: /base schemes: - http paths: /api/v{api-version}/no+tag: tags: [] get: operationId: ServiceWithEmptyTag patch: responses: default: description: OK put: operationId: foo+Wow responses: default: description: OK /api/v{api-version}/simple: get: tags: - Simple operationId: GetCallWithoutParametersAndResponse put: tags: - Simple operationId: PutCallWithoutParametersAndResponse post: tags: - Simple operationId: PostCallWithoutParametersAndResponse delete: tags: - Simple operationId: DeleteCallWithoutParametersAndResponse options: tags: - Simple operationId: OptionsCallWithoutParametersAndResponse head: tags: - Simple operationId: HeadCallWithoutParametersAndResponse patch: tags: - Simple operationId: PatchCallWithoutParametersAndResponse /api/v{api-version}/descriptions/: post: tags: - Descriptions operationId: CallWithDescriptions parameters: - description: |- Testing multiline comments in string: First line Second line Fourth line name: parameterWithBreaks in: query type: string - description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work' name: parameterWithBackticks in: query type: string - description: "Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work" name: parameterWithSlashes in: query type: string - description: 'Testing expression placeholders in string: ${expression} should work' name: parameterWithExpressionPlaceholders in: query type: string - description: 'Testing quotes in string: ''single quote'''''' and "double quotes""" should work' name: parameterWithQuotes in: query type: string - description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work' name: parameterWithReservedCharacters in: query type: string /api/v{api-version}/parameters/{parameterPath}: post: tags: - Parameters operationId: CallWithParameters parameters: - description: This is the parameter that goes into the header name: parameterHeader in: header type: string required: true - description: This is the parameter that goes into the query params name: parameterQuery in: query type: string required: true - description: This is the parameter that goes into the form data name: parameterForm in: formData type: string required: true - description: This is the parameter that goes into the path name: parameterPath in: path type: string required: true - description: api-version should be required in standalone clients name: api-version in: path type: string required: true /api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}: post: tags: - Parameters operationId: CallWithWeirdParameterNames parameters: - description: This is the parameter that goes into the path name: parameter.path.1 in: path type: string required: false - description: This is the parameter that goes into the path name: parameter-path-2 in: path type: string required: false - description: This is the parameter that goes into the path name: PARAMETER-PATH-3 in: path type: string required: false - description: This is the parameter with a reserved keyword name: default in: query type: string required: false - description: This is the parameter that goes into the request header name: parameter.header in: header type: string required: true - description: This is the parameter that goes into the request query params name: parameter-query in: query type: string required: true - description: This is the parameter that is sent as request body name: PARAMETER-BODY in: body required: true schema: type: string - description: api-version should be required in standalone clients name: api-version in: path type: string required: true /api/v{api-version}/defaults: get: tags: - Defaults operationId: CallWithDefaultParameters parameters: - description: This is a simple string with default value name: parameterString in: query required: true default: Hello World! type: string - description: This is a simple number with default value name: parameterNumber in: query required: true default: 123 type: number - description: This is a simple boolean with default value name: parameterBoolean in: query required: true default: true type: boolean - description: This is a simple enum with default value name: parameterEnum in: query required: true default: 0 enum: - Success - Warning - Error - description: This is a simple model with default value name: parameterModel in: query required: true default: prop: Hello World! $ref: '#/definitions/ModelWithString' post: tags: - Defaults operationId: CallWithDefaultOptionalParameters parameters: - description: This is a simple string that is optional with default value name: parameterString in: query default: Hello World! type: string - description: This is a simple number that is optional with default value name: parameterNumber in: query default: 123 type: number - description: This is a simple boolean that is optional with default value name: parameterBoolean in: query default: true type: boolean - description: This is a simple enum that is optional with default value name: parameterEnum in: query default: 0 enum: - Success - Warning - Error put: tags: - Defaults operationId: CallToTestOrderOfParams parameters: - description: This is a optional string with default name: parameterOptionalStringWithDefault in: query required: false default: Hello World! type: string - description: This is a optional string with empty default name: parameterOptionalStringWithEmptyDefault in: query required: false default: '' type: string - description: This is a optional string with no default name: parameterOptionalStringWithNoDefault in: query required: false type: string - description: This is a string with default name: parameterStringWithDefault in: query required: true default: Hello World! type: string - description: This is a string with empty default name: parameterStringWithEmptyDefault in: query required: true default: '' type: string - description: This is a string with no default name: parameterStringWithNoDefault in: query required: true type: string - x-nullable: true description: This is a string that can be null with no default name: parameterStringNullableWithNoDefault in: query required: false type: string - x-nullable: true description: This is a string that can be null with default name: parameterStringNullableWithDefault in: query required: false type: string default: null /api/v{api-version}/duplicate: delete: tags: - Duplicate operationId: DuplicateName get: tags: - Duplicate operationId: DuplicateName2 post: tags: - Duplicate operationId: DuplicateName3 put: tags: - Duplicate operationId: DuplicateName4 /api/v{api-version}/no-content: get: tags: - NoContent operationId: CallWithNoContentResponse responses: '204': description: Success /api/v{api-version}/multiple-tags/response-and-no-content: get: tags: - Response - NoContent operationId: CallWithResponseAndNoContentResponse produces: - application/json responses: '200': description: Response is a simple number schema: type: number '204': description: Success /api/v{api-version}/multiple-tags/a: get: tags: - MultipleTags1 - MultipleTags2 operationId: DummyA responses: '204': description: Success /api/v{api-version}/multiple-tags/b: get: tags: - MultipleTags1 - MultipleTags2 - MultipleTags3 operationId: DummyB responses: '204': description: Success /api/v{api-version}/response: get: tags: - Response operationId: CallWithResponse responses: default: description: Message for default response schema: $ref: '#/definitions/ModelWithString' post: tags: - Response operationId: CallWithDuplicateResponses responses: '201': description: Message for 201 response schema: $ref: '#/definitions/ModelWithString' '202': description: Message for 202 response schema: $ref: '#/definitions/ModelWithString' '500': description: Message for 500 error schema: $ref: '#/definitions/ModelWithStringError' '501': description: Message for 501 error schema: $ref: '#/definitions/ModelWithStringError' '502': description: Message for 502 error schema: $ref: '#/definitions/ModelWithStringError' default: description: Message for default response schema: $ref: '#/definitions/ModelWithString' put: tags: - Response operationId: CallWithResponses responses: '200': description: Message for 200 response schema: type: object properties: '@namespace.string': type: string readOnly: true '@namespace.integer': type: integer readOnly: true value: type: array items: $ref: '#/definitions/ModelWithString' readOnly: true '201': description: Message for 201 response schema: $ref: '#/definitions/ModelThatExtends' '202': description: Message for 202 response schema: $ref: '#/definitions/ModelThatExtendsExtends' '500': description: Message for 500 error schema: $ref: '#/definitions/ModelWithStringError' '501': description: Message for 501 error schema: $ref: '#/definitions/ModelWithStringError' '502': description: Message for 502 error schema: $ref: '#/definitions/ModelWithStringError' default: description: Message for default response schema: $ref: '#/definitions/ModelWithString' /api/v{api-version}/collectionFormat: get: tags: - CollectionFormat operationId: CollectionFormat parameters: - description: This is an array parameter that is sent as csv format (comma-separated values) name: parameterArrayCSV in: query required: true type: array items: type: string collectionFormat: csv - description: This is an array parameter that is sent as ssv format (space-separated values) name: parameterArraySSV in: query required: true type: array items: type: string collectionFormat: ssv - description: This is an array parameter that is sent as tsv format (tab-separated values) name: parameterArrayTSV in: query required: true type: array items: type: string collectionFormat: tsv - description: This is an array parameter that is sent as pipes format (pipe-separated values) name: parameterArrayPipes in: query required: true type: array items: type: string collectionFormat: pipes - description: This is an array parameter that is sent as multi format (multiple parameter instances) name: parameterArrayMulti in: query required: true type: array items: type: string collectionFormat: multi /api/v{api-version}/types: get: tags: - Types operationId: Types parameters: - description: This is a number parameter name: parameterNumber in: query required: true default: 123 type: number - description: This is a string parameter name: parameterString in: query required: true default: default type: string - description: This is a boolean parameter name: parameterBoolean in: query required: true default: true type: boolean - description: This is an array parameter name: parameterArray in: query required: true type: array items: type: string - description: This is a dictionary parameter name: parameterDictionary in: query required: true type: object items: type: string - description: This is an enum parameter name: parameterEnum in: query required: true enum: - Success - Warning - Error - description: This is a number parameter name: id in: path type: integer format: int32 responses: '200': description: Response is a simple number schema: type: number '201': description: Response is a simple string schema: type: string '202': description: Response is a simple boolean schema: type: boolean '203': description: Response is a simple object default: null schema: type: object /api/v{api-version}/complex: get: tags: - Complex operationId: ComplexTypes parameters: - description: Parameter containing object name: parameterObject in: query required: true type: object properties: first: type: object properties: second: type: object properties: third: type: string - description: Parameter containing reference name: parameterReference in: query required: true $ref: '#/definitions/ModelWithString' responses: '200': description: Successful response schema: type: array items: $ref: '#/definitions/ModelWithString' '400': description: 400 server error '500': description: 500 server error /api/v{api-version}/header: post: tags: - Header operationId: CallWithResultFromHeader responses: '200': description: Successful response headers: operation-location: type: string '400': description: 400 server error '500': description: 500 server error /api/v{api-version}/error: post: tags: - Error operationId: testErrorCode parameters: - description: Status code to return name: status in: query type: string required: true responses: '200': description: 'Custom message: Successful response' '500': description: 'Custom message: Internal Server Error' '501': description: 'Custom message: Not Implemented' '502': description: 'Custom message: Bad Gateway' '503': description: 'Custom message: Service Unavailable' /api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串: post: tags: - Non-Ascii-æøåÆØÅöôêÊ operationId: nonAsciiæøåÆØÅöôêÊ字符串 parameters: - description: Dummy input param name: nonAsciiParamæøåÆØÅöôêÊ in: query required: true type: integer responses: '200': description: Successful response schema: $ref: '#/definitions/NonAsciiStringæøåÆØÅöôêÊ字符串' /api/v{api-version}/body: post: description: Body should not be unknown consumes: - application/json produces: - application/json summary: Body should not be unknown parameters: - description: Body should not be unknown name: request in: body required: true schema: $ref: '#/definitions/parameter.ActivityParams' responses: '200': description: OK schema: $ref: '#/definitions/response.PostActivityResponse' '400': description: Bad Request schema: $ref: '#/definitions/failure.Failure' '500': description: Internal Server Error schema: $ref: '#/definitions/failure.Failure' definitions: ExternalRefA: description: External ref to shared model (A) $ref: './external-shared.json#/definitions/ExternalSharedModel' ExternalRefB: description: External ref to shared model (B) $ref: './external-shared.json#/definitions/ExternalSharedModel' CommentWithBreaks: description: |- Testing multiline comments in string: First line Second line Fourth line type: integer CommentWithBackticks: description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work' type: integer CommentWithBackticksAndQuotes: description: 'Testing backticks and quotes in string: `backticks`, ''quotes'', "double quotes" and ```multiple backticks``` should work' type: integer CommentWithSlashes: description: "Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work" type: integer CommentWithExpressionPlaceholders: description: 'Testing expression placeholders in string: ${expression} should work' type: integer CommentWithQuotes: description: 'Testing quotes in string: ''single quote'''''' and "double quotes""" should work' type: integer CommentWithReservedCharacters: description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work' type: integer SimpleInteger: description: This is a simple number type: integer SimpleBoolean: description: This is a simple boolean type: boolean SimpleString: description: This is a simple string type: string NonAsciiStringæøåÆØÅöôêÊ字符串: description: A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) type: string SimpleFile: description: This is a simple file format: binary type: string SimpleReference: description: This is a simple reference $ref: '#/definitions/ModelWithString' SimpleStringWithPattern: description: This is a simple string type: string maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ EnumWithStrings: description: This is a simple enum with strings enum: - Success - Warning - Error - "'Single Quote'" - '"Double Quotes"' - 'Non-ascii: øæåôöØÆÅÔÖ字符串' EnumWithNumbers: description: This is a simple enum with numbers enum: - 1 - 2 - 3 - 1.1 - 1.2 - 1.3 - 100 - 200 - 300 - -100 - -200 - -300 - -1.1 - -1.2 - -1.3 EnumFromDescription: description: Success=1,Warning=2,Error=3 type: number EnumWithExtensions: description: This is a simple enum with numbers enum: - 200 - 400 - 500 x-enum-varnames: - CUSTOM_SUCCESS - CUSTOM_WARNING - CUSTOM_ERROR x-enum-descriptions: - Used when the status of something is successful - Used when the status of something has a warning - Used when the status of something has an error ArrayWithNumbers: description: This is a simple array with numbers type: array items: type: integer ArrayWithBooleans: description: This is a simple array with booleans type: array items: type: boolean ArrayWithStrings: description: This is a simple array with strings type: array items: type: string ArrayWithReferences: description: This is a simple array with references type: array items: $ref: '#/definitions/ModelWithString' ArrayWithArray: description: This is a simple array containing an array type: array items: type: array items: $ref: '#/definitions/ModelWithString' ArrayWithProperties: description: This is a simple array with properties type: array items: type: object properties: foo: type: string bar: type: string DictionaryWithString: description: This is a string dictionary type: object additionalProperties: type: string DictionaryWithReference: description: This is a string reference type: object additionalProperties: $ref: '#/definitions/ModelWithString' DictionaryWithArray: description: This is a complex dictionary type: object additionalProperties: type: array items: $ref: '#/definitions/ModelWithString' DictionaryWithDictionary: description: This is a string dictionary type: object additionalProperties: type: object additionalProperties: type: string DictionaryWithProperties: description: This is a complex dictionary type: object additionalProperties: type: object properties: foo: type: string bar: type: string Date: description: This is a type-only model that defines Date as a string type: string ModelWithInteger: description: This is a model with one number property type: object properties: prop: description: This is a simple number property type: integer ModelWithBoolean: description: This is a model with one boolean property type: object properties: prop: description: This is a simple boolean property type: boolean ModelWithString: description: This is a model with one string property type: object properties: prop: description: This is a simple string property type: string ModelWithStringError: description: This is a model with one string property type: object properties: prop: description: This is a simple string property type: string ModelWithNullableString: description: This is a model with one string property type: object required: - nullableRequiredProp properties: nullableProp: description: This is a simple string property type: string x-nullable: true nullableRequiredProp: description: This is a simple string property type: string x-nullable: true ModelWithEnum: description: This is a model with one enum type: object properties: test: description: This is a simple enum with strings enum: - Success - Warning - Error - ØÆÅ字符串 statusCode: description: These are the HTTP error code enums enum: - '100' - 200 FOO - 300 FOO_BAR - 400 foo-bar - 500 foo.bar - 600 foo&bar bool: description: Simple boolean enum type: boolean enum: - true ModelWithEnumFromDescription: description: This is a model with one enum type: object properties: test: type: integer description: Success=1,Warning=2,Error=3 ModelWithNestedEnums: description: This is a model with nested enums type: object properties: dictionaryWithEnum: type: object additionalProperties: enum: - Success - Warning - Error dictionaryWithEnumFromDescription: type: object additionalProperties: type: integer description: Success=1,Warning=2,Error=3 arrayWithEnum: type: array items: enum: - Success - Warning - Error arrayWithDescription: type: array items: type: integer description: Success=1,Warning=2,Error=3 ModelWithReference: description: This is a model with one property containing a reference type: object properties: prop: $ref: '#/definitions/ModelWithProperties' ModelWithArray: description: This is a model with one property containing an array type: object properties: prop: type: array items: $ref: '#/definitions/ModelWithString' propWithFile: type: array items: format: binary type: string propWithNumber: type: array items: type: number ModelWithDictionary: description: This is a model with one property containing a dictionary type: object properties: prop: type: object additionalProperties: type: string ModelWithCircularReference: description: This is a model with one property containing a circular reference type: object properties: prop: $ref: '#/definitions/ModelWithCircularReference' ModelWithProperties: description: This is a model with one nested property type: object required: - required - requiredAndReadOnly properties: required: type: string requiredAndReadOnly: type: string readOnly: true string: type: string number: type: number boolean: type: boolean reference: $ref: '#/definitions/ModelWithString' property with space: type: string default: type: string try: type: string '@namespace.string': type: string readOnly: true '@namespace.integer': type: integer readOnly: true ModelWithNestedProperties: description: This is a model with one nested property type: object required: - first properties: first: type: object required: - second readOnly: true properties: second: type: object required: - third readOnly: true properties: third: type: string readOnly: true ModelWithDuplicateProperties: description: This is a model with duplicated properties type: object properties: prop: $ref: '#/definitions/ModelWithString' ModelWithOrderedProperties: description: This is a model with ordered properties type: object properties: zebra: type: string apple: type: string hawaii: type: string ModelWithDuplicateImports: description: This is a model with duplicated imports type: object properties: propA: $ref: '#/definitions/ModelWithString' propB: $ref: '#/definitions/ModelWithString' propC: $ref: '#/definitions/ModelWithString' ModelThatExtends: description: This is a model that extends another model type: object allOf: - $ref: '#/definitions/ModelWithString' - type: object properties: propExtendsA: type: string propExtendsB: $ref: '#/definitions/ModelWithString' ModelThatExtendsExtends: description: This is a model that extends another model type: object allOf: - $ref: '#/definitions/ModelWithString' - $ref: '#/definitions/ModelThatExtends' - type: object properties: propExtendsC: type: string propExtendsD: $ref: '#/definitions/ModelWithString' default: type: object properties: name: type: string ModelWithPattern: description: This is a model that contains a some patterns type: object required: - key - name properties: key: maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ type: string name: maxLength: 255 type: string enabled: type: boolean readOnly: true modified: type: string format: date-time readOnly: true id: type: string pattern: ^\d{2}-\d{3}-\d{4}$ text: type: string pattern: ^\w+$ patternWithSingleQuotes: type: string pattern: ^[a-zA-Z0-9']*$ patternWithNewline: type: string pattern: aaa\nbbb patternWithBacktick: type: string pattern: aaa`bbb patternWithUnicode: type: string pattern: ^\p{L}+$ parameter.ActivityParams: type: object properties: description: type: string graduate_id: type: integer organization_id: type: integer parent_activity: type: integer post_id: type: integer response.PostActivityResponse: type: object properties: description: type: string graduate_id: type: integer organization_id: type: integer parent_activity_id: type: integer post_id: type: integer failure.Failure: type: object properties: error: type: string message: type: string reference_code: type: string ================================================ FILE: specs/2.0.x/invalid/operationId-unique.yaml ================================================ swagger: 2.0 info: title: Invalid OpenAPI 2.0 operationId unique example version: 1 paths: /foo: get: operationId: foo produces: - application/json responses: '200': description: OK schema: type: string post: operationId: foo responses: '200': description: OK schema: type: string ================================================ FILE: specs/2.0.x/ref-deep.yaml ================================================ swagger: '2.0' info: title: OpenAPI 2.0 ref deep example version: '1' paths: /foo: get: responses: '200': description: OK content: application/json: schema: type: array items: type: object properties: foo: type: integer bar: type: string post: responses: '200': description: OK content: application/json: schema: type: object properties: foo: $ref: '#/paths/~1foo/get/responses/200/content/application~1json/schema/items' bar: type: string definitions: Foo: type: object properties: foo: type: array items: type: object properties: baz: type: string bar: type: array items: type: object properties: baz: type: string Bar: type: object properties: foo: type: array items: $ref: '#/definitions/Foo/properties/foo/items' bar: type: array items: $ref: '#/definitions/Foo/properties/bar/items' ================================================ FILE: specs/2.0.x/schema-unknown.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 schema unknown example description: https://github.com/hey-api/openapi-ts/issues/1402 version: 1 host: api.postmarkapp.com basePath: / produces: - application/json consumes: - application/json definitions: SendEmailRequest: properties: From: description: The sender email address. Must have a registered and confirmed Sender Signature. type: string To: description: Recipient email address. Multiple addresses are comma seperated. Max 50. type: string Cc: description: Recipient email address. Multiple addresses are comma seperated. Max 50. type: string Bcc: description: Bcc recipient email address. Multiple addresses are comma seperated. Max 50. type: string Subject: description: Email Subject type: string Tag: description: Email tag that allows you to categorize outgoing emails and get detailed statistics. type: string HtmlBody: description: If no TextBody specified HTML email message type: string TextBody: description: If no HtmlBody specified Plain text email message type: string ReplyTo: description: Reply To override email address. Defaults to the Reply To set in the sender signature. type: string TrackOpens: description: Activate open tracking for this email. type: boolean TrackLinks: description: Replace links in content to enable "click tracking" stats. Default is 'null', which uses the server's LinkTracking setting'. type: string enum: ['None', 'HtmlAndText', 'HtmlOnly', 'TextOnly'] Headers: $ref: '#/definitions/HeaderCollection' Attachments: $ref: '#/definitions/AttachmentCollection' MessageHeader: description: A single header for an email message. properties: Name: description: The header's name. type: string Value: description: The header's value. type: string HeaderCollection: type: array items: $ref: '#/definitions/MessageHeader' Attachment: description: An attachment for an email message. properties: Name: type: string Content: type: string ContentType: type: string ContentID: type: string AttachmentCollection: type: array items: $ref: '#/definitions/Attachment' SendEmailResponse: description: The standard response when a postmark message is sent properties: To: type: string SubmittedAt: type: string format: 'date-time' MessageID: type: string ErrorCode: type: integer Message: type: string StandardPostmarkResponse: description: 'A Postmark API error.' properties: ErrorCode: type: integer Message: type: string responses: 422: description: 'An error was generated due to incorrect use of the API. See the Message associated with this response for more information.' schema: $ref: '#/definitions/StandardPostmarkResponse' 500: description: 'Indicates an internal server error occurred.' paths: #Message Sending API /email: post: operationId: sendEmail tags: - Sending API summary: Send a single email parameters: - name: X-Postmark-Server-Token required: true description: The token associated with the Server on which this request will operate. type: string in: header - name: body in: body schema: $ref: '#/definitions/SendEmailRequest' responses: 200: description: OK schema: $ref: '#/definitions/SendEmailResponse' 422: $ref: '#/responses/422' 500: $ref: '#/responses/500' ================================================ FILE: specs/2.0.x/sdk-instance.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 sdk instance example version: 1 paths: /foo: get: tags: - fooBaz produces: - application/json responses: '200': description: OK schema: type: string post: tags: - fooBaz operationId: foo.-post produces: - application/json responses: '200': description: OK schema: type: string put: tags: - fooBaz operationId: /foo/-put/ produces: - application/json responses: '200': description: OK schema: type: string /foo/bar: get: tags: - barBaz produces: - application/json responses: '200': description: OK schema: type: string post: tags: - fooBaz - barBaz operationId: foo.bar.post produces: - application/json responses: '200': description: OK schema: type: string put: tags: - fooBaz - barBaz operationId: /foo/bar/put/ produces: - application/json responses: '200': description: OK schema: type: string ================================================ FILE: specs/2.0.x/sdk-nested-classes.yaml ================================================ swagger: '2.0' info: title: OpenAPI 2.0 sdk nested classes example version: 1.0.0 description: Test schema for nested class generation with various operationId patterns host: api.example.com basePath: /v1 schemes: - https paths: /business/providers/domains: get: tags: - business - providers - domains operationId: business.providers.domains.get produces: - '*/*' responses: '200': description: OK schema: type: string post: tags: - providers - domains - business operationId: business.providers.domains.post produces: - '*/*' responses: '200': description: OK schema: type: string put: tags: - domains produces: - '*/*' responses: '200': description: OK schema: type: string /locations/businesses: get: tags: - locations - business operationId: business.get produces: - '*/*' responses: '200': description: OK schema: type: string /locations: get: tags: - locations operationId: get produces: - '*/*' responses: '200': description: OK schema: type: string ================================================ FILE: specs/2.0.x/security-api-key.yaml ================================================ swagger: '2.0' info: title: OpenAPI 2.0 security api key example version: '1' paths: /foo: get: responses: '200': description: OK security: - foo: [] securityDefinitions: foo: in: query name: foo type: apiKey ================================================ FILE: specs/2.0.x/security-basic.json ================================================ { "swagger": "2.0", "info": { "title": "OpenAPI 2.0 security basic example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK" } }, "security": [ { "foo": [] } ] } } }, "securityDefinitions": { "foo": { "type": "basic" } } } ================================================ FILE: specs/2.0.x/security-oauth2.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 security oauth2 example version: 1 paths: /foo: get: responses: '200': description: OK security: - foo: [] securityDefinitions: foo: flow: 'password' scopes: {} tokenUrl: '/' type: 'oauth2' ================================================ FILE: specs/2.0.x/servers-base-path.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 servers base path example version: 1 basePath: /v1 paths: /foo: get: produces: - application/json responses: '200': description: OK schema: type: string ================================================ FILE: specs/2.0.x/servers-host.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 servers host example version: 1 host: foo.com paths: /foo: get: produces: - application/json responses: '200': description: OK schema: type: string ================================================ FILE: specs/2.0.x/servers.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 servers example version: 1 host: foo.com basePath: /v1 schemes: - https paths: /foo: get: produces: - application/json responses: '200': description: OK schema: type: string ================================================ FILE: specs/2.0.x/transforms-read-write.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 transforms read write example version: 1 produces: - application/json consumes: - application/json paths: /foo-read: post: parameters: - name: body in: body required: true schema: $ref: '#/definitions/FooRead' responses: '200': schema: $ref: '#/definitions/FooRead' description: OK definitions: FooRead: allOf: - $ref: '#/definitions/BarRead' - type: object properties: foo: readOnly: true type: string BarRead: allOf: - $ref: '#/definitions/Baz' - type: object properties: bar: readOnly: true type: string Baz: type: object properties: baz: type: string QuxAllRead: type: object properties: baz: readOnly: true type: string Quux: type: object properties: baz: type: array items: $ref: '#/definitions/Baz' qux: $ref: '#/definitions/QuxAllRead' Corge: type: object properties: foo: type: string bar: type: object properties: baz: type: boolean readOnly: true ================================================ FILE: specs/2.0.x/transforms-schemas-name.yaml ================================================ swagger: '2.0' info: title: Schema Name Transform Test (Swagger 2.0) version: 1.0.0 paths: /users: get: summary: Get users produces: - application/json responses: '200': description: Success schema: $ref: '#/definitions/User_v1_0_0_User' /posts: post: summary: Create post consumes: - application/json produces: - application/json parameters: - in: body name: body schema: $ref: '#/definitions/Post_v2_1_3_Post' responses: '201': description: Created schema: $ref: '#/definitions/Post_v2_1_3_Post' definitions: User_v1_0_0_User: type: object properties: id: type: string name: type: string profile: $ref: '#/definitions/UserProfile_v1_0_0_UserProfile' UserProfile_v1_0_0_UserProfile: type: object properties: bio: type: string avatar: type: string Post_v2_1_3_Post: type: object properties: id: type: string title: type: string author: $ref: '#/definitions/User_v1_0_0_User' comments: type: array items: $ref: '#/definitions/Comment_v1_5_2_Comment' Comment_v1_5_2_Comment: type: object properties: id: type: string text: type: string author: $ref: '#/definitions/User_v1_0_0_User' ================================================ FILE: specs/2.0.x/type-format.yaml ================================================ swagger: 2.0 info: title: OpenAPI 2.0 type format example version: 1 paths: /foo: post: produces: - application/json responses: '200': description: OK schema: $ref: '#/definitions/Foo' definitions: Foo: type: object properties: bar: type: integer foo: default: 0 format: int64 type: integer id: type: string format: typeid example: 'user_123' required: - id - foo Bar: type: object required: - foo properties: foo: type: integer additionalProperties: type: integer ================================================ FILE: specs/3.0.x/additional-properties-false.json ================================================ { "openapi": "3.0.1", "info": { "title": "OpenAPI 3.0.1 additional properties false example", "version": "1" }, "components": { "schemas": { "Foo": { "required": ["foo"], "type": "object", "properties": { "foo": { "type": "string" } }, "additionalProperties": false }, "Bar": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "type": "object", "additionalProperties": false } ] }, "Baz": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "required": ["bar"], "type": "object", "properties": { "bar": { "type": "string" } }, "additionalProperties": false } ] } } } } ================================================ FILE: specs/3.0.x/additional-properties-true.json ================================================ { "openapi": "3.0.1", "info": { "title": "OpenAPI 3.0.1 additional properties true example", "version": "1" }, "components": { "schemas": { "Foo": { "required": ["foo"], "type": "object", "properties": { "foo": { "type": "string" } }, "additionalProperties": true }, "Bar": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "type": "object", "additionalProperties": true } ] }, "Baz": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "required": ["bar"], "type": "object", "properties": { "bar": { "type": "string" } }, "additionalProperties": true } ] }, "Qux": { "type": "object", "additionalProperties": {} } } } } ================================================ FILE: specs/3.0.x/additional-properties-undefined.json ================================================ { "openapi": "3.0.4", "info": { "title": "OpenAPI 3.0.4 additional properties undefined example", "version": "1" }, "components": { "schemas": { "Foo": { "properties": { "foo": { "type": "object" } }, "required": ["foo"], "type": "object" } } } } ================================================ FILE: specs/3.0.x/array-items-all-of.yaml ================================================ openapi: 3.0.2 info: title: OpenAPI 3.0.2 array items allOf example version: '1' components: schemas: # Test case 1: Array with allOf of object schemas ArrayWithAllOfObjects: type: array items: allOf: - type: object properties: id: type: integer - type: object properties: name: type: string # Test case 2: Array with allOf of primitives ArrayWithAllOfPrimitives: type: array items: allOf: - type: number - type: string # Test case 3: Array with allOf including refs ArrayWithAllOfRefs: type: array items: allOf: - $ref: '#/components/schemas/BaseModel' - type: object properties: extra: type: string BaseModel: type: object properties: id: type: integer createdAt: type: string format: date-time ================================================ FILE: specs/3.0.x/array-items-one-of-length-1.yaml ================================================ openapi: 3.0.2 info: title: OpenAPI 3.0.2 array items oneOf length 1 example version: '1' components: schemas: Foo: type: object properties: foo: type: array items: oneOf: - $ref: '#/components/schemas/Bar' maxItems: 2147483647 minItems: 1 Bar: type: string ================================================ FILE: specs/3.0.x/array-nested-one-of.yaml ================================================ openapi: 3.0.3 info: title: OpenAPI 3.0.3 array nested one of example version: 1 components: schemas: Foo: oneOf: - type: array items: oneOf: - type: object properties: foo: type: string bar: type: string - type: object properties: baz: type: string qux: type: string - type: array items: type: object properties: foo: type: string bar: type: string ================================================ FILE: specs/3.0.x/body-binary-format.yaml ================================================ openapi: 3.0.0 info: title: OpenAPI 3.0.0 binary format body example version: 1 paths: /upload-zip: post: summary: Upload a zip file operationId: uploadZip requestBody: required: true content: application/zip: schema: type: string format: binary responses: '204': description: Successfully uploaded /upload-pdf: post: summary: Upload a PDF file operationId: uploadPdf requestBody: required: true content: application/pdf: schema: type: string format: binary responses: '204': description: Successfully uploaded /upload-binary: post: summary: Upload binary data operationId: uploadBinary requestBody: required: true content: application/octet-stream: schema: type: string format: binary responses: '204': description: Successfully uploaded ================================================ FILE: specs/3.0.x/body-response-text-plain.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 body response text plain example version: 1 paths: /foo: post: requestBody: content: 'text/plain': schema: type: string required: true responses: '200': description: OK content: text/plain: schema: type: string ================================================ FILE: specs/3.0.x/case.yaml ================================================ openapi: 3.0.2 info: title: OpenAPI 3.0.2 case example version: '1' paths: /foo: get: parameters: - description: 'original name: fooBar' in: query name: fooBar required: true schema: type: string - description: 'original name: BarBaz' in: query name: BarBaz required: true schema: type: string - description: 'original name: qux_quux' in: query name: qux_quux required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/Foo' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Foo' '201': description: OK content: application/json: schema: $ref: '#/components/schemas/201' components: schemas: '201': description: 'original name: 201' type: number Foo: description: 'original name: Foo' properties: fooBar: description: 'original name: fooBar' allOf: - $ref: '#/components/schemas/foo_bar' BarBaz: description: 'original name: BarBaz' allOf: - $ref: '#/components/schemas/Foo' qux_quux: description: 'original name: qux_quux' properties: fooBar: description: 'original name: fooBar' allOf: - $ref: '#/components/schemas/fooBar' BarBaz: description: 'original name: BarBaz' allOf: - $ref: '#/components/schemas/FooBar' qux_quux: description: 'original name: qux_quux' type: boolean required: - fooBar - BarBaz - qux_quux type: object required: - fooBar - BarBaz - qux_quux type: object foo_bar: description: 'original name: foo_bar' type: boolean fooBar: description: 'original name: fooBar' type: number FooBar: description: 'original name: FooBar' type: string ================================================ FILE: specs/3.0.x/circular.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 circular example version: 1 components: schemas: Foo: type: object properties: quux: $ref: '#/components/schemas/Quux' Bar: type: object properties: bar: $ref: '#/components/schemas/Bar' baz: $ref: '#/components/schemas/Baz' Baz: type: object properties: quux: $ref: '#/components/schemas/Quux' Qux: discriminator: propertyName: type mapping: array: '#/components/schemas/Foo' struct: '#/components/schemas/Corge' oneOf: - $ref: '#/components/schemas/Corge' - $ref: '#/components/schemas/Foo' Quux: type: object properties: qux: $ref: '#/components/schemas/Qux' Corge: type: object properties: baz: type: array items: $ref: '#/components/schemas/Baz' ================================================ FILE: specs/3.0.x/components-request-bodies.json ================================================ { "openapi": "3.0.4", "info": { "title": "OpenAPI 3.0.4 components request bodies example", "version": "1" }, "paths": { "/foo": { "post": { "requestBody": { "$ref": "#/components/requestBodies/Foo" }, "responses": { "200": { "description": "OK" } } } } }, "components": { "requestBodies": { "Foo": { "description": "Foo", "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "page": { "type": "number" } } } } } } } } } ================================================ FILE: specs/3.0.x/content-binary.json ================================================ { "openapi": "3.0.0", "info": { "title": "OpenAPI 3.0.0 content binary example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "content": { "image/png": { "schema": { "type": "string", "contentMediaType": "image/png", "contentEncoding": "base64" } } } } } } }, "/bar": { "get": { "responses": { "200": { "content": { "application/zip": {} } } } } } } } ================================================ FILE: specs/3.0.x/content-types.yaml ================================================ openapi: 3.0.0 info: title: OpenAPI 3.0.0 content types example version: '1' paths: /foo: get: responses: '200': description: OK content: text/plain: schema: type: string application/json: schema: type: string text/json: schema: type: string ================================================ FILE: specs/3.0.x/discriminator-all-of.yaml ================================================ openapi: 3.0.3 info: title: OpenAPI 3.0.3 discriminator all of example version: 1 components: schemas: Foo: type: object required: - id properties: id: type: string discriminator: propertyName: id Bar: allOf: - $ref: '#/components/schemas/Foo' - type: object properties: bar: type: string Baz: allOf: - $ref: '#/components/schemas/Foo' - type: object properties: baz: type: string Qux: allOf: - $ref: '#/components/schemas/Foo' - type: object properties: qux: type: boolean FooMapped: type: object required: - id properties: id: type: string discriminator: propertyName: id mapping: bar: '#/components/schemas/BarMapped' baz: '#/components/schemas/BazMapped' BarMapped: allOf: - $ref: '#/components/schemas/FooMapped' - type: object properties: bar: type: string BazMapped: allOf: - $ref: '#/components/schemas/FooMapped' - type: object properties: baz: type: string QuxMapped: allOf: - $ref: '#/components/schemas/FooMapped' - type: object properties: qux: type: boolean FooUnion: oneOf: - $ref: '#/components/schemas/BarUnion' - $ref: '#/components/schemas/BazUnion' discriminator: propertyName: id mapping: bar: '#/components/schemas/BarUnion' baz: '#/components/schemas/BazUnion' BarUnion: type: object properties: id: type: string bar: type: string BazUnion: type: object properties: id: type: string baz: type: string QuxExtend: # this is a schema that extends the FooUnion schema allOf: - $ref: '#/components/schemas/FooUnion' ================================================ FILE: specs/3.0.x/discriminator-allof-inline.json ================================================ { "openapi": "3.0.3", "info": { "title": "Discriminator allOf inline schema mapping", "version": "1.0.0", "description": "Reproduces a bug where a schema extending a parent whose allOf contains both a $ref (with a discriminator that doesn't map the child) and an inline schema (with a discriminator that does map the child) gets the wrong discriminator value. The inline discriminator mapping should win, not the $ref discriminator fallback." }, "paths": { "/foos": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/Bar" }, { "$ref": "#/components/schemas/Baz" }, { "$ref": "#/components/schemas/Qux" } ] } } } } } } } }, "components": { "schemas": { "Foo": { "required": ["$type"], "type": "object", "properties": { "$type": { "type": "string" }, "foo": { "type": "string" } }, "discriminator": { "propertyName": "$type", "mapping": { "FooBar": "#/components/schemas/Bar", "FooBaz": "#/components/schemas/Baz" } } }, "Bar": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "required": ["$type"], "type": "object", "properties": { "$type": { "type": "string" }, "bar": { "type": "string" } }, "discriminator": { "propertyName": "$type", "mapping": { "BarQux": "#/components/schemas/Qux" } } } ] }, "Baz": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "type": "object", "properties": { "baz": { "type": "string" } } } ] }, "Qux": { "allOf": [ { "$ref": "#/components/schemas/Bar" }, { "type": "object", "properties": { "qux": { "type": "string" } } } ] } } } } ================================================ FILE: specs/3.0.x/discriminator-allof-nested.json ================================================ { "openapi": "3.0.3", "info": { "title": "Minimal Polymorphic Discriminator Reproduction", "version": "1.0.0", "description": "Demonstrates an issue where TypeScript type generation results in wrong discriminator for nested allOf inheritance with discriminators at multiple levels." }, "paths": { "/cars": { "get": { "summary": "Get cars", "responses": { "200": { "description": "List of cars", "content": { "application/json": { "schema": { "type": "array", "items": { "oneOf": [ { "$ref": "#/components/schemas/CarDto" }, { "$ref": "#/components/schemas/VolvoDto" } ] } } } } } } } } }, "components": { "schemas": { "VehicleDto": { "type": "object", "required": ["$type", "id"], "properties": { "$type": { "type": "string" }, "id": { "type": "integer" } }, "discriminator": { "propertyName": "$type", "mapping": { "Car": "#/components/schemas/CarDto", "Volvo": "#/components/schemas/VolvoDto" } } }, "CarDto": { "allOf": [ { "$ref": "#/components/schemas/VehicleDto" }, { "type": "object", "required": ["modelName"], "properties": { "modelName": { "type": "string" } } } ] }, "VolvoDto": { "allOf": [ { "$ref": "#/components/schemas/CarDto" }, { "type": "object", "required": ["seatbeltCount"], "properties": { "seatbeltCount": { "type": "integer" } } } ] } } } } ================================================ FILE: specs/3.0.x/discriminator-any-of.yaml ================================================ openapi: 3.0.3 info: title: OpenAPI 3.0.3 discriminator any of example version: 1 components: schemas: Foo: anyOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' discriminator: propertyName: type Baz: allOf: - $ref: '#/components/schemas/Qux' Bar: allOf: - $ref: '#/components/schemas/Qux' Spæcial: allOf: - $ref: '#/components/schemas/Qux' Qux: type: object properties: id: type: string type: $ref: '#/components/schemas/Quux' required: - id - type Quux: enum: - Bar - Baz type: string Quuz: anyOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/Spæcial' discriminator: propertyName: type mapping: bar: '#/components/schemas/Bar' baz: '#/components/schemas/Baz' 'non-ascii': '#/components/schemas/Spæcial' ================================================ FILE: specs/3.0.x/discriminator-mapped-many.yaml ================================================ openapi: 3.0.0 info: title: OpenAPI 3.0.0 discriminator mapped many example version: 1 components: schemas: Foo: oneOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/Spæcial' discriminator: propertyName: foo mapping: one: '#/components/schemas/Bar' two: '#/components/schemas/Bar' three: '#/components/schemas/Baz' four: '#/components/schemas/Spæcial' Bar: type: object properties: foo: type: string enum: - one - two Baz: type: object properties: foo: type: string enum: - three Spæcial: type: object properties: foo: type: string enum: - four ================================================ FILE: specs/3.0.x/discriminator-non-string.yaml ================================================ openapi: 3.0.3 info: title: Non-string discriminator test version: 1 components: schemas: # --- Boolean discriminator (oneOf) --- BooleanOneOf: oneOf: - $ref: '#/components/schemas/AutoConfig' - $ref: '#/components/schemas/CustomConfig' discriminator: propertyName: use_custom mapping: 'False': '#/components/schemas/AutoConfig' 'True': '#/components/schemas/CustomConfig' AutoConfig: type: object required: - use_custom - auto_setting properties: use_custom: type: boolean const: false auto_setting: type: string CustomConfig: type: object required: - use_custom - custom_value properties: use_custom: type: boolean const: true custom_value: type: integer # --- Boolean discriminator (anyOf) --- BooleanAnyOf: anyOf: - $ref: '#/components/schemas/AutoConfig' - $ref: '#/components/schemas/CustomConfig' discriminator: propertyName: use_custom mapping: 'False': '#/components/schemas/AutoConfig' 'True': '#/components/schemas/CustomConfig' # --- Integer discriminator (oneOf) --- IntegerOneOf: oneOf: - $ref: '#/components/schemas/TypeOne' - $ref: '#/components/schemas/TypeTwo' discriminator: propertyName: type_id mapping: '1': '#/components/schemas/TypeOne' '2': '#/components/schemas/TypeTwo' TypeOne: type: object required: - type_id - one_data properties: type_id: type: integer const: 1 one_data: type: string TypeTwo: type: object required: - type_id - two_data properties: type_id: type: integer const: 2 two_data: type: string # --- Number (float) discriminator (oneOf) --- NumberOneOf: oneOf: - $ref: '#/components/schemas/VersionAlpha' - $ref: '#/components/schemas/VersionBeta' discriminator: propertyName: version mapping: '1.0': '#/components/schemas/VersionAlpha' '2.5': '#/components/schemas/VersionBeta' VersionAlpha: type: object required: - version - alpha_field properties: version: type: number const: 1.0 alpha_field: type: string VersionBeta: type: object required: - version - beta_field properties: version: type: number const: 2.5 beta_field: type: string # --- Integer discriminator (allOf) --- IntegerAllOfBase: type: object required: - kind properties: kind: type: integer discriminator: propertyName: kind mapping: '1': '#/components/schemas/IntegerAllOfChildA' '2': '#/components/schemas/IntegerAllOfChildB' IntegerAllOfChildA: allOf: - $ref: '#/components/schemas/IntegerAllOfBase' - type: object required: - child_a_field properties: child_a_field: type: string IntegerAllOfChildB: allOf: - $ref: '#/components/schemas/IntegerAllOfBase' - type: object required: - child_b_field properties: child_b_field: type: string ================================================ FILE: specs/3.0.x/discriminator-object-self-mapped.json ================================================ { "openapi": "3.0.3", "info": { "title": "Discriminator object schema with self mapping", "version": "1.0.0", "description": "Ensures a concrete schema with a discriminator mapping to itself gets a literal discriminator value instead of falling back to string." }, "paths": { "/blog-posts": { "get": { "summary": "Get blog posts", "responses": { "200": { "description": "List of blog posts", "content": { "application/json": { "schema": { "type": "array", "items": { "oneOf": [ { "$ref": "#/components/schemas/BlogPostDto" }, { "$ref": "#/components/schemas/BlogPostWithImageDto" } ] } } } } } } } } }, "components": { "schemas": { "BlogPostDto": { "type": "object", "required": ["$type", "id", "title"], "properties": { "$type": { "type": "string" }, "id": { "type": "integer" }, "title": { "type": "string" } }, "discriminator": { "propertyName": "$type", "mapping": { "BlogPost": "#/components/schemas/BlogPostDto", "BlogPostWithImage": "#/components/schemas/BlogPostWithImageDto" } } }, "BlogPostWithImageDto": { "allOf": [ { "$ref": "#/components/schemas/BlogPostDto" }, { "type": "object", "required": ["imageUrl"], "properties": { "imageUrl": { "type": "string" } } } ] } } } } ================================================ FILE: specs/3.0.x/discriminator-one-of.yaml ================================================ openapi: 3.0.3 info: title: OpenAPI 3.0.3 discriminator one of example version: 1 components: schemas: Foo: oneOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' discriminator: propertyName: type Baz: allOf: - $ref: '#/components/schemas/Qux' Bar: allOf: - $ref: '#/components/schemas/Qux' Spæcial: allOf: - $ref: '#/components/schemas/Qux' Qux: type: object properties: id: type: string type: $ref: '#/components/schemas/Quux' required: - id - type Quux: enum: - Bar - Baz type: string Quuz: oneOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/Spæcial' discriminator: propertyName: type mapping: bar: '#/components/schemas/Bar' baz: '#/components/schemas/Baz' 'non-ascii': '#/components/schemas/Spæcial' ================================================ FILE: specs/3.0.x/dutchie.json ================================================ { "openapi": "3.0.4", "info": { "title": "Dutchie Point of Sale API", "description": "\r\n**Comprehensive REST API for Dutchie Point of Sale Platform Integration**\r\n\r\nThe Dutchie Point of Sale API provides complete access to your cannabis retail operations, enabling seamless integration with third-party systems, custom applications, and business intelligence tools.\r\n\r\n**Core Capabilities:**\r\n• **Product Management** - Create, update, and sync product catalogs with real-time inventory\r\n• **Customer Operations** - Manage customer profiles, loyalty programs, and purchase history \r\n• **Inventory Control** - Track stock levels, receive shipments, and monitor product movement\r\n• **Reporting & Analytics** - Access comprehensive sales, inventory, and customer data\r\n• **Compliance Integration** - Maintain regulatory compliance with automated state reporting\r\n\r\n**Base URL:** `https://api.pos.dutchie.com`\r\n\r\n**Authentication:** All requests require a valid API key provided via HTTP Basic Authentication (username: your API key, password: leave empty).\r\n\r\n**Rate Limiting:** Requests are limited to ensure optimal performance for all users. See individual endpoints for specific limits.\r\n", "version": "v1.0.0" }, "servers": [ { "url": "/", "description": "Current Host" }, { "url": "https://api.pos.dutchie.com", "description": "Production API Server" } ], "paths": { "/batch/lab-results": { "post": { "tags": ["Batch"], "summary": "Create or Update Batch Lab Results", "description": "**Purpose:** Create or update comprehensive laboratory testing results for a specific batch to ensure compliance with cannabis regulations and provide quality assurance data.\n\n**Request Requirements:**\n- \"PackageWrite\" role authorization required for lab data operations\n- `UpdateBatchLabResultsRequest` object in request body with lab result data\n- Content-Type: application/json\n- BatchName must exist and be accessible to your location\n\n**Response Data:**\n- Returns success confirmation (HTTP 200) upon successful creation or update\n- No response body content (void return)\n- Lab results are validated and stored for compliance and quality tracking\n- Updates are reflected immediately in batch data and inventory systems\n\n**Create vs Update Behavior:**\n- **CREATE**: When no lab results exist for the batch, new lab results will be created\n- **UPDATE**: When lab results already exist for the batch, existing results will be updated\n- **Validation**: Lab result data must pass validation requirements for regulatory compliance\n- **Batch Sharing**: All packages within the same batch share identical lab results\n\n**Request Body Fields:**\n- BatchName: Name of the batch to update lab results for (required)\n- SampleWeight: Weight of the sample tested (optional, defaults to -1)\n- LabResults: Array of lab result objects with test data (required)\n\n**Sparse Update Behavior:**\n- **Provided lab results**: Will overwrite existing test data with new values\n- **Omitted lab results**: Existing test data for those analytes will be preserved\n- **Special handling**: If multiple packages exist in the same batch, all will share the updated results\n- **Validation**: All provided lab data must meet regulatory testing standards\n\n**Lab Result Data Types:**\n- **Cannabinoid Testing**: THC, THCA, CBD, CBDA, CBN, CBG concentrations\n- **Safety Testing**: Pesticides, heavy metals, microbials, mycotoxins results\n- **Quality Testing**: Moisture content, foreign matter, residual solvents\n- **Potency Testing**: Total THC/CBD calculations and verification\n- **Terpene Testing**: Terpene profiles and concentration data\n\n**Common Use Cases:**\n- Submit initial lab results from testing laboratory for compliance reporting\n- Update lab results when retesting or additional testing is performed\n- Correct lab result data when errors are discovered\n- Add supplementary testing results (terpenes, additional cannabinoids)\n- Maintain accurate Certificate of Analysis (COA) data for regulatory compliance\n\n**Performance & Limits:**\n- Single batch operation for targeted lab result updates\n- Immediate validation and compliance checking\n- Changes propagate to all packages within the batch immediately\n- Optimized for laboratory workflow integration\n\n**Related Endpoints:**\n- `POST /package/lab-results` - Update lab results by package ID instead of batch name\n- `GET /inventory/labresults` - Retrieve lab results for display and verification\n- `GET /reference/lab-result-units` - Get valid units for lab result data\n- `GET /reference/lab-results-names` - Get valid analyte names for testing\n\n**Important Notes:**\n- **Batch Sharing**: All packages in the same batch will share these lab results\n- **Compliance Critical**: Lab results are required for legal cannabis sales and regulatory reporting\n- **Data Integrity**: Validation ensures lab results meet regulatory standards\n- **Certificate Updates**: Changes update Certificate of Analysis (COA) documentation\n- **Alternative Access**: Use POST /package/lab-results if you prefer to work with package IDs", "operationId": "BatchLab-resultsPost", "requestBody": { "description": "Batch lab results update request with batch name and lab data - UpdateBatchLabResultsRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdateBatchLabResultsRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdateBatchLabResultsRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdateBatchLabResultsRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdateBatchLabResultsRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Lab results successfully created or updated" }, "400": { "description": "Bad Request - String error message (parse response body as plain text) OR `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "404": { "description": "Not Found - Batch with specified name does not exist", "content": { "application/json": { "schema": { "type": "string" } } } }, "500": { "description": "Something went wrong." } } } }, "/brand": { "get": { "tags": ["Brand"], "summary": "Get All Brands", "description": "**Purpose:** Retrieve comprehensive list of all active product brands available for the authenticated location.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of brand objects: `[{ Brand }, ...]`\n- Array typically contains 10-100 brands per location\n- Returns empty array `[]` if no brands configured for location\n- Brand ID, name, and optional external catalog identifiers\n- Only active, non-deleted brands are included in results\n- Results automatically filtered to authenticated location\n\n**Common Use Cases:**\n- Populate brand dropdown lists in product creation and editing forms\n- Show available brands for product categorization and filtering on e-commerce sites\n- Group products by brand for inventory management and organization\n- Generate brand-specific reports for regulatory compliance requirements\n- Organize dispensary menus by brand for customer browsing\n- Synchronize brand data with external POS and e-commerce systems\n\n**Performance & Limits:**\n- Lightweight data that is typically small and fast to retrieve\n- This endpoint is commonly called for form population and product management\n- No pagination needed due to typically small brand datasets\n\n**Related Endpoints:**\n- `GET /products` - Get products which include brand information in response\n- `POST /brand` - Create or update brand information\n\n**Important Notes:**\n- Despite the singular endpoint name `/brand`, this method returns multiple brands (an array)\n- Brands are automatically scoped to the authenticated dispensary location\n- Only active brands are returned; deleted brands are excluded\n- Brands returned here can be used when creating or updating products", "operationId": "BrandGet", "responses": { "200": { "description": "Success - Returns array of brand objects: `[{ Brand }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Brand" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for brand access" }, "500": { "description": "Internal Server Error - Server error occurred" } } }, "post": { "tags": ["Brand"], "summary": "Create or Update Brand", "description": "**Purpose:** Creates a new brand or updates an existing brand with the provided brand information.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- `BrandEditRequest` object in request body with brand details\n- Content-Type: application/json\n\n**Response Data:**\n- Returns brand object: `{ Brand }`\n- Includes assigned or updated brand ID and all brand properties\n\n**Create vs Update Behavior:**\n- **CREATE**: When `BrandId` is null or omitted, a new brand will be created\n- **UPDATE**: When `BrandId` is provided with a valid brand ID, the existing brand will be updated\n- **Validation**: Brand name is required for both operations and must be unique within the location\n\n**Sparse Update Behavior:**\n- **Provided fields**: Will overwrite existing brand values with provided data\n- **Omitted fields**: Will preserve existing brand values (no data loss)\n- **Required validation**: BrandName must be provided even for updates\n\n**Common Use Cases:**\n- Add new product brands to the system for product categorization\n- Update existing brand information when details change\n- Maintain brand consistency across products and inventory\n- Synchronize brand data from external systems\n\n**Performance & Limits:**\n- Single brand operation for targeted updates\n- Immediate validation and response\n- Changes are reflected immediately in brand listings\n\n**Related Endpoints:**\n- `GET /brand` - Retrieve all brands to see current brand list\n- `GET /products` - View products that use specific brands\n\n**Important Notes:**\n- Brand name must be unique within the authenticated location\n- All validation errors will be returned in a structured error response\n- This endpoint handles a single brand per request\n- Successful operations return the complete brand object", "operationId": "BrandPost", "requestBody": { "description": "Brand information to create or update - BrandEditRequest object with brand details", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/BrandEditRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/BrandEditRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/BrandEditRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/BrandEditRequest" } } }, "x-bodyName": "brand" }, "responses": { "200": { "description": "Success - Returns brand object: `{ Brand }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Brand" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Internal server error" } } } }, "/customer/customers": { "get": { "tags": ["Customer"], "summary": "Get Customers", "description": "**Purpose:** Retrieves a list of customers with optional filtering by modification date, customer ID, or unique ID for customer management and data synchronization.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- Optional query parameters for filtering results\n- No request body needed\n\n**Response Data:**\n- Returns array of customer objects: `[{ Customer }, ...]`\n- Array may contain 0 to 10,000+ customers depending on location and filtering\n- Returns empty array `[]` if no customers match criteria (not null)\n- Includes loyalty status and qualifying conditions when available\n- Results automatically filtered by the authenticated user's location\n- Customer profiles with contact information and preferences\n\n**Filtering Options:**\n- No parameters: Returns all customers for the location\n- fromLastModifiedDateUTC: Returns customers modified after this date for incremental sync\n- toLastModifiedDateUTC: Returns customers modified before this date for date range filtering\n- customerID: Returns a specific customer by internal ID\n- uniqueId: Returns a specific customer by unique identifier\n- includeAnonymous: Include/exclude anonymous customers (default: true)\n\n**Common Use Cases:**\n- Call without parameters for initial sync to get all customers\n- Use fromLastModifiedDateUTC for incremental sync to get only recent changes\n- Use customerID or uniqueId for specific customer retrieval\n- Sync customer data for point-of-sale systems integration\n- Export customer data for external CRM or marketing systems\n\n**Performance & Limits:**\n- Maximum date range is configurable per location (default: 90 days)\n- Use incremental sync for large datasets to avoid timeouts\n- Optimized for high-volume data synchronization\n- Consider using paginated endpoint for very large customer bases\n\n**Related Endpoints:**\n- `GET /customer/customers-paginated` - Paginated version for large datasets\n- `POST /customer` - Create or update customer information\n- `POST /customerLookup` - Find existing customers by various search criteria\n\n**Important Notes:**\n- Results filtered to authenticated user's location for data security\n- Date range limits help prevent timeouts with large customer databases\n- Anonymous customers can be included or excluded based on business needs\n- Loyalty status information included when available for customer insights", "operationId": "CustomerCustomersGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Optional date filter to return customers modified after this timestamp - Used for incremental sync", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Optional date filter to return customers modified before this timestamp - Used for date range filtering", "schema": { "type": "string", "format": "date-time" } }, { "name": "customerID", "in": "query", "description": "Optional customer ID to return a specific customer by internal ID", "schema": { "type": "integer", "format": "int32" } }, { "name": "includeAnonymous", "in": "query", "description": "Include/exclude anonymous customers in results - Default: true", "schema": { "type": "boolean", "default": true } }, { "name": "uniqueId", "in": "query", "description": "Optional unique ID to return a specific customer by unique identifier - Must be valid long integer when provided", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Success - Returns array of customer objects: `[{ Customer }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Customer" } } } } }, "400": { "description": "Bad Request - Invalid date range or uniqueId format", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for customer data operations" }, "404": { "description": "Not Found - Customer not found when searching by customerID or uniqueId" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/customer/customers-paginated": { "get": { "tags": ["Customer"], "summary": "Get Customers (Paginated)", "description": "**Purpose:** Retrieves customers in paginated chunks for better performance with large customer datasets and efficient memory management.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- Optional query parameters for pagination and filtering\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ Customer }, { Customer }, ...]`\n- **No pagination metadata**: Response contains only data array without total counts or page information\n- Array contains up to PageSize customers (default 1000, max 10000)\n- Returns empty array `[]` if no customers found for page (not null)\n- Includes loyalty status and qualifying conditions when available\n- Results automatically filtered by the authenticated user's location\n\n**Pagination Usage:**\n- **First Request**: Call with PageNumber=0 to get first page\n- **Subsequent Requests**: Increment PageNumber for each additional page\n- **End Detection**: Continue requesting pages until you receive an empty array `[]`\n- **Page Size Control**: Use PageSize parameter to control items per page (max 10,000)\n- **Example Flow**: Request PageNumber=0 → Process results → Increment PageNumber → Repeat until empty `[]` response\n\n**Pagination Detection:**\n- **End of data detection**: Continue requesting pages until you receive an empty array `[]`\n- **No metadata provided**: Response does not include total counts, page counts, or hasNextPage indicators\n- **Sequential access**: Increment PageNumber from 0 until empty response indicates no more data\n\n**Filtering Options:**\n- fromLastModifiedDateUTC: Returns customers modified after this date\n- toLastModifiedDateUTC: Returns customers modified before this date\n- includeAnonymous: Include/exclude anonymous customers (default: true)\n\n**Common Use Cases:**\n- Process large customer databases efficiently for data export\n- Batch processing customers to avoid memory issues in applications\n- Large-scale customer data synchronization with external systems\n- Generate customer reports without overwhelming system resources\n- Support high-volume customer data operations with controlled memory usage\n\n**Performance & Limits:**\n- Maximum 10,000 customers per page for optimal performance\n- Use consistent page size throughout pagination sequence for efficiency\n- Monitor response times and adjust page size for optimal performance\n- Cache results locally to minimize API calls and improve responsiveness\n- Recommended over non-paginated endpoint for datasets over 1000 customers\n\n**Related Endpoints:**\n- `GET /customer/customers` - Non-paginated version for smaller datasets\n- `POST /customer` - Create or update customer information\n- `POST /customerLookup` - Find specific customers by search criteria\n\n**Important Notes:**\n- Use this endpoint instead of /customers for better performance with large datasets\n- Results filtered to authenticated user's location for data security\n- Pagination state management required in client applications\n- Suitable for batch processing and large-scale data operations", "operationId": "CustomerCustomers-paginatedGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Optional date filter to return customers modified after this timestamp", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Optional date filter to return customers modified before this timestamp", "schema": { "type": "string", "format": "date-time" } }, { "name": "PageNumber", "in": "query", "description": "Page number for sequential pagination (integer, starts at 0) - Default: 0", "schema": { "type": "integer", "format": "int32", "default": 0 } }, { "name": "PageSize", "in": "query", "description": "Number of items per page (integer) - Default: 1000, Maximum: 10000", "schema": { "type": "integer", "format": "int32", "default": 1000 } }, { "name": "includeAnonymous", "in": "query", "description": "Include/exclude anonymous customers in results - Default: true", "schema": { "type": "boolean", "default": true } } ], "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Customer" } } } } }, "400": { "description": "Bad Request - PageSize exceeds maximum limit of 10,000", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/customer/customer-types": { "get": { "tags": ["Customer"], "summary": "Get Customer Types", "description": "**Purpose:** Retrieve the complete list of customer types available for the authenticated location, used for customer categorization and compliance.\n\n**Request Requirements:**\n- Valid API key authentication required (no specific role restrictions)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of `CustomerType` objects with customer type information\n- Response format: `[{ CustomerType }, ...]`\n- Array typically contains 2-10 customer types per location\n- Returns empty array `[]` if no customer types enabled for location (rare)\n- Each customer type includes: Id, Name, IsRetail, IsMedical flags\n- Display names include \"Adult Use\", \"Medical\", \"Wholesale\", etc.\n- Results automatically filtered to authenticated location's enabled types\n\n**Customer Type Fields:**\n- Id: Unique identifier for the customer type\n- Name: Display name of the customer type\n- IsRetail: Boolean indicating if this type is for retail customers\n- IsMedical: Boolean indicating if this type is for medical patients\n\n**Common Use Cases:**\n- Populate dropdown/selection lists for customer type in registration forms\n- Ensure customers are assigned to valid, location-specific types for compliance validation\n- Configure point-of-sale systems with available customer categories\n- Configure online ordering systems with proper customer types for e-commerce setup\n- Understand customer type structure for reporting classification and analytics\n- Validate customer type IDs before creating/updating customers\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Customer types rarely change; safe to cache for several hours\n- Small dataset suitable for client-side caching\n- Location-specific results based on API key access\n\n**Integration Workflow:**\n1. Call this endpoint to get available customer types for your location\n2. Present options to users in registration/update forms\n3. Use selected Id in POST /customer requests as CustomerTypeId\n4. Implement validation to ensure selected type is valid for your location\n\n**Related Endpoints:**\n- `POST /customer` - Create customers using these customer type IDs\n- `GET /customer/customers` - Get customers with their assigned types\n- `GET /customer/referral-sources` - Get referral source reference data\n\n**Important Notes:**\n- Customer types are location-specific and may vary between dispensary locations\n- Only returns customer types enabled for your specific location\n- Results automatically filtered based on your API key's location access\n- Use Name field for user-facing displays, Id for API calls\n- Use IsRetail/IsMedical flags for business rule implementation and compliance logic", "operationId": "CustomerCustomer-typesGet", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/CustomerType" } } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/customer/referral-sources": { "get": { "tags": ["Customer"], "summary": "Get Referral Sources", "description": "**Purpose:** Retrieve the complete list of referral sources available system-wide, used for tracking customer acquisition and marketing campaign effectiveness.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of string values representing available referral source options\n- Response format: `[\"string\", \"string\", ...]`\n- Array typically contains 10-20 predefined referral sources\n- Returns empty array `[]` if no referral sources configured (rare)\n- Examples include: \"Google\", \"Facebook\", \"Word of Mouth\", \"Print Ad\", \"Radio\", \"TV\", \"Yelp\", \"Instagram\"\n- Standardized list ensures consistent marketing attribution across all locations\n- System-wide reference data for marketing tracking\n\n**Common Use Cases:**\n- Populate \"How did you hear about us?\" dropdown fields in customer registration\n- Track which channels are driving customer acquisition for marketing attribution\n- Measure effectiveness of different marketing strategies for campaign analysis\n- Ensure valid referral source selection in customer profiles for form validation\n- Feed data into marketing analytics and reporting systems for analytics integration\n- Connect customer acquisition costs to specific marketing channels for ROI tracking\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Referral sources change infrequently; safe to cache for extended periods\n- Small static dataset suitable for client-side caching\n- Consistent across all organizations and locations\n\n**Integration Workflow:**\n1. Call this endpoint to get available referral source options\n2. Present options in customer registration or profile update forms\n3. Include selected value when creating/updating customers (if supported)\n4. Use for reporting to analyze customer acquisition patterns\n\n**Marketing Benefits:**\n- Attribution tracking to understand which marketing channels are most effective\n- Budget allocation optimization based on referral source performance\n- Campaign ROI measurement for different marketing campaigns\n- Customer insights to learn how customers discover your dispensary\n\n**Related Endpoints:**\n- `POST /customer` - Create customers with referral source information\n- `GET /customer/customer-types` - Get customer type reference data\n- `GET /customer/customers` - Get customers with their referral source data\n\n**Important Notes:**\n- Returns system-wide referral sources for consistent reporting across all locations\n- Consider adding \"Other\" or \"Prefer not to say\" options in your UI implementation\n- Use these values to populate selection lists in customer forms\n- Validate referral source values against this list before submitting customer data\n- Essential for marketing analytics and customer acquisition tracking", "operationId": "CustomerReferral-sourcesGet", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/customer/customer": { "post": { "tags": ["Customer"], "summary": "Create or Update Customer", "description": "**Purpose:** Create new customer profiles or update existing customer information for dispensary operations and e-commerce integration.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- `EcomCustomerEdit` object in request body with customer details\n- Content-Type: application/json\n- Optional query parameter to bypass deduplication\n- **Idempotency Support**: Requires `ConsumerKey` header and `IdempotencyKey` field for duplicate prevention (see [Idempotency Documentation](/pages/idempotency.html))\n\n**Response Data:**\n- Returns single `Customer` object (not array) with assigned system ID\n- Response format: `{ Customer }`\n- Includes loyalty program enrollment and qualification status\n- Provides both internal and external system identifiers\n- Contains full customer profile with contact and address information\n\n**Create vs Update Behavior:**\n- **CREATE**: When `CustomerId` is null, 0, or omitted, a new customer record will be created\n- **UPDATE**: When `CustomerId` is provided with a valid customer ID, the existing customer will be updated\n- **Validation**: FirstName, Address1, City, State, PostalCode, Status, and CustomerType are required\n- **Deduplication**: Create operations include smart duplicate detection unless bypassed with query parameter\n\n**Request Body Format:**\n- For new customers: Leave `CustomerId` null or 0 (will be auto-generated)\n- For updates: Include the `CustomerId` in the request\n- FirstName is required (Name will be used as FirstName if FirstName is empty)\n- Address1, City, State, PostalCode are required for address information\n- Status and CustomerType are required for customer classification\n\n**Optional Fields:**\n- DateOfBirth (must be between 1800-01-01 and current date)\n- LastName, MiddleName, NameSuffix, NamePrefix for name information\n- Address2 for additional address details\n- Phone, EmailAddress for contact information\n- EcomUserId for external e-commerce system identifier\n- UniqueId for external system integration\n\n**Sparse Update Behavior:**\n- **Provided fields**: Will overwrite existing values with provided data\n- **Omitted fields**: Will preserve existing values (no data loss for updates)\n- **Special handling**: Name field will be used as FirstName if FirstName is omitted during updates\n- **Validation**: Required fields for updates are more relaxed than for new customer creation\n\n**Smart Deduplication System:**\n- Default behavior automatically searches for existing customers with matching details\n- Helps prevent creating multiple records for the same person\n- Use `bypassDeduplication=true` to force creation of new customer record\n\n**Common Use Cases:**\n- Sync customer profiles from online ordering platforms for e-commerce integration\n- Create new customer accounts during in-store visits and walk-in registration\n- Update existing customer contact and address information\n- Add customers to dispensary loyalty and rewards programs\n- Maintain customer records for regulatory compliance requirements\n- Synchronize customer data with external customer relationship management systems\n\n**Performance & Limits:**\n- Rate limited to 1500 requests per minute (higher limit for high-volume customer operations)\n- Single customer operation for targeted updates\n- Immediate validation and duplicate detection\n- Changes are reflected immediately in customer listings\n- Smart matching algorithms optimize deduplication performance\n\n**Related Endpoints:**\n- `POST /customerLookup` - Find existing customers by various search criteria\n- `POST /search` - Search customers by name, phone, or email for quick lookup\n- `GET /by-external-id` - Retrieve customers using external system identifiers\n- `GET /customers` - List all customers with optional filtering\n\n**Important Notes:**\n- Date of birth must be realistic (between 1800 and current date) for age verification\n- Smart matching helps prevent multiple records for the same person\n- Some fields may be required based on location-specific compliance regulations\n- System validates contact information format and completeness for data quality", "operationId": "CustomerCustomerPost", "parameters": [ { "name": "bypassDeduplication", "in": "query", "description": "Skip duplicate detection and force creation of new customer record - Default: false", "schema": { "type": "boolean", "default": false } }, { "name": "ConsumerKey", "in": "header", "description": "Optional GUID for idempotency checks. When provided with IdempotencyKey in request body, prevents duplicate customer creation", "schema": { "type": "string" } } ], "requestBody": { "description": "Customer information to create or update - EcomCustomerEdit object with customer details", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } }, "application/json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } }, "text/json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } } }, "x-bodyName": "customer" }, "responses": { "200": { "description": "Success - Returns complete Customer object with assigned ID and loyalty status", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Customer" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for customer management" }, "404": { "description": "Not Found - Customer ID provided for update but customer does not exist", "content": { "application/json": { "schema": { "type": "string" } } } }, "500": { "description": "Internal Server Error - Server error occurred during customer processing" } } } }, "/customer/customerLookup": { "post": { "tags": ["Customer"], "operationId": "CustomerCustomerLookupPost", "requestBody": { "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } }, "application/json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } }, "text/json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/EcomCustomerEdit" } } }, "x-bodyName": "customer" }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Customer" } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "type": "string" } } } }, "500": { "description": "Internal Server Error" } } } }, "/customer/search": { "post": { "tags": ["Customer"], "summary": "Customer Search (PREVIEW)", "description": "**NOTE - THIS ENDPOINT IS CURRENTLY IN PREVIEW - IT MAY UNDERGO BREAKING CHANGES IN UPCOMING RELEASES**\n\n\n**Purpose:** Search for customers using multiple criteria with flexible matching to support customer identification and lookup workflows.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- `CustomerSearchRequest` object in request body with search criteria\n- Content-Type: application/json\n- At least one search criterion must be provided\n- Rate limited to 360 requests per minute\n\n**Response Data:**\n- Returns array of `CustomerSearchResult` objects with matching customer information\n- Response format: `[{ CustomerSearchResult }, ...]`\n- Array may contain 0 to 100+ customers depending on search criteria specificity\n- Returns empty array `[]` if no customers match search criteria (not null)\n- Same customer may appear multiple times with different match types\n- Includes match type information to identify which criteria matched\n- Results automatically filtered to authenticated location\n\n**Search Criteria (Independent Matching):**\n- **MMJ ID**: Medical marijuana patient identification number\n- **Drivers License ID**: State-issued driver's license number\n- **Email Address**: Customer's email address (exact match)\n- **Phone Number**: Customer's phone number (normalized matching)\n- **LastName + DateOfBirth**: Combined name and birth date search (both required together)\n\n**Search Behavior:**\n- **Independent Fields**: Most fields are searched independently\n- **Combined Fields**: LastName and DateOfBirth must be used together\n- **Multiple Matches**: Same customer may appear with different match types\n- **Location Scoped**: Results filtered to authenticated location only\n- **Case Sensitivity**: Email and name searches are case-insensitive\n\n**Common Use Cases:**\n- Find customers during check-in process for identification verification\n- Locate existing customer records before creating new accounts\n- Search for customers using partial or alternative identification methods\n- Verify customer identity using multiple data points\n- Support customer service lookup workflows\n\n**Performance & Limits:**\n- Rate limited to 360 requests per minute for system protection\n- Optimized for common customer lookup patterns\n- Results limited to reasonable set size for performance\n- Indexed searches for fast response times\n\n**Related Endpoints:**\n- `POST /customer/customerLookup` - Single customer lookup with hierarchy\n- `GET /customer/customers` - List all customers with filtering\n- `POST /customer/customer` - Create or update customer records\n\n**Important Notes:**\n- **PREVIEW STATUS**: This endpoint may undergo breaking changes in future releases\n- **Multiple Results**: Same customer can appear multiple times with different match types\n- **Location Filtering**: Results are automatically scoped to your authenticated location\n- **Rate Limiting**: 360 requests per minute limit applies for system stability\n- **Validation**: At least one search criterion must be provided in the request", "operationId": "CustomerSearchPost", "requestBody": { "description": "Customer search request with search criteria - CustomerSearchRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CustomerSearchRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CustomerSearchRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CustomerSearchRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CustomerSearchRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/CustomerSearchResult" } } } } }, "400": { "description": "Bad Request - Validation errors or no search criteria provided", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/customer/by-external-id": { "get": { "tags": ["Customer"], "operationId": "CustomerBy-external-idGet", "parameters": [ { "name": "externalId", "in": "query", "schema": { "type": "string" } } ], "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/CustomerSearchResult" } } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "404": { "description": "Not Found" }, "500": { "description": "Internal Server Error" } } } }, "/customer-journal": { "get": { "tags": ["CustomerJournal"], "summary": "Get Customer Journal Entries", "description": "**Purpose:** Retrieves all journal entries (notes/comments) associated with a specific customer for customer service and account management.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- Customer ID query parameter required\n- No request body needed\n\n**Response Data:**\n- Returns array of journal entry objects: `[{ JournalEntry }, ...]`\n- Array may contain 0 to 100+ entries depending on customer interaction history\n- Returns empty array `[]` if no journal entries exist for customer (not null)\n- Includes entry ID, subject, body, and date\n- Results filtered by customer accessibility to authenticated location\n\n**Common Use Cases:**\n- View interaction history and notes about a customer for customer service\n- Review previous communications and issues for account management\n- Maintain audit trail of customer interactions for compliance\n- Track resolution history and follow-ups for support tickets\n\n**Performance & Limits:**\n- Efficient retrieval for individual customer journal histories\n- Results scoped to specific customer and location\n- No pagination needed for typical journal entry volumes\n\n**Related Endpoints:**\n- `POST /customer-journal/create` - Create new journal entries\n- `POST /customer-journal/update` - Update existing journal entries\n\n**Important Notes:**\n- Customer ID must exist and be accessible to your location\n- Requires customer validation before retrieving entries\n- Entries are returned in database order (not explicitly sorted)", "operationId": "Customer-journalGet", "parameters": [ { "name": "customerId", "in": "query", "description": "Internal customer ID to retrieve journal entries for - Must exist and be accessible to your location", "schema": { "type": "integer", "format": "int32" } } ], "responses": { "200": { "description": "Success - Returns array of journal entry objects: `[{ JournalEntry }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/JournalEntry" } } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for customer access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/customer-journal/update": { "post": { "tags": ["CustomerJournal"], "summary": "Update Customer Journal Entry", "description": "**Purpose:** Updates an existing journal entry's date, subject, and/or body content for customer service record management.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- `UpdateJournalEntryRequest` object in request body\n- Content-Type: application/json\n- Journal entry must exist and be accessible to your location\n\n**Response Data:**\n- Returns journal entry object: `{ JournalEntry }`\n- Includes entry ID, updated subject, body, and date\n- Confirms successful update with complete entry details\n\n**Request Body Fields:**\n- JournalEntryId: The ID of the journal entry to update (required)\n- Subject: New title or summary for the entry (required)\n- Body: New detailed content for the entry (required)\n- Date: New date for the entry (required)\n\n**Update Behavior:**\n- **All fields required**: JournalEntryId, Subject, Body, and Date must all be provided\n- **Complete replacement**: All entry fields will be updated with provided values\n- **Validation**: Entry must exist and be accessible to your location\n\n**Common Use Cases:**\n- Fix typos or errors in previously created entries for correction\n- Add more details to existing notes for additional information\n- Update resolution status or follow-up information for status updates\n- Modify entries to meet regulatory requirements for compliance updates\n\n**Performance & Limits:**\n- Single entry update operation for targeted modifications\n- Immediate validation and response\n- Changes reflected immediately in journal entry lists\n\n**Related Endpoints:**\n- `GET /customer-journal` - Retrieve journal entries for a customer\n- `POST /customer-journal/create` - Create new journal entries\n\n**Important Notes:**\n- Journal entry must exist and be accessible to your location\n- Validation performed before update to ensure data integrity\n- All request fields are required for successful update", "operationId": "Customer-journalUpdatePost", "requestBody": { "description": "Journal entry update request with required fields to update - UpdateJournalEntryRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdateJournalEntryRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdateJournalEntryRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdateJournalEntryRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdateJournalEntryRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Returns journal entry object: `{ JournalEntry }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/JournalEntry" } } } }, "400": { "description": "Bad Request - Validation errors or invalid journal entry ID", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for customer access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/customer-journal/create": { "post": { "tags": ["CustomerJournal"], "summary": "Create Customer Journal Entry", "description": "**Purpose:** Creates a new journal entry (note/comment) for a specific customer to maintain interaction records and customer service history.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for customer data operations\n- `CreateJournalEntryRequest` object in request body\n- Content-Type: application/json\n- Customer must exist and be accessible to your location\n\n**Response Data:**\n- Returns journal entry object: `{ JournalEntry }`\n- Includes assigned entry ID, subject, body, and date\n- Confirms successful creation with complete entry details\n\n**Request Body Fields:**\n- CustomerId: The customer to create the journal entry for (required)\n- Subject: Brief title or summary of the entry (required)\n- Body: Detailed content of the journal entry (required)\n- Date: When this entry should be dated (required)\n\n**Common Use Cases:**\n- Record interaction details and resolutions for customer service notes\n- Document changes to customer information for account updates\n- Log problems and their resolution status for issue tracking\n- Maintain required interaction records for compliance documentation\n- Schedule future contact or actions for follow-up reminders\n\n**Performance & Limits:**\n- Single entry creation operation for immediate record keeping\n- Immediate validation and creation\n- New entries appear immediately in journal entry lists\n\n**Related Endpoints:**\n- `GET /customer-journal` - Retrieve journal entries for a customer\n- `POST /customer-journal/update` - Update existing journal entries\n\n**Important Notes:**\n- Customer must exist and be accessible to your location\n- Validation performed before creation to ensure data integrity\n- All request fields are required for successful creation", "operationId": "Customer-journalCreatePost", "requestBody": { "description": "Journal entry creation request with customer ID and entry details - CreateJournalEntryRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CreateJournalEntryRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CreateJournalEntryRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CreateJournalEntryRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CreateJournalEntryRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Returns journal entry object: `{ JournalEntry }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/JournalEntry" } } } }, "400": { "description": "Bad Request - Validation errors or invalid customer ID", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for customer access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/Deliveries": { "get": { "tags": ["Deliveries"], "summary": "Get Deliveries", "description": "**Purpose:** Retrieve delivery status information and order details for cannabis delivery operations and tracking.\n\n**Request Requirements:**\n- \"Deliveries\" role authorization required for delivery data access\n- Optional query parameters for filtering and data inclusion\n- Rate limited to 100 requests per minute\n- No request body needed\n\n**Response Data:**\n- Returns array of delivery objects: `[{ DeliveryOrderStatus }, ...]`\n- Array may contain 0 to 100+ deliveries depending on filtering criteria\n- Returns empty array `[]` if no deliveries match criteria (not null)\n- Delivery status, timing, and location information included\n- Optional line item details when includeLineItems=true\n- Results automatically filtered to authenticated location\n\n**Query Parameters:**\n- PreOrderId: Get delivery status for a specific pre-order (optional)\n- TransactionId: Get delivery status for a specific transaction (optional)\n- transactionIds: Get delivery status for multiple transactions (optional array)\n- deliveryStatus: Filter by delivery status (optional)\n- includeLineItems: Include detailed line item data (default: false)\n\n**Parameter Rules:**\n- **Mutually Exclusive**: Use only ONE of PreOrderId, TransactionId, transactionIds, or deliveryStatus\n- **Default Behavior**: If no parameters provided, returns all open deliveries from last 14 days\n- **Open Definition**: Status of 'filled' or 'received' within the last 14 days\n- **Line Items**: Only available for packages assigned to orders, not unassigned pre-order items\n\n**Delivery Status Values:**\n- **Placed**: Order has been placed but not yet processed\n- **Filled**: Order has been fulfilled and packaged for delivery\n- **Received**: Order has been received by delivery team\n- **In Transit**: Order is currently being delivered\n- **Delivered**: Order has been successfully delivered to customer\n- **Cancelled**: Order has been cancelled\n\n**Common Use Cases:**\n- Monitor delivery status for customer service and tracking\n- Generate delivery reports for operational management\n- Track order fulfillment and delivery performance\n- Provide delivery updates to customers and delivery teams\n- Integrate with third-party delivery tracking systems\n\n**Performance & Limits:**\n- Rate limited to 100 requests per minute for system protection\n- Optimized for delivery tracking and status monitoring\n- Line item data loading is conditional for performance\n- Results filtered to location scope for operational relevance\n\n**Related Endpoints:**\n- `POST /deliveries/set-route-detail` - Update delivery route and driver information\n- `GET /drivers` - Get available drivers for delivery assignments\n- `GET /preorder` - Get pre-order information that may become deliveries\n\n**Important Notes:**\n- **Exclusive Parameters**: Only use one filtering parameter at a time\n- **Line Item Limitation**: Line items only shown for assigned packages, not pre-order items\n- **Time Window**: Default query covers last 14 days of open deliveries\n- **Rate Limiting**: 100 requests per minute limit for delivery tracking operations\n- **Status Tracking**: Provides real-time delivery status for customer and operational visibility", "operationId": "DeliveriesGet", "parameters": [ { "name": "PreOrderId", "in": "query", "description": "Pre-order ID to get delivery status for - Optional, mutually exclusive with other filters", "schema": { "type": "integer", "format": "int32" } }, { "name": "TransactionId", "in": "query", "description": "Transaction ID to get delivery status for - Optional, mutually exclusive with other filters", "schema": { "type": "integer", "format": "int32" } }, { "name": "transactionIds", "in": "query", "description": "Array of transaction IDs to get delivery status for - Optional, mutually exclusive with other filters", "schema": { "type": "array", "items": { "type": "integer", "format": "int32" } } }, { "name": "includeLineItems", "in": "query", "description": "Include detailed line item data in response - Default: false", "schema": { "type": "boolean", "default": false } }, { "name": "deliveryStatus", "in": "query", "description": "Filter deliveries by status - Optional, mutually exclusive with other filters", "schema": { "type": "string", "default": "" } } ], "responses": { "200": { "description": "Success - Returns array of delivery objects: `[{ DeliveryOrderStatus }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/DeliveryOrderStatus" } } } } }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for delivery access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/Deliveries/set-route-detail": { "post": { "tags": ["Deliveries"], "summary": "Set Delivery Route Detail", "description": "**Purpose:** Update delivery route information including vehicle, driver assignments, route details, and delivery status for operational management.\n\n**Request Requirements:**\n- \"Deliveries\" role authorization required for delivery operations\n- `UpdateDeliveryRouteDetailRequest` object in request body with route details\n- Content-Type: application/json\n- Rate limited to 100 requests per minute\n- Valid delivery ID must exist and be accessible to your location\n\n**Response Data:**\n- Returns success confirmation (HTTP 200) upon successful update\n- No response body content (void return)\n- Route details are validated and stored for delivery operations\n\n\n**Request Body Fields:**\n- TransactionId: The delivery transaction to update (required)\n- DriverId: Primary driver assignment for the delivery (optional)\n- DriverId2: Secondary driver assignment for the delivery (optional)\n- VehicleId: Vehicle assigned to the delivery (optional)\n- Route: Route information or notes (optional)\n- Status: Delivery status update (optional)\n\n**Route Detail Updates:**\n- **Vehicle Assignment**: Set vehicle ID for the delivery\n- **Driver Assignment**: Assign primary and optional secondary drivers\n- **Route Information**: Update route notes or details\n- **Status Updates**: Modify delivery status\n\n**Common Use Cases:**\n- Assign delivery vehicles and drivers to pending orders\n- Update delivery routes for optimal efficiency and timing\n- Modify delivery status as orders progress through fulfillment\n- Reassign deliveries to different drivers or vehicles\n- Update delivery information for customer tracking and notifications\n\n**Performance & Limits:**\n- Rate limited to 100 requests per minute for system protection\n- Single delivery operation for targeted route updates\n- Immediate validation and storage of route information\n- Changes propagate to delivery tracking systems immediately\n\n**Related Endpoints:**\n- `GET /deliveries` - Retrieve current delivery status and information\n- `GET /drivers` - Get available drivers for delivery assignments\n- `GET /preorder` - Access pre-order information for delivery preparation\n\n**Important Notes:**\n- **Driver and Vehicle IDs**: Must reference valid drivers and vehicles in the system\n- **Validation**: Request fields are validated before processing updates\n- **Status Tracking**: Updates enable delivery tracking for operations\n- **Rate Limiting**: 100 requests per minute limit for delivery management operations", "operationId": "DeliveriesSet-route-detailPost", "requestBody": { "description": "Delivery route detail update request with transaction ID and delivery information - UpdateDeliveryRouteDetailRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdateDeliveryRouteDetailRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdateDeliveryRouteDetailRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdateDeliveryRouteDetailRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdateDeliveryRouteDetailRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Route details successfully updated" }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for delivery access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/discounts": { "get": { "tags": ["Discounts"], "summary": "Get Discounts (Legacy)", "description": "**Purpose:** Retrieves basic discount information using the legacy data structure with limited configuration details.\n\n**LEGACY WARNING:** This endpoint is deprecated. Migrate to `GET /discounts/v2/list` for complete functionality.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for discount data access\n- Optional query parameters for filtering\n- No request body needed\n\n**Response Data:**\n- Returns array of `PublishedDiscount` objects with basic discount information\n- Array typically contains 5-50 discounts per location depending on active promotions\n- Returns empty array `[]` if no discounts are active or configured\n- Validity dates are converted from Eastern Time to UTC in response\n- Automatically excludes \"Loyalty Multiplier\" discount types\n- Results are filtered by the authenticated location\n\n**Key Limitations vs V2:**\n- Basic response model with limited discount information\n- Missing detailed reward and constraint configuration\n- Does not support advanced discount capabilities\n- Simple inclusion/exclusion data structure only\n\n**Common Use Cases:**\n- Legacy system integrations that cannot be updated immediately\n- Basic discount display when minimal information is sufficient\n- Temporary implementations before V2 migration\n\n**Performance & Limits:**\n- Lightweight response for basic discount listing\n- Filtered results improve response time\n- Consider V2 endpoint for comprehensive discount data\n\n**Related Endpoints:**\n- `GET /discounts/v2/list` - Recommended enhanced endpoint with complete configuration\n\n**Important Notes:**\n- This endpoint is deprecated and may be removed in future versions\n- New integrations should use the V2 endpoint\n- Date conversion assumes Eastern Time input, converts to UTC output", "operationId": "DiscountsGet", "parameters": [ { "name": "includeInactive", "in": "query", "description": "Include deleted or inactive discounts in results - Default: false", "schema": { "type": "boolean", "default": false } }, { "name": "includeInclusionExclusionData", "in": "query", "description": "Include detailed product/category restriction data - Default: false", "schema": { "type": "boolean", "default": false } } ], "responses": { "200": { "description": "Success - Returns array of basic discount information", "content": { "text/plain": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/PublishedDiscount" } } }, "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/PublishedDiscount" } } }, "text/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/PublishedDiscount" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/discounts/v2/list": { "get": { "tags": ["Discounts"], "summary": "Get Discounts V2 (Recommended)", "description": "**Purpose:** Retrieves comprehensive discount information including detailed reward configuration, payment restrictions, and advanced bundling logic.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for discount data access\n- Optional query parameters for enhanced data inclusion\n- No request body needed\n\n**Response Data:**\n- Returns array of `DiscountApiResponse` objects with complete discount configuration\n- Array typically contains 5-50 discounts per location depending on active promotions\n- Returns empty array `[]` if no discounts are active or configured\n- Validity dates are converted from Eastern Time to UTC in response\n- Includes detailed reward structure and constraint details\n- Results are filtered by the authenticated location\n\n**Enhanced Features vs Legacy:**\n- Complete response model with detailed discount configuration\n- Full discount reward structure and constraint details\n- Payment method restrictions (credit card, cash, etc.)\n- Advanced bundle discount logic and stacking configuration\n- E-commerce menu display configuration and ranking\n- Optimized data retrieval and processing\n\n**Common Use Cases:**\n- New discount integrations requiring complete configuration data\n- E-commerce systems needing full discount logic implementation\n- Point-of-sale systems requiring comprehensive discount rules\n- Advanced analytics and discount performance analysis\n- Payment processing systems validating payment method restrictions\n\n**Performance & Limits:**\n- Single request retrieves all discount data efficiently\n- Optimized processing for large discount configurations\n- Consider parameter filtering to reduce response size when needed\n\n**Related Endpoints:**\n- `GET /discounts` - Legacy endpoint with basic discount information (deprecated)\n\n**Important Notes:**\n- This is the recommended endpoint for all new integrations\n- Includes latest discount capabilities and improvements\n- Date conversion assumes Eastern Time input, converts to UTC output", "operationId": "DiscountsV2ListGet", "parameters": [ { "name": "includeInactive", "in": "query", "description": "Include deleted or inactive discounts in results - Default: false", "schema": { "type": "boolean", "default": false } }, { "name": "includeInclusionExclusionData", "in": "query", "description": "Include detailed product/category restriction data - Default: false", "schema": { "type": "boolean", "default": false } }, { "name": "includePaymentRestrictions", "in": "query", "description": "Include credit card and payment method restrictions - Default: false", "schema": { "type": "boolean", "default": false } } ], "responses": { "200": { "description": "Success - Returns array of comprehensive discount configuration objects", "content": { "text/plain": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/DiscountApiResponse" } } }, "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/DiscountApiResponse" } } }, "text/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/DiscountApiResponse" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/drivers": { "get": { "tags": ["Drivers"], "summary": "Get Drivers", "description": "**Purpose:** Retrieves the complete list of drivers for the authenticated location for delivery operations and transportation management.\n\n**Request Requirements:**\n- \"Reporting\" or \"Deliveries\" role authorization required for driver data access\n- No query parameters or request body needed\n\n**Response Data:**\n- Response format: `[{ DriverDetail }, { DriverDetail }, ...]`\n- Array typically contains 2-20 drivers per location\n- Returns empty array `[]` if no drivers configured for location\n- Includes driver ID, name, state ID, and driver's license number\n- Location-specific driver roster for delivery and transportation operations\n\n**Common Use Cases:**\n- Populate driver dropdown lists in delivery assignment systems\n- Support delivery operations and route management workflows\n- Validate driver assignments in delivery and transportation systems\n- Access basic driver information for compliance and operational purposes\n\n**Performance & Limits:**\n- Location-specific driver data filtered to authenticated location\n- No pagination needed for typical location driver counts\n- Optimized for delivery operations and transportation management\n\n**Related Endpoints:**\n- `POST /drivers` - Create or update driver information\n- `GET /deliveries` - Get deliveries that may be assigned to these drivers\n- Delivery and transportation endpoints that utilize driver assignments\n\n**Important Notes:**\n- Drivers are scoped to location level for operational relevance\n- Requires Reporting or Deliveries role for access to driver information\n- Essential for delivery operations and transportation compliance\n- Driver information includes basic licensing information\n- Used for delivery assignment and route management", "operationId": "DriversGet", "responses": { "200": { "description": "Success - Returns array of driver objects: `[{ DriverDetail }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/DriverDetail" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for driver access" }, "500": { "description": "Internal Server Error - Server error occurred" } } }, "post": { "tags": ["Drivers"], "summary": "Create or Update Driver", "description": "**Purpose:** Creates a new driver or updates existing driver information for delivery operations and transportation management.\n\n**Request Requirements:**\n- \"Reporting\" or \"Deliveries\" role authorization required for driver data operations\n- `DriverDetail` object in request body with driver information\n- Content-Type: application/json\n- Driver data must pass validation requirements\n\n**Response Data:**\n- Response format: `200 OK` (no response body)\n- Returns success confirmation upon successful creation or update\n- Driver information is validated and stored for operational use\n- Updates reflected immediately in driver listings and assignments\n\n**Request Body Fields:**\n- DriverId: Driver identifier for updates (0 for new drivers)\n- Name: Driver's full name (required)\n- StateId: State identifier for licensing (optional)\n- DriversLicense: Driver's license number (required)\n\n**Create vs Update Behavior:**\n- **CREATE**: When DriverId is 0 or omitted, creates a new driver record\n- **UPDATE**: When DriverId is provided with valid driver ID, updates existing driver\n- **Validation**: All provided data must pass driver validation requirements\n\n**Common Use Cases:**\n- Add new drivers to the delivery team for expanding operations\n- Update existing driver information when licenses or details change\n- Maintain accurate driver records for compliance and operational purposes\n- Support driver onboarding and management workflows\n\n**Performance & Limits:**\n- Single driver operation for targeted updates\n- Immediate validation and storage\n- Changes reflected immediately in driver listings\n- Location-scoped driver management for operational relevance\n\n**Related Endpoints:**\n- `GET /drivers` - Retrieve current driver information\n- `GET /deliveries` - Get deliveries that may be assigned to drivers\n- Delivery management endpoints that utilize driver assignments\n\n**Important Notes:**\n- Driver information must pass validation before storage\n- Drivers are scoped to location level for operational management\n- Essential for delivery operations and transportation compliance\n- Basic licensing information required for compliance\n- Changes immediately available for delivery assignment and scheduling", "operationId": "DriversPost", "requestBody": { "description": "Driver information to create or update - DriverDetail object with driver details", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/DriverDetail" } }, "application/json": { "schema": { "$ref": "#/components/schemas/DriverDetail" } }, "text/json": { "schema": { "$ref": "#/components/schemas/DriverDetail" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/DriverDetail" } } }, "x-bodyName": "driver" }, "responses": { "200": { "description": "Success - Driver successfully created or updated" }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for driver access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/employees": { "get": { "tags": ["Employees"], "summary": "Get Employees", "description": "**Purpose:** Retrieves the complete list of employees for the authenticated organization for staff management and operational workflows.\n\n**Request Requirements:**\n- \"Employee\" role authorization required for employee data access\n- No query parameters or request body needed\n- Rate limited to 300 requests per minute\n\n**Response Data:**\n- Returns array of employee objects: `[{ Employee }, ...]`\n- Array typically contains 5-100 employees per organization\n- Returns empty array `[]` if no employees configured (rare)\n- Includes employee ID, name, location assignments, and permission details\n- Organization-level employee directory filtered to authenticated organization\n- Staff information for operational and management purposes\n\n**Common Use Cases:**\n- Populate employee dropdown lists in scheduling and assignment systems\n- Support staff management and operational workflow assignments\n- Generate employee directories and contact lists for internal use\n- Validate employee assignments in transaction and operational systems\n- Enable staff-based reporting and analytics for management\n- Support payroll and HR integration systems\n\n**Performance & Limits:**\n- Rate limited to 300 requests per minute for optimal performance\n- Organization-level employee data filtered to authenticated organization\n- No pagination needed for typical organization employee counts\n- Optimized for internal operational and management use cases\n\n**Related Endpoints:**\n- Transaction endpoints that may reference employee assignments\n- Operational endpoints that utilize employee information\n- Reporting endpoints that include employee-based analytics\n\n**Important Notes:**\n- Employees are scoped to organization level (LSP) for data security\n- Requires Employee role authorization for access to sensitive staff information\n- Rate limiting enforced to protect employee data and system performance\n- Essential for staff management and operational workflow support\n- Employee information may be used for transaction tracking and audit trails\n- Supports internal operational systems and management workflows", "operationId": "EmployeesGet", "responses": { "200": { "description": "Success - Returns array of Employee objects: `[{ Employee }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Employee" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for employee access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/guestlist": { "get": { "tags": ["GuestList"], "summary": "Guest List (Active Check-ins)", "description": "**Purpose:** Retrieves a real-time list of customers currently checked into the dispensary location for queue management and customer service.\n\n**Request Requirements:**\n- \"Customer\" role authorization required for guest management functions\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of guest objects: `[{ GuestListEntry }, ...]`\n- Array typically contains 0-50 active guests depending on current business volume\n- Returns empty array `[]` if no customers are currently checked in\n- Customer details including name, customer ID, customer type, and contact information\n- Check-in status with current status and check-in timestamp in UTC\n- Transaction data with associated transaction ID and reference number\n- Terminal information showing POS terminal name where check-in occurred\n- Pre-order source indicating origin of the order (online, walk-in, etc.)\n- Returns only guests checked into the authenticated location\n\n**Data Filtering:**\n- Real-time data showing only currently active check-ins\n- Guests who have completed their visit and checked out will not appear\n- Automatically excludes guests in hidden rooms (administrative areas)\n- Automatically excludes guests in on-hold rooms (temporary holding areas)\n- Results filtered to show only the most recent check-in per customer\n\n**Common Use Cases:**\n- Monitor current guest queue and wait times for queue management\n- Display active customers for budtender assignment on staff dashboards\n- Maintain records of dispensary occupancy for compliance tracking\n- Identify guests and their order status for customer service\n- Track check-in patterns and peak hours for analytics\n\n**Performance & Limits:**\n- Data optimized for real-time display applications\n- Consider implementing appropriate polling intervals for your use case\n- Live data reflects current check-in status immediately\n- Efficient filtering for large guest lists\n\n**Related Endpoints:**\n- `POST /transaction/create-anonymous` - Create anonymous customer check-ins\n\n**Important Notes:**\n- All timestamps are returned in UTC format for consistent processing across time zones\n- Only shows currently active check-ins; completed visits are excluded\n- Location-specific data filtered to authenticated dispensary location\n- Requires customer role authorization for access to guest management functions", "operationId": "GuestlistGet", "responses": { "200": { "description": "Success - Returns array of guest objects: `[{ GuestListEntry }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/GuestListEntry" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for customer access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/harvest": { "get": { "tags": ["Harvest"], "summary": "Get Harvests", "description": "**Purpose:** Retrieve harvest records for cannabis cultivation operations including tracking, compliance, and operational management.\n\n**Request Requirements:**\n- Either \"Inventory\" or \"Cultivation\" role required for harvest data access\n- Optional query parameters for filtering and date range selection\n- No request body needed\n\n**Response Data:**\n- Returns array of `Harvest` objects with comprehensive harvest information\n- Array may contain 0 to 1,000+ harvests depending on cultivation scale and filtering\n- Returns empty array `[]` if no harvests match criteria (not null)\n- Results ordered by last modified date (most recent first)\n- Harvest details include timing, quantities, strain information, and compliance data\n- Results automatically filtered to authenticated location\n\n**Filtering Options:**\n- fromLastModifiedDateUTC: Returns harvests modified after this date for incremental sync\n- toLastModifiedDateUTC: Returns harvests modified before this date for date range filtering\n- activeHarvests: Filter by harvest status (true=active, false=completed, null=completed only)\n\n**Harvest Status Definitions:**\n- **Active Harvests**: Currently in progress, not yet completed or processed\n- **Completed Harvests**: Finished harvest operations, ready for processing or completed\n- **Default Behavior**: Returns completed harvests only when activeHarvests parameter is null\n\n**Common Use Cases:**\n- Monitor harvest progress and completion status for cultivation management\n- Generate harvest reports for compliance and regulatory reporting\n- Track harvest yields and timing for operational optimization\n- Synchronize harvest data with cultivation management systems\n- Support inventory management and product traceability requirements\n\n**Performance & Limits:**\n- Optimized for cultivation tracking and harvest management workflows\n- Date range filtering recommended for large cultivation operations\n- Results sorted by modification date for chronological tracking\n- Location-scoped results for operational relevance and security\n\n**Related Endpoints:**\n- `POST /harvest` - Create or update individual harvest records\n- `POST /harvest/bulk` - Create or update multiple harvests efficiently\n- `GET /inventory` - View products created from harvest operations\n- Plant and cultivation tracking endpoints for complete workflow\n\n**Important Notes:**\n- **Default Filter**: Returns completed harvests only unless activeHarvests parameter is specified\n- **Date Filtering**: Use date parameters for incremental sync and performance optimization\n- **Compliance Tracking**: Harvest records support cannabis regulatory compliance requirements\n- **Cultivation Integration**: Links with plant tracking and inventory management systems\n- **Yield Tracking**: Provides harvest quantity and quality data for operational analytics", "operationId": "HarvestGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Filter harvests modified after this date for incremental sync - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Filter harvests modified before this date for date range filtering - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "activeHarvests", "in": "query", "description": "Filter by harvest status: true=active, false=completed, null=completed only - Default: null (completed only)", "schema": { "type": "boolean" } } ], "responses": { "200": { "description": "Success - Returns array of harvest objects: `[{ Harvest }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Harvest" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for cultivation or inventory access" }, "500": { "description": "Internal Server Error - Server error occurred" } } }, "post": { "tags": ["Harvest"], "summary": "Create or Update Harvest", "description": "**Purpose:** Create a new harvest record or update an existing harvest with comprehensive cultivation data for compliance tracking and operational management.\n\n**Request Requirements:**\n- \"CultivationWrite\" role authorization required for harvest data operations\n- `CreateOrUpdateHarvest` object in request body with harvest details\n- Content-Type: application/json\n- Plant and strain information must be valid and accessible to your location\n\n**Response Data:**\n- Returns single integer harvest ID (not array) for the created or updated harvest\n- New harvests receive newly assigned harvest ID\n- Updated harvests return the existing harvest ID\n- ID can be used for subsequent harvest operations and tracking\n\n**Create vs Update Behavior:**\n- **CREATE**: When HarvestId is null or omitted, a new harvest record will be created\n- **UPDATE**: When HarvestId is provided with a valid harvest ID, the existing harvest will be updated\n- **Validation**: Plant and strain data must be valid for both create and update operations\n- **Compliance**: All harvest data must meet cannabis regulatory requirements\n\n**Request Body Fields:**\n- HarvestId: ID for updates (null for new harvests)\n- Plant identification and tracking information\n- Harvest timing and scheduling details\n- Yield quantities and measurement data\n- Strain and genetic information\n- Compliance and regulatory tracking data\n\n**Sparse Update Behavior:**\n- **Provided fields**: Will overwrite existing values with provided data\n- **Omitted fields**: Will preserve existing values (no data loss for updates)\n- **Special handling**: Plant and strain associations require valid references\n- **Validation**: All provided data must meet cultivation and compliance standards\n\n**Common Use Cases:**\n- Record new harvest operations as plants are processed\n- Update harvest records with final yield and quality data\n- Maintain compliance with cannabis cultivation tracking requirements\n- Track harvest timing and efficiency for operational optimization\n- Link harvests to plant tracking and inventory management systems\n\n**Performance & Limits:**\n- Single harvest operation for targeted tracking\n- Immediate validation and compliance checking\n- Changes reflected immediately in harvest listings and reporting\n- Optimized for cultivation workflow integration\n\n**Related Endpoints:**\n- `GET /harvest` - Retrieve harvest records for review and tracking\n- `POST /harvest/bulk` - Create or update multiple harvests efficiently\n- Plant tracking endpoints for complete cultivation workflow\n- `GET /inventory` - View products created from harvest operations\n\n**Important Notes:**\n- **Compliance Critical**: Harvest records are required for cannabis regulatory compliance\n- **Plant Tracking**: Must link to valid plant records for traceability\n- **Yield Accuracy**: Accurate yield data is essential for inventory and compliance\n- **Timing Tracking**: Harvest dates and timing support compliance reporting\n- **Bulk Alternative**: Use POST /harvest/bulk for multiple harvest operations", "operationId": "HarvestPost", "requestBody": { "description": "Harvest information to create or update - CreateOrUpdateHarvest object with harvest details", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CreateOrUpdateHarvest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CreateOrUpdateHarvest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CreateOrUpdateHarvest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CreateOrUpdateHarvest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Returns harvest ID for created or updated harvest: `integer`", "content": { "application/json": { "schema": { "type": "integer", "format": "int32" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for cultivation write access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/harvest/bulk": { "post": { "tags": ["Harvest"], "summary": "Bulk Create or Update Harvests", "description": "**Purpose:** Create or update multiple harvest records in a single operation for efficient cultivation data management and compliance tracking.\n\n**Request Requirements:**\n- \"CultivationWrite\" role authorization required for harvest data operations\n- `BulkCreateOrUpdateHarvest` object in request body with array of harvest details\n- Content-Type: application/json\n- All plant and strain information must be valid and accessible to your location\n- Request validation performed before any operations are executed\n\n**Response Data:**\n- Returns single `BulkCreateOrUpdateHarvestResponse` object (not array) with operation results\n- CreatedHarvestIds: Array of newly created harvest IDs\n- UpdatedHarvestIds: Array of updated harvest IDs\n- Success message confirming completion of operations\n- All operations are atomic - either all succeed or all fail\n\n**Create vs Update Behavior:**\n- **CREATE**: When HarvestId is null or omitted in harvest objects, new harvest records will be created\n- **UPDATE**: When HarvestId is provided with valid harvest IDs, existing harvests will be updated\n- **Mixed Operations**: Single request can include both create and update operations\n- **Validation**: All harvest data must pass validation before any operations are executed\n- **Atomic Processing**: All operations succeed together or all operations fail together\n\n**Request Body Structure:**\n- Harvests: Array of CreateOrUpdateHarvest objects\n- Each harvest object contains the same fields as individual harvest operations\n- Plant identification, timing, yield, strain, and compliance data for each harvest\n- Mixed create (HarvestId=null) and update (HarvestId=provided) operations supported\n\n**Bulk Processing Benefits:**\n- **Efficiency**: Process multiple harvests in single API call\n- **Performance**: Optimized database operations for large cultivation operations\n- **Consistency**: Atomic operations ensure data integrity\n- **Compliance**: Batch compliance checking and validation\n- **Convenience**: Simplifies integration for cultivation management systems\n\n**Common Use Cases:**\n- Process multiple harvest operations from cultivation management systems\n- Synchronize harvest data between external systems and LeafLogix\n- Update multiple harvest records with final yield and quality data\n- Import harvest data from spreadsheets or external cultivation tracking\n- Maintain compliance with cannabis cultivation tracking requirements\n\n**Performance & Limits:**\n- Optimized for bulk cultivation data processing\n- Atomic transaction processing ensures data consistency\n- All validation performed before any operations are executed\n- Efficient for large-scale cultivation operations\n- Changes reflected immediately in harvest listings and reporting\n\n**Related Endpoints:**\n- `GET /harvest` - Retrieve harvest records for review and tracking\n- `POST /harvest` - Create or update individual harvest records\n- Plant tracking endpoints for complete cultivation workflow\n- `GET /inventory` - View products created from harvest operations\n\n**Important Notes:**\n- **Atomic Operations**: All harvests in the request succeed or fail together\n- **Validation Required**: Complete validation performed before any processing\n- **Compliance Critical**: All harvest records must meet cannabis regulatory requirements\n- **Plant Tracking**: All harvests must link to valid plant records for traceability\n- **Efficiency**: Preferred method for multiple harvest operations", "operationId": "HarvestBulkPost", "requestBody": { "description": "Bulk harvest request with array of harvest operations - BulkCreateOrUpdateHarvest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/BulkCreateOrUpdateHarvest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/BulkCreateOrUpdateHarvest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/BulkCreateOrUpdateHarvest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/BulkCreateOrUpdateHarvest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Returns bulk harvest response object: `{ BulkCreateOrUpdateHarvestResponse }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BulkCreateOrUpdateHarvestResponse" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for cultivation write access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/okcomputer": { "get": { "tags": ["HealthCheck"], "summary": "Health Check Endpoint", "description": "**Purpose:** Provides a simple health check endpoint to verify the API service is running and responsive.\n\n**Request Requirements:**\n- No authentication or API key required for infrastructure access\n- AllowAnonymous endpoint for monitoring systems\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns health status object: `{ SuccessResult }`\n- HTTP 200 status when the service is healthy\n- Lightweight JSON response for fast monitoring\n\n**Common Use Cases:**\n- Load balancer health checks to route traffic only to healthy instances\n- External monitoring services (Pingdom, DataDog) for uptime alerting\n- Infrastructure monitoring by DevOps teams for service availability\n- Service verification before making other API calls\n- Automated health monitoring in deployment pipelines\n\n**Performance & Limits:**\n- Designed to respond quickly with minimal system requirements\n- No rate limiting applied to health checks\n- Minimal dependencies to ensure reliable health indication\n- Optimized for frequent polling by monitoring systems\n\n**Related Endpoints:**\n- No related endpoints - this is a standalone health check\n\n**Important Notes:**\n- This endpoint bypasses normal authentication for infrastructure access\n- Designed for automated monitoring and load balancer health checks\n- Simple response format optimized for parsing by monitoring tools\n- Available on both `/health-check` and `/okcomputer` routes", "operationId": "OkcomputerGet", "responses": { "200": { "description": "Success - Service is healthy and responsive", "content": { "text/plain": { "schema": { "$ref": "#/components/schemas/SuccessResult" } }, "application/json": { "schema": { "$ref": "#/components/schemas/SuccessResult" } }, "text/json": { "schema": { "$ref": "#/components/schemas/SuccessResult" } } } }, "500": { "description": "Internal Server Error - Service is experiencing issues" } } } }, "/integration/integration-recon": { "get": { "tags": ["Integration"], "summary": "Get Inventory Integration Reconciliation", "description": "**Purpose:** Retrieve inventory reconciliation data between LeafLogix and external state tracking systems for compliance and integration monitoring.\n\n**Request Requirements:**\n- \"Integrations\" role authorization required for integration data access\n- No query parameters or request body needed\n- Integration management permissions for system reconciliation\n\n**Response Data:**\n- Returns single `InventoryIntegrationReconResponse` object (not array) with reconciliation results\n- Includes inventory discrepancies and integration status information\n- State system synchronization details and compliance tracking data\n- Integration health and data consistency information\n\n**Reconciliation Information Included:**\n- **Inventory Discrepancies**: Items with differences between systems\n- **Integration Status**: Current state of external system synchronization\n- **Compliance Data**: Regulatory tracking and audit trail information\n- **Sync Health**: Integration system connectivity and data flow status\n\n**Common Use Cases:**\n- Monitor inventory synchronization between LeafLogix and state tracking systems\n- Identify and resolve inventory discrepancies for compliance\n- Support compliance audits and regulatory reporting requirements\n- Troubleshoot integration issues and data synchronization problems\n- Maintain accurate inventory records across integrated systems\n\n**Performance & Limits:**\n- Real-time reconciliation data for immediate integration monitoring\n- Comprehensive reconciliation across integrated state tracking systems\n- Optimized for compliance monitoring and integration management workflows\n- Results include comprehensive integration status and discrepancy details\n\n**Related Endpoints:**\n- `GET /inventory` - View current inventory status for comparison\n- `GET /plant` - Check plant inventory integration status\n- `GET /harvest` - Monitor harvest integration synchronization\n\n**Important Notes:**\n- **Compliance Critical**: Essential for regulatory compliance and audit requirements\n- **Integration Monitoring**: Real-time visibility into external system synchronization\n- **Complete Data Access**: Provides comprehensive reconciliation across all integrated systems\n- **State System Integration**: Specific to external state tracking system connectivity\n- **Audit Ready**: Data formatted for compliance reporting and audit requirements", "operationId": "IntegrationIntegration-reconGet", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/InventoryIntegrationReconResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/inventory": { "get": { "tags": ["Inventory"], "summary": "Get Inventory", "description": "**Purpose:** Retrieve current inventory levels and product details for API-enabled products with available stock.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for inventory data access\n- Optional query parameters for enhanced data inclusion\n- No request body needed\n\n**Response Data:**\n- Returns array of `InventoryItem` objects with current stock and product information\n- Response format: `[{ InventoryItem }, { InventoryItem }, ...]`\n- Array may contain 0 to 5,000+ inventory items depending on location inventory size\n- Returns empty array `[]` if no inventory items have stock or meet criteria\n- Stock levels including available quantities, unit weights, flower equivalent amounts\n- Product details with SKU, name, description, category, brand, pricing (retail/medical)\n- Package data including package ID, batch name, package status, expiration dates\n- Lab results with potency testing, cannabinoid profiles, test dates (when includeLabResults=true)\n- Room breakdown showing quantities by storage location (when includeRoomQuantities=true)\n- Compliance data including external package IDs (METRC/BioTrack), strain information, producer details\n\n**Filtering Options:**\n- includeLabResults: Include detailed lab testing data and cannabinoid profiles (default: false)\n- includeRoomQuantities: Include quantity breakdown by storage room/location (default: false)\n\n**Common Use Cases:**\n- Update online store inventory levels and product availability for e-commerce sync\n- Perform real-time stock checks during sales transactions for POS integration\n- Monitor stock levels across multiple storage locations for inventory management\n- Track package-level inventory for regulatory compliance reporting\n- Show potency and testing information to customers for lab data display\n\n**Performance & Limits:**\n- Response times optimized for high-volume integrations\n- Use minimal parameters for fastest response times\n- Standard rate limits apply for high-volume integrations\n- Data reflects current system state with real-time accuracy\n\n**Related Endpoints:**\n- `GET /products` - Complete product catalog regardless of stock levels (use for menu/catalog display)\n\n**Important Notes:**\n- Only products enabled for API access are returned for access control\n- Products with zero inventory are automatically excluded\n- Results automatically filtered to authenticated user's location only\n- Inventory data reflects current stock levels with real-time accuracy", "operationId": "InventoryGet", "parameters": [ { "name": "includeLabResults", "in": "query", "description": "Include detailed lab testing data and cannabinoid profiles - Default: false", "schema": { "type": "boolean", "default": false } }, { "name": "includeRoomQuantities", "in": "query", "description": "Include quantity breakdown by storage room/location - Default: false", "schema": { "type": "boolean", "default": false } } ], "responses": { "200": { "description": "Success - Returns array of inventory items with product and stock details", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/InventoryItem" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for inventory access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/inventory/labresults": { "get": { "tags": ["Inventory"], "operationId": "InventoryLabresultsGet", "parameters": [ { "name": "BatchName", "in": "query", "schema": { "type": "string" } } ], "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LabResult" } } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } } }, "/inventory/snapshot": { "get": { "tags": ["Inventory"], "operationId": "InventorySnapshotGet", "parameters": [ { "name": "fromDate", "in": "query", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/InventorySnapshot" } } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } } }, "/inventory/receivedinventory": { "get": { "tags": ["Inventory"], "operationId": "InventoryReceivedinventoryGet", "parameters": [ { "name": "receiveInventoryHistoryId", "in": "query", "schema": { "type": "integer", "format": "int32" } }, { "name": "startDate", "in": "query", "schema": { "type": "string", "format": "date-time" } }, { "name": "endDate", "in": "query", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ReceivedInventory" } } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } } }, "/inventory/inventorytransaction": { "get": { "tags": ["Inventory"], "operationId": "InventoryInventorytransactionGet", "parameters": [ { "name": "startDate", "in": "query", "schema": { "type": "string", "format": "date-time" } }, { "name": "endDate", "in": "query", "schema": { "type": "string", "format": "date-time" } }, { "name": "transactionType", "in": "query", "schema": { "type": "string" } } ], "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/InventoryTransaction" } } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } } }, "/inventory/receiveinventory": { "post": { "tags": ["Inventory"], "summary": "Create Receive Inventory Order", "description": "**Purpose:** Create a new inventory receive order for incoming transfers, purchase orders, or direct inventory additions.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for inventory operations\n- `ReceiveInventorySave` object in request body with vendor and item details\n- Content-Type: application/json\n- UserId or UserName required when ReceiveIntoInventory=true\n\n**Response Data:**\n- Response format: `{ SavedReceive }`\n- Returns transaction ID and processing status information\n\n**Processing Options:**\n- **Draft Mode (ReceiveIntoInventory=false):** Creates a saved receive order that can be opened/edited in LeafLogix\n- **Direct Processing (ReceiveIntoInventory=true):** Immediately processes items into inventory (requires UserId or UserName)\n\n**Required Information:**\n- **Items Array:** Product details, quantities, costs, room assignments, batch information\n- **Vendor Information:** VendorId, delivery details, licensing information\n- **User Context:** UserId or UserName (required when ReceiveIntoInventory=true)\n\n**Item Details Required:**\n- **Product Identification:** ProductId or SKU, product name\n- **Quantities:** Receive quantity, unit of measure\n- **Costs:** Unit cost, total cost (for cost tracking)\n- **Storage:** Room assignment, expiration dates\n- **Compliance:** Package tags, batch names, lab testing status\n\n**Common Use Cases:**\n- **Transfer Processing:** Receive inventory from other licensed locations\n- **Purchase Orders:** Process incoming vendor deliveries\n- **Direct Additions:** Add inventory directly to stock levels\n- **Compliance Tracking:** Maintain chain of custody for regulatory reporting\n- **Batch Processing:** Handle multiple items in a single receive transaction\n\n**Validation Features:**\n- **Vendor Verification:** Validates vendor exists and is active\n- **Room Validation:** Confirms room assignments are valid for location\n- **Potency Indicators:** Validates required compliance fields\n- **Duplicate Prevention:** ExternalId checking prevents duplicate receives\n- **User Authorization:** Verifies user permissions for inventory operations\n\n**Important Notes:**\n- **User Requirement:** UserId or UserName required when ReceiveIntoInventory=true (cannot specify both)\n- **External ID Uniqueness:** ExternalId must be unique or omitted to prevent duplicates\n- **Vendor License Support:** Supports vendor license code mapping for compliance requirements\n- **Location Scoped:** All operations scoped to authenticated user's location\n- **Enhanced Validation:** Additional validation rules may apply based on location settings\n\n**Request Format:**\nProvide a `ReceiveInventorySave` object containing vendor details, delivery information, and an array of items to receive.", "operationId": "InventoryReceiveinventoryPost", "requestBody": { "description": "Receive inventory order details including vendor, delivery, and item information", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/ReceiveInventorySave" } }, "application/json": { "schema": { "$ref": "#/components/schemas/ReceiveInventorySave" } }, "text/json": { "schema": { "$ref": "#/components/schemas/ReceiveInventorySave" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/ReceiveInventorySave" } } }, "x-bodyName": "recInv" }, "responses": { "200": { "description": "Success - Returns SavedReceive object with transaction details", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SavedReceive" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) OR String error message (parse response body as plain text)", "content": { "application/json": { "schema": { "type": "string" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for inventory access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/lineages": { "get": { "tags": ["Lineage"], "summary": "Get Lineages", "description": "**Purpose:** Retrieves the complete list of genetic lineages available for the authenticated organization for product classification and cannabis genetic tracking.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of lineage objects: `[{ Lineage }, ...]`\n- Array typically contains 10-50 genetic lineages per organization\n- Returns empty array `[]` if no lineages configured (rare)\n- Includes lineage ID, name, and genetic classification details\n- Cannabis genetic lineages and hereditary information for product categorization\n- Results filtered to authenticated organization level\n\n**Common Use Cases:**\n- Track genetic lineage and hereditary information for cannabis products\n- Support compliance reporting with genetic background documentation\n- Populate lineage dropdown lists in product creation and strain management forms\n- Validate genetic lineage assignments in product and cultivation systems\n- Generate lineage-specific reports for cultivation and breeding programs\n- Enable genetic tracking for quality control and consistency\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small dataset suitable for client-side caching\n- No pagination needed due to manageable number of genetic lineages\n- Results consistent across all locations within organization\n\n**Related Endpoints:**\n- `GET /strains` - Get strains that may be associated with these lineages\n- `GET /products` - Get products with lineage genetic information\n- Cultivation and breeding endpoints that utilize genetic lineage data\n\n**Important Notes:**\n- Lineages are defined at organization level (LSP) for consistency\n- Essential for cannabis genetic tracking and breeding program documentation\n- Used for compliance reporting and genetic background verification\n- Supports cultivation operations with genetic lineage documentation\n- May be required for certain cannabis regulations and track-and-trace systems\n- Helps maintain genetic consistency and quality control in cultivation", "operationId": "LineagesGet", "responses": { "200": { "description": "Success - Returns array of lineage objects: `[{ Lineage }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Lineage" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/package/set-tags": { "post": { "tags": ["Package"], "summary": "Set Package Tags", "description": "**Purpose:** Set inventory tags for packages, completely replacing any existing tags with the new tag set for organization and tracking.\n\n**Request Requirements:**\n- \"PackageWrite\" role authorization required for package tag operations\n- `UpdatePackageTagsRequest` object in request body with package identifiers and tags\n- Content-Type: application/json\n- Must specify either InventoryIds OR PackageIds, but not both\n- All specified packages must be accessible to your location\n\n**Response Data:**\n- Returns success confirmation (HTTP 200) upon successful tag assignment\n- No response body content (void return)\n- Tags are validated and applied immediately to specified packages\n- Changes are reflected immediately in inventory listings and package data\n\n**Package Identification Options:**\n- **InventoryIds**: Target specific inventory records directly (one-to-one relationship)\n- **PackageIds**: Target packages by serial numbers (may affect multiple inventory records)\n- **Mutually Exclusive**: Specify either InventoryIds OR PackageIds, never both\n- **Validation**: Using both types will result in 400 Bad Request error\n\n**Tag Operation Behavior:**\n- **Complete Replacement**: All existing tags are removed and replaced with new tags\n- **Tag Validation**: All tags must be valid and available in the system\n- **Immediate Effect**: Changes apply immediately to all specified packages\n- **Bulk Operation**: Can target multiple packages in a single request\n\n**Request Body Fields:**\n- InventoryIds: Array of inventory record IDs (optional, mutually exclusive with PackageIds)\n- PackageIds: Array of package serial numbers (optional, mutually exclusive with InventoryIds)\n- Tags: Array of tag names to apply to the specified packages (required)\n\n**Common Use Cases:**\n- Standardize tag sets across multiple packages for consistency\n- Replace outdated or incorrect tags with current classification\n- Implement new tagging schema by completely updating existing tags\n- Clean up tag sets by removing unwanted tags and setting only desired ones\n- Maintain organized inventory classification for operational efficiency\n\n**Performance & Limits:**\n- Bulk operation optimized for multiple package updates\n- Immediate validation and tag assignment\n- Changes propagate to inventory systems immediately\n- Efficient for large-scale tag management operations\n\n**Related Endpoints:**\n- `POST /package/add-tags` - Add tags while preserving existing tags\n- `POST /package/remove-tags` - Remove specific tags while preserving others\n- `GET /tags` - Retrieve available tag options for validation\n- `GET /inventory` - View packages with their current tag assignments\n\n**Important Notes:**\n- **Complete Replacement**: This operation removes ALL existing tags and replaces them\n- **Tag Validation**: All tags must exist in the system and be valid\n- **Package Access**: All specified packages must be accessible to your authenticated location\n- **Mutual Exclusion**: Cannot use both InventoryIds and PackageIds in the same request\n- **Alternative Operations**: Use add-tags or remove-tags for partial tag modifications", "operationId": "PackageSet-tagsPost", "requestBody": { "description": "Package tag update request with package identifiers and replacement tags - UpdatePackageTagsRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Tags successfully set on specified packages" }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/package/add-tags": { "post": { "tags": ["Package"], "summary": "Add Package Tags", "description": "**Purpose:** Add new inventory tags to packages while preserving all existing tags for enhanced organization and classification.\n\n**Request Requirements:**\n- \"PackageWrite\" role authorization required for package tag operations\n- `UpdatePackageTagsRequest` object in request body with package identifiers and tags\n- Content-Type: application/json\n- Must specify either InventoryIds OR PackageIds, but not both\n- All specified packages must be accessible to your location\n\n**Response Data:**\n- Returns success confirmation (HTTP 200) upon successful tag addition\n- No response body content (void return)\n- New tags are validated and added immediately to specified packages\n- Changes are reflected immediately in inventory listings and package data\n\n**Package Identification Options:**\n- **InventoryIds**: Target specific inventory records directly (one-to-one relationship)\n- **PackageIds**: Target packages by serial numbers (may affect multiple inventory records)\n- **Mutually Exclusive**: Specify either InventoryIds OR PackageIds, never both\n- **Validation**: Using both types will result in 400 Bad Request error\n\n**Tag Operation Behavior:**\n- **Additive Operation**: New tags are added while preserving all existing tags\n- **Duplicate Handling**: Duplicate tags are automatically ignored (no error)\n- **Tag Validation**: All new tags must be valid and available in the system\n- **Immediate Effect**: Changes apply immediately to all specified packages\n- **Bulk Operation**: Can target multiple packages in a single request\n\n**Request Body Fields:**\n- InventoryIds: Array of inventory record IDs (optional, mutually exclusive with PackageIds)\n- PackageIds: Array of package serial numbers (optional, mutually exclusive with InventoryIds)\n- Tags: Array of tag names to add to the specified packages (required)\n\n**Common Use Cases:**\n- Add seasonal or promotional tags to existing products without losing current classification\n- Enhance product categorization by adding supplementary organizational tags\n- Apply new quality control or testing tags while maintaining existing product tags\n- Add compliance or regulatory tags for audit trails without disrupting inventory organization\n- Implement progressive tagging workflows where tags are added over time\n\n**Performance & Limits:**\n- Bulk operation optimized for multiple package updates\n- Immediate validation and tag addition\n- Changes propagate to inventory systems immediately\n- Efficient for incremental tag management operations\n\n**Related Endpoints:**\n- `POST /package/set-tags` - Replace all existing tags with new tag set\n- `POST /package/remove-tags` - Remove specific tags while preserving others\n- `GET /tags` - Retrieve available tag options for validation\n- `GET /inventory` - View packages with their current tag assignments\n\n**Important Notes:**\n- **Preserves Existing**: This operation keeps ALL existing tags and adds new ones\n- **Duplicate Safe**: Adding tags that already exist will not cause errors\n- **Tag Validation**: All new tags must exist in the system and be valid\n- **Package Access**: All specified packages must be accessible to your authenticated location\n- **Mutual Exclusion**: Cannot use both InventoryIds and PackageIds in the same request", "operationId": "PackageAdd-tagsPost", "requestBody": { "description": "Package tag update request with package identifiers and additional tags - UpdatePackageTagsRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Tags successfully added to specified packages" }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array" }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/package/remove-tags": { "post": { "tags": ["Package"], "summary": "Remove Package Tags", "description": "**Purpose:** Remove specific inventory tags from packages while preserving all other existing tags for selective tag management.\n\n**Request Requirements:**\n- \"PackageWrite\" role authorization required for package tag operations\n- `UpdatePackageTagsRequest` object in request body with package identifiers and tags to remove\n- Content-Type: application/json\n- Must specify either InventoryIds OR PackageIds, but not both\n- All specified packages must be accessible to your location\n\n**Response Data:**\n- Returns success confirmation (HTTP 200) upon successful tag removal\n- No response body content (void return)\n- Specified tags are removed immediately from specified packages\n- Changes are reflected immediately in inventory listings and package data\n\n**Package Identification Options:**\n- **InventoryIds**: Target specific inventory records directly (one-to-one relationship)\n- **PackageIds**: Target packages by serial numbers (may affect multiple inventory records)\n- **Mutually Exclusive**: Specify either InventoryIds OR PackageIds, never both\n- **Validation**: Using both types will result in 400 Bad Request error\n\n**Tag Operation Behavior:**\n- **Selective Removal**: Only specified tags are removed, all others are preserved\n- **Missing Tag Handling**: Removing tags that don't exist is silently ignored (no error)\n- **Immediate Effect**: Changes apply immediately to all specified packages\n- **Bulk Operation**: Can target multiple packages in a single request\n- **Preservation**: All non-specified tags remain unchanged\n\n**Request Body Fields:**\n- InventoryIds: Array of inventory record IDs (optional, mutually exclusive with PackageIds)\n- PackageIds: Array of package serial numbers (optional, mutually exclusive with InventoryIds)\n- Tags: Array of tag names to remove from the specified packages (required)\n\n**Common Use Cases:**\n- Remove outdated seasonal or promotional tags while keeping product classification\n- Clean up temporary testing or quality control tags after completion\n- Remove incorrect or duplicate tags while preserving accurate classification\n- Implement tag lifecycle management by removing obsolete organizational tags\n- Support compliance workflows by removing temporary audit or review tags\n\n**Performance & Limits:**\n- Bulk operation optimized for multiple package updates\n- Immediate tag removal processing\n- Changes propagate to inventory systems immediately\n- Efficient for selective tag cleanup operations\n\n**Related Endpoints:**\n- `POST /package/set-tags` - Replace all existing tags with new tag set\n- `POST /package/add-tags` - Add new tags while preserving existing tags\n- `GET /tags` - Retrieve available tag options for validation\n- `GET /inventory` - View packages with their current tag assignments\n\n**Important Notes:**\n- **Preserves Others**: This operation keeps ALL non-specified tags unchanged\n- **Missing Tag Safe**: Removing tags that don't exist will not cause errors\n- **Package Access**: All specified packages must be accessible to your authenticated location\n- **Mutual Exclusion**: Cannot use both InventoryIds and PackageIds in the same request\n- **Selective Operation**: Use for precise tag management without affecting other classification", "operationId": "PackageRemove-tagsPost", "requestBody": { "description": "Package tag update request with package identifiers and tags to remove - UpdatePackageTagsRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdatePackageTagsRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Tags successfully removed from specified packages" }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array" }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant": { "get": { "tags": ["Plant"], "summary": "Get Plants", "description": "**Purpose:** Retrieve cannabis plant records for cultivation tracking, compliance monitoring, and operational management.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant data access\n- Optional query parameters for filtering by plant attributes and date ranges\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ Plant }, { Plant }, ...]`\n- Returns array of `Plant` objects with comprehensive plant information\n- Array may contain 0 to 10,000+ plants depending on cultivation scale and filtering\n- Returns empty array `[]` if no plants match criteria (not null)\n- Plant details include identification, growth status, cultivation tracking, and compliance data\n- Results automatically filtered to authenticated location\n\n**Filtering Options:**\n- plantId: Filter by specific LeafLogix internal plant ID for individual plant lookup\n- serialNumber: Filter by plant serial number for tracking system integration\n- status: Filter by plant status (Active, Harvesting, Harvested, Retired)\n- lastModifiedDateStart: Returns plants modified after this date for incremental sync\n- lastModifiedDateEnd: Returns plants modified before this date for date range filtering\n\n**Plant Status Definitions:**\n- **Active**: Plants currently growing and under cultivation\n- **Harvesting**: Plants currently being harvested or in harvest process\n- **Harvested**: Plants that have completed harvest operations\n- **Retired**: Plants that have been retired from cultivation (destroyed, failed, etc.)\n\n**Common Use Cases:**\n- Monitor plant growth progress and cultivation status for operational management\n- Generate compliance reports for regulatory tracking and auditing\n- Synchronize plant data with cultivation management and tracking systems\n- Track plant lifecycle from cultivation through harvest completion\n- Support inventory management and product traceability requirements\n\n**Performance & Limits:**\n- Optimized for cultivation tracking and plant management workflows\n- Date range filtering recommended for large cultivation operations\n- Plant status filtering efficient for operational dashboards\n- Location-scoped results for operational relevance and security\n\n**Related Endpoints:**\n- `POST /plant/harvest` - Move plants into harvest status\n- `POST /harvest` - Create harvest records for harvested plants\n- `GET /inventory` - View products created from harvested plants\n- Plant lifecycle and cultivation management endpoints\n\n**Important Notes:**\n- **Compliance Tracking**: Plant records support cannabis regulatory compliance requirements\n- **Lifecycle Management**: Tracks complete plant lifecycle from cultivation to harvest\n- **Date Filtering**: Use date parameters for incremental sync and performance optimization\n- **Status Filtering**: Essential for operational workflows and cultivation management\n- **Traceability**: Links with harvest and inventory systems for complete product tracking", "operationId": "PlantGet", "parameters": [ { "name": "plantId", "in": "query", "description": "Dutchie internal plant ID for specific plant lookup - Optional", "schema": { "type": "integer", "format": "int32" } }, { "name": "serialNumber", "in": "query", "description": "Plant serial number for tracking system integration - Optional", "schema": { "type": "string" } }, { "name": "status", "in": "query", "description": "Plant status filter: Active, Harvesting, Harvested, Retired - Optional", "schema": { "type": "string" } }, { "name": "lastModifiedDateStart", "in": "query", "description": "Filter plants modified after this date for incremental sync - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "lastModifiedDateEnd", "in": "query", "description": "Filter plants modified before this date for date range filtering - Optional", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Plant" } } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } }, "post": { "tags": ["Plant"], "summary": "Add Plant", "description": "**Purpose:** Create a new cannabis plant record in the cultivation system with unique identification and tracking for compliance monitoring and operational management.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant creation operations\n- `CreatePlantRequest` object in request body with plant identification and group details\n- Content-Type: application/json\n- Serial number must be unique within the facility\n- Plant group must exist or strain must be provided for new group creation\n\n**Response Data:**\n- Response format: `int` (Plant ID)\n- Returns the newly created plant's unique LeafLogix plant ID\n- Plant ID can be used in subsequent plant management operations\n- Immediate plant creation with tracking system integration\n\n**Request Body Fields:**\n- `PlantGroupName`: Name of plant group for batch tracking (required)\n- `SerialNumber`: Unique plant identifier for compliance tracking (required, must be unique)\n- `Strain`: Strain name for new plant groups (required when creating new plant group)\n- `Room`: Cultivation room name for plant location (required when using state integrations)\n- `BypassStateIntegration`: Skip external system integration (optional, default: false)\n- `DateCreated`: Plant creation date (optional, defaults to current UTC time)\n- `PhaseStartDate`: Initial growth phase start date (optional, defaults to current UTC time)\n\n**Plant Group Behavior:**\n- **Existing Groups**: If plant group exists, strain information is inherited\n- **New Groups**: If plant group doesn't exist, strain must be provided for group creation\n- **Batch Tracking**: Plant groups enable batch-based cultivation tracking and compliance\n- **Strain Assignment**: All plants in a group share the same strain genetics\n\n**Validation Rules:**\n- **Serial Number**: Must be unique across the facility for compliance tracking\n- **Plant Group**: Required for batch organization and cultivation management\n- **Strain Requirement**: Must provide strain when creating new plant groups\n- **Room Validation**: Room name must exist and be accessible when using integrations\n- **State Integration**: Room required unless bypassing external system integration\n\n**Common Use Cases:**\n- Register new clones or seedlings entering the cultivation facility\n- Create plant records for compliance tracking and regulatory reporting\n- Initialize plant tracking for cultivation workflow management\n- Support batch-based cultivation and harvest planning\n- Integrate with external cultivation and compliance systems\n\n**Performance & Limits:**\n- Single plant creation for precise record management\n- Immediate validation and unique identifier assignment\n- Optional integration with external cultivation systems\n- Efficient for individual plant registration workflows\n\n**Related Endpoints:**\n- `GET /plant` - Retrieve created plant information and status\n- `POST /plant/assign-plants-to-group` - Assign existing plants to groups\n- `POST /plant/move` - Move plants between cultivation rooms\n- Plant lifecycle management endpoints for complete workflow\n\n**Important Notes:**\n- **Unique Tracking**: Serial numbers must be unique for compliance and tracking\n- **Compliance Critical**: Plant registration is required for cannabis regulatory compliance\n- **Group Management**: Plant groups support batch-based cultivation workflows\n- **Integration**: External system integration supports cultivation management platforms\n- **Immediate Processing**: Plant creation is immediate with tracking system updates", "operationId": "PlantPost", "requestBody": { "description": "Plant creation request with identification and group details - see `CreatePlantRequest` model for complete field documentation", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CreatePlantRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CreatePlantRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CreatePlantRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CreatePlantRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success - Returns newly created plant ID as integer", "content": { "application/json": { "schema": { "type": "integer", "format": "int32" } } } }, "400": { "description": "Bad Request - Validation errors or duplicate serial number", "content": { "application/json": { "schema": { "type": "object" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/harvest": { "post": { "tags": ["Plant"], "summary": "Harvest Plants", "description": "**Purpose:** Move plants from cultivation into harvest status with optional weight tracking for cannabis cultivation compliance and operational management.\n\n**Request Requirements:**\n- \"CultivationWrite\" role authorization required for plant harvest operations\n- `HarvestPlantRequest` object in request body with plant identifiers and harvest details\n- Content-Type: application/json\n- Rate limited to 300 requests per minute\n- All specified plants must be accessible to your location and in valid status for harvesting\n\n**Response Data:**\n- Response format: No response body (void)\n- Returns success confirmation (HTTP 200) upon successful harvest initiation\n- No response body content (void return)\n- Plants are moved to harvesting status immediately\n- Changes are reflected immediately in plant listings and cultivation tracking\n\n**Request Body Fields:**\n- Plant identifiers for the plants to be harvested\n- Optional wet weight measurements for harvest tracking\n- Harvest timing and operational details\n- Compliance and tracking information required for regulatory reporting\n\n**Harvest Operation Behavior:**\n- **Status Change**: Plants are moved from Active to Harvesting status\n- **Weight Tracking**: Optional wet weight can be recorded for yield tracking\n- **Bulk Processing**: Multiple plants can be harvested in a single operation\n- **Compliance**: All operations logged for regulatory compliance requirements\n- **Immediate Effect**: Status changes apply immediately to all specified plants\n\n**Common Use Cases:**\n- Initiate harvest operations for mature cannabis plants ready for processing\n- Record harvest timing and initial weight measurements for yield tracking\n- Maintain compliance with cannabis cultivation and harvest regulations\n- Support cultivation workflow transitions from growing to processing phases\n- Track harvest operations for operational efficiency and planning\n\n**Performance & Limits:**\n- Rate limited to 300 requests per minute for cultivation workflow protection\n- Bulk operation optimized for multiple plant processing\n- Immediate status updates and tracking system integration\n- Efficient for large-scale cultivation harvest operations\n\n**Related Endpoints:**\n- `GET /plant` - Retrieve plant records and current status\n- `POST /harvest` - Create harvest records for tracking and compliance\n- `GET /harvest` - Monitor harvest progress and completion status\n- Cultivation and inventory management endpoints for complete workflow\n\n**Important Notes:**\n- **Status Requirements**: Plants must be in Active status to be harvested\n- **Compliance Critical**: Harvest operations are required for cannabis regulatory compliance\n- **Weight Tracking**: Wet weight measurements support yield tracking and compliance\n- **Rate Limiting**: 300 requests per minute limit for cultivation workflow stability\n- **Immediate Processing**: Status changes are immediate and irreversible through this endpoint", "operationId": "PlantHarvestPost", "requestBody": { "description": "Plant harvest request with plant identifiers and optional weight data - HarvestPlantRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/HarvestPlantRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/HarvestPlantRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/HarvestPlantRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/HarvestPlantRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Plants successfully moved to harvest status" }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/move": { "post": { "tags": ["Plant"], "summary": "Move Plants", "description": "**Purpose:** Move cannabis plants to a different room or cultivation area within the same facility for cultivation workflow management and compliance tracking.\n\n**Request Requirements:**\n- \"CultivationWrite\" role authorization required for plant movement operations\n- `MovePlantRequest` object in request body with plant IDs and target room information\n- Content-Type: application/json\n- All specified plants must be accessible to your location and in moveable status\n- Target room must be within the same facility (location)\n\n**Response Data:**\n- Response format: No response body (void)\n- Returns success confirmation (HTTP 200) upon successful plant movement\n- No response body content (void return)\n- Plants are moved to new room immediately\n- Changes are reflected immediately in plant location tracking\n\n**Request Body Fields:**\n- `PlantIds`: Array of LeafLogix plant IDs to move (required)\n- `RoomId`: Target room ID within the same facility (required)\n- `TableId`: Optional table assignment within the target room\n\n**Movement Operation Behavior:**\n- **Location Validation**: Target room must belong to the same facility\n- **Bulk Processing**: Multiple plants can be moved in a single operation\n- **Stage Updates**: If target room has cultivation stage, plants automatically update to that stage\n- **Compliance**: All movement operations logged for regulatory compliance requirements\n- **Integration**: Movement synchronized with external cultivation systems when configured\n\n**Common Use Cases:**\n- Move plants between cultivation rooms as they progress through growth stages\n- Relocate plants for environmental optimization and cultivation management\n- Transfer plants to harvest preparation areas when ready for processing\n- Support cultivation workflow automation and plant lifecycle management\n- Maintain compliance with cannabis cultivation and tracking regulations\n\n**Performance & Limits:**\n- Bulk operation optimized for multiple plant processing\n- Immediate location updates and tracking system integration\n- Efficient for large-scale cultivation facility operations\n- Location validation prevents cross-facility security violations\n\n**Related Endpoints:**\n- `GET /plant` - Retrieve current plant locations and status\n- `POST /plant/change-phase` - Update growth phases when moving between rooms\n- `GET /room` - List available rooms for plant movement planning\n- Cultivation management endpoints for complete workflow\n\n**Important Notes:**\n- **Facility Restriction**: Plants cannot be moved to rooms in different facilities\n- **Compliance Critical**: Plant movements are required for cannabis regulatory compliance\n- **Stage Automation**: Room-specific cultivation stages applied automatically when configured\n- **Immediate Processing**: Location changes are immediate and tracked for audit purposes\n- **Integration**: Movement synchronized with external cultivation and compliance systems", "operationId": "PlantMovePost", "requestBody": { "description": "Plant movement request with plant IDs and target room information - see `MovePlantRequest` model for complete field documentation", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/MovePlantRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/MovePlantRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/MovePlantRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/MovePlantRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Plants successfully moved to target room" }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)" }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/change-phase": { "post": { "tags": ["Plant"], "summary": "Change Plants Growth Phase", "description": "**Purpose:** Update the cultivation growth phase of cannabis plants to track their development stage and optimize cultivation management.\n\n**Request Requirements:**\n- \"CultivationWrite\" role authorization required for plant growth phase operations\n- `ChangeGrowthPhaseRequest` object in request body with plant IDs and growth phase information\n- Content-Type: application/json\n- All specified plants must be accessible to your location and in valid status for phase changes\n- Growth phase must be one of the valid phase values\n\n**Response Data:**\n- Response format: No response body (void)\n- Returns success confirmation (HTTP 200) upon successful phase change\n- No response body content (void return)\n- Plants are updated to new growth phase immediately\n- Changes are reflected immediately in plant cultivation tracking\n\n**Request Body Fields:**\n- `PlantIds`: Array of LeafLogix plant IDs to update (required)\n- `GrowthPhase`: Target cultivation phase - must be one of: `Vegetative`, `Propagation`, `Flowering` (required)\n- `PhaseStartDate`: Date when new phase begins - defaults to current UTC time if omitted (optional)\n\n**Growth Phase Values:**\n- **Propagation**: Initial plant development and cloning phase\n- **Vegetative**: Active vegetative growth before flowering initiation\n- **Flowering**: Reproductive growth phase leading to harvest\n\n**Phase Change Operation Behavior:**\n- **Phase Validation**: Growth phase value validated against allowed phases\n- **Bulk Processing**: Multiple plants can be updated in a single operation\n- **Date Management**: Phase start date defaults to current time if not specified\n- **Compliance**: All phase changes logged for regulatory compliance requirements\n- **Integration**: Phase updates synchronized with external cultivation systems when configured\n\n**Common Use Cases:**\n- Transition plants from vegetative to flowering phase for harvest timing\n- Update plant phases during cultivation workflow automation\n- Maintain accurate cultivation records for compliance reporting\n- Support cultivation planning and scheduling optimization\n- Synchronize growth phases with environmental control systems\n\n**Performance & Limits:**\n- Bulk operation optimized for multiple plant processing\n- Immediate phase updates and tracking system integration\n- Efficient for large-scale cultivation facility operations\n- Phase validation prevents invalid cultivation state transitions\n\n**Related Endpoints:**\n- `GET /plant` - Retrieve current plant phases and cultivation status\n- `POST /plant/move` - Move plants between rooms optimized for different phases\n- `POST /plant/harvest` - Harvest plants when flowering phase is complete\n- Cultivation management endpoints for complete workflow\n\n**Important Notes:**\n- **Phase Validation**: Only `Vegetative`, `Propagation`, and `Flowering` phases are accepted\n- **Compliance Critical**: Phase tracking is required for cannabis regulatory compliance\n- **Date Tracking**: Phase start dates support cultivation timeline management\n- **Immediate Processing**: Phase changes are immediate and tracked for audit purposes\n- **Integration**: Phase updates synchronized with external cultivation and compliance systems", "operationId": "PlantChange-phasePost", "requestBody": { "description": "Growth phase change request with plant IDs and target phase information - see `ChangeGrowthPhaseRequest` model for complete field documentation", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/ChangeGrowthPhaseRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/ChangeGrowthPhaseRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/ChangeGrowthPhaseRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/ChangeGrowthPhaseRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Plants successfully updated to new growth phase" }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)" }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/retire": { "post": { "tags": ["Plant"], "summary": "Retire Plants", "description": "**Purpose:** Permanently retire cannabis plants from cultivation due to various reasons such as disease, damage, or end-of-life for compliance tracking and waste management.\n\n**Request Requirements:**\n- \"CultivationWrite\" role authorization required for plant retirement operations\n- `RetirePlantRequest` object in request body with plant IDs and retirement details\n- Content-Type: application/json\n- Rate limited to 300 requests per minute\n- All specified plants must be accessible to your location and in retirable status\n- Either `ReasonId` or `ReasonCode` must be provided for retirement justification\n\n**Response Data:**\n- Response format: No response body (void)\n- Returns success confirmation (HTTP 200) upon successful plant retirement\n- No response body content (void return)\n- Plants are permanently retired from cultivation immediately\n- Changes are reflected immediately in plant status and compliance tracking\n\n**Request Body Fields:**\n- `PlantIds`: Array of LeafLogix plant IDs to retire (required)\n- `ReasonId`: Numeric reason ID for retirement - use if known (optional if ReasonCode provided)\n- `ReasonCode`: String reason code for retirement - use if ReasonId unknown (optional if ReasonId provided)\n- `RoomId`: Room where retirement occurs for waste tracking (required)\n- `WasteType`: Type of waste generated from retirement (optional)\n- `WasteWeight`: Weight of waste material in specified units (optional)\n- `PlantWeight`: Weight of plant material being retired (optional)\n- `WasteDate`: Date of waste generation for compliance tracking (optional)\n- Additional waste tracking and compliance fields\n\n**Reason Code Management:**\n- **ReasonId Priority**: If both ReasonId and ReasonCode provided, ReasonId takes precedence\n- **Code Lookup**: ReasonCode automatically looked up to find corresponding ReasonId\n- **Validation**: Invalid ReasonId or ReasonCode will result in 400 Bad Request response\n- **Flexibility**: Use ReasonCode when integrating without pre-knowledge of reason IDs\n\n**Retirement Operation Behavior:**\n- **Permanent Action**: Plant retirement is irreversible once completed\n- **Bulk Processing**: Multiple plants can be retired in a single operation\n- **Waste Tracking**: Optional waste weight and material tracking for compliance\n- **Compliance**: All retirement operations logged for regulatory compliance requirements\n- **Integration**: Retirement synchronized with external cultivation and waste tracking systems\n\n**Common Use Cases:**\n- Retire diseased or damaged plants to prevent contamination spread\n- Remove plants that have reached end-of-life or failed quality standards\n- Comply with regulatory requirements for plant destruction documentation\n- Manage cultivation space by removing non-productive plants\n- Support waste tracking and disposal compliance reporting\n\n**Performance & Limits:**\n- Rate limited to 300 requests per minute for cultivation workflow protection\n- Bulk operation optimized for multiple plant processing\n- Immediate retirement status updates and tracking system integration\n- Efficient for large-scale cultivation facility operations\n\n**Related Endpoints:**\n- `GET /plant` - Retrieve current plant status before retirement\n- `GET /plant/get-reason-codes` - List available retirement reason codes\n- `POST /waste` - Create waste records for retired plant material\n- Cultivation and compliance management endpoints\n\n**Important Notes:**\n- **Irreversible Action**: Plant retirement cannot be undone once completed\n- **Reason Required**: Either ReasonId or ReasonCode must be provided for compliance\n- **Compliance Critical**: Retirement tracking is required for cannabis regulatory compliance\n- **Rate Limiting**: 300 requests per minute limit for cultivation workflow stability\n- **Waste Integration**: Retirement can generate waste records for disposal tracking", "operationId": "PlantRetirePost", "requestBody": { "description": "Plant retirement request with plant IDs, reason codes, and waste tracking details - see `RetirePlantRequest` model for complete field documentation", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/RetirePlantRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/RetirePlantRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/RetirePlantRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/RetirePlantRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Plants successfully retired from cultivation" }, "400": { "description": "Bad Request - Invalid reason ID/code or validation errors", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/get-reason-codes": { "get": { "tags": ["Plant"], "summary": "Get Plant Reason Codes", "description": "**Purpose:** Retrieve the list of valid reason codes for cannabis plant retirement operations to support compliance documentation and proper retirement categorization.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant data access\n- No query parameters or request body needed\n\n**Response Data:**\n- Response format: `[string, string, ...]`\n- Returns array of string reason codes for plant retirement\n- Array typically contains 5-20 reason codes depending on organization configuration\n- Returns empty array `[]` if no reason codes configured (rare)\n- Reason codes are organization-specific and configurable by administrators\n- Results automatically filtered to authenticated organization\n\n**Common Reason Code Examples:**\n- Disease or pest infestation requiring plant destruction\n- Physical damage or environmental stress failures\n- Quality control failures or contamination issues\n- End-of-life or harvest completion scenarios\n- Regulatory compliance or audit requirements\n\n**Common Use Cases:**\n- Populate reason code dropdown lists in plant retirement forms\n- Validate reason codes before submitting plant retirement requests\n- Generate compliance reports showing retirement reasons and frequencies\n- Support cultivation management workflows with proper retirement categorization\n- Maintain audit trails for regulatory compliance and operational analysis\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small dataset suitable for client-side caching\n- No pagination needed due to manageable reason code catalog sizes\n- Results filtered to organization-specific reason configurations\n\n**Related Endpoints:**\n- `POST /plant/retire` - Retire plants using these reason codes for compliance\n- `GET /plant` - Retrieve plant status before determining retirement reasons\n- Plant lifecycle and cultivation management endpoints\n\n**Important Notes:**\n- **Organization-Specific**: Reason codes vary by organization and compliance requirements\n- **Compliance Required**: Proper reason codes are essential for cannabis regulatory compliance\n- **Validation**: Use these codes to validate retirement requests before submission\n- **Reference Data**: Cache locally for performance in plant retirement workflows\n- **Administrative**: Reason codes are configured by system administrators", "operationId": "PlantGet-reason-codesGet", "responses": { "200": { "description": "Success - Returns array of reason code strings: `[string, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/assign-plants-to-group": { "post": { "tags": ["Plant"], "summary": "Assign Plants to Group", "description": "**Purpose:** Assign existing cannabis plants to a specific plant group for batch management and cultivation workflow organization using plant serial numbers.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant group management operations\n- `AssignPlantsToGroupRequest` object in request body with group name and plant serial numbers\n- Content-Type: application/json\n- All specified plant serial numbers must exist and be accessible to your location\n- Target plant group must exist within the facility\n\n**Response Data:**\n- Response format: No response body (void)\n- Returns success confirmation (HTTP 200) upon successful plant assignment\n- No response body content (void return)\n- Plants are assigned to target group immediately\n- Changes are reflected immediately in plant group organization and batch tracking\n\n**Request Body Fields:**\n- `PlantGroupName`: Name of target plant group for batch organization (required)\n- `PlantSerialNumbers`: Array of plant serial numbers to assign to the group (required)\n\n**Plant Group Assignment Behavior:**\n- **Batch Organization**: Plants assigned to groups for batch-based cultivation tracking\n- **Serial Number Lookup**: Plants identified by serial numbers for precise assignment\n- **Group Validation**: Target plant group must exist before assignment\n- **Bulk Processing**: Multiple plants can be assigned to the same group in a single operation\n- **Immediate Processing**: Group assignments are immediate and tracked for compliance\n\n**Validation Rules:**\n- **Plant Existence**: All serial numbers must correspond to existing plants\n- **Location Access**: Plants must be accessible to the authenticated location\n- **Group Existence**: Target plant group must exist within the facility\n- **Serial Number Format**: Serial numbers must match existing plant tracking identifiers\n\n**Common Use Cases:**\n- Reorganize plants into batch groups for cultivation workflow management\n- Assign newly created plants to existing cultivation batches\n- Support batch-based harvest planning and cultivation scheduling\n- Maintain proper plant group organization for compliance reporting\n- Facilitate cultivation management and operational efficiency\n\n**Performance & Limits:**\n- Bulk operation optimized for multiple plant assignment\n- Immediate group assignment and tracking system integration\n- Efficient for cultivation workflow organization and batch management\n- Serial number validation ensures accurate plant identification\n\n**Related Endpoints:**\n- `GET /plant` - Retrieve current plant group assignments and status\n- `POST /plant` - Create new plants that can be assigned to groups\n- Plant group and cultivation management endpoints for complete workflow\n\n**Important Notes:**\n- **Batch Management**: Plant groups enable batch-based cultivation tracking and compliance\n- **Serial Number Precision**: Use exact serial numbers for accurate plant identification\n- **Compliance Support**: Proper group organization supports regulatory compliance requirements\n- **Immediate Processing**: Group assignments are immediate and tracked for audit purposes\n- **Workflow Integration**: Supports cultivation management and harvest planning workflows", "operationId": "PlantAssign-plants-to-groupPost", "requestBody": { "description": "Plant group assignment request with group name and plant serial numbers - see `AssignPlantsToGroupRequest` model for complete field documentation", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/AssignPlantsToGroupRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/AssignPlantsToGroupRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/AssignPlantsToGroupRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/AssignPlantsToGroupRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success - Plants successfully assigned to target group" }, "400": { "description": "Bad Request - Validation errors or invalid plant serial numbers", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/nonsts/update": { "post": { "tags": ["PlantNonsts"], "summary": "Update Existing Plants (Non-State Tracking)", "description": "**Purpose:** Update existing plant records with cultivation data without reporting to state traceability systems for internal plant management.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant data modification\n- `UpdatePlantsRequest` object in request body with plant update details\n- Content-Type: application/json\n- Valid PlantId required for each plant to be updated\n- Feature flag \"rollout.trym-integration\" must be enabled\n\n**Response Data:**\n- Returns single `SuccessResult` object (not array) with operation confirmation\n- Includes success message confirming plants were updated\n- Operation status and any relevant update information\n\n**Sparse Update Behavior:**\n- **Null/Empty/Omitted Fields**: Will NOT have their data updated (preserves existing values)\n- **Provided Fields**: Only fields with values in the request will be updated\n- **Field Independence**: Each field can be updated independently without affecting others\n- **Safe Updates**: Omitted fields maintain their current database values\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Updates are for internal cultivation tracking only\n- **No External Reporting**: Changes are NOT reported to state traceability systems\n- **Cultivation Focus**: Designed for internal plant management and cultivation workflows\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Common Use Cases:**\n- Update internal plant cultivation notes and observations\n- Modify plant growth stage information for internal tracking\n- Update plant location within cultivation facility\n- Record internal plant health and development data\n- Maintain cultivation workflow information without state system updates\n\n**Performance & Limits:**\n- Batch plant updates for efficient cultivation management\n- Validation performed before any changes to ensure data integrity\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility management workflows\n\n**Related Endpoints:**\n- `GET /plant` - Retrieve current plant data before updates\n- `POST /plant/nonsts` - Create new plants for internal tracking\n- `POST /plant/harvest` - Official plant harvest operations (state tracked)\n\n**Important Notes:**\n- **Feature Gated**: Requires \"rollout.trym-integration\" feature flag to be enabled\n- **Internal Tracking**: Updates are for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Validation Required**: Plant IDs must exist and be valid for the location\n- **Cultivation Focus**: Designed specifically for cultivation facility workflows", "operationId": "PlantNonstsUpdatePost", "requestBody": { "description": "Plant update request with PlantId and field updates - UpdatePlantsRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdatePlantsRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdatePlantsRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdatePlantsRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdatePlantsRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SuccessResult" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/nonsts/batch/immatureplants": { "post": { "tags": ["PlantNonsts"], "summary": "Create Immature Plant Batch (Non-State Tracking)", "description": "**Purpose:** Create a batch of immature plants for internal cultivation tracking without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant creation\n- `PostImmatureBatchRequest` object in request body with batch details\n- Content-Type: application/json\n- Valid plant data for each immature plant in the batch\n- Feature flag \"rollout.trym-integration\" must be enabled\n\n**Response Data:**\n- Returns single `ApiResult` object (not array) with creation results\n- Includes array of created plant IDs for tracking and reference\n- Batch creation status and success confirmation\n- Plant ID assignments for newly created immature plants\n\n**Batch Creation Process:**\n- **Multiple Plants**: Creates multiple immature plants in a single operation\n- **ID Assignment**: Each plant receives a unique PlantId for future operations\n- **Validation**: All plant data validated before batch creation\n- **Atomic Operation**: Batch succeeds or fails as a complete unit\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Plant creation for internal cultivation tracking only\n- **No External Reporting**: Plant creation NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal plant management and cultivation workflows\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Immature Plant Characteristics:**\n- **Growth Stage**: Plants in early vegetative or seedling stage\n- **Tracking Ready**: Created with unique identifiers for cultivation tracking\n- **Development Phase**: Pre-flowering plants requiring cultivation management\n- **Internal Records**: Maintained in internal cultivation systems only\n\n**Common Use Cases:**\n- Create batches of seedlings for internal cultivation tracking\n- Initialize plant records for new cultivation cycles\n- Set up immature plant inventory for facility management\n- Start cultivation workflows without state system integration\n- Manage internal plant genetics and breeding programs\n\n**Performance & Limits:**\n- Batch processing for efficient plant creation workflows\n- Validation performed before any plant creation\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility startup and expansion workflows\n\n**Related Endpoints:**\n- `POST /plant/nonsts/update` - Update created plants with cultivation data\n- `GET /plant` - Retrieve created plant information\n- `POST /plant/harvest` - Official plant harvest operations (state tracked)\n\n**Important Notes:**\n- **Feature Gated**: Requires \"rollout.trym-integration\" feature flag to be enabled\n- **Plant IDs Returned**: Save returned plant IDs for future plant management operations\n- **Internal Tracking**: Plants created for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Batch Efficiency**: Creates multiple plants efficiently in single operation", "operationId": "PlantNonstsBatchImmatureplantsPost", "requestBody": { "description": "Immature plant batch request with plant details - PostImmatureBatchRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/PostImmatureBatchRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/PostImmatureBatchRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/PostImmatureBatchRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/PostImmatureBatchRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateImmaturePlantBatchResponseApiResult" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/nonsts/batch/convert/immatureplants": { "post": { "tags": ["PlantNonsts"], "summary": "Convert Immature Plant Batch to Mature (Non-State Tracking)", "description": "**Purpose:** Convert immature plant batches to mature plant status for internal cultivation tracking without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant conversion\n- `ConvertImmatureBatchRequest` object in request body with conversion details\n- Content-Type: application/json\n- Valid immature batch data for conversion to mature plants\n- Feature flag \"rollout.trym-integration\" must be enabled\n\n**Response Data:**\n- Returns single `ApiResult` object (not array) with conversion results\n- Includes array of converted plant IDs for tracking and reference\n- Plant conversion status and success confirmation\n- Mature plant ID assignments for newly converted plants\n\n**Plant Conversion Process:**\n- **Status Transition**: Converts immature plants to mature plant status\n- **ID Retention**: Existing plant IDs maintained through conversion process\n- **Validation**: All conversion data validated before processing\n- **Batch Processing**: Multiple immature plants converted in single operation\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Plant creation for internal cultivation tracking only\n- **No External Reporting**: Plant conversion NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal plant management and cultivation workflows\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Maturity Transition:**\n- **Growth Stage**: Immature to mature plant status transition\n- **Cultivation Ready**: Mature plants ready for flowering phase management\n- **Tracking Continuity**: Maintains plant tracking through maturity transition\n- **Workflow Integration**: Supports cultivation facility growth phase workflows\n\n**Common Use Cases:**\n- Convert vegetative plants to mature flowering status\n- Transition immature batches to mature cultivation phases\n- Progress plants through cultivation development stages\n- Support internal cultivation workflow maturity management\n- Manage plant lifecycle transitions without state system integration\n\n**Performance & Limits:**\n- Efficient plant conversion for cultivation management\n- Validation performed before any plant conversion\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility maturity workflows\n\n**Related Endpoints:**\n- `POST /plant/nonsts/update` - Update converted plants with cultivation data\n- `GET /plant` - Retrieve converted plant information\n- `POST /plant/harvest` - Official plant harvest operations (state tracked)\n\n**Important Notes:**\n- **Feature Gated**: Requires \"rollout.trym-integration\" feature flag to be enabled\n- **Plant IDs Returned**: Save returned plant IDs for future plant management operations\n- **Internal Tracking**: Plants converted for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Cultivation Ready**: Mature plants ready for internal cultivation tracking workflows", "operationId": "PlantNonstsBatchConvertImmatureplantsPost", "requestBody": { "description": "Immature batch conversion request with conversion details - ConvertImmatureBatchRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/ConvertImmatureBatchRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/ConvertImmatureBatchRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/ConvertImmatureBatchRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/ConvertImmatureBatchRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ConvertImmaturePlantResponseApiResult" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/nonsts/batch/matureplants": { "post": { "tags": ["PlantNonsts"], "summary": "Create Mature Plant Batch (Non-State Tracking)", "description": "**Purpose:** Create a batch of mature plants ready for flowering phase cultivation tracking without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for mature plant creation\n- `CreateMatureBatchRequest` object in request body with mature plant batch details\n- Content-Type: application/json\n- Valid mature plant data for each plant in the batch\n- Feature flag \"rollout.trym-integration\" must be enabled\n\n**Response Data:**\n- Returns single `ApiResult` object (not array) with creation results\n- Includes array of created plant IDs for tracking and reference\n- Batch creation status and success confirmation\n- Plant ID assignments for newly created mature plants\n\n**Mature Plant Batch Creation:**\n- **Multiple Plants**: Creates multiple mature plants in a single operation\n- **Flowering Ready**: Plants created at mature stage ready for flowering phase\n- **ID Assignment**: Each plant receives a unique PlantId for future operations\n- **Validation**: All plant data validated before batch creation\n- **Atomic Operation**: Batch succeeds or fails as a complete unit\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Plant creation for internal cultivation tracking only\n- **No External Reporting**: Plant creation NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal mature plant management and flowering workflows\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Mature Plant Characteristics:**\n- **Growth Stage**: Plants ready for flowering phase cultivation\n- **Cultivation Ready**: Created with unique identifiers for flowering management\n- **Production Phase**: Mature plants prepared for harvest cultivation workflows\n- **Internal Records**: Maintained in internal cultivation systems only\n\n**Common Use Cases:**\n- Create batches of mature plants for flowering room management\n- Initialize mature plant inventory for production cycles\n- Set up flowering phase plant tracking for facility management\n- Start mature cultivation workflows without state system integration\n- Manage internal mature plant genetics and production programs\n\n**Performance & Limits:**\n- Batch processing for efficient mature plant creation workflows\n- Validation performed before any plant creation\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility flowering phase workflows\n\n**Related Endpoints:**\n- `POST /plant/nonsts/update` - Update created mature plants with cultivation data\n- `POST /plant/nonsts/batch/immatureplants` - Create immature plant batches\n- `POST /plant/nonsts/batch/convert/immatureplants` - Convert immature to mature plants\n- `GET /plant` - Retrieve created mature plant information\n- `POST /plant/harvest` - Official plant harvest operations (state tracked)\n\n**Important Notes:**\n- **Feature Gated**: Requires \"rollout.trym-integration\" feature flag to be enabled\n- **Plant IDs Returned**: Save returned plant IDs for future mature plant management operations\n- **Internal Tracking**: Plants created for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Flowering Ready**: Mature plants ready for flowering phase cultivation workflows\n- **Batch Efficiency**: Creates multiple mature plants efficiently in single operation", "operationId": "PlantNonstsBatchMatureplantsPost", "requestBody": { "description": "Mature plant batch request with plant details - CreateMatureBatchRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CreateMatureBatchRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CreateMatureBatchRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CreateMatureBatchRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CreateMatureBatchRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success - Returns ApiResult with created plant IDs: `{ \"data\": { \"createdPlants\": [plantId1, plantId2, ...] }, \"message\": \"Successfully created mature plants from batches.\", \"success\": true }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateMaturePlantsResponseApiResult" } } } }, "400": { "description": "Bad Request - Validation failed or invalid request data", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for mature plant creation or feature flag disabled" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/plant/nonsts/retag": { "post": { "tags": ["PlantNonsts"], "summary": "Retag Plant or Clone (Non-State Tracking)", "description": "**Purpose:** Update plant or clone tag identification for internal cultivation tracking without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant retagging\n- `RetagPlantRequest` object in request body with retagging details\n- Content-Type: application/json\n- Valid existing plant identification and new tag information\n- Feature flag \"rollout.trym-integration\" must be enabled\n\n**Response Data:**\n- Returns HTTP 200 with no response body on success\n- No data returned - operation confirmation only\n- Operation status confirms successful retagging completion\n\n**Retagging Process:**\n- **Tag Replacement**: Updates existing plant tag with new identification\n- **Plant Identification**: Maintains plant record while updating tag reference\n- **Validation**: Ensures new tag is unique and valid for the facility\n- **Immediate Update**: Tag change reflected immediately in cultivation systems\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Tag updates for internal cultivation tracking only\n- **No External Reporting**: Retagging NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal plant management and tag organization\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Retagging Applications:**\n- **Tag Damage**: Replace damaged or unreadable plant tags\n- **Organization**: Update tag numbering for facility organization\n- **Growth Stage**: Retag plants when moving between cultivation areas\n- **Clone Management**: Update clone tags for genetic tracking\n\n**Common Use Cases:**\n- Replace damaged plant tags for continued tracking\n- Update plant identification for facility reorganization\n- Retag clones for genetic lineage management\n- Maintain plant tag consistency across cultivation areas\n- Support internal cultivation workflow tag requirements\n\n**Performance & Limits:**\n- Single plant retagging operation for targeted tag management\n- Validation performed before any tag changes\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility tag management workflows\n\n**Related Endpoints:**\n- `POST /plant/nonsts/update` - Update other plant data beyond tags\n- `GET /plant` - Retrieve plant information with current tags\n- `POST /plant/nonsts` - Create new plants with initial tags\n\n**Important Notes:**\n- **Feature Gated**: Requires \"rollout.trym-integration\" feature flag to be enabled\n- **Tag Uniqueness**: New tag must be unique within the cultivation facility\n- **Internal Tracking**: Tag changes for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Cultivation Continuity**: Maintains plant tracking continuity with updated identification", "operationId": "PlantNonstsRetagPost", "requestBody": { "description": "Plant retagging request with plant and new tag details - RetagPlantRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/RetagPlantRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/RetagPlantRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/RetagPlantRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/RetagPlantRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success" }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/nonsts/batch/retire": { "post": { "tags": ["PlantNonsts"], "summary": "Retire Immature Plant Batch (Non-State Tracking)", "description": "**Purpose:** Retire batches of immature plants or clones from active cultivation for internal tracking without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for plant retirement\n- `RetireImmaturePlantsRequest` object in request body with retirement details\n- Content-Type: application/json\n- Valid immature plant or clone identification for retirement\n- Plants must be in immature stage for this operation\n\n**Response Data:**\n- Returns HTTP 200 with no response body on success\n- No data returned - operation confirmation only\n- Status confirmation indicates successful plant retirement completion\n\n**Plant Retirement Process:**\n- **Batch Retirement**: Retires multiple immature plants or clones in single operation\n- **Status Change**: Updates plant status to retired/inactive in cultivation systems\n- **Validation**: Ensures plants are valid and in immature stage before retirement\n- **Immediate Effect**: Retirement status applied immediately to cultivation records\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Plant retirement for internal cultivation tracking only\n- **No External Reporting**: Retirement actions NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal plant lifecycle management\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Immature Plant Retirement Reasons:**\n- **Quality Control**: Remove plants that don't meet cultivation standards\n- **Space Management**: Retire excess plants for cultivation area optimization\n- **Health Issues**: Remove unhealthy or diseased plants from active cultivation\n- **Selection Process**: Retire plants not selected for continued cultivation\n- **Facility Management**: Clear immature plants for cultivation workflow changes\n\n**Common Use Cases:**\n- Retire poor-performing immature plants or clones\n- Remove excess immature plants to optimize cultivation space\n- Clear unhealthy plants from cultivation areas\n- Support cultivation selection and quality control processes\n- Manage immature plant inventory for facility efficiency\n\n**Performance & Limits:**\n- Batch processing for efficient plant retirement workflows\n- Validation performed before any retirement actions\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility plant lifecycle management\n\n**Related Endpoints:**\n- `POST /plant/nonsts/batch/immatureplants` - Create immature plant batches\n- `POST /plant/nonsts/update` - Update immature plants before retirement\n- `GET /plant` - Retrieve plant information including retirement status\n- `POST /plant/nonsts/batch/convert/immatureplants` - Convert immature to mature plants\n\n**Important Notes:**\n- **Immature Only**: This endpoint specifically handles immature plants and clones\n- **Batch Operation**: Can retire multiple plants efficiently in single request\n- **Internal Tracking**: Retirement for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Irreversible**: Plant retirement action cannot be easily undone\n- **Validation Required**: Plants must exist and be in immature stage for retirement", "operationId": "PlantNonstsBatchRetirePost", "requestBody": { "description": "Immature plant retirement request with plant details - RetireImmaturePlantsRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/RetireImmaturePlantsRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/RetireImmaturePlantsRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/RetireImmaturePlantsRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/RetireImmaturePlantsRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success - No response body, operation completed successfully" }, "400": { "description": "Bad Request - Validation failed or invalid plant data", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for plant retirement" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/plant/nonsts/batch/finish-harvest": { "post": { "tags": ["PlantNonsts"], "summary": "Finish or Unfinish Harvest Batch (Non-State Tracking)", "description": "**Purpose:** Mark harvest batches as finished or unfinished for internal cultivation tracking without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for harvest status management\n- `FinishHarvestBatchRequest` object in request body with harvest batch details\n- Content-Type: application/json\n- Valid harvest batch identification and finish/unfinish action\n- Feature flag \"rollout.trym-integration\" must be enabled\n\n**Response Data:**\n- Returns HTTP 200 with no response body on success\n- No data returned - operation confirmation only\n- Status confirmation indicates successful harvest batch update\n\n**Finish/Unfinish Operations:**\n- **FINISH**: Marks harvest batch as completed and ready for processing\n- **UNFINISH**: Reverts harvest batch to in-progress status for continued work\n- **Status Toggle**: Can switch between finished and unfinished states as needed\n- **Batch Management**: Affects entire harvest batch status uniformly\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Harvest status updates for internal cultivation tracking only\n- **No External Reporting**: Status changes NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal harvest workflow management\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Harvest Batch Status Management:**\n- **Workflow Control**: Controls harvest batch progression through processing stages\n- **Quality Gates**: Finish status indicates batch readiness for next processing steps\n- **Reversible Actions**: Unfinish allows returning to active harvest work\n- **Batch Integrity**: Maintains harvest batch data consistency\n\n**Common Use Cases:**\n- Mark harvest batches as complete when cultivation work is finished\n- Unfinish harvest batches to allow additional cultivation work\n- Control harvest workflow progression through processing stages\n- Manage harvest batch status for internal tracking and reporting\n- Support cultivation facility harvest workflow requirements\n\n**Performance & Limits:**\n- Single batch operation for targeted harvest status management\n- Immediate status update reflected in cultivation systems\n- Optimized for harvest workflow management and status tracking\n- Validation performed before any status changes\n\n**Related Endpoints:**\n- `GET /harvest` - Retrieve harvest batch information and current status\n- `POST /plant/harvest` - Official plant harvest operations (state tracked)\n- `POST /plant/nonsts/update` - Update plant data related to harvest\n\n**Important Notes:**\n- **Feature Gated**: Requires \"rollout.trym-integration\" feature flag to be enabled\n- **Reversible Operation**: Finish and unfinish actions can be toggled as needed\n- **Internal Tracking**: Status changes for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Workflow Control**: Critical for managing internal harvest processing workflows", "operationId": "PlantNonstsBatchFinish-harvestPost", "requestBody": { "description": "Harvest batch finish/unfinish request with batch details - FinishHarvestBatchRequest object", "content": { "application/json-patch+json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/FinishOrUnfinishBatchDetails" } } }, "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/FinishOrUnfinishBatchDetails" } } }, "text/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/FinishOrUnfinishBatchDetails" } } }, "application/*+json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/FinishOrUnfinishBatchDetails" } } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success" }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/plant/nonsts/split": { "post": { "tags": ["PlantNonsts"], "summary": "Split Immature Plant Batch (Non-State Tracking)", "description": "**Purpose:** Split immature plant or clone batches into two separate batches for internal cultivation management without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for batch splitting\n- `SplitImmaturePlantsRequest` object in request body with split details\n- Content-Type: application/json\n- Valid immature batch identification and split configuration\n- Source batch must contain multiple plants to enable splitting\n\n**Response Data:**\n- Returns single `ApiResult` object (not array) with split results\n- Includes details of both resulting batches after split operation\n- Batch split status and success confirmation\n- Plant distribution information for the two new batches\n\n**Batch Splitting Process:**\n- **Source Division**: Divides single immature batch into two separate batches\n- **Plant Distribution**: Distributes plants between original and new batch\n- **Batch Integrity**: Maintains plant tracking continuity through split operation\n- **Validation**: Ensures source batch is valid and contains sufficient plants for splitting\n- **Atomic Operation**: Split succeeds or fails as complete operation\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Batch splitting for internal cultivation tracking only\n- **No External Reporting**: Split operations NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal batch management and cultivation workflows\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Immature Batch Splitting Applications:**\n- **Facility Management**: Split large batches for different cultivation areas\n- **Growth Phase Management**: Separate plants based on development stage\n- **Quality Control**: Isolate high-performing plants from standard batches\n- **Genetic Management**: Separate clones for different breeding programs\n- **Space Optimization**: Distribute plants across multiple cultivation rooms\n\n**Common Use Cases:**\n- Split large immature plant batches for better facility management\n- Separate high-quality clones from standard cultivation batches\n- Distribute plants across different cultivation rooms or areas\n- Create specialized batches for different cultivation treatments\n- Support cultivation workflow organization and plant management\n\n**Performance & Limits:**\n- Single batch operation creating two resulting batches\n- Validation performed before any batch splitting\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility batch management workflows\n\n**Related Endpoints:**\n- `POST /plant/nonsts/batch/immatureplants` - Create original immature plant batches\n- `POST /plant/nonsts/update` - Update plants within split batches\n- `GET /plant` - Retrieve plant information for both resulting batches\n- `POST /plant/nonsts/batch/convert/immatureplants` - Convert split batches to mature\n\n**Important Notes:**\n- **Immature Only**: This endpoint specifically handles immature plant and clone batches\n- **Two-Batch Result**: Split operation always creates exactly two batches\n- **Plant Continuity**: All plants maintain their tracking through the split process\n- **Internal Tracking**: Split operations for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Batch Requirements**: Source batch must contain multiple plants to enable splitting", "operationId": "PlantNonstsSplitPost", "requestBody": { "description": "Immature plant batch split request with batch and split details - SplitImmaturePlantsRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/SplitImmaturePlantsRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/SplitImmaturePlantsRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/SplitImmaturePlantsRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/SplitImmaturePlantsRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success - Returns ApiResult with split batch details: `{ \"data\": { \"originalBatch\": {...}, \"newBatch\": {...} }, \"message\": \"Successfully split immature batches of plants.\", \"success\": true }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SplitImmaturePlantResultApiResult" } } } }, "400": { "description": "Bad Request - Validation failed or invalid batch data", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for batch splitting" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/plant/nonsts/batch": { "post": { "tags": ["PlantNonsts"], "summary": "Update Plant Batch (Non-State Tracking)", "description": "**Purpose:** Update plant batch information such as strain or location for internal cultivation tracking without reporting to state traceability systems.\n\n**Request Requirements:**\n- \"Inventory\" or \"Cultivation\" role authorization required for batch data modification\n- `UpdateBatchRequest` object in request body with batch update details\n- Content-Type: application/json\n- Valid batch identification and field updates\n- Feature flag \"rollout.trym-integration\" must be enabled\n\n**Response Data:**\n- Returns HTTP 200 with no response body on success\n- No data returned - operation confirmation only\n- Status confirmation indicates successful batch update completion\n\n**Batch Update Capabilities:**\n- **Strain Updates**: Modify strain information for entire plant batch\n- **Location Updates**: Change cultivation location or room assignment for batch\n- **Batch Properties**: Update other batch-level cultivation characteristics\n- **Bulk Changes**: Apply updates to all plants within the specified batch\n\n**Sparse Update Behavior:**\n- **Selective Updates**: Only provided fields in the request will be updated\n- **Field Independence**: Each batch property can be updated independently\n- **Preservation**: Omitted fields maintain their current values\n- **Validation**: All provided updates validated before application\n\n**Non-State Tracking (NONSTS) Behavior:**\n- **Internal Only**: Batch updates for internal cultivation tracking only\n- **No External Reporting**: Changes NOT transmitted to state traceability systems\n- **Cultivation Focus**: Designed for internal batch management and cultivation workflows\n- **Compliance Safe**: Does not interfere with official state tracking requirements\n\n**Common Use Cases:**\n- Update strain information when batch genetics are reclassified\n- Move plant batches to different cultivation rooms or areas\n- Modify batch properties for improved cultivation tracking\n- Correct batch information for accurate facility management\n- Support cultivation workflow batch organization requirements\n\n**Performance & Limits:**\n- Single batch operation affecting all plants in the specified batch\n- Validation performed before any batch changes\n- Changes reflected immediately in internal cultivation systems\n- Optimized for cultivation facility batch management workflows\n\n**Related Endpoints:**\n- `POST /plant/nonsts/update` - Update individual plant data within batches\n- `GET /plant` - Retrieve current plant and batch information\n- `POST /plant/nonsts` - Create new plant batches with initial properties\n\n**Important Notes:**\n- **Feature Gated**: Requires \"rollout.trym-integration\" feature flag to be enabled\n- **Batch-Wide Impact**: Updates affect all plants within the specified batch\n- **Internal Tracking**: Changes for internal cultivation management only\n- **State Compliance**: Does not affect official state traceability system records\n- **Cultivation Efficiency**: Streamlines batch-level cultivation management operations", "operationId": "PlantNonstsBatchPost", "requestBody": { "description": "Batch update request with batch identification and field updates - UpdateBatchRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdateBatchRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdateBatchRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdateBatchRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdateBatchRequest" } } }, "x-bodyName": "request" }, "responses": { "200": { "description": "Success" }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/preorder/submit": { "post": { "tags": ["PreOrder"], "summary": "Create PreOrder", "description": "**Purpose:** Create a new customer pre-order by submitting cart items with customer information and fulfillment details.\n\n**Request Requirements:**\n- \"PreOrder\" role authorization required for order creation\n- `CreatePreOrderRequest` object in request body with complete order details\n- Content-Type: application/json\n- Valid customer ID that exists in the system\n- **Idempotency Support**: Requires `ConsumerKey` header and `IdempotencyKey` field for duplicate prevention (see [Idempotency Documentation](/pages/idempotency.html))\n\n**Response Data:**\n- Returns `PreOrderResponse` object with assigned order ID and transaction ID\n- Order ID can be used for tracking and future order operations\n- Transaction ID links to the transaction for fulfillment tracking\n\n**Required Request Information:**\n- Valid CustomerId for the order recipient\n- Array of cart items with products, quantities, and any special instructions\n- Order source for tracking and reporting (Web, In-Store, Express)\n- Fulfillment details with pickup or delivery information and timing\n\n**Order Sources Available:**\n- Web: Online orders from e-commerce platforms\n- In-Store: Orders placed directly at dispensary location\n- Express: Expedited or curbside pickup orders\n- Note: Order Source is deprecated and will be replaced with more comprehensive tracking values\n\n**Delivery Time Windows:**\n- TimeWindowXXXDateUtc fields express desired delivery time windows\n- May be expanded to pickup orders in the future\n- Data exposed to locations with \"Delivery Management\" feature enabled\n\n**Redemptions Support:**\n- Third-party loyalty redemptions and LeafLogix discount codes supported\n- Valid types: SpringBig Rewards/Offers, Alpine IQ, LeafLogix Codes, Fyllo\n- Redemption ID should be discount code, reward ID, offer ID, or template ID\n\n**Common Use Cases:**\n- Process e-commerce orders from online platforms\n- Create pickup orders for customer convenience\n- Handle delivery orders with specified time windows\n- Apply loyalty rewards and promotional discounts\n- Enable customers to secure products before visiting store\n\n**Performance & Limits:**\n- Uses idempotency key to prevent duplicate order creation\n- Product validation ensures availability and purchase limits\n- Customer verification confirms validity for location\n- Compliance checking for local regulations and restrictions\n\n**Related Endpoints:**\n- `POST /preorder/price-cart` - Calculate pricing before order submission\n- `POST /transaction/create-anonymous` - Anonymous customers without full profiles\n\n\n**Important Notes:**\n- Payment occurs later at pickup/delivery, not during order creation\n- System validates product availability and customer purchase limits\n- Customer must exist and be valid for the authenticated location\n- Orders must comply with local regulations and purchase restrictions\n- Use IdempotencyKey to prevent duplicate order creation", "operationId": "PreorderSubmitPost", "requestBody": { "description": "Pre-order details including customer, cart items, and fulfillment information - CreatePreOrderRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CreatePreOrderRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CreatePreOrderRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CreatePreOrderRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CreatePreOrderRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Returns orderId and transactionId for the created pre-order", "content": { "application/json": { "schema": { "type": "integer", "format": "int32" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/preorder/update": { "post": { "tags": ["PreOrder"], "summary": "Update PreOrder", "description": "**✏️ Purpose:** Modify an existing pre-order's items, delivery information, notes, or redemptions.\n\n**🔄 Updatable Fields:**\n- **Cart Items:** Add, remove, or modify product quantities and special instructions\n- **Order Notes:** Update customer notes or special handling instructions\n- **Delivery Information:** Change delivery address or timing preferences\n- **Loyalty Redemptions:** Add, remove, or modify applied discounts and rewards\n- **Order Source:** Update tracking source information\n\n**🚫 Non-Updatable Fields:**\n- **Customer ID:** Cannot transfer order to different customer\n- **Idempotency Key:** Cannot modify unique transaction identifier\n- **Order ID:** Core order identifier remains fixed\n\n**📋 Update Behavior:**\n- **Redemptions:** If redemptions field is omitted, existing redemptions are preserved\n- **Items:** Complete replacement of cart items with provided array\n- **Delivery:** Updates only if delivery information is provided\n- **Incremental Changes:** Only provided fields are modified\n\n**⏰ Update Restrictions:**\nOrders can only be updated while in specific states:\n- ✅ **Submitted/Pending:** Full updates allowed\n- ✅ **Processing:** Limited updates may be available\n- ❌ **Filled/Complete:** No updates permitted\n- ❌ **Checked Out:** Payment completed, updates blocked\n\n**🎯 Common Use Cases:**\n- **Cart Modifications:** Customer wants to add/remove items before fulfillment\n- **Address Changes:** Update delivery location for customer convenience\n- **Special Instructions:** Add preparation notes or customer preferences\n- **Discount Updates:** Apply newly available promotions or loyalty rewards\n- **Fulfillment Changes:** Switch between pickup and delivery options\n\n**🔧 Request Format:**\nProvide an `UpdatePreOrderRequest` object with OrderId and the fields to be updated.\n\n**⚠️ Important Notes:**\n- **Status Check:** Use the status endpoint to verify order is still updateable\n- **Inventory Impact:** Item changes may affect product availability\n- **Pricing Recalculation:** Updates may change order totals and taxes\n- **Delivery Validation:** Address changes subject to delivery zone verification", "operationId": "PreorderUpdatePost", "requestBody": { "description": "Update details including OrderId and fields to be modified", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdatePreOrderRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdatePreOrderRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdatePreOrderRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdatePreOrderRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Order updated successfully" }, "400": { "description": "Bad Request - Empty response body (handle via HTTP status code only)" }, "404": { "description": "Not Found - Order ID does not exist" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/preorder/cancel": { "post": { "tags": ["PreOrder"], "summary": "Cancel PreOrder", "description": "**❌ Purpose:** Cancel an existing pre-order and release any reserved inventory.\n\n**🔍 Cancellation Requirements:**\nOrder must be in a cancellable state - use the status endpoint to verify before attempting cancellation.\n\n**✅ Cancellable States:**\n- **Submitted/Pending:** Order not yet started by staff\n- **Processing:** Order in early preparation stages (may vary by location)\n\n**🚫 Non-Cancellable States:**\n- **Checked Out:** Payment has been processed\n- **Filled/Complete:** Order fulfillment finished\n- **Partially Filled:** Some items already prepared/dispensed\n- **In Transit:** Delivery orders already out for delivery\n\n**🔄 Cancellation Effects:**\n- **Inventory Release:** Reserved items returned to available inventory\n- **Payment Handling:** Refunds processed according to payment method\n- **Loyalty Redemptions:** Applied rewards/discounts are restored to customer account\n- **Order Status:** Permanently marked as cancelled\n- **Customer Notification:** Automated notifications sent if configured\n\n**🎯 Common Cancellation Reasons:**\n- **Customer Request:** Customer no longer wants the order\n- **Inventory Issues:** Items became unavailable after order placement\n- **Payment Problems:** Payment processing failed or was declined\n- **Delivery Issues:** Address problems or delivery zone restrictions\n- **Business Operations:** Store closure or emergency situations\n\n**🔧 Request Format:**\nProvide a `CancelPreOrderRequest` object with the OrderId to cancel.\n\n**Performance & Limits:**\n- Rate limited to 240 requests per minute for order management protection\n- Single order cancellation operation for targeted processing\n- Immediate inventory and payment processing upon successful cancellation\n\n**⚠️ Important Notes:**\n- **Irreversible Action:** Cancelled orders cannot be restored or reactivated\n- **Status Verification:** Always check cancellable status before attempting cancellation\n- **Refund Processing:** Payment refunds may take time depending on payment method\n- **Inventory Impact:** Cancellation immediately releases reserved inventory\n- **Customer Communication:** Consider notifying customer of cancellation reason", "operationId": "PreorderCancelPost", "requestBody": { "description": "Cancellation request containing the OrderId to cancel", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CancelPreorderRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CancelPreorderRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CancelPreorderRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CancelPreorderRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Order cancelled successfully", "content": { "application/json": { "schema": { "type": "integer", "format": "int32" } } } }, "400": { "description": "Bad Request - Empty response body (handle via HTTP status code only)" }, "404": { "description": "Not Found - Order ID does not exist" }, "500": { "description": "Internal Server Error - Server error occurred", "content": { "application/json": { "schema": { "type": "string" } } } } } } }, "/preorder/Status": { "get": { "tags": ["PreOrder"], "summary": "Get PreOrder Status", "description": "**📊 Purpose:** Retrieve current status and details for pre-orders to track fulfillment progress.\n\n**🔍 Query Options:**\n- **Specific Order:** Provide PreOrderId to get detailed status for a single order\n- **All Open Orders:** Omit PreOrderId to retrieve all recent active orders (last 14 days)\n- **Line Item Details:** Set includeLineItems=true for detailed product information (requires PreOrderId)\n\n**📋 Status Information Returned:**\n- **Order Details:** Order ID, transaction ID, customer information, timestamps\n- **Current Status:** Order state (Submitted, Processing, Filled, Complete, Cancelled)\n- **Fulfillment Info:** Pickup/delivery details, estimated completion times\n- **Update Permissions:** Whether order can still be modified or cancelled\n- **Payment Status:** Payment processing state and totals\n- **Line Items:** Product details, quantities, allocated inventory (when requested)\n\n**📦 Order Status States:**\n- **Submitted:** Order received and queued for processing\n- **Processing:** Staff actively preparing order items\n- **Filled:** All items prepared and ready for customer\n- **Complete:** Customer has received order (pickup/delivery completed)\n- **Cancelled:** Order cancelled and inventory released\n\n**⚡ Performance Features:**\n- **Optimized for Real-Time:** Designed for frequent status checking and monitoring\n- **Batch Queries:** Retrieve multiple order statuses efficiently without PreOrderId\n- **Selective Detail:** Choose level of detail needed with includeLineItems parameter\n\n**🎯 Common Use Cases:**\n- **Customer Updates:** Provide real-time order progress to customers\n- **Operations Dashboard:** Monitor all active orders across fulfillment workflow\n- **Integration Sync:** Keep external systems updated with current order states\n- **Customer Service:** Quick lookup of order status for support inquiries\n- **Automated Notifications:** Trigger customer alerts based on status changes\n\n**⚠️ Important Notes:**\n- **Line Item Restriction:** includeLineItems requires a specific PreOrderId\n- **Recent Orders Filter:** Bulk queries return orders from last 14 days only\n- **Location Scoped:** Results filtered to authenticated user's location\n- **Real-Time Data:** Status reflects current state, may change during fulfillment", "operationId": "PreorderStatusGet", "parameters": [ { "name": "PreOrderId", "in": "query", "description": "Specific order ID to retrieve status for (optional - omit for all open orders)", "schema": { "type": "integer", "format": "int32" } }, { "name": "includeLineItems", "in": "query", "description": "Include detailed product line item information (requires PreOrderId)", "schema": { "type": "boolean", "default": false } } ], "responses": { "200": { "description": "Success - Returns PreOrderStatus object(s) with current order information", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PreOrderStatus" } } } }, "400": { "description": "Bad Request - Empty response body (handle via HTTP status code only)" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/preorder/price-cart": { "post": { "tags": ["PreOrder"], "summary": "Calculate Cart Pricing", "description": "**💰 Purpose:** Calculate accurate pricing for a cart before order submission, including taxes, discounts, and final totals.\n\n**📋 Required Information:**\n- **Customer Identity:** Either CustomerId (existing customer) OR CustomerTypeId (customer category)\n- **Cart Items:** Array of products with quantities to be priced\n- **Fulfillment Type:** Specify if delivery pricing applies (affects taxes/fees)\n\n**💵 Pricing Components Calculated:**\n- **Subtotal:** Base product prices multiplied by quantities\n- **Taxes:** Location-specific tax rates applied to taxable items\n- **Discounts:** Customer-specific pricing, loyalty discounts, promotional offers\n- **Delivery Fees:** Additional charges for delivery service (if applicable)\n- **Final Total:** Complete order amount including all fees and adjustments\n\n**🎯 Customer Pricing Options:**\n- **Existing Customer:** Use CustomerId for personalized pricing and loyalty benefits\n- **Customer Type:** Use CustomerTypeId for category-based pricing (Medical, Recreational, etc.)\n- **Delivery Context:** Set IsDelivery=true to include delivery-specific pricing\n\n**🔍 Pricing Accuracy:**\n- **Real-Time Calculations:** Pricing reflects current product costs and tax rates\n- **Location-Specific:** Taxes and fees calculated based on dispensary location\n- **Customer-Specific:** Applies individual discounts, loyalty rewards, and membership benefits\n- **Delivery Zones:** Delivery fees calculated based on customer address when provided\n\n**🎯 Common Use Cases:**\n- **Cart Preview:** Show customers accurate totals before checkout\n- **Price Comparison:** Compare costs across different customer types or delivery options\n- **Integration Sync:** Keep external e-commerce platforms synchronized with current pricing\n- **Customer Service:** Provide accurate quotes for customer inquiries\n- **Mobile Apps:** Real-time cart totals for mobile ordering experiences\n\n**🔧 Request Format:**\nProvide a `PriceCartRequest` object with customer information, cart items, and delivery preferences.\n\n**Performance & Limits:**\n- Rate limited to 240 requests per minute for pricing calculation protection\n- Real-time pricing calculations optimized for responsive user experience\n- Single cart operation for immediate pricing feedback\n\n**⚠️ Important Notes:**\n- **Unique Products:** Each product should only appear once in the cart array\n- **Customer Requirement:** Must specify either CustomerId OR CustomerTypeId (not both)\n- **Pricing Volatility:** Prices may change between calculation and order submission\n- **Location Dependency:** Pricing is specific to the authenticated dispensary location\n- **Address Impact:** Delivery address affects tax calculations and delivery fees", "operationId": "PreorderPrice-cartPost", "requestBody": { "description": "Pricing request containing customer information, cart items, and delivery preferences", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/PriceCartRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/PriceCartRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/PriceCartRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/PriceCartRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Returns detailed pricing breakdown for the cart", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CartPrice" } } } }, "400": { "description": "Bad Request - String error message (parse response body as plain text)", "content": { "application/json": { "schema": { "type": "string" } } } }, "500": { "description": "Internal Server Error - Server error occurred during pricing calculation" } } } }, "/pricing-tiers": { "get": { "tags": ["PricingTier"], "summary": "Get Pricing Tiers", "description": "**Purpose:** Retrieves the complete list of pricing tiers available for the authenticated organization for product pricing strategy and customer segmentation.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of pricing tier objects: `[{ PricingTier }, ...]`\n- Array typically contains 2-8 pricing tiers per organization\n- Returns empty array `[]` if no pricing tiers configured (rare)\n- Includes tier ID, name, and configuration details\n- Organization-level pricing tiers for customer segmentation (e.g., \"Retail\", \"Wholesale\", \"Medical\", \"VIP\")\n- Results filtered to authenticated organization level\n\n**Common Use Cases:**\n- Configure product pricing based on customer tier assignments\n- Support tiered pricing strategies for different customer segments\n- Populate pricing tier dropdown lists in customer management forms\n- Validate pricing tier assignments in product and order management systems\n- Generate tier-specific pricing reports and analytics\n- Enable dynamic pricing based on customer classifications\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small dataset suitable for client-side caching\n- No pagination needed due to limited number of pricing tiers\n- Results consistent across all locations within organization\n\n**Related Endpoints:**\n- `GET /products` - Get products with tier-based pricing\n- `GET /customer/customer-types` - Get customer types that may use pricing tiers\n- Pricing calculation endpoints that utilize these tiers\n\n**Important Notes:**\n- Pricing tiers are defined at organization level (LSP) not location level\n- Essential for implementing tiered pricing strategies and customer segmentation\n- Used for dynamic pricing calculations based on customer classifications\n- Supports business models with wholesale, retail, and VIP pricing structures\n- May be used in conjunction with customer types for comprehensive pricing strategies", "operationId": "Pricing-tiersGet", "responses": { "200": { "description": "Success - Returns array of pricing tier objects: `[{ PricingTier }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/PricingTier" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/producers": { "get": { "tags": ["Producer"], "summary": "Get Producers", "description": "**Purpose:** Retrieve basic producer identification information for product attribution and reference data needs.\n\n**Request Requirements:**\n- Valid authentication required for producer data access\n- No request body needed\n- No query parameters required\n\n**Response Data:**\n- Returns array of producer objects: `[{ Producer }, ...]`\n- Array typically contains 1-50 producers per organization\n- Returns empty array `[]` if no producers configured (rare)\n- Producer details include basic identification information only\n- Results automatically filtered to authenticated organization and exclude deleted records\n\n**Producer Information:**\n- **Producer ID**: Unique identifier for the producer\n- **Producer Name**: Display name of the producer\n\n**Common Use Cases:**\n- Populate producer dropdown lists in product management forms\n- Display producer names for product attribution and branding\n- Support basic producer identification in product catalogs\n- Enable producer-based filtering and organization in product displays\n- Provide producer reference data for product creation workflows\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Organization-scoped results for operational relevance and security\n- Small dataset suitable for client-side caching\n- Essential reference data for basic producer identification\n\n**Related Endpoints:**\n- `GET /products` - View products that include producer information\n- `GET /brands` - Related brand information for product attribution\n- `GET /vendors` - Related vendor information and business relationships\n\n**Important Notes:**\n- **Basic Reference Data**: Provides minimal producer identification information\n- **Organization Scoped**: Results filtered to authenticated organization level and exclude deleted records\n- **Limited Data**: Only includes producer ID and name - no licensing, contact, or compliance details\n- **Product Attribution**: Enables basic producer attribution for product displays", "operationId": "ProducersGet", "responses": { "200": { "description": "Success - Returns array of producer objects: `[{ Producer }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Producer" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/products/location-overrides": { "get": { "tags": ["Product"], "summary": "Get Location Product Overrides", "description": "**Purpose:** Retrieve all location-specific product overrides for pricing, availability, and display customization at the current location.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for product override data access\n- No query parameters required\n- No request body needed\n\n**Response Data:**\n- Returns array of `LocationProductOverride` objects with location-specific settings\n- Array typically contains 50-5,000+ overrides depending on location customization\n- Returns empty array `[]` if no overrides exist for the location (not null)\n- If a field is `null`, then the product master version of that field applies\n- Includes pricing overrides, availability settings, and display configurations\n- Results automatically filtered to authenticated location\n\n**Override Behavior:**\n- **Null Fields**: When override field is null, the product master value is used\n- **Set Fields**: When override field has a value, it replaces the master value\n- **Location Specific**: Overrides only apply to the authenticated location\n- **Inheritance**: Non-overridden fields inherit from product master data\n\n**Common Use Cases:**\n- Retrieve location-specific pricing for multi-location businesses\n- Get availability overrides for location inventory management\n- Access display customizations for location-specific product presentation\n- Synchronize location overrides with external point-of-sale systems\n- Generate location-specific product catalogs and pricing sheets\n\n**Performance & Limits:**\n- Optimized for location-specific product management workflows\n- Results filtered automatically to current location scope\n- Efficient for multi-location businesses with location-specific pricing\n- Consider caching for frequent access to override data\n\n**Related Endpoints:**\n- `POST /products/location-overrides` - Create or update location overrides\n- `GET /products` - Get product master data with default values\n- `GET /inventory` - Get current inventory levels for overridden products\n\n**Important Notes:**\n- **Inheritance Model**: Null override fields inherit from product master data\n- **Location Scoped**: Results automatically filtered to authenticated location\n- **Override Priority**: Location overrides take precedence over master product data\n- **Multi-Location**: Essential for businesses operating multiple dispensary locations\n- **Pricing Control**: Enables location-specific pricing strategies and market adaptation", "operationId": "ProductsLocation-overridesGet", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LocationProductOverride" } } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } }, "post": { "tags": ["Product"], "summary": "Create or Update Location Product Overrides", "description": "**Purpose:** Create or update location-specific product overrides for pricing, availability, and display customization to support multi-location business operations.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for product override modification\n- Array of `LocationProductOverrideRequest` objects in request body\n- Content-Type: application/json\n- Valid ProductId required for each override\n\n**Response Data:**\n- Returns HTTP 200 with no response body on success\n- No data returned - operation confirmation only\n- Returns HTTP 400 with validation errors if request data is invalid\n- Partial success possible: some overrides may save even if others fail\n\n**Create vs Update Behavior:**\n- **CREATE**: When no existing override exists for the ProductId at this location, a new override is created\n- **UPDATE**: When an override already exists for the ProductId at this location, it is updated\n- **Identification**: Override existence determined by ProductId and authenticated location\n- **Automatic Detection**: System automatically determines create vs update based on existing data\n\n**Sparse Update Behavior:**\n- **Omitted Fields**: Retain their current override value (no change)\n- **Null Values**: Remove the override for that field (product master value will apply)\n- **Set Values**: Update the override with the provided value\n- **Field Independence**: Each field can be updated independently without affecting others\n\n**Override Management:**\n- **Removal**: Set fields to null to remove overrides and revert to product master values\n- **Addition**: Set fields to specific values to create new overrides\n- **Location Scoped**: All overrides apply only to the authenticated location\n- **Dual Pricing**: Automatically handles recreational price sync when dual pricing is disabled\n\n**Common Use Cases:**\n- Set location-specific pricing for multi-location businesses\n- Override product availability for location inventory management\n- Customize product display settings for location-specific presentation\n- Manage location-based pricing strategies and market adaptation\n- Synchronize pricing changes from external systems to specific locations\n\n**Performance & Limits:**\n- Batch processing for efficient multi-product override updates\n- Validation performed before any changes to ensure data integrity\n- Partial success handling: some overrides may succeed even if others fail\n- Optimized for location-specific product management workflows\n\n**Related Endpoints:**\n- `GET /products/location-overrides` - Retrieve current location overrides\n- `GET /products` - Get product master data for comparison\n- `GET /inventory` - Check inventory levels for overridden products\n\n**Important Notes:**\n- **Partial Success**: Some overrides may save successfully even if others fail validation\n- **Null Behavior**: Setting fields to null removes overrides and reverts to master data\n- **Location Isolation**: Overrides only affect the authenticated location\n- **Validation Required**: All ProductIds must exist and be valid for the location\n- **Dual Pricing Sync**: Recreational prices automatically sync with medical when dual pricing disabled", "operationId": "ProductsLocation-overridesPost", "requestBody": { "description": "Array of location product override requests with ProductId and override values - LocationProductOverrideRequest objects", "content": { "application/json-patch+json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LocationProductOverrideRequest" } } }, "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LocationProductOverrideRequest" } } }, "text/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LocationProductOverrideRequest" } } }, "application/*+json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LocationProductOverrideRequest" } } } }, "x-bodyName": "updates" }, "responses": { "200": { "description": "Success" }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)" }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong. One or more overrides may have been saved" } } } }, "/products": { "get": { "tags": ["Product"], "summary": "Get Products", "description": "**Purpose:** Retrieve comprehensive product catalog information for API-enabled products, regardless of current inventory levels.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for product data access\n- Optional query parameters for filtering results\n- No request body needed\n\n**Response Data:**\n- Returns array of product objects: `[{ ProductDetail }, ...]`\n- Array may contain 0 to 10,000+ products depending on location inventory size\n- Returns empty array `[]` if no products match criteria (not null)\n- Product details including SKU, name, description, category, brand, strain information\n- Pricing data with retail and medical pricing, tax rates, discount eligibility\n- Classification data including product types, categories, regulatory classifications\n- Lab results with potency data, cannabinoid profiles, test results when available\n- Inventory data showing stock levels and availability status\n- Media assets including product images and visual content\n- Compliance data with external IDs, producer information, regulatory data\n\n**Filtering Options:**\n- No parameters: Returns all API-enabled products for the location\n- fromLastModifiedDateUTC: Returns products modified after this date for incremental sync\n- isActive: Filter by active status (true/false/null for all)\n\n**Product Filtering Logic:**\n- Only products specifically enabled for API access are returned\n- Only includes products with online availability enabled (onlyOnlineAvailable = true)\n- Products returned even if currently out of stock\n- Results automatically filtered to authenticated user's location only\n\n**Common Use Cases:**\n- Get complete product catalog for first-time integration setup\n- Use incremental updates with fromLastModifiedDateUTC to sync only recent changes\n- Populate e-commerce online store with complete product information\n- Maintain up-to-date product database for point-of-sale systems\n- Build dispensary menus with detailed product information\n- Analyze product catalog for purchasing and inventory planning decisions\n\n**Performance & Limits:**\n- Use incremental sync with fromLastModifiedDateUTC for regular updates to minimize data transfer\n- Filter by isActive=true to exclude discontinued products for better performance\n- Run full catalog sync during off-peak hours for optimal performance\n- Large product catalogs may require pagination in future versions\n\n**Related Endpoints:**\n- `GET /inventory` - Current stock levels for products with available inventory\n- `GET /products/strains` - Strain-specific information and genetics data\n- `GET /products/external-categories` - Product categorization and classification data\n\n**Important Notes:**\n- This endpoint respects the \"API access\" setting on products for access control\n- Returns only online-available products (excludes products not enabled for online sales)\n- Response includes comprehensive product information for full integration capabilities\n- Products are automatically filtered to the authenticated location", "operationId": "ProductsGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Optional date filter to return only products modified after this timestamp - Used for incremental sync", "schema": { "type": "string", "format": "date-time" } }, { "name": "isActive", "in": "query", "description": "Optional status filter - true for active products only, false for inactive only, null for all products", "schema": { "type": "boolean" } } ], "responses": { "200": { "description": "Success - Returns array of product objects: `[{ ProductDetail }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ProductDetail" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for inventory access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/products/product": { "post": { "tags": ["Product"], "summary": "Create or Update Product", "description": "**Purpose:** Creates a new product or updates an existing product with comprehensive product information for inventory management.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for product data access\n- `ProductDetailUpload` object in request body with product details\n- Content-Type: application/json\n- SKU and ProductName required for new products\n\n**Response Data:**\n- Returns single `ProductDetail` object (not array) with updated product information\n- Response format: `{ ProductDetail }`\n- Includes assigned product ID for new products or updated ID for existing products\n- Complete product information with all fields populated\n\n**CRITICAL DATA LOSS WARNING:**\nMost fields will be overwritten with null/zero values if not provided in the request.\nRECOMMENDED APPROACH: First GET the existing product, modify only the fields you want to change, then POST the complete object back.\n\n**Required Fields:**\n- For CREATE: SKU and ProductName are required\n- For UPDATE: Only ProductId is required (SKU and ProductName can be omitted to preserve existing values)\n\n**Field Behavior:**\n- Optional Fields: Can be explicitly set to null or omitted to preserve existing values\n- Regular Fields: Will be set to null/zero if omitted, potentially causing data loss\n- Exception: Fields like SKU and ProductName preserve existing values when omitted during updates\n\n**Common Use Cases:**\n- Add new products to the catalog for inventory management\n- Update existing product information when details change\n- Synchronize product data from external inventory systems\n- Bulk product updates for pricing or categorization changes\n- Maintain accurate product information for compliance and sales\n\n**Performance & Limits:**\n- Single product operation for targeted updates\n- Immediate validation and response\n- Changes reflected immediately in product catalogs\n- Consider using GET before POST to avoid data loss\n\n**Related Endpoints:**\n- `GET /products` - Retrieve existing product data before updates\n- `GET /brand` - Get valid brand IDs for product association\n- `GET /strains` - Get valid strain IDs for product classification\n\n**Important Notes:**\n- Data loss risk: Always retrieve existing product data before updates\n- Product ID assignment for successful new product creation\n- Validation performed before creation/update to ensure data integrity\n- Changes propagate to inventory and sales systems immediately", "operationId": "ProductsProductPost", "requestBody": { "description": "Product information to create or update - ProductDetailUpload object with product details", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/ProductDetailUpload" } }, "application/json": { "schema": { "$ref": "#/components/schemas/ProductDetailUpload" } }, "text/json": { "schema": { "$ref": "#/components/schemas/ProductDetailUpload" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/ProductDetailUpload" } } }, "x-bodyName": "product" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductDetail" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/products/products": { "post": { "tags": ["Product"], "summary": "Bulk Create or Update Products", "description": "**Purpose:** Create or update multiple products in a single operation for efficient catalog management and bulk data synchronization.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for product data operations\n- Array of `ProductDetailUpload` objects in request body with product details\n- Content-Type: application/json\n- Each product requires SKU and ProductName for creation, ProductId for updates\n\n**Response Data:**\n- Returns mixed array: `[{ ProductDetail }, { SaveProductError }, ...]`\n- Successful operations return complete `ProductDetail` objects with updated product information\n- Failed operations return `SaveProductError` objects with ProductId, SKU, ProductName, and ErrorMessage\n- HTTP 200 for successful processing - check individual items in response array for success/error status\n- HTTP 400 for validation errors that prevent processing\n- Mixed array allows partial success - some products may succeed while others fail\n\n**CRITICAL DATA LOSS WARNING:**\nMost fields will be overwritten with null/zero values if not provided in the request.\n**RECOMMENDED APPROACH:** First GET existing products, modify only desired fields, then POST complete objects back.\n\n**Create vs Update Behavior:**\n- **CREATE**: When ProductId is null or omitted, new product records will be created\n- **UPDATE**: When ProductId is provided with valid product IDs, existing products will be updated\n- **Mixed Operations**: Single request can include both create and update operations\n- **Validation**: SKU and ProductName required for creates, ProductId required for updates\n- **Individual Processing**: Each product processed independently - some may succeed while others fail\n\n**Field Preservation Behavior:**\n- **Optional Fields**: Can be explicitly set to null or omitted to preserve existing values\n- **Regular Fields**: Will be set to null/zero if omitted, potentially causing data loss\n- **Preserved Fields**: SKU and ProductName preserve existing values when omitted during updates\n- **Best Practice**: Always provide complete product objects to avoid unintended data loss\n\n**Error Handling:**\n- **Partial Success**: Some products may succeed while others fail within the same request\n- **Error Identification**: Failed products include ErrorMessage, ProductId, SKU, and ProductName\n- **Validation Errors**: Returns HTTP 400 for validation errors that prevent processing\n- **Processing Errors**: Returns HTTP 200 with mixed results for individual product errors\n- **Rollback Behavior**: No automatic rollback - successful operations persist even if others fail\n\n**Common Use Cases:**\n- Import large product catalogs from external systems efficiently\n- Synchronize product changes across multiple products simultaneously\n- Bulk update pricing, categorization, or product attributes\n- Migrate product data between systems with batch processing\n- Update multiple products after inventory or regulatory changes\n\n**Performance & Limits:**\n- Optimized for bulk product operations and catalog management\n- Individual product validation and processing for data integrity\n- No automatic external system broadcasting for performance\n- Efficient for large-scale product catalog updates\n\n**Related Endpoints:**\n- `GET /products` - Retrieve existing product data before bulk updates\n- `POST /products/product` - Create or update individual products with external sync\n- `GET /brand` - Get valid brand IDs for product associations\n- `GET /strains` - Get valid strain IDs for product classifications\n\n**Important Notes:**\n- **Individual Processing**: Each product processed independently with separate success/failure results\n- **No External Broadcast**: Traceability system broadcasting not supported on this endpoint\n- **Data Loss Risk**: Always retrieve existing product data before bulk updates\n- **Error Checking Required**: Always check response for individual product errors\n- **Performance Optimized**: Designed for efficient bulk operations without external system overhead", "operationId": "ProductsProductsPost", "requestBody": { "description": "Array of product information to create or update - IEnumerable objects", "content": { "application/json-patch+json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ProductDetailUpload" } } }, "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ProductDetailUpload" } } }, "text/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ProductDetailUpload" } } }, "application/*+json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ProductDetailUpload" } } } }, "x-bodyName": "products" }, "responses": { "200": { "description": "Success - Products processed with individual success/error results", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "object" } } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors) OR `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/products/set-image": { "post": { "tags": ["Product"], "summary": "Set Product Image", "description": "**Purpose:** Add or update a single image for a product to enhance product presentation and visual merchandising.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for product image management\n- `SetImageRequest` object in request body with ProductId and image data\n- Content-Type: application/json\n- Valid ProductId and base64-encoded image data required\n\n**Response Data:**\n- Returns single image response object: `{ SetImageResponse }`\n- Includes unique image ID for future image management operations\n- Provides image URL for immediate access to uploaded image\n- Contains ImageId (integer) and ImageUrl (string) fields only\n\n**Image Processing:**\n- **Single Image**: Adds one image per request to the specified product\n- **Image ID Assignment**: Returns unique DPOS product image ID for tracking\n- **Format Support**: Supports standard image formats via base64 encoding\n- **Validation**: Validates image data and product existence before processing\n\n**Integration Behavior:**\n- **Metrc Integration**: If using Metrc with upload product images enabled, the image will automatically upload to Metrc on next product save\n- **Automatic Sync**: Integration occurs when `Save Product` is called for this ProductId\n- **Compliance**: Supports regulatory compliance through integrated system image sync\n- **External Systems**: Compatible with cultivation and compliance system requirements\n\n**Common Use Cases:**\n- Add product photos for e-commerce and point-of-sale display\n- Update existing product images for marketing and merchandising\n- Comply with regulatory requirements for product visual documentation\n- Enhance customer experience with high-quality product imagery\n- Support integrated systems with automated image synchronization\n\n**Performance & Limits:**\n- Single image processing for targeted product updates\n- Base64 encoding for secure image data transmission\n- Validation performed before processing to ensure data integrity\n- Optimized for product visual merchandising workflows\n\n**Related Endpoints:**\n- `POST /products/remove-image` - Remove product images using the returned image ID\n- `POST /products/product` - Save product data and trigger Metrc image sync\n- `GET /products` - Retrieve products with associated image information\n\n**Important Notes:**\n- **Image ID Required**: Save the returned image ID for future image management operations\n- **Metrc Auto-Upload**: Images automatically sync to Metrc on next product save when enabled\n- **Single Operation**: One image per request - use multiple requests for multiple images\n- **Validation Required**: ProductId must exist and image data must be valid\n- **Integration Ready**: Supports automated compliance system synchronization", "operationId": "ProductsSet-imagePost", "requestBody": { "description": "Image upload request with ProductId and base64 image data - SetImageRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/SetImageRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/SetImageRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/SetImageRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/SetImageRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SetImageResponse" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/products/remove-image": { "post": { "tags": ["Product"], "summary": "Delete Product Image", "description": "**Purpose:** Remove a specific image from a product using the image ID to maintain clean product presentation and manage visual merchandising.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for product image management\n- `DeleteImageRequest` object in request body with ProductId and ImageId\n- Content-Type: application/json\n- Valid ProductId and ImageId required (ImageId obtained from set-image response)\n\n**Response Data:**\n- Returns success confirmation object: `{ SuccessResult }`\n- Simple success confirmation with HTTP 200 status\n- No additional data fields returned beyond success indicator\n\n**Image Removal Process:**\n- **Targeted Deletion**: Removes specific image identified by ImageId\n- **Product Association**: Verifies image belongs to the specified ProductId\n- **Validation**: Ensures both ProductId and ImageId exist and are valid\n- **Clean Removal**: Permanently removes image from product and storage systems\n\n**Safety & Validation:**\n- **Existence Check**: Validates ProductId and ImageId before deletion\n- **Ownership Verification**: Ensures image belongs to the specified product\n- **Authorization**: Confirms user has permission to modify product images\n- **Error Handling**: Returns appropriate errors for invalid requests\n\n**Common Use Cases:**\n- Remove outdated or incorrect product images from visual merchandising\n- Clean up product galleries by deleting unwanted or duplicate images\n- Manage product image lifecycle for marketing and compliance requirements\n- Maintain accurate product representation in e-commerce and point-of-sale systems\n- Support product image management workflows and content updates\n\n**Performance & Limits:**\n- Single image deletion for targeted image management\n- Immediate removal from product and storage systems\n- Validation performed before deletion to ensure data integrity\n- Optimized for product visual merchandising and content management workflows\n\n**Related Endpoints:**\n- `POST /products/set-image` - Add images and obtain ImageId for future deletion\n- `GET /products` - Retrieve products with current image information\n- `POST /products/product` - Update product data and manage overall product information\n\n**Important Notes:**\n- **ImageId Required**: Use ImageId returned from set-image endpoint for deletion\n- **Permanent Operation**: Image deletion is permanent and cannot be undone\n- **Validation Critical**: Both ProductId and ImageId must be valid and associated\n- **Single Target**: One image per request - use multiple requests for multiple deletions\n- **Clean Management**: Essential for maintaining organized product image galleries", "operationId": "ProductsRemove-imagePost", "requestBody": { "description": "Image deletion request with ProductId and ImageId - DeleteImageRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/DeleteImageRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/DeleteImageRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/DeleteImageRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/DeleteImageRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SuccessResult" } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/products/strains": { "get": { "tags": ["Product"], "summary": "Get Product Strains", "description": "**Purpose:** Retrieve all available cannabis strains for product classification and inventory management in compliance with industry standards.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for strain data access\n- No query parameters required\n- No request body needed\n\n**Response Data:**\n- Returns array of strain objects: `[{ StrainDetail }, ...]`\n- Array typically contains 50-1,000+ strains depending on dispensary catalog\n- Returns empty array `[]` if no strains are configured (not null)\n- Basic strain information including ID, name, description, type, and external ID\n- Results automatically filtered to authenticated location strain catalog\n\n**Strain Information:**\n- **Strain ID**: Unique identifier for the strain\n- **Strain Name**: Display name of the strain\n- **Strain Description**: Basic text description of the strain\n- **Strain Abbreviation**: Short code or abbreviation for the strain\n- **Strain Type**: Basic type classification (e.g., Indica, Sativa, Hybrid)\n- **External ID**: External system identifier for integration\n\n**Common Use Cases:**\n- Populate strain dropdown lists in product creation and management forms\n- Display basic strain information for product attribution\n- Support strain-based product categorization and filtering\n- Enable strain identification in inventory management systems\n- Provide strain reference data for product classification workflows\n\n**Performance & Limits:**\n- Optimized for product classification and strain selection workflows\n- Comprehensive strain database for complete cannabis product categorization\n- Results filtered to location-specific strain catalog\n- Efficient for strain-based product search and filtering operations\n\n**Related Endpoints:**\n- `GET /products` - View products with assigned strain classifications\n- `POST /products/product` - Assign strains to products during creation/update\n- `GET /strains` - Manage strain master data and configurations\n\n**Important Notes:**\n- **Basic Reference Data**: Provides essential strain identification information only\n- **Limited Data**: Only includes basic strain details - no cannabinoid profiles, genetics, or effects\n- **Product Classification**: Strains used for basic product categorization and identification\n- **Location Catalog**: Results filtered to strains available for the authenticated location\n- **External Integration**: Includes External ID for traceability system integration", "operationId": "ProductsStrainsGet", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/StrainDetail" } } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/products/external-categories": { "get": { "tags": ["Product"], "summary": "Get External Categories", "description": "**Purpose:** Retrieve external system categories for product classification to support integration with traceability and compliance systems.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for external category data access\n- UserId query parameter highly recommended for traceability system integration\n- No request body needed\n\n**Response Data:**\n- Returns array of string values with external category names\n- Response format: `[string, string, ...]`\n- Array contains categories available from integrated traceability systems\n- Returns empty array `[]` if no external categories are available (not null)\n- Category names correspond to external system classification standards\n- Used for populating ExternalCategory field in product data\n- Results depend on configured integrated systems and user permissions\n\n**Integration Requirements:**\n- **Traceability Systems**: Categories pulled from connected compliance systems (e.g., Metrc, BioTrack)\n- **User Context**: UserId parameter provides system access context for category retrieval\n- **System Configuration**: Available categories depend on integrated system configuration\n- **Compliance Mapping**: Categories align with regulatory compliance requirements\n\n**Parameter Guidelines:**\n- **UserId**: Technically optional but highly recommended for traceability system calls\n- **System Failure**: Call may fail without UserId when categories come from traceability systems\n- **Permission Context**: UserId provides proper system access permissions for category retrieval\n- **Default Fallback**: Uses default user (ID 6) when UserId not provided\n\n**Common Use Cases:**\n- Populate product ExternalCategory field with valid compliance categories\n- Synchronize product classifications with regulatory traceability systems\n- Ensure product categories align with state compliance requirements\n- Support automated product categorization for integrated systems\n- Validate product classifications against external system standards\n\n**Performance & Limits:**\n- Real-time integration with external traceability systems\n- Response time dependent on external system availability\n- Error handling for external system connectivity issues\n- Optimized for product classification and compliance workflows\n\n**Related Endpoints:**\n- `POST /products/product` - Use external categories in ExternalCategory field\n- `GET /products` - View products with assigned external categories\n- `POST /products/products` - Bulk assign external categories to products\n\n**Important Notes:**\n- **UserId Critical**: Highly recommended to prevent traceability system call failures\n- **External Dependency**: Categories sourced from integrated traceability systems\n- **Compliance Essential**: External categories required for regulatory compliance\n- **System Specific**: Available categories depend on configured integrated systems\n- **Error Handling**: May return errors if external systems are unavailable", "operationId": "ProductsExternal-categoriesGet", "parameters": [ { "name": "userId", "in": "query", "description": "User ID for traceability system access context (highly recommended) - Optional but prevents system failures", "schema": { "type": "integer", "format": "int32" } } ], "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } } } } }, "400": { "description": "Bad Request - String error message (parse response body as plain text)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/product-category": { "get": { "tags": ["ProductCategory"], "summary": "Get Product Categories", "description": "**Purpose:** Retrieves the complete list of product categories available for the authenticated organization for product classification and menu organization.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of product category objects: `[{ ProductCategory }, ...]`\n- Array typically contains 10-30 product categories per organization\n- Returns empty array `[]` if no categories configured (rare)\n- Includes category ID, name, and master category classification\n- Standard cannabis product categories (Flower, Edibles, Concentrates, etc.)\n- Results filtered to authenticated organization level and exclude deleted records\n\n**Common Use Cases:**\n- Populate product category dropdown lists in product creation forms\n- Organize product menus by category for customer browsing\n- Validate product categorization in inventory management systems\n- Generate category-specific reports for sales analytics\n- Support e-commerce product filtering and navigation\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small dataset suitable for client-side caching\n- No pagination needed due to limited number of categories\n- Results consistent across all locations within organization\n\n**Related Endpoints:**\n- `GET /products` - Get products that use these categories\n- `POST /product` - Create products with category assignments\n- `GET /regulatory-category` - Get regulatory category classifications\n\n**Important Notes:**\n- Categories are defined at organization level (LSP) not location level\n- Standard cannabis industry categories for compliance and consistency\n- Used for product menu organization and customer filtering\n- Essential reference data for product management workflows", "operationId": "Product-categoryGet", "responses": { "200": { "description": "Success - Returns array of product category objects: `[{ ProductCategory }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ProductCategory" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/purchase-order": { "get": { "tags": ["PurchaseOrder"], "summary": "Get Purchase Orders", "description": "**Purpose:** Retrieve purchase orders with comprehensive filtering options to support procurement management and vendor relationship tracking.\n\n**Request Requirements:**\n- \"PurchaseOrder\" role authorization required for purchase order data access\n- Optional query parameters available for filtering purchase orders\n- Purchase order management permissions for procurement operations\n\n**Response Data:**\n- Response format: `[{ PurchaseOrderData }, { PurchaseOrderData }, ...]`\n- **No pagination metadata**: Response contains only data array without total counts or page information\n- Array contains up to PageSize purchase orders (default 1000)\n- Returns empty array `[]` if no purchase orders match filtering criteria\n- Includes comprehensive purchase order details and line item information\n- Results automatically filtered to authenticated location\n\n**Pagination Usage:**\n- **First Request**: Call with PageNumber=0 to get first page\n- **Subsequent Requests**: Increment PageNumber for each additional page\n- **End Detection**: Continue requesting pages until you receive an empty array `[]`\n- **Page Size Control**: Use PageSize parameter to control items per page\n- **Example Flow**: Request PageNumber=0 → Process results → Increment PageNumber → Repeat until empty `[]` response\n\n**Pagination Detection:**\n- **End of data detection**: Continue requesting pages until you receive an empty array `[]`\n- **No metadata provided**: Response does not include total counts, page counts, or hasNextPage indicators\n- **Sequential access**: Increment PageNumber from 0 until empty response indicates no more data\n\n**Filtering Options:**\n- **FromDateCreated**: Optional date parameter to filter orders created after specific date\n- **ToDateCreated**: Optional date parameter to filter orders created before specific date\n- **PurchaseOrderId**: Optional integer parameter to retrieve specific purchase order\n- **IncludeItemDetails**: Optional boolean to include detailed line item information\n\n**Purchase Order Information Included:**\n- **Order Details**: Purchase order identification, status, and vendor information\n- **Line Items**: Product details and quantities (when IncludeItemDetails is true)\n- **Dates**: Creation, modification, and expected delivery dates\n- **Financial Data**: Order totals, costs, and payment information\n\n**Common Use Cases:**\n- Display purchase orders for procurement management and vendor tracking\n- Filter orders by date ranges for reporting and analysis\n- Retrieve specific purchase orders for detailed review and management\n- Support vendor relationship management and procurement workflows\n- Generate procurement reports and purchase order analytics\n\n**Performance & Limits:**\n- Use consistent page size throughout pagination sequence for efficiency\n- Monitor response times and adjust page size for optimal performance\n- Cache results locally to minimize API calls and improve responsiveness\n- Validation performed on all query parameters before processing\n- Optimized for procurement management and vendor tracking workflows\n\n**Related Endpoints:**\n- `POST /purchase-order` - Create or update purchase orders\n- `GET /vendors` - View vendors associated with purchase orders\n- `GET /inventory` - View inventory levels for procurement planning\n\n**Important Notes:**\n- **Procurement Integration**: Essential for vendor management and procurement workflows\n- **Flexible Filtering**: Multiple parameters can be combined for precise order lookup\n- **Location Scoped**: Purchase orders filtered to authenticated location operations\n- **Validation Required**: All query parameters validated before purchase order retrieval", "operationId": "Purchase-orderGet", "parameters": [ { "name": "FromDateCreated", "in": "query", "description": "Start date filter for purchase orders created after this date (optional).", "schema": { "type": "string", "format": "date-time" } }, { "name": "ToDateCreated", "in": "query", "description": "End date filter for purchase orders created before this date (optional).", "schema": { "type": "string", "format": "date-time" } }, { "name": "PurchaseOrderId", "in": "query", "description": "Specific purchase order identifier for single order retrieval (optional).", "schema": { "type": "integer", "format": "int32" } }, { "name": "IncludeItemDetails", "in": "query", "description": "Whether to include detailed line item information in the response (default: false).", "schema": { "type": "boolean" } }, { "name": "PageNumber", "in": "query", "description": "Page number for pagination control (default: 0).", "schema": { "type": "integer", "format": "int32" } }, { "name": "PageSize", "in": "query", "description": "Number of results per page for pagination (default: 1000).", "schema": { "type": "integer", "format": "int32" } } ], "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/PurchaseOrderData" } } } } }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } }, "post": { "tags": ["PurchaseOrder"], "summary": "Create or Update Purchase Orders", "description": "**Purpose:** Create new purchase orders or update existing purchase orders for procurement management and vendor relationship operations.\n\n**Request Requirements:**\n- \"PurchaseOrder\" role authorization required for purchase order modification\n- `CreateUpdatePurchaseOrdersRequest` object in request body with purchase order details\n- Content-Type: application/json\n- Purchase order management permissions for procurement operations\n\n**Response Data:**\n- Returns result object with purchase order creation/update status\n- Response format: `{ \"createdPurchaseOrderIds\": [int, ...], \"updatedPurchaseOrderIds\": [int, ...] }`\n- Includes arrays of created and updated purchase order IDs\n- Purchase order identification and processing results\n\n**Create vs Update Behavior:**\n- **CREATE**: When PurchaseOrderId is null, a new purchase order will be created\n- **UPDATE**: When PurchaseOrderId is non-null, the existing purchase order will be updated\n- **Identification**: Purchase order existence determined by PurchaseOrderId value\n- **Line Item Updates**: Updates affect both purchase order header and line item details\n\n**Purchase Order Data Fields:**\n- **Header Information**: Vendor details, order dates, and procurement specifications\n- **Line Items**: Product details, quantities, costs, and delivery requirements\n- **Financial Data**: Order totals, taxes, and payment terms\n- **Status Information**: Order status and processing workflow details\n\n**Common Use Cases:**\n- Create new purchase orders for vendor procurement operations\n- Update existing purchase orders with revised quantities or specifications\n- Modify purchase order line items for procurement adjustments\n- Support vendor relationship management and procurement workflows\n- Maintain accurate procurement records and vendor tracking\n\n**Performance & Limits:**\n- Validation performed before any purchase order processing\n- Batch processing for multiple purchase order operations\n- Optimized for procurement management and vendor tracking workflows\n- Changes reflected immediately in procurement and vendor systems\n\n**Related Endpoints:**\n- `GET /purchase-order` - Retrieve purchase orders for review before updates\n- `GET /vendors` - View vendors for purchase order creation\n- `GET /inventory` - Check inventory levels for procurement planning\n\n**Important Notes:**\n- **Validation Critical**: All purchase order data validated before processing\n- **Procurement Integration**: Purchase orders affect vendor management and procurement workflows\n- **Location Scoped**: Purchase orders automatically associated with authenticated location\n- **Batch Processing**: Multiple purchase orders can be processed in single operation\n- **Vendor Relationships**: Purchase order creation strengthens vendor tracking and management", "operationId": "Purchase-orderPost", "requestBody": { "description": "Purchase order creation/update request with order details - CreateUpdatePurchaseOrdersRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CreateUpdatePurchaseOrdersRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CreateUpdatePurchaseOrdersRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CreateUpdatePurchaseOrdersRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CreateUpdatePurchaseOrdersRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateUpdatePurchaseOrderResponse" } } } }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/reference/units": { "get": { "tags": ["ReferenceData"], "summary": "Get Units", "description": "**Purpose:** Retrieves the complete list of measurement units available for product tracking and inventory management.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of unit objects: `[{ Unit }, ...]`\n- Array typically contains 20-30 measurement units\n- Returns empty array `[]` if no units configured (rare)\n- Includes unit ID, name, abbreviation, and conversion factors\n- Standard measurement units (grams, ounces, pounds, units, etc.)\n- Essential reference data for product weight and quantity tracking\n\n**Common Use Cases:**\n- Configure product measurement units in inventory systems\n- Support weight-based pricing and inventory calculations\n- Validate unit measurements in product and package operations\n- Generate reports with proper unit conversions and formatting\n- Enable accurate compliance reporting with regulatory weight requirements\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small static dataset suitable for client-side caching\n- No pagination needed due to limited number of standard units\n- Consistent across all organizations and locations\n\n**Related Endpoints:**\n- `GET /reference/unit-types` - Get unit type classifications\n- `GET /products` - Get products with unit measurements\n- `GET /inventory` - Get inventory with unit-based quantities\n\n**Important Notes:**\n- Standard cannabis industry measurement units for compliance\n- Essential for accurate weight tracking and regulatory reporting\n- Used throughout the system for product and inventory operations\n- Supports both metric and imperial measurement systems", "operationId": "ReferenceUnitsGet", "responses": { "200": { "description": "Success - Returns array of unit objects: `[{ Unit }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Unit" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reference/unit-types": { "get": { "tags": ["ReferenceData"], "summary": "Get Unit Types", "description": "**Purpose:** Retrieves the complete list of unit type classifications used to categorize different measurement units.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of unit type objects: `[{ UnitType }, ...]`\n- Array typically contains 5-10 unit type categories\n- Returns empty array `[]` if no unit types configured (rare)\n- Includes type ID, name, and category descriptions\n- Unit type categories (Weight, Volume, Count, etc.) for measurement classification\n- Reference data for organizing units by measurement type\n\n**Common Use Cases:**\n- Organize units by measurement type in user interfaces\n- Validate unit assignments based on product type requirements\n- Support advanced filtering and categorization of measurement units\n- Enable proper unit selection based on product characteristics\n- Generate reports organized by measurement type categories\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small static dataset suitable for client-side caching\n- No pagination needed due to limited number of unit types\n- Consistent across all organizations and locations\n\n**Related Endpoints:**\n- `GET /reference/units` - Get specific units within these types\n- `GET /products` - Get products using typed unit measurements\n- `GET /inventory` - Get inventory with type-based unit tracking\n\n**Important Notes:**\n- Standard measurement type categories for consistent classification\n- Helps organize units for better user experience and validation\n- Used for advanced unit selection and validation logic\n- Essential for proper measurement type categorization", "operationId": "ReferenceUnit-typesGet", "responses": { "200": { "description": "Success - Returns array of unit type objects: `[{ UnitType }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/UnitType" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reference/lab-result-units": { "get": { "tags": ["ReferenceData"], "summary": "Get Lab Result Units", "description": "**Purpose:** Retrieves the complete list of measurement units specifically used for laboratory test results and cannabinoid/terpene reporting.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of lab result unit objects: `[{ LabResultUnitData }, ...]`\n- Array typically contains 5-15 specialized lab measurement units\n- Returns empty array `[]` if no lab units configured (rare)\n- Includes lab result unit ID and unit name/abbreviation\n- Specialized units for cannabinoid and terpene concentration measurements\n- Essential reference data for laboratory test result reporting\n\n**Common Use Cases:**\n- Configure lab result units in testing and compliance systems\n- Validate unit measurements in laboratory data submissions\n- Support cannabinoid and terpene concentration reporting\n- Generate compliance reports with proper lab result unit formatting\n- Enable accurate potency testing and COA (Certificate of Analysis) generation\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small static dataset suitable for client-side caching\n- No pagination needed due to limited number of lab result units\n- Consistent across all organizations and locations\n\n**Related Endpoints:**\n- `GET /reference/lab-results-names` - Get available lab result names\n- `GET /reference/units` - Get general measurement units\n- Lab result POST endpoints (for submitting test data)\n\n**Important Notes:**\n- Specialized units for cannabis laboratory testing and analysis\n- Essential for compliance with cannabis testing regulations\n- Used specifically for cannabinoid and terpene concentration measurements\n- Required for accurate Certificate of Analysis (COA) reporting\n- Different from general product measurement units", "operationId": "ReferenceLab-result-unitsGet", "responses": { "200": { "description": "Success - Returns array of lab result unit objects: `[{ LabResultUnitData }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LabResultUnitData" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reference/lab-results-names": { "get": { "tags": ["ReferenceData"], "summary": "Get Lab Result Names", "description": "**Purpose:** Retrieves the complete list of available lab result names that can be used with lab result POST endpoints for cannabinoid and terpene testing.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of strings with valid lab result names: `[\"string\", ...]`\n- Array typically contains 50-100 cannabinoid and terpene names\n- Returns empty array `[]` if no lab result names configured (rare)\n- Standard cannabinoid names (THC, CBD, CBG, CBN, etc.)\n- Common terpene names (Myrcene, Limonene, Pinene, etc.)\n- All acceptable values for lab result name validation\n\n**Common Use Cases:**\n- Validate lab result names before submitting test data\n- Populate dropdown lists for lab result entry forms\n- Reference data for cannabinoid and terpene testing workflows\n- Support laboratory data integration and validation\n- Generate dynamic forms for Certificate of Analysis (COA) entry\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Static dataset suitable for client-side caching\n- No pagination needed due to manageable list size\n- Consistent across all organizations and locations\n\n**Related Endpoints:**\n- `GET /reference/lab-result-units` - Get valid units for these results\n- Lab result POST endpoints - Submit test data using these names\n- `GET /products` - Get products with lab result data\n\n**Important Notes:**\n- These are the only valid values accepted for lab result names\n- Standard cannabis testing terminology for consistency\n- Essential for proper cannabinoid and terpene data submission\n- Used throughout the system for lab result validation\n- Required for compliance with cannabis testing standards", "operationId": "ReferenceLab-results-namesGet", "responses": { "200": { "description": "Success - Returns array of strings with lab result names: `[\"string\", ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/regulatory-category": { "get": { "tags": ["RegulatoryCategory"], "summary": "Get Regulatory Categories", "description": "**Purpose:** Retrieves the complete list of regulatory categories available for the authenticated location for compliance reporting and state-mandated product classification.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of regulatory category objects: `[{ RegulatoryCategory }, ...]`\n- Array typically contains 5-20 regulatory categories per jurisdiction\n- Returns empty array `[]` if no regulatory categories configured (rare)\n- Includes category ID, name, and state-specific compliance codes\n- State-mandated product categories for regulatory reporting (varies by jurisdiction)\n- Results filtered to authenticated location's regulatory requirements\n\n**Common Use Cases:**\n- Validate product regulatory classification for compliance reporting\n- Generate state-mandated reports with proper category classifications\n- Ensure product data meets regulatory requirements for each jurisdiction\n- Support track-and-trace system integration with proper categorization\n- Populate regulatory category fields in product management systems\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small dataset specific to location's regulatory jurisdiction\n- No pagination needed due to limited number of regulatory categories\n- Results may vary by location based on state/local regulations\n\n**Related Endpoints:**\n- `GET /product-category` - Get general product categories\n- `GET /products` - Get products with regulatory category assignments\n- `POST /product` - Create products with regulatory category classifications\n\n**Important Notes:**\n- Categories are specific to location's regulatory jurisdiction\n- Required for compliance with state cannabis regulations\n- Essential for accurate track-and-trace system reporting\n- Category requirements may change based on evolving regulations\n- Used for state-mandated reporting and audit compliance", "operationId": "Regulatory-categoryGet", "responses": { "200": { "description": "Success - Returns array of regulatory category objects: `[{ RegulatoryCategory }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/RegulatoryCategory" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/inventory": { "get": { "tags": ["Reporting"], "operationId": "ReportingInventoryGet", "parameters": [ { "name": "includeLabResults", "in": "query", "schema": { "type": "boolean", "default": false } }, { "name": "includeRoomQuantities", "in": "query", "schema": { "type": "boolean", "default": false } }, { "name": "includeAllocated", "in": "query", "schema": { "type": "boolean", "default": false } }, { "name": "includeLineage", "in": "query", "schema": { "type": "boolean", "default": false } } ], "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ReportingInventoryItem" } } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } } }, "/reporting/transactions": { "get": { "tags": ["Reporting"], "summary": "Transactions List", "description": "Retrieves POS and Wholesale transaction(s) from the provided dates and/or transactionId.\nThe use of transactionId, to/from transaction date, and to/from last modified date are mutually exclusive.\nProviding more than one will result in a validation error.\n\n**Performance & Limits:**\n- Rate limited to 600 requests per minute (higher limit for frequently accessed transaction data)\n- Optimized for transaction reporting and financial analysis workflows\n- Use date range filtering to limit result size for better performance", "operationId": "ReportingTransactionsGet", "parameters": [ { "name": "TransactionId", "in": "query", "description": "Specific transaction identifier for single transaction lookup.", "schema": { "type": "integer", "format": "int32" } }, { "name": "FromLastModifiedDateUTC", "in": "query", "description": "Start date for filtering transactions by last modified date (UTC) for incremental sync.", "schema": { "type": "string", "format": "date-time" } }, { "name": "ToLastModifiedDateUTC", "in": "query", "description": "End date for filtering transactions by last modified date (UTC) for incremental sync.", "schema": { "type": "string", "format": "date-time" } }, { "name": "FromDateUTC", "in": "query", "description": "Start date for filtering transactions by transaction date (UTC) for periodic reports.", "schema": { "type": "string", "format": "date-time" } }, { "name": "ToDateUTC", "in": "query", "description": "End date for filtering transactions by transaction date (UTC) for periodic reports.", "schema": { "type": "string", "format": "date-time" } }, { "name": "IncludeDetail", "in": "query", "description": "Flag to include detailed transaction item information for comprehensive reporting.", "schema": { "type": "boolean" } }, { "name": "IncludeTaxes", "in": "query", "description": "Flag to include tax information for financial compliance reporting.", "schema": { "type": "boolean" } }, { "name": "IncludeOrderIds", "in": "query", "description": "Flag to include order identifiers for order fulfillment tracking.", "schema": { "type": "boolean" } }, { "name": "IncludeFeesAndDonations", "in": "query", "description": "Flag to include fees and donations for complete financial analysis.", "schema": { "type": "boolean" } } ], "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Transaction" } } } } }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." }, "503": { "description": "Temporarily disabled (kill switch)." } } } }, "/reporting/customers": { "get": { "tags": ["Reporting"], "summary": "Customers List (Reporting)", "description": "**Purpose:** Retrieves a comprehensive list of wholesale and POS customers optimized for reporting and analytics.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for analytics data access\n- Optional UTC date parameters for filtering\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ Customer }, { Customer }, ...]`\n- Array of `Customer` objects with complete customer information\n- Includes primary and secondary qualifying conditions for medical customers\n- Contains customer profile data, contact information, and preferences\n- Results are automatically filtered by the authenticated location\n\n**How This Differs from `/customer/customers`:**\n- Requires \"Reporting\" role instead of \"Customer\" role authorization\n- Optimized for reporting and analytics rather than operational management\n- Returns ALL customers for comprehensive reporting purposes\n- Enhanced date range filtering designed for reporting workflows\n- Performance tuned for bulk data export and analysis\n\n**Common Use Cases:**\n- Generate comprehensive customer reports and analytics\n- Export customer data for external systems or compliance requirements\n- Synchronize customer changes with external databases using incremental sync\n- Review customer records for regulatory compliance audits\n- Analyze customer demographics and behavior patterns for marketing\n\n**Performance & Limits:**\n- Rate limited to 600 requests per minute (higher limit for frequently accessed reporting data)\n- Use date range filtering to limit result size for better performance\n- Consider using `/reporting/customers-paginated` for very large datasets\n- Cache results locally and use incremental sync for regular updates\n- May return large datasets as it includes ALL customer types\n\n**Related Endpoints:**\n- `GET /reporting/customers-paginated` - Paginated version for large datasets\n- `GET /customer/customers` - Operational customer management endpoint\n\n**Important Notes:**\n- This endpoint returns ALL customers (wholesale and POS) and may return large datasets\n- Requires reporting authorization role for access\n- Use date filtering to improve performance with large customer bases", "operationId": "ReportingCustomersGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Filter customers modified after this UTC date - Used for incremental sync", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Filter customers modified before this UTC date - Used for date range filtering", "schema": { "type": "string", "format": "date-time" } }, { "name": "includeAnonymous", "in": "query", "description": "Include anonymous customers in results - Default: true", "schema": { "type": "boolean", "default": true } } ], "responses": { "200": { "description": "Success - Returns array of customer objects", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Customer" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/customers-paginated": { "get": { "tags": ["Reporting"], "summary": "Get Customers (Paginated, Reporting)", "description": "**Purpose:** Retrieve paginated customer data optimized for reporting and analytics with enhanced performance for large-scale customer analysis.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for analytics data access\n- Optional query parameters for filtering and pagination control\n- No request body needed\n- Maximum page size of 10,000 customers for optimal performance\n\n**Response Data:**\n- Response format: `[{ Customer }, { Customer }, ...]`\n- Returns array of `Customer` objects for the requested page\n- Array contains up to PageSize customers (default 1000, max 10,000)\n- Returns empty array `[]` if no customers match criteria for the page (not null)\n- **No pagination metadata**: Response contains only customer data without total counts or page information\n- Includes primary and secondary qualifying conditions for medical customers\n- Contains customer profile data, contact information, and preferences\n- Results automatically filtered to authenticated location\n\n**Pagination Usage:**\n- **First Request**: Call with PageNumber=0 to get first page\n- **Subsequent Requests**: Increment PageNumber for each additional page\n- **End Detection**: Continue requesting pages until you receive an empty array `[]`\n- **Page Size Control**: Use PageSize parameter to control items per page (max 10,000)\n- **Example Flow**: Request PageNumber=0 → Process results → Increment PageNumber → Repeat until empty `[]` response\n\n**Key Differences from `/customer/customers-paginated`:**\n- **Authorization**: Requires \"Reporting\" role vs \"Customer\" role\n- **Purpose**: Optimized for reporting and analytics vs operational customer management\n- **Page Size**: Higher maximum page size limits for bulk reporting\n- **Profile Sharing**: Enhanced customer profile sharing logic for reporting\n- **Performance**: Designed for large-scale data export and analysis\n\n**Filtering Options:**\n- fromLastModifiedDateUTC: Returns customers modified after this date (incremental sync)\n- toLastModifiedDateUTC: Returns customers modified before this date (date range filtering)\n- includeAnonymous: Include anonymous customers in results (default: true)\n\n**Common Use Cases:**\n- Handle thousands of customers efficiently with paginated processing\n- Process customers in manageable chunks for batch operations\n- Avoid loading entire customer base at once for memory-conscious applications\n- Stream customer data for live reporting dashboards and analytics\n- Transfer customer data between systems in controlled batches\n\n**Performance & Limits:**\n- Maximum 10,000 customers per page for optimal performance\n- Start with PageNumber=0 and increment until no more data available\n- Use consistent PageSize throughout pagination sequence for efficiency\n- Monitor response times and adjust PageSize for optimal performance\n- Cache results locally to minimize API calls and improve responsiveness\n\n**Pagination Detection:**\n- **End of data detection**: Continue requesting pages until you receive an empty array `[]`\n- **No metadata provided**: Response does not include total counts, page counts, or hasNextPage indicators\n- **Sequential access**: Increment PageNumber from 0 until empty response indicates no more data\n\n**Related Endpoints:**\n- `GET /reporting/customers` - Non-paginated version for smaller datasets\n- `GET /customer/customers` - Operational customer management endpoint\n\n**Important Notes:**\n- **Pagination Required**: Large customer bases require multiple page requests\n- **Enhanced Profile Logic**: Uses advanced customer profile sharing based on LSP configuration\n- **Reporting Optimized**: Designed for analytics and large-scale data processing\n- **Location Scoped**: Results automatically filtered to authenticated location\n- **Page Size Validation**: Requests exceeding 10,000 customers per page will be rejected", "operationId": "ReportingCustomers-paginatedGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Filter customers modified after this UTC date for incremental sync - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Filter customers modified before this UTC date for date range filtering - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "PageNumber", "in": "query", "description": "Page number for sequential pagination (integer, starts at 0) - Default: 0", "schema": { "type": "integer", "format": "int32", "default": 0 } }, { "name": "PageSize", "in": "query", "description": "Number of items per page (integer) - Default: 1000, Maximum: 10000", "schema": { "type": "integer", "format": "int32", "default": 1000 } }, { "name": "includeAnonymous", "in": "query", "description": "Include anonymous customers in results - Default: true", "schema": { "type": "boolean", "default": true } } ], "responses": { "200": { "description": "Success - Returns array of customer objects for the requested page", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Customer" } } } } }, "400": { "description": "Bad Request - `BadRequestResponse` object with `message` string field (check `propertyErrors`: null for simple message, array for field-specific errors)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BadRequestResponse" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/register-adjustments": { "get": { "tags": ["Reporting"], "summary": "Get Register Adjustments", "description": "**Purpose:** Retrieve register adjustment transactions for cash management and reconciliation reporting with detailed audit trail information.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for financial data access\n- Optional query parameters for date range filtering\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ RegisterAdjustment }, { RegisterAdjustment }, ...]`\n- Returns array of `RegisterAdjustment` objects with detailed transaction information\n- Array may contain 0 to 1,000+ adjustments depending on date range and activity\n- Returns empty array `[]` if no adjustments match criteria (not null)\n- Includes adjustment amounts, types, timestamps, and employee information\n- Contains reason codes and descriptions for each adjustment\n- Results automatically filtered to authenticated location\n\n**Transaction Types Included:**\n- **Adjustments**: Manual cash register corrections and balancing entries\n- **Close Outs**: End-of-shift register closing transactions\n- **Deposits**: Cash deposits made to the register\n- **Withdrawals**: Cash withdrawals from the register\n- **Cash Drops**: Safe drops and cash removal transactions\n\n**Filtering Options:**\n- fromLastModifiedDateUTC: Returns adjustments modified after this date (incremental sync)\n- toLastModifiedDateUTC: Returns adjustments modified before this date (date range filtering)\n\n**Common Use Cases:**\n- Track all register cash movements for balancing and reconciliation\n- Maintain detailed records of cash handling activities for audit trails\n- Generate end-of-shift cash management summaries and reports\n- Document cash handling for regulatory requirements and compliance\n- Analyze cash flow patterns and adjustment trends for financial analysis\n- Monitor unusual adjustment patterns or discrepancies for loss prevention\n\n**Performance & Limits:**\n- Use date range filtering to limit results to specific time periods for optimal performance\n- Combine with cash-summary endpoint for comprehensive cash reporting\n- Cache results locally and use incremental sync for regular updates\n- Optimized for financial reconciliation and audit trail workflows\n\n**Related Endpoints:**\n- `GET /reporting/register-transactions` - Complete register activity including sales\n- `GET /reporting/cash-summary` - Comprehensive cash reporting and summaries\n- `GET /reporting/closing-report` - Financial closing reports with cash details\n\n**Important Notes:**\n- **Adjustment Focus**: This endpoint focuses specifically on register adjustments only\n- **Complete Activity**: For complete register activity including sales, use register-transactions\n- **Audit Trail**: Maintains detailed records of all cash handling activities\n- **Location Scoped**: Results automatically filtered to authenticated location\n- **Employee Tracking**: Includes employee information for accountability and audit purposes", "operationId": "ReportingRegister-adjustmentsGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Filter adjustments modified after this date for incremental sync - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Filter adjustments modified before this date for date range filtering - Optional", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "Success - Returns array of register adjustment objects", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/RegisterAdjustment" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/register-transactions": { "get": { "tags": ["Reporting"], "summary": "Get Register Transactions (Comprehensive Transaction History)", "description": "**Purpose:** Retrieve comprehensive register transaction history including sales, adjustments, cash management, and operational activities for complete financial reporting.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for financial transaction data access\n- Optional query parameters for date range filtering\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ RegisterTransaction }, { RegisterTransaction }, ...]`\n- Returns array of `RegisterTransaction` objects with comprehensive transaction data\n- Array may contain 0 to 50,000+ transactions depending on date range and business volume\n- Returns empty array `[]` if no transactions match criteria (not null)\n- Includes financial details, customer information, product details, and employee tracking\n- Complete audit trail with timestamps, register context, and status information\n- Results automatically filtered to authenticated location\n\n**Transaction Types Included:**\n- **Sales Transactions**: Completed customer purchases and returns\n- **Register Adjustments**: Manual cash corrections and balance adjustments\n- **Cash Management**: Deposits, withdrawals, cash drops, and till operations\n- **Register Close-Outs**: End-of-shift register balancing and reconciliation\n- **Payment Processing**: Credit card, cash, and other payment method transactions\n- **Operational Activities**: Register opening, closing, and maintenance operations\n\n**Transaction Data Returned:**\n- **Financial Details**: Transaction amounts, payment methods, taxes, and fees\n- **Customer Information**: Customer IDs, types, and transaction associations\n- **Product Details**: Items sold, quantities, prices, and categories\n- **Employee Tracking**: Staff members who processed transactions\n- **Timestamps**: Creation, modification, and completion times\n- **Register Context**: Terminal/register identification and session information\n- **Status Information**: Transaction status, voiding, and modification history\n\n**Filtering Options:**\n- fromLastModifiedDateUTC: Returns transactions modified after this date (incremental sync)\n- toLastModifiedDateUTC: Returns transactions modified before this date (date range filtering)\n\n**Common Use Cases:**\n- Balance daily sales across all registers and payment methods for financial reconciliation\n- Generate comprehensive revenue reports and analytics for sales reporting\n- Maintain detailed transaction records for compliance and audit preparation\n- Track all cash movements and register balancing activities for cash management\n- Analyze sales patterns, employee performance, and business trends for performance analysis\n- Extract detailed tax information for regulatory compliance and tax reporting\n- Monitor transaction patterns for unusual activities and fraud prevention\n\n**Performance & Limits:**\n- Large datasets: This endpoint can return substantial amounts of transaction data\n- Use date range filtering to limit results for better performance\n- Use fromLastModifiedDateUTC for regular data synchronization and incremental sync\n- Schedule large data exports during low-traffic periods for optimal performance\n- Optimized for comprehensive financial reporting and audit trail requirements\n\n**Related Endpoints:**\n- `GET /reporting/register-adjustments` - Cash adjustments and corrections only\n- `GET /reporting/closing-report` - Summary financial reports for specific date ranges\n- `GET /reporting/cash-summary` - Cash-specific summaries and balancing information\n\n**Important Notes:**\n- **Comprehensive Data**: Returns ALL register activities, resulting in potentially large datasets\n- **Real-Time Updates**: Transaction data reflects current state and may include recent modifications\n- **Location Scoped**: Results automatically filtered to authenticated dispensary location\n- **Historical Accuracy**: Maintains complete audit trail for all register operations\n- **Complete Activity**: This is the most comprehensive endpoint for all register transaction types", "operationId": "ReportingRegister-transactionsGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Filter transactions modified after this date for incremental sync - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Filter transactions modified before this date for date range filtering - Optional", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "Success - Returns array of RegisterTransaction objects with comprehensive transaction data", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/RegisterTransaction" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/cash-summary": { "get": { "tags": ["Reporting"], "summary": "Get Cash Summary (Real-time Register Activity)", "description": "**Purpose:** Retrieve real-time register cash activity summary with comprehensive financial reconciliation data for cash management and balancing.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for financial data access\n- Optional query parameters for date range filtering\n- Date range must be within the last 7 days for optimal performance\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ RegisterCashSummary }, { RegisterCashSummary }, ...]`\n- Returns array of `RegisterCashSummary` objects with detailed cash flow information\n- Array may contain 1-50+ register summaries depending on number of active registers\n- Returns empty array `[]` if no cash activity matches criteria (not null)\n- Real-time data reflecting current register status and activities\n- Includes variance calculations and reconciliation details\n- Results automatically filtered to authenticated location\n\n**Summary Data Included:**\n- **Starting Balance**: Register opening cash amount for the period\n- **Ending Balance**: Current or closing register cash amount\n- **Sales**: Total cash sales transactions processed\n- **Returns**: Cash refunds and return transactions\n- **Deposits**: Cash deposits added to the register\n- **Adjustments**: Manual cash corrections and modifications\n- **Over/Short**: Cash variance from expected amounts\n\n**Filtering Options:**\n- fromLastModifiedDateUTC: Returns activity after this date (incremental sync, within 7 days)\n- toLastModifiedDateUTC: Returns activity before this date (date range filtering)\n\n**Common Use Cases:**\n- Track current register cash status throughout the day for real-time monitoring\n- Balance register cash at shift changes for reconciliation\n- Generate end-of-day cash summaries for closing procedures\n- Identify and investigate cash discrepancies for variance analysis\n- Create comprehensive cash flow reports for financial reporting\n- Maintain detailed cash handling records for audit preparation\n\n**Performance & Limits:**\n- Rate limited to 480 requests per minute (higher limit for frequent cash monitoring)\n- Date range restriction: fromLastModifiedDateUTC must be within the last 7 days\n- Use recent date ranges (within 7 days) for fastest response times\n- Combine with register-adjustments endpoint for detailed transaction breakdown\n- Cache results and refresh periodically for dashboard applications\n- Optimized for real-time cash monitoring and reconciliation workflows\n\n**Related Endpoints:**\n- `GET /reporting/register-adjustments` - Detailed transaction breakdown\n- `GET /reporting/register-transactions` - Complete register transaction history\n- `GET /reporting/closing-report` - Comprehensive financial closing reports\n\n**Important Notes:**\n- **Real-time Data**: Provides real-time data and may show different results than historical reports during active business hours\n- **7-Day Limit**: Date filtering restricted to last 7 days for optimal performance\n- **Active Business Hours**: Results may vary during active operations due to real-time updates\n- **Location Scoped**: Results automatically filtered to authenticated location\n- **Variance Tracking**: Includes over/short calculations for cash discrepancy identification", "operationId": "ReportingCash-summaryGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Filter activity after this date (must be within last 7 days) - Optional", "schema": { "type": "string", "format": "date-time" } }, { "name": "toLastModifiedDateUTC", "in": "query", "description": "Filter activity before this date for date range filtering - Optional", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "Success - Returns array of register cash summary objects", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/RegisterCashSummary" } } } } }, "400": { "description": "Bad Request - String error message (parse response body as plain text)", "content": { "application/json": { "schema": { "type": "string" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/loyalty-snapshot": { "get": { "tags": ["Reporting"], "summary": "Get Loyalty Balance Snapshot (Daily)", "description": "**Purpose:** Retrieve current loyalty point balances for all customers with nightly batch processing for comprehensive loyalty program reporting and analysis.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for loyalty data access\n- No query parameters required\n- No request body needed\n- Rate limited to 1 request per minute for system protection\n\n**Response Data:**\n- Response format: `[{ LoyaltySnapshot }, { LoyaltySnapshot }, ...]`\n- Returns array of `LoyaltySnapshot` objects with customer loyalty information\n- Array typically contains 100-10,000+ customers depending on loyalty program participation\n- Returns empty array `[]` if no customers have loyalty activity (not null)\n- Includes current point balances, loyalty tier information, and customer identifiers\n- Contains earned points, redeemed points, and available balance details\n- Results automatically filtered to authenticated location\n\n**Data Characteristics:**\n- **Update Frequency**: Nightly batch processing (updated once per day)\n- **Data Freshness**: Reflects loyalty activity through the previous business day\n- **Scope**: All customers with loyalty program participation\n- **Balance Types**: Current available points, earned points, redeemed points\n- **Configuration**: Uses either loyalty ledger service or database depending on system configuration\n\n**Common Use Cases:**\n- Generate end-of-day loyalty summaries for daily loyalty reports\n- Check customer loyalty balances and history for customer service\n- Identify customers by loyalty tier or balance ranges for marketing campaigns\n- Document loyalty program activity for audits and compliance reporting\n- Export loyalty data to external systems for data synchronization\n- Analyze loyalty program engagement and effectiveness for analytics\n\n**Consumption Guidelines:**\n- **Recommended Frequency**: Once per day (after nightly processing completes)\n- **Optimal Timing**: Early morning hours after batch processing\n- **Caching Strategy**: Cache results for 24 hours, refresh daily\n\n**Performance & Limits:**\n- Rate limited to 1 request per minute for system protection\n- Schedule automated calls during off-peak hours for optimal performance\n- Cache results locally to avoid repeated calls within the same day\n- Use for batch processing rather than real-time customer lookups\n- Optimized for daily loyalty program management and reporting workflows\n\n**Related Endpoints:**\n- `GET /reporting/customer-loyalty-snapshot` - Individual customer loyalty data\n- `GET /reporting/loyalty-transactions-paginated` - Detailed loyalty transaction history\n- `GET /reporting/national-loyalty-snapshot-paginated` - Cross-organization loyalty data\n\n**Important Notes:**\n- **Snapshot Data**: This is a snapshot of loyalty balances as of the last nightly processing\n- **Real-time Alternative**: For real-time loyalty transactions, use other loyalty endpoints\n- **Nightly Processing**: Data reflects activity through the previous business day\n- **Location Scoped**: Results filtered to authenticated location loyalty participants\n- **Rate Limited**: Maximum 1 request per minute to protect system resources", "operationId": "ReportingLoyalty-snapshotGet", "responses": { "200": { "description": "Success - Returns array of loyalty balance snapshot objects", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/LoyaltySnapshot" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/products": { "get": { "tags": ["Reporting"], "summary": "Get Products (Master List, Reporting)", "description": "**Purpose:** Retrieve the complete product master list with comprehensive product data for reporting and analytics, including all products regardless of API or online availability settings.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for comprehensive product data access\n- Optional query parameters for incremental sync filtering\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ ProductDetail }, { ProductDetail }, ...]`\n- Returns array of `ProductDetail` objects with complete product information\n- Array typically contains 100-50,000+ products depending on catalog size\n- Returns empty array `[]` if no products exist or match criteria (not null)\n- Includes ALL products in the system (active and inactive)\n- Contains pricing, categories, strains, lab results, and inventory data\n- Results automatically filtered to authenticated location\n\n**Key Differences from `/products`:**\n- **No API Access Filter**: Returns ALL products, not just those enabled for API access\n- **No Online Filter**: Ignores online availability settings used by standard products endpoint\n- **Master Data Focus**: Designed for comprehensive product data exports and reporting\n- **Complete Dataset**: Includes inactive and non-public products for complete catalog view\n\n**Filtering Options:**\n- fromLastModifiedDateUTC: Returns products modified after this date (incremental sync)\n\n**Common Use Cases:**\n- Get complete product catalog for analysis and comprehensive reporting\n- Export all product data for external systems and data warehousing\n- Review all products regardless of API/online settings for inventory audits\n- Maintain complete product records for master data management\n- Generate reports including all products for compliance reporting\n\n**When to Use This vs `/products`:**\n- **Use `/reporting/products`**: For complete data exports, reporting, audits, and analytics\n- **Use `/products`**: For e-commerce, POS integration, and customer-facing applications\n\n**Performance & Limits:**\n- Large datasets: This endpoint can return substantial product catalogs\n- Use fromLastModifiedDateUTC for incremental sync to optimize performance\n- Optimized for comprehensive product reporting and analytics workflows\n- Consider pagination for very large product catalogs (50,000+ products)\n\n**Related Endpoints:**\n- `GET /products` - Customer-facing products with API and online filters\n- `GET /inventory` - Product inventory levels and availability\n- `GET /product-categories` - Product categorization data\n\n**Important Notes:**\n- **Complete Dataset**: Returns ALL products, including those not intended for public API access or online sales\n- **Master Data**: This is the authoritative source for complete product catalog data\n- **Reporting Focus**: Designed for analytics and reporting rather than customer-facing operations\n- **Location Scoped**: Results filtered to authenticated location product catalog\n- **Incremental Sync**: Use date filtering for efficient data synchronization", "operationId": "ReportingProductsGet", "parameters": [ { "name": "fromLastModifiedDateUTC", "in": "query", "description": "Filter products modified after this date for incremental sync - Optional", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ProductDetail" } } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/reporting/closing-report": { "get": { "tags": ["Reporting"], "summary": "Get Closing Report (Comprehensive Financial Summary)", "description": "**Purpose:** Retrieve comprehensive closing report with detailed financial summaries, payment breakdowns, and business analytics for specified date range reporting.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for financial data access\n- fromDateUTC and toDateUTC parameters required (both must be provided)\n- Date range must be between 12 hours and 31 days maximum\n- UTC datetime format required for all date parameters\n\n**Response Data:**\n- Response format: `{ ClosingReport }` or `{ ClosingReportV2 }` (structure varies by system configuration)\n- Returns `ClosingReport` or `ClosingReportV2` object with comprehensive financial data\n- Single object containing multi-dimensional analysis across all business aspects\n- Not an array - returns one comprehensive report object for the date range\n- Multi-dimensional analysis across payment methods, customer types, and product categories\n- Detailed tax calculations and compliance information\n- Payment processor-specific data and settlement details\n- Results automatically filtered to authenticated location\n\n**Date Range Restrictions:**\n- **Maximum Range**: 31 days or less\n- **Minimum Range**: Greater than 12 hours\n- **Format**: UTC datetime values\n- **Both Required**: fromDateUTC and toDateUTC must be provided\n\n**Report Sections Included:**\n- **Payment Summary**: Breakdown by payment method (cash, card, etc.)\n- **Customer Type Summary**: Sales analysis by customer categories\n- **Category Summary**: Revenue breakdown by product categories\n- **Tax Summary**: Detailed tax calculations and rates\n- **Order Source Summary**: Sales by channel (online, in-store, etc.)\n- **Order Type Summary**: Analysis by order types (delivery, pickup, etc.)\n- **Fees & Donations**: Processing fees and charitable donations (when enabled)\n- **Pay-by-Bank Details**: ACH transaction summaries and batch files (when enabled)\n\n**Response Version Determination:**\n- Response structure varies based on internal system configuration\n- **V1 (ClosingReport)**: Standard financial summaries without tips/fees\n- **V2 (ClosingReportV2)**: Enhanced with tips, fees, and Pay-by-Bank details\n- **API Consumer Guidance**: Both versions share common base fields, V2 extends V1 with additional properties\n- **Breaking Change Protection**: V2 is additive-only (safe to parse as V1 and ignore extra fields)\n\n**Handling Variable Response Types:**\n- **Recommended Approach**: Parse response for common fields first, then check for V2-specific properties\n- **Common Base Properties**: All versions include PaymentSummary, CustomerTypeSummary, CategorySummary, TaxSummary\n- **V2 Additional Properties**: TipsSummary, FeesSummary, PayByBankDetails (when present)\n\n**Common Use Cases:**\n- Generate end-of-period financial summaries for daily/weekly closing\n- Balance sales across all payment methods and channels for financial reconciliation\n- Extract detailed tax information for compliance and tax reporting\n- Analyze sales performance across multiple dimensions for business analytics\n- Reconcile payment processor settlements for payment processing\n- Generate comprehensive financial documentation for audit preparation\n\n**Performance & Limits:**\n- This report processes large amounts of transactional data\n- Longer date ranges may take additional time to generate\n- Use shorter date ranges for faster processing\n- Schedule report generation during off-peak hours for optimal performance\n- Cache results for frequently accessed date ranges\n\n**Related Endpoints:**\n- `GET /reporting/register-transactions` - Detailed transaction-level data\n- `GET /reporting/cash-summary` - Cash-specific summaries\n- `GET /reporting/register-adjustments` - Register adjustment details\n\n**Important Notes:**\n- **Processing Intensive**: This report processes large amounts of transactional data\n- **Date Range Validation**: Requests with invalid date ranges will be rejected\n- **Comprehensive Data**: Includes all financial aspects of business operations\n- **Location Scoped**: Results filtered to authenticated location financial data\n- **Version Dependent**: Response object type depends on system configuration and features enabled", "operationId": "ReportingClosing-reportGet", "parameters": [ { "name": "fromDateUTC", "in": "query", "description": "Start date for the report period (required) - Must be UTC datetime", "schema": { "type": "string", "format": "date-time" } }, { "name": "toDateUTC", "in": "query", "description": "End date for the report period (required) - Must be UTC datetime", "schema": { "type": "string", "format": "date-time" } } ], "responses": { "200": { "description": "Success - Returns comprehensive closing report object", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ClosingReportV2" } } } }, "400": { "description": "Bad Request - String error message (parse response body as plain text)", "content": { "application/json": { "schema": { "type": "string" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/reporting/discounts": { "get": { "tags": ["Reporting"], "summary": "Get Discounts (Complete Discount Configuration)", "description": "**Purpose:** Retrieve comprehensive discount configuration data for all discounts regardless of status, type, or activation state for promotional reporting and analysis.\n\n**Request Requirements:**\n- \"Reporting\" role authorization required for discount configuration data access\n- Optional query parameter for including deleted discounts\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ ReportingDiscountDetail }, { ReportingDiscountDetail }, ...]`\n- Returns array of `ReportingDiscountDetail` objects with complete discount configurations\n- Array typically contains 5-500+ discounts depending on promotional activity\n- Returns empty array `[]` if no discounts exist (not null)\n- Includes all restriction types and eligibility criteria\n- Contains scheduling and recurrence information\n- Provides location-specific applicability data\n- Results automatically filtered to authenticated location\n\n**Unique Endpoint:** This is the only discounts endpoint in the Public API - there is no parallel non-reporting version.\n\n**Filtering Options:**\n- includeDeleted: Include deleted/archived discounts in results (default: false)\n\n**Discount Information Included:**\n- **Basic Details**: Discount names, descriptions, and identifiers\n- **Status Information**: Active/inactive status and deletion state\n- **Type Classification**: Manual vs automatic discount types\n- **Validity Periods**: Start and end dates (converted to UTC)\n- **Discount Groups**: Associated discount group memberships\n- **Product Restrictions**: Specific products eligible for the discount\n- **Category Restrictions**: Product categories covered by the discount\n- **Strain Restrictions**: Cannabis strain-specific discount rules\n- **Brand Restrictions**: Brand-specific discount applications\n- **Vendor Restrictions**: Vendor-specific discount configurations\n- **Weekly Recurrence**: Recurring discount schedule information\n- **Location Mapping**: Multi-location discount applicability\n\n**Common Use Cases:**\n- Analyze discount effectiveness and usage patterns for discount analysis\n- Export complete discount configurations for configuration backup\n- Document promotional activities for regulatory review and compliance reporting\n- Synchronize discount rules with external systems for system integration\n- Review existing promotions for campaign planning and marketing planning\n- Maintain comprehensive records of all promotional activities for audit preparation\n\n**Performance & Limits:**\n- Use includeDeleted=false for active discount analysis to optimize performance\n- Cache results locally as discount configurations change infrequently\n- Process restriction arrays to understand discount eligibility logic\n- Optimized for promotional reporting and marketing analysis workflows\n\n**Related Endpoints:**\n- `GET /reporting/closing-report` - Financial impact of discount usage\n- `GET /reporting/register-transactions` - Transaction-level discount application\n- `GET /products` - Products eligible for discount restrictions\n\n**Important Notes:**\n- **Complete Configuration**: Returns ALL discount configurations including inactive and deleted discounts when requested\n- **Use Filtering**: Use includeDeleted parameter appropriately for your use case\n- **UTC Conversion**: All validity periods are automatically converted to UTC\n- **Location Scoped**: Results filtered to authenticated location discount configurations\n- **Unique Endpoint**: This is the only public API endpoint for discount data access", "operationId": "ReportingDiscountsGet", "parameters": [ { "name": "includeDeleted", "in": "query", "description": "Include deleted/archived discounts in results - Default: false", "schema": { "type": "boolean", "default": false } } ], "responses": { "200": { "description": "Success - Returns array of comprehensive discount configuration objects", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ReportingDiscountDetail" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for reporting access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/room/rooms": { "get": { "tags": ["Room"], "summary": "Get Rooms", "description": "**Purpose:** Retrieve cultivation rooms and facility areas configured for the location to support cultivation operations and facility management.\n\n**Request Requirements:**\n- \"Room\" role authorization required for room data access\n- Optional filtering parameters available for specific room lookup\n- Cultivation facility management permissions required\n\n**Response Data:**\n- Returns array of `Room` objects with room identification and type information\n- Array typically contains 5-50 rooms depending on cultivation facility size\n- Returns empty array `[]` if no rooms match criteria (not null)\n- Includes room identification, naming, and functional type flags\n- Results automatically filtered to authenticated location\n\n**Filtering Options:**\n- **roomId**: Optional integer parameter to retrieve specific room by ID\n- **roomName**: Optional string parameter to search rooms by name\n- **Combined Filtering**: Parameters can be used together for precise room lookup\n- **No Filters**: Returns all rooms when no parameters provided\n\n**Room Information Included:**\n- **RoomId**: Unique identifier for each cultivation room or facility area\n- **RoomName**: Human-readable name for room identification and management\n- **Location Information**: Facility location details (when integrator is Dutchie)\n- **Room Type Flags**: Boolean flags indicating room functionality (IsQuarantineRoom, IsVaultRoom, IsSalesFloor, etc.)\n\n**Common Use Cases:**\n- Populate room dropdown lists in cultivation management interfaces\n- Display available rooms for plant placement and cultivation tracking\n- Support cultivation facility room management and organization\n- Enable room-specific cultivation tracking and environmental monitoring\n- Facilitate cultivation workflow room assignments and plant movement\n\n**Performance & Limits:**\n- Efficient room lookup optimized for cultivation facility workflows\n- Optimized database queries for improved performance\n- Flexible filtering for specific room management needs\n- Results consistent across cultivation and facility management systems\n\n**Related Endpoints:**\n- `POST /room` - Create or update room configuration\n- `GET /plant` - View plants assigned to specific cultivation rooms\n- `GET /harvest` - Track harvest operations by cultivation room\n\n**Important Notes:**\n- **Cultivation Integration**: Essential for cultivation facility management and plant tracking\n- **Location Specific**: Results filtered to authenticated location facility setup\n- **Integrator Dependent**: Location information visibility controlled by integrator type\n- **Cultivation Ready**: Room data used throughout cultivation tracking workflows", "operationId": "RoomRoomsGet", "parameters": [ { "name": "roomId", "in": "query", "description": "Optional room ID for specific room lookup - integer", "schema": { "type": "integer", "format": "int32" } }, { "name": "roomName", "in": "query", "description": "Optional room name for searching rooms by name - string", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Success - Returns array of room objects: `[{ Room }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Room" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for room access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/room": { "post": { "tags": ["Room"], "summary": "Create or Update Room", "description": "**Purpose:** Create a new cultivation room or update an existing room configuration for cultivation facility management and plant tracking operations.\n\n**Request Requirements:**\n- \"Room\" role authorization required for room data modification\n- `Room` object in request body with room configuration details\n- Content-Type: application/json\n- Cultivation facility management permissions required\n\n**Response Data:**\n- Returns single `Room` object (not array) with updated room information\n- Includes assigned RoomId for new rooms or updated ID for existing rooms\n- Complete room information with all fields populated\n- Room identification, naming, and type flag information\n\n**Create vs Update Behavior:**\n- **CREATE**: When RoomId is null or 0, a new room record will be created\n- **UPDATE**: When RoomId is provided with a valid room ID, the existing room will be updated\n- **Identification**: Room existence determined by RoomId value\n- **Automatic Detection**: System automatically determines create vs update based on RoomId\n\n**Room Data Fields:**\n- **RoomId**: Unique identifier for room (null/0 for new rooms, specific ID for updates)\n- **RoomName**: Human-readable name for room identification and cultivation tracking\n- **Room Type Flags**: Boolean indicators for room functionality (IsQuarantineRoom, IsVaultRoom, etc.)\n\n**Common Use Cases:**\n- Add new cultivation rooms to facility management system\n- Update existing room names or configuration details\n- Modify room setup for cultivation facility reorganization\n- Create room assignments for cultivation tracking workflows\n- Support cultivation facility expansion and room management\n\n**Performance & Limits:**\n- Single room operation for targeted cultivation facility management\n- Immediate room configuration update reflected in cultivation systems\n- Optimized for cultivation facility management and plant tracking workflows\n- Changes reflected immediately in room assignment and cultivation systems\n\n**Related Endpoints:**\n- `GET /room/rooms` - Retrieve existing room configuration before updates\n- `GET /plant` - View plants assigned to cultivation rooms\n- `POST /plant/nonsts/update` - Update plant room assignments\n\n**Important Notes:**\n- **RoomId Assignment**: New rooms receive automatically generated RoomId\n- **Cultivation Integration**: Room configuration affects plant tracking and cultivation workflows\n- **Location Scoped**: Rooms automatically associated with authenticated location\n- **Cultivation Ready**: Room data immediately available for plant assignment operations\n- **Facility Management**: Supports cultivation facility organization and room tracking", "operationId": "RoomPost", "requestBody": { "description": "Room information to create or update - Room object with RoomId, RoomName, and room type flags", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/Room" } }, "application/json": { "schema": { "$ref": "#/components/schemas/Room" } }, "text/json": { "schema": { "$ref": "#/components/schemas/Room" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/Room" } } }, "x-bodyName": "room" }, "responses": { "200": { "description": "Success - Returns single room object: `{ Room }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Room" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for room modification" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/sizes": { "get": { "tags": ["Size"], "summary": "Get Product Sizes", "description": "**Purpose:** Retrieves the complete list of product sizes available for the authenticated organization for product configuration and inventory management.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of size objects: `[{ Size }, ...]`\n- Response format: `[{ Size }, { Size }, ...]`\n- Example: `[{ \"SizeId\": 1, \"SizeName\": \"1g\", \"Description\": \"One gram flower package\" }, { \"SizeId\": 2, \"SizeName\": \"3.5g\", \"Description\": \"Eighth ounce flower package\" }, ...]`\n- Array typically contains 15-40 product sizes per organization\n- Returns empty array `[]` if no sizes configured (rare)\n- Includes size ID, name, and measurement details\n- Standard product sizes (grams, ounces, units, etc.) for cannabis products\n- Results filtered to authenticated organization level\n\n**Common Use Cases:**\n- Populate product size dropdown lists in product creation forms\n- Configure product variants with different size options\n- Support inventory management with size-based tracking\n- Generate size-specific pricing and inventory reports\n- Enable e-commerce product configuration with size selections\n\n**Performance & Limits:**\n- Lightweight reference data optimized for frequent access\n- Small dataset suitable for client-side caching\n- No pagination needed due to limited number of standard sizes\n- Results consistent across all locations within organization\n\n**Related Endpoints:**\n- `GET /products` - Get products that use these size configurations\n- `POST /product` - Create products with size assignments\n- `GET /inventory` - Get inventory levels by product size\n\n**Important Notes:**\n- Sizes are defined at organization level (LSP) not location level\n- Standard cannabis industry size configurations for consistency\n- Used for product configuration and inventory tracking\n- Essential reference data for product and pricing management\n- Supports both weight-based and unit-based product sizing", "operationId": "SizesGet", "responses": { "200": { "description": "Success - Returns array of size objects: `[{ Size }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Size" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/strains": { "post": { "tags": ["Strains"], "operationId": "StrainsPost", "requestBody": { "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/UpdateStrain" } }, "application/json": { "schema": { "$ref": "#/components/schemas/UpdateStrain" } }, "text/json": { "schema": { "$ref": "#/components/schemas/UpdateStrain" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/UpdateStrain" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/StrainDetail" } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "type": "string" } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } }, "get": { "tags": ["Strains"], "summary": "Get Strains", "description": "**Purpose:** Retrieves all cannabis strains available for the authenticated location with genetic and classification information.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for strain data access\n- No query parameters or request body needed\n\n**Response Data:**\n- Response format: `[{ StrainDetail }, { StrainDetail }, ...]`\n- Array typically contains 10-100 strains per location\n- Returns empty array `[]` if no strains configured for location\n- Results automatically filtered to authenticated location\n- See `StrainDetail` model for complete field descriptions\n\n**Data Filtering:**\n- Results are automatically scoped to the authenticated location\n- Only active strains are included in the response\n- Strain types include full classification information for categorization\n\n**Common Use Cases:**\n- Populate strain dropdown lists in product creation and editing forms\n- Display available strain genetics for product categorization and filtering\n- Synchronize strain catalog with external inventory management systems\n- Generate strain-specific compliance reports and analytics\n- Support product menu organization by genetic type and characteristics\n- Cache strain data for offline product creation workflows\n\n**Performance & Limits:**\n- Lightweight data optimized for frequent access and caching\n- Typically small dataset (10-100 strains) suitable for client-side storage\n- No pagination needed due to manageable strain catalog sizes per location\n- Response time typically under 50ms for standard strain catalogs\n- Safe for frequent polling (recommended: cache for 5-10 minutes)\n\n**Integration Patterns:**\n- **UI Dropdowns**: Cache response locally for form population\n- **Product Creation**: Use strain IDs for product categorization\n- **External Sync**: Compare ExternalId values for third-party integration\n- **Menu Display**: Filter products by strain type and characteristics\n\n**Related Endpoints:**\n- `POST /strains` - Create or update strain information in this catalog\n- `GET /strains/types` - Get valid strain type classifications for filtering\n\n**Important Notes:**\n- Strain catalog is location-specific and varies by dispensary\n- External ID values enable synchronization with cultivation management systems\n- Strain information directly affects product categorization and compliance reporting", "operationId": "StrainsGet", "responses": { "200": { "description": "Success - Returns array of strain objects: `[{ StrainDetail }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/StrainDetail" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for inventory access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/strains/types": { "get": { "tags": ["Strains"], "summary": "Get Strain Types", "description": "**Purpose:** Retrieves the list of valid strain type classifications for cannabis strain categorization.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for strain data access\n- No query parameters or request body needed\n\n**Response Data:**\n- Response format: `[string, string, string, string]`\n- Example: `[\"Indica\", \"Sativa\", \"Hybrid\", \"CBD\"]`\n- Returns available strain type classifications\n- Includes standard classifications: Indica, Sativa, Hybrid, CBD\n- Reference data for strain type validation\n\n**Common Use Cases:**\n- Validate strain type values before creating or updating strains\n- Populate strain type dropdown lists in user interfaces\n- Reference data for strain classification validation\n- Support product categorization by genetic type\n- Ensure consistency in strain type terminology\n\n**Performance & Limits:**\n- Reference data with immediate response\n- Small dataset suitable for frequent caching\n- No location filtering needed for standard classifications\n- Consistent across all locations and organizations\n\n**Related Endpoints:**\n- `POST /strains` - Create or update strains (validates against these types)\n- `GET /strains` - Get all strains with their assigned types\n\n**Important Notes:**\n- These are the only valid values accepted for strain type in strain creation/updates\n- Values are case-sensitive when used in strain operations\n- Standard cannabis industry classifications for genetic types\n- Used for product menu organization and customer filtering", "operationId": "StrainsTypesGet", "responses": { "200": { "description": "Success - Returns array of strings with strain type names: `[\"Indica\", \"Sativa\", \"Hybrid\", \"CBD\"]`", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for inventory access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/table/tables": { "get": { "tags": ["Table"], "summary": "Get Tables", "description": "**Purpose:** Retrieve dining tables or seating areas configured for the location to support hospitality operations and table management.\n\n**Request Requirements:**\n- \"Room\" role authorization required for table data access\n- Optional filtering parameters available for specific table lookup\n- Table management permissions for hospitality operations\n\n**Response Data:**\n- Returns array of `Table` objects with table identification details\n- Array typically contains 10-100 tables depending on hospitality operation size\n- Returns empty array `[]` if no tables match criteria (not null)\n- Includes table identification and naming information (TableId, TableName)\n- Results automatically filtered to authenticated location\n\n**Filtering Options:**\n- **tableId**: Optional integer parameter to retrieve specific table by ID\n- **tableName**: Optional string parameter to search tables by name\n- **Combined Filtering**: Parameters can be used together for precise table lookup\n- **No Filters**: Returns all tables when no parameters provided\n\n**Table Information Included:**\n- **TableId**: Unique identifier for each dining table or seating area\n- **TableName**: Human-readable name for table identification and assignment\n\n**Common Use Cases:**\n- Populate table dropdown lists in reservation and seating management\n- Display available tables for customer seating assignments\n- Support hospitality operation table management and configuration\n- Enable table-specific service tracking and order management\n- Facilitate dining room management and table allocation workflows\n\n**Performance & Limits:**\n- Efficient table lookup optimized for hospitality operation workflows\n- Flexible filtering for specific table management needs\n- No pagination needed for typical table counts per location\n- Results consistent across hospitality and service management systems\n\n**Related Endpoints:**\n- `POST /table` - Create or update table configuration\n- `GET /guest-list` - View guest check-ins by table assignments\n- `POST /transaction` - Process transactions linked to table service\n\n**Important Notes:**\n- **Hospitality Integration**: Essential for dining room management and table service\n- **Table Management**: Supports table configuration and seating assignments\n- **Location Specific**: Results filtered to authenticated location table setup\n- **Service Ready**: Table data used throughout hospitality service workflows\n- **Flexible Lookup**: Multiple filtering options for precise table management", "operationId": "TableTablesGet", "parameters": [ { "name": "tableId", "in": "query", "description": "Optional table ID for specific table lookup - integer", "schema": { "type": "integer", "format": "int32" } }, { "name": "tableName", "in": "query", "description": "Optional table name for searching tables by name - string", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Success - Returns array of table objects: `[{ Table }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Table" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for table access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/table": { "post": { "tags": ["Table"], "summary": "Create or Update Table", "description": "**Purpose:** Create a new dining table or update an existing table configuration for hospitality operations and seating management.\n\n**Request Requirements:**\n- \"Room\" role authorization required for table data modification\n- `Table` object in request body with table information\n- Content-Type: application/json\n- Table management permissions for hospitality operations\n\n**Response Data:**\n- Returns single `Table` object (not array) with updated table information\n- Includes assigned TableId for new tables or updated ID for existing tables\n- Complete table information with all fields populated (TableId, TableName)\n- Table identification and naming information\n\n**Create vs Update Behavior:**\n- **CREATE**: When TableId is null or 0, a new table record will be created\n- **UPDATE**: When TableId is provided with a positive integer, the existing table will be updated\n- **Identification**: Table existence determined by TableId value (null/0 = create, positive = update)\n- **Automatic Detection**: System automatically determines create vs update based on TableId\n\n**Table Data Fields:**\n- **TableId**: Unique identifier for table (null/0 for new tables, positive integer for updates)\n- **TableName**: Human-readable name for table identification and assignment\n\n**Common Use Cases:**\n- Add new dining tables to hospitality seating configuration\n- Update existing table names or configuration details\n- Modify table setup for dining room reorganization\n- Create table assignments for hospitality service workflows\n- Support dining room management and table allocation systems\n\n**Performance & Limits:**\n- Single table operation for targeted table management\n- Immediate table configuration update reflected in hospitality systems\n- Optimized for dining room management and seating workflows\n- Changes reflected immediately in table assignment and service systems\n\n**Related Endpoints:**\n- `GET /table/tables` - Retrieve existing table configuration before updates\n- `GET /guest-list` - View guest check-ins that use table assignments\n- `POST /transaction` - Process transactions linked to table service\n\n**Important Notes:**\n- **TableId Assignment**: New tables receive automatically generated TableId\n- **Hospitality Integration**: Table configuration affects seating and service workflows\n- **Location Scoped**: Tables automatically associated with authenticated location\n- **Service Ready**: Table data immediately available for hospitality operations\n- **Configuration Management**: Supports dining room setup and table organization", "operationId": "TablePost", "requestBody": { "description": "Table information to create or update - Table object with TableId and TableName fields", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/Table" } }, "application/json": { "schema": { "$ref": "#/components/schemas/Table" } }, "text/json": { "schema": { "$ref": "#/components/schemas/Table" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/Table" } } }, "x-bodyName": "table" }, "responses": { "200": { "description": "Success - Returns single table object: `{ Table }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Table" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for table modification" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/tag": { "get": { "tags": ["Tag"], "summary": "Get Tags", "description": "**Purpose:** Retrieve all inventory tracking tags available for the location to support inventory management and regulatory compliance tracking.\n\n**Request Requirements:**\n- \"Inventory\" role authorization required for tag data access\n- No query parameters or request body needed\n- Inventory management permissions for tag tracking operations\n\n**Response Data:**\n- Returns array of `Tag` objects with tag identification information\n- Array typically contains 100-10,000 tags depending on facility operation size\n- Returns empty array `[]` if no tags are available (not null)\n- Includes tag names and unique identifiers for inventory assignment\n- Results automatically filtered to authenticated service provider level\n\n**Tag Information Included:**\n- **TagId**: Unique numeric identifier for each tag\n- **TagName**: Human-readable name or label for the tag\n- **Assignment Ready**: Tag information available for inventory assignment operations\n\n**Common Use Cases:**\n- Populate tag dropdown lists in inventory management interfaces\n- Display available tags for plant and package assignment workflows\n- Support inventory tracking and regulatory compliance operations\n- Enable tag allocation and assignment for cultivation and retail workflows\n- Facilitate state system integration and regulatory reporting requirements\n\n**Performance & Limits:**\n- Comprehensive tag data retrieval for inventory management\n- Service provider level tag access for facility operations\n- Optimized for inventory tracking and compliance workflows\n- Results include all available tags for assignment and tracking\n\n**Related Endpoints:**\n- `POST /package/set-tags` - Assign tags to inventory packages\n- `POST /package/add-tags` - Add additional tags to packages\n- `POST /package/remove-tags` - Remove tags from inventory packages\n\n**Important Notes:**\n- **Compliance Critical**: Essential for regulatory compliance and state system integration\n- **Inventory Integration**: Tag data used throughout inventory tracking workflows\n- **Service Provider Scoped**: Tags filtered to authenticated service provider level\n- **Assignment Ready**: Tag data immediately available for inventory assignment operations\n- **Regulatory Tracking**: Tags support state system compliance and audit requirements", "operationId": "TagGet", "responses": { "200": { "description": "Success - Returns array of tag objects: `[{ Tag }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Tag" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for inventory access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/terminals": { "get": { "tags": ["Terminals"], "summary": "Get Terminals", "description": "**Purpose:** Retrieve all point-of-sale terminals configured for the location to support transaction processing and retail operations.\n\n**Request Requirements:**\n- Valid API key authentication required for terminal data access\n- No specific role restrictions beyond authentication\n- No query parameters or request body needed\n\n**Response Data:**\n- Returns array of `Terminal` objects with terminal identification information\n- Response format: `[{ Terminal }, { Terminal }, ...]`\n- Array typically contains 1-10 terminals depending on retail operation size\n- Returns empty array `[]` if no terminals are configured (not null)\n- Includes terminal identification and naming information only\n- Results automatically filtered to authenticated location\n\n**Terminal Information Included:**\n- **TerminalId**: Unique numeric identifier for each point-of-sale terminal\n- **TerminalName**: Human-readable name for terminal identification\n\n**Common Use Cases:**\n- Populate terminal dropdown lists in transaction processing interfaces\n- Display available terminals for cashier assignment and management\n- Support point-of-sale system configuration and setup\n- Enable terminal-specific transaction tracking and reporting\n- Facilitate retail operation management and terminal allocation\n\n**Performance & Limits:**\n- Lightweight operation optimized for frequent terminal lookups\n- Small dataset suitable for real-time retail operation workflows\n- No pagination needed due to limited terminal counts per location\n- Results consistent across point-of-sale and transaction systems\n\n**Related Endpoints:**\n- `POST /transaction` - Process transactions using configured terminals\n- `GET /reporting/register-transactions` - View terminal-specific transaction history\n- `GET /reporting/cash-summary` - Terminal cash management and reconciliation\n\n**Important Notes:**\n- **Retail Integration**: Essential for point-of-sale operations and transaction processing\n- **Terminal Management**: Supports retail terminal configuration and assignment\n- **Location Specific**: Results filtered to authenticated location terminal setup\n- **Real-time Access**: Current terminal availability and configuration information\n- **Transaction Ready**: Terminal data used throughout retail transaction workflows", "operationId": "TerminalsGet", "responses": { "200": { "description": "Success - Returns array of terminal objects: `[{ Terminal }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Terminal" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/transaction/create-anonymous": { "post": { "tags": ["Transaction"], "summary": "Create Anonymous Customer Transaction", "description": "**Purpose:** Create an anonymous customer profile and automatically check them into the dispensary guest list for pickup or service.\n\n**Request Requirements:**\n- \"PreOrder\" role authorization required for transaction creation\n- `CreateAnonymousTransactionRequest` object in request body\n- Content-Type: application/json\n- Optional transaction reference for internal tracking\n\n**Response Data:**\n- Returns anonymous transaction object: `{ AnonymousTransaction }`\n- CustomerId: Temporary customer identifier for this session\n- TransactionId: Transaction identifier for order processing and tracking\n- UniqueId: System-generated unique identifier for customer lookup\n\n**Process Flow:**\n1. Anonymous profile creation: Generate temporary customer record with unique identifier\n2. Guest list check-in: Automatically add customer to dispensary queue/guest list\n3. Transaction setup: Create transaction record for order processing\n4. Unique tracking: Assign unique ID for following up on order status\n\n**Common Use Cases:**\n- Process walk-in customers without pre-existing accounts\n- Provide quick service for customers who prefer not to create full accounts\n- Handle one-time or occasional customers efficiently\n- Accommodate privacy-focused customers who prefer minimal data collection\n- Bridge anonymous sales with customer tracking systems for POS integration\n\n**Performance & Limits:**\n- Immediate customer profile and transaction creation\n- Automatic guest list integration for streamlined workflow\n- Temporary records designed for single-session use\n- Optimized for high-volume walk-in customer processing\n\n**Related Endpoints:**\n- `POST /preorder/submit` - Create orders for existing customers with full profiles\n- `GET /guest-list` - View current guest list including anonymous customers\n\n**Important Notes:**\n- Anonymous customer profiles are temporary and session-based\n- Customer automatically appears in dispensary queue/guest list\n- Optional transaction reference field for external system correlation\n- Each anonymous customer gets a unique system identifier\n- Minimal data collection while maintaining operational requirements\n- Choose this for walk-ins who don't want accounts; use preorder endpoints for existing customers", "operationId": "TransactionCreate-anonymousPost", "requestBody": { "description": "Anonymous transaction request with optional transaction reference - CreateAnonymousTransactionRequest object", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/CreateAnonymousTransactionRequest" } }, "application/json": { "schema": { "$ref": "#/components/schemas/CreateAnonymousTransactionRequest" } }, "text/json": { "schema": { "$ref": "#/components/schemas/CreateAnonymousTransactionRequest" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/CreateAnonymousTransactionRequest" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "Success - Returns anonymous transaction object: `{ AnonymousTransaction }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AnonymousTransaction" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for transaction creation" }, "500": { "description": "Internal Server Error - Server error occurred during transaction creation" } } } }, "/util/AuthorizationHeader/{apiKey}": { "get": { "tags": ["Util"], "summary": "Generate Authorization Header", "description": "**Purpose:** Convert an API key into a properly formatted authorization header for initial API client setup and testing.\n\n**Intended Use:** This utility endpoint is designed for initial setup and testing workflows. For production applications, consider encoding headers client-side using Base64: `Basic {base64(api_key:)}`\n\n**Request Requirements:**\n- No authentication required - public utility endpoint\n- API key provided as URL path parameter\n- Utility function for API client development and testing\n\n**Response Data:**\n- Returns single string value (not array) with formatted authorization header\n- Basic authentication header format: \"Basic [base64-encoded-api-key]\"\n- Ready-to-use authorization header value for HTTP clients\n- Base64 encoded API key in standard HTTP Basic authentication format\n\n**Authorization Header Format:**\n- **Encoding**: API key converted to Base64 ASCII encoding\n- **Format**: \"Basic {base64-encoded-key}\" format for HTTP Authorization header\n- **Standards Compliant**: Follows HTTP Basic Authentication specification\n- **Client Ready**: Direct usage in HTTP client authorization headers\n\n**Common Use Cases:**\n- Initial API client setup and configuration\n- Development and testing workflows\n- Manual header generation for API testing tools\n- Integration development and troubleshooting\n\n**Related Endpoints:**\n- `GET /whoami` - Verify API key validity and location access\n- `GET /health` - Test basic API connectivity\n- All other endpoints that require the generated authorization header\n\n**Important Notes:**\n- **Public Utility**: No authentication required for this utility endpoint\n- **Developer Tool**: Designed for API client development and testing support\n- **Header Generation**: Produces standard HTTP Basic authentication headers\n- **Standards Compliant**: Follows HTTP Basic Authentication formatting requirements", "operationId": "UtilAuthorizationHeaderByApiKeyGet", "parameters": [ { "name": "apiKey", "in": "path", "description": "API key to convert into authorization header format - string", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Success - Returns formatted authorization header string: \"Basic {base64-encoded-key}\"", "content": { "application/json": { "schema": { "type": "string" } } } } } } }, "/vehicles": { "get": { "tags": ["Vehicles"], "summary": "Get Vehicles", "description": "**Purpose:** Retrieve all vehicles available for delivery and transportation operations to support logistics and compliance tracking.\n\n**Request Requirements:**\n- \"Reporting\" or \"Deliveries\" role authorization required for vehicle data access\n- No query parameters or request body needed\n\n**Response Data:**\n- Response format: `[{ VehicleDetail }, { VehicleDetail }, ...]`\n- Array typically contains 1-20 vehicles depending on delivery operation size\n- Returns empty array `[]` if no vehicles are configured (not null)\n- Includes vehicle identification, specifications, and operational details\n- License plate numbers, make/model information, and registration data\n- Results automatically filtered to authenticated location\n\n**Vehicle Information Included:**\n- **Identification**: Vehicle ID, license plate, VIN numbers\n- **Specifications**: Make, model, year, color, and vehicle type\n- **Registration**: Registration status and compliance information\n- **Operational**: Availability status and assignment details\n\n**Common Use Cases:**\n- Populate vehicle dropdown lists in delivery assignment forms\n- Display vehicle fleet information for logistics management\n- Support delivery route planning and vehicle allocation\n- Maintain vehicle records for compliance and regulatory requirements\n- Generate vehicle utilization reports for operational analysis\n\n**Performance & Limits:**\n- Lightweight operation optimized for frequent vehicle lookups\n- Small dataset suitable for real-time delivery assignment workflows\n- No pagination needed due to limited fleet sizes\n- Results consistent across delivery management operations\n\n**Related Endpoints:**\n- `POST /vehicles` - Create or update vehicle information\n- `GET /drivers` - Get drivers who can operate vehicles\n- `POST /deliveries/set-route-detail` - Assign vehicles to delivery routes\n\n**Important Notes:**\n- **Fleet Management**: Essential for delivery operations and logistics coordination\n- **Compliance Ready**: Vehicle data supports regulatory compliance and tracking\n- **Location Specific**: Results filtered to authenticated location vehicle fleet\n- **Real-time Access**: Current vehicle availability and status information\n- **Delivery Integration**: Vehicle data used throughout delivery assignment workflows", "operationId": "VehiclesGet", "responses": { "200": { "description": "Success - Returns array of vehicle objects: `[{ VehicleDetail }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/VehicleDetail" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for vehicle access" }, "500": { "description": "Internal Server Error - Server error occurred" } } }, "post": { "tags": ["Vehicles"], "summary": "Create or Update Vehicle", "description": "**Purpose:** Create a new vehicle or update an existing vehicle with comprehensive fleet information for delivery operations and compliance tracking.\n\n**Request Requirements:**\n- \"Reporting\" or \"Deliveries\" role authorization required for vehicle data modification\n- `VehicleDetail` object in request body with vehicle information\n- Content-Type: application/json\n- Validation performed on vehicle data before processing\n\n**Response Data:**\n- Response format: `200 OK` (no response body)\n- No data returned - operation confirmation only\n- Returns HTTP 400 with validation errors if request data is invalid\n\n**Create vs Update Behavior:**\n- **CREATE**: When VehicleId is null, 0, or omitted, a new vehicle record will be created\n- **UPDATE**: When VehicleId is provided with a valid vehicle ID, the existing vehicle will be updated\n- **Identification**: Vehicle existence determined by VehicleId value\n- **Automatic Detection**: System automatically determines create vs update based on vehicle data\n\n**Sparse Update Behavior:**\n- **Validation Required**: All provided vehicle data must pass validation checks\n- **Field Updates**: Provided fields will update existing vehicle information\n- **Data Integrity**: Validation ensures vehicle data meets operational requirements\n- **Fleet Consistency**: Updates maintain fleet data consistency and compliance standards\n\n**Vehicle Data Fields:**\n- **Identification**: License plate, VIN, vehicle ID\n- **Specifications**: Make, model, year, color, vehicle type\n- **Registration**: Registration information and compliance data\n- **Operational**: Status, availability, and assignment details\n\n**Common Use Cases:**\n- Add new vehicles to delivery fleet for expanded operations\n- Update existing vehicle information when details change\n- Maintain vehicle registration and compliance records\n- Support fleet management and vehicle tracking requirements\n- Ensure accurate vehicle data for delivery route assignments\n\n**Performance & Limits:**\n- Single vehicle operation for targeted fleet management\n- Comprehensive validation performed before any changes\n- Changes reflected immediately in delivery assignment systems\n- Optimized for fleet management and compliance workflows\n\n**Related Endpoints:**\n- `GET /vehicles` - Retrieve existing vehicle data before updates\n- `GET /drivers` - Manage driver assignments for vehicles\n- `POST /deliveries/set-route-detail` - Assign updated vehicles to delivery routes\n\n**Important Notes:**\n- **Validation Critical**: All vehicle data must pass validation before processing\n- **Fleet Integration**: Vehicle updates affect delivery assignment and logistics systems\n- **Compliance Essential**: Vehicle data must meet regulatory requirements for delivery operations\n- **Location Scoped**: Vehicles automatically associated with authenticated location\n- **Operation Confirmation**: Success indicated by HTTP 200 status (no response body)", "operationId": "VehiclesPost", "requestBody": { "description": "Vehicle information to create or update - VehicleDetail object with fleet details", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/VehicleDetail" } }, "application/json": { "schema": { "$ref": "#/components/schemas/VehicleDetail" } }, "text/json": { "schema": { "$ref": "#/components/schemas/VehicleDetail" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/VehicleDetail" } } }, "x-bodyName": "vehicle" }, "responses": { "200": { "description": "Success" }, "400": { "description": "Bad Request - `ValidationResult` object with `isValid` boolean, `errors` array, and `ruleSetsExecuted` array", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationResult" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/vendor/vendors": { "get": { "tags": ["Vendor"], "summary": "Get Vendors", "description": "**Purpose:** Retrieves a list of vendors with optional filtering by vendor ID or name for procurement and inventory management.\n\n**Request Requirements:**\n- \"Vendor\" role authorization required for vendor data access\n- Optional query parameters for filtering results\n- No request body needed\n\n**Response Data:**\n- Response format: `[{ Vendor }, { Vendor }, ...]`\n- Array typically contains 5-50 vendors per location\n- Returns empty array `[]` if no vendors configured or match filtering criteria\n- Includes contact details, address, and license information\n- Results are automatically filtered by the authenticated user's location\n- Vendor ID, name, and contact information included\n\n**Filtering Options:**\n- No parameters: Returns all vendors for the location\n- vendorId: Returns specific vendor by ID\n- vendorName: Filters vendors by name with partial matching support\n- Both parameters: Can be used together for more specific filtering\n\n**Common Use Cases:**\n- Populate vendor dropdown lists in purchase order creation forms\n- Search for specific vendors by name or ID for quick lookup\n- Synchronize vendor data with external inventory management systems\n- Display vendor contact information for procurement and purchasing\n- Maintain vendor databases for supply chain management\n\n**Performance & Limits:**\n- Rate limiting disabled for this endpoint to support frequent lookups\n- Lightweight response for fast vendor list population\n- Efficient filtering for large vendor databases\n- Results cached for improved performance\n\n**Related Endpoints:**\n- `POST /vendor` - Create or update vendor information\n\n**Important Notes:**\n- Results are automatically filtered to the authenticated user's location\n- Vendor name filtering supports partial matching for flexible search\n- Both filtering parameters can be used simultaneously for precise results\n- No rate limiting applied to support frequent vendor lookups", "operationId": "VendorVendorsGet", "parameters": [ { "name": "vendorId", "in": "query", "description": "Optional vendor ID to filter by specific vendor - Returns exact match", "schema": { "type": "integer", "format": "int32" } }, { "name": "vendorName", "in": "query", "description": "Optional vendor name to filter by - Supports partial matching for flexible search", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Success - Returns array of vendor objects: `[{ Vendor }, ...]`", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Vendor" } } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for vendor access" }, "500": { "description": "Internal Server Error - Server error occurred" } } } }, "/vendor": { "post": { "tags": ["Vendor"], "summary": "Create or Update Vendor", "description": "**Purpose:** Create a new vendor or update an existing vendor with comprehensive supplier information for procurement and inventory management.\n\n**Request Requirements:**\n- \"Vendor\" role authorization required for vendor data modification\n- `Vendor` object in request body with vendor details\n- Content-Type: application/json\n- All vendor fields are optional (no validation performed)\n\n**Response Data:**\n- Response format: `{ Vendor }`\n- Returns single `Vendor` object (not array) with updated vendor information\n- Includes assigned VendorId for new vendors or updated ID for existing vendors\n- Complete vendor information with all fields populated\n- Contact details, address, and license information included\n\n**Create vs Update Behavior:**\n- **CREATE**: When VendorId is null, 0, or omitted, a new vendor record will be created\n- **UPDATE**: When VendorId is provided with a valid vendor ID, the existing vendor will be updated\n- **Identification**: Vendor existence determined by VendorId value\n- **Automatic Detection**: System automatically determines create vs update based on VendorId\n\n**Sparse Update Behavior:**\n- **No Required Fields**: All fields are optional\n- **Optional Fields**: Address, contact, and license fields can be omitted to preserve existing values\n- **Null Handling**: Null values will overwrite existing data (use with caution)\n- **Field Independence**: Each field can be updated independently\n\n**Required Fields:**\n- **None**: No validation is performed on any fields\n\n**Optional Fields:**\n- **Address, City, State, PostalCode**: Physical address information for shipping and contact\n- **LicenseNumber**: Vendor's business license number for compliance tracking\n- **ContactName, ContactEmail, ContactPhone**: Primary contact information for procurement\n\n**Common Use Cases:**\n- Add new suppliers to the vendor database for procurement management\n- Update existing vendor contact information when details change\n- Maintain vendor address and license details for compliance\n- Establish vendor relationships for purchase orders and inventory management\n- Synchronize vendor data with external procurement systems\n\n**Performance & Limits:**\n- Single vendor operation for targeted supplier management\n- Immediate validation and response with complete vendor data\n- Changes reflected immediately in vendor catalogs and purchase order systems\n- Optimized for vendor relationship management workflows\n\n**Related Endpoints:**\n- `GET /vendor/vendors` - Retrieve existing vendor data before updates\n- `POST /purchase-orders` - Create purchase orders using vendor relationships\n- `GET /inventory` - View inventory from specific vendors\n\n**Important Notes:**\n- **VendorId Assignment**: New vendors receive automatically generated VendorId\n- **No Validation**: No validation is performed before creation/update\n- **Supplier Relationships**: Vendor data used throughout procurement and inventory systems\n- **Location Scoped**: Vendors automatically associated with authenticated location\n- **Contact Management**: Maintain accurate contact information for effective supplier communication", "operationId": "VendorPost", "requestBody": { "description": "Vendor information to create or update - Vendor object with supplier details", "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/Vendor" } }, "application/json": { "schema": { "$ref": "#/components/schemas/Vendor" } }, "text/json": { "schema": { "$ref": "#/components/schemas/Vendor" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/Vendor" } } }, "x-bodyName": "vendor" }, "responses": { "200": { "description": "Success - Returns vendor object: `{ Vendor }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Vendor" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - Account not authorized for vendor management" }, "500": { "description": "Internal Server Error - Server error occurred during vendor operation" } } } }, "/waste": { "get": { "tags": ["Waste"], "summary": "Get Waste Records", "description": "**Purpose:** Retrieve comprehensive waste disposal records for cultivation and compliance tracking to support regulatory reporting and facility management.\n\n**Request Requirements:**\n- \"CultivationWrite\" role authorization required for waste data access\n- No query parameters or request body needed\n- Waste tracking permissions essential for compliance operations\n\n**Response Data:**\n- Returns single `WasteSummary` object (not array) with comprehensive waste information\n- Response format: `{ WasteSummary }`\n- Includes categorized waste records by type and source\n- Contains room waste, harvest waste, and plant waste details\n- Waste disposal tracking and compliance documentation\n- Results automatically filtered to authenticated location\n\n**Waste Categories Included:**\n- **Room Waste**: General cultivation room waste disposal records\n- **Harvest Waste**: Plant material disposal from harvest operations\n- **Plant Waste**: Individual plant disposal and destruction records\n\n**Common Use Cases:**\n- Generate regulatory compliance reports for waste disposal\n- Track cultivation facility waste management and disposal\n- Support compliance audits and regulatory inspections\n- Monitor waste disposal efficiency and facility operations\n- Maintain cultivation facility waste tracking for legal requirements\n\n**Performance & Limits:**\n- Comprehensive waste data retrieval for facility management\n- Location-specific waste records for compliance tracking\n- Optimized for regulatory reporting and compliance workflows\n- Results include all waste categories and disposal records\n\n**Related Endpoints:**\n- `GET /harvest` - View harvest operations that generate waste\n- `GET /plant` - Track plants before waste disposal\n- `POST /plant/harvest` - Harvest operations that create waste records\n\n**Important Notes:**\n- **Compliance Critical**: Essential for regulatory compliance and waste tracking\n- **Cultivation Focus**: Specific to cultivation facility waste management\n- **Location Scoped**: Waste records filtered to authenticated location\n- **Regulatory Ready**: Data formatted for compliance reporting requirements\n- **Disposal Tracking**: Comprehensive waste disposal and destruction records", "operationId": "WasteGet", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WasteSummary" } } } }, "401": { "description": "Invalid API Key" }, "403": { "description": "Account not authorized" }, "500": { "description": "Something went wrong." } } } }, "/waste/HarvestWaste": { "post": { "tags": ["Waste"], "operationId": "WasteHarvestWastePost", "requestBody": { "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/HarvestWasteDetailWaste" } }, "application/json": { "schema": { "$ref": "#/components/schemas/HarvestWasteDetailWaste" } }, "text/json": { "schema": { "$ref": "#/components/schemas/HarvestWasteDetailWaste" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/HarvestWasteDetailWaste" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object" } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "type": "string" } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } } }, "/waste/PlantWaste": { "post": { "tags": ["Waste"], "operationId": "WastePlantWastePost", "requestBody": { "content": { "application/json-patch+json": { "schema": { "$ref": "#/components/schemas/PlantWasteDetailWaste" } }, "application/json": { "schema": { "$ref": "#/components/schemas/PlantWasteDetailWaste" } }, "text/json": { "schema": { "$ref": "#/components/schemas/PlantWasteDetailWaste" } }, "application/*+json": { "schema": { "$ref": "#/components/schemas/PlantWasteDetailWaste" } } }, "x-bodyName": "req" }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object" } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "type": "string" } } } }, "401": { "description": "Unauthorized" }, "403": { "description": "Forbidden" }, "500": { "description": "Internal Server Error" } } } }, "/whoami": { "get": { "tags": ["WhoAmI"], "summary": "Verify API key and get location identity information", "description": "**Purpose:** Verifies your API key is valid and returns detailed information about the location/store it's associated with.\n\n**Request Requirements:**\n- Any authenticated role authorization (no specific role required)\n- No query parameters or request body needed\n\n**Response Data:**\n- Response format: `{ LocationIdentity }`\n- Returns location identity object with complete location and company information\n- Location details including name, address, license number, and business information\n- Parent company (LSP) details and global identifiers\n- Configuration settings like customer profile sharing preferences\n- Regional data for compliance and routing\n\n**Common Use Cases:**\n- Confirm your API key is working correctly for API key validation\n- Identify which store/location your API key accesses for location discovery\n- Determine current location context for multi-location applications\n- Get location details for application initialization and configuration setup\n- Troubleshoot authentication and location access issues during debugging\n\n**Performance & Limits:**\n- Lightweight operation with immediate response\n- No rate limiting typically applied to identity verification\n- Recommended as first call when setting up API integration\n- Cached results can be used for session duration\n\n**Related Endpoints:**\n- No direct related endpoints - this is a foundational identity endpoint\n\n**Important Notes:**\n- Call this endpoint first when setting up API integration\n- Verify authentication and understand your location context before other calls\n- Response includes both location-specific and company-wide identifiers\n- Regional information helps with compliance and API routing decisions\n\n**Response Fields:**\n- `LocationId` / `LocationName` for store identification\n- `LspId` / `LspName` for parent company information\n- `Address`, `City`, `State`, `PostalCode` for physical location\n- `LicenseNumber` for business license and compliance\n- `ShareCustomerProfiles` for customer data sharing configuration\n- `LocationGlobalId` / `LspGlobalId` for global unique identifiers", "operationId": "WhoamiGet", "responses": { "200": { "description": "Success - Returns location identity object: `{ LocationIdentity }`", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LocationIdentity" } } } }, "401": { "description": "Unauthorized - Invalid or missing API key" }, "403": { "description": "Forbidden - API key doesn't have access to this location" }, "404": { "description": "Not Found - Location not found for the authenticated API key" }, "500": { "description": "Internal Server Error - Server error occurred" } } } } }, "components": { "schemas": { "Address": { "type": "object", "properties": { "addressId": { "type": "integer", "format": "int32", "nullable": true }, "customerId": { "type": "integer", "format": "int32" }, "street": { "type": "string", "nullable": true }, "street2": { "type": "string", "nullable": true }, "city": { "type": "string", "nullable": true }, "state": { "type": "string", "nullable": true }, "postal_code": { "type": "string", "nullable": true }, "country_Code": { "type": "string", "nullable": true }, "latitude": { "type": "number", "format": "double", "nullable": true }, "longitude": { "type": "number", "format": "double", "nullable": true }, "county": { "type": "string", "nullable": true }, "additionalStateIdentifiers": { "type": "string", "nullable": true } }, "additionalProperties": false }, "AllocatedDeliveryItem": { "type": "object", "properties": { "transactionId": { "type": "integer", "format": "int32" }, "productName": { "type": "string", "nullable": true }, "quantity": { "type": "number", "format": "double" }, "totalPrice": { "type": "number", "format": "double" }, "totalDiscount": { "type": "number", "format": "double" }, "totalTax": { "type": "number", "format": "double" } }, "additionalProperties": false }, "AllocatedPreOrderItem": { "type": "object", "properties": { "productName": { "type": "string", "nullable": true }, "quantity": { "type": "number", "format": "double" }, "totalPrice": { "type": "number", "format": "double" }, "totalDiscount": { "type": "number", "format": "double" }, "totalTax": { "type": "number", "format": "double" } }, "additionalProperties": false }, "AnonymousTransaction": { "type": "object", "properties": { "customerId": { "type": "integer", "description": "Unique identifier for the customer record associated with this anonymous transaction.", "format": "int32" }, "transactionId": { "type": "integer", "description": "Unique identifier for the transaction record.", "format": "int32" }, "uniqueId": { "type": "string", "description": "String representation of the unique identifier for API responses.", "nullable": true, "readOnly": true } }, "additionalProperties": false, "description": "Anonymous transaction response model containing transaction identifiers for guest checkout operations." }, "AppliedDiscount": { "type": "object", "properties": { "discountId": { "type": "integer", "description": "Unique identifier for the discount program or campaign applied.", "format": "int32" }, "discountName": { "type": "string", "description": "Display name of the discount for customer receipts and reporting.", "nullable": true }, "discountReason": { "type": "string", "description": "Reason or justification for the discount application (e.g., \"Loyalty Reward\", \"Medical Patient\").", "nullable": true }, "amount": { "type": "number", "description": "Discount amount applied to the transaction item (in USD, positive value represents savings).", "format": "double" }, "transactionItemId": { "type": "integer", "description": "Reference identifier linking this discount back to the specific transaction line item.\nNot guaranteed to be unique outside of a single transaction.", "format": "int32", "readOnly": true } }, "additionalProperties": false, "description": "Discount information applied to a specific transaction item in cannabis retail operations." }, "AssignPlantsToGroupRequest": { "type": "object", "properties": { "plantGroupName": { "type": "string", "description": "Name of target plant group for batch organization and cultivation tracking", "nullable": true }, "plantSerialNumbers": { "type": "array", "items": { "type": "string" }, "description": "Collection of plant serial numbers to assign to the specified plant group", "nullable": true } }, "additionalProperties": false, "description": "Request model for assigning existing cannabis plants to a specific plant group for batch management and cultivation workflow organization.\n\n**Plant Group Assignment:**\n- Assigns existing plants to target plant group using serial numbers\n- Supports batch organization for cultivation workflow management\n- Plants identified by serial numbers for precise assignment\n- Validates target plant group exists before assignment\n\n**Serial Number Identification:**\n- Plants identified by their unique serial numbers rather than IDs\n- All serial numbers must correspond to existing plants in the facility\n- Plants must be accessible to the authenticated location\n- Serial numbers must match exact plant tracking identifiers\n\n**Batch Management:**\n- Plant groups enable batch-based cultivation tracking and compliance\n- Supports harvest planning and cultivation scheduling optimization\n- Facilitates cultivation management and operational efficiency" }, "BadRequestPropertyError": { "type": "object", "properties": { "propertyName": { "type": "string", "description": "Name of the property that failed validation.", "nullable": true }, "propertyError": { "type": "string", "description": "Description of the validation error for the specified property.", "nullable": true } }, "additionalProperties": false, "description": "Field-specific validation error details for BadRequest responses." }, "BadRequestResponse": { "type": "object", "properties": { "message": { "type": "string", "description": "General error message describing the nature of the bad request.", "nullable": true }, "propertyErrors": { "type": "array", "items": { "$ref": "#/components/schemas/BadRequestPropertyError" }, "description": "Collection of field-specific validation errors for detailed feedback.", "nullable": true } }, "additionalProperties": false, "description": "Standardized error response model for HTTP 400 Bad Request responses across the API." }, "BatchDetails": { "type": "object", "properties": { "batchName": { "type": "string", "description": "Display name for the immature plant batch for identification and organization.", "nullable": true }, "plantType": { "type": "string", "description": "Plant type designation for the batch (e.g., \"Seedling\", \"Clone\", \"Cutting\").", "nullable": true }, "plantCount": { "type": "integer", "description": "Number of plants in the immature batch for inventory tracking and compliance.", "format": "int32" }, "strainId": { "type": "integer", "description": "Strain identifier for the cannabis strain being cultivated in this batch.", "format": "int32" }, "roomId": { "type": "integer", "description": "Room identifier for the immature batch location assignment.", "format": "int32" }, "tableId": { "type": "integer", "description": "Table identifier within the room for precise location tracking (optional).", "format": "int32", "nullable": true }, "motherPlantId": { "type": "integer", "description": "Mother plant identifier for tracking genetic lineage (required for clone batches).", "format": "int32", "nullable": true }, "dateCreated": { "type": "string", "description": "Date when the immature batch was created for cultivation timeline documentation.", "format": "date-time", "nullable": true } }, "additionalProperties": false, "description": "Detailed specification for creating individual immature plant batches with cultivation and compliance information." }, "BooleanNullableOptional": { "type": "boolean", "additionalProperties": false }, "BooleanOptional": { "type": "boolean", "additionalProperties": false }, "Brand": { "type": "object", "properties": { "brandId": { "type": "integer", "format": "int32" }, "brandName": { "type": "string", "nullable": true }, "brandCatalogBrandId": { "type": "string", "nullable": true } }, "additionalProperties": false }, "BrandEditRequest": { "type": "object", "properties": { "brandId": { "type": "integer", "format": "int32", "nullable": true }, "brandName": { "type": "string", "nullable": true } }, "additionalProperties": false }, "BroadcastedResponses": { "type": "object", "properties": { "responses": { "type": "array", "items": { "$ref": "#/components/schemas/LocationResponse" }, "nullable": true } }, "additionalProperties": false }, "BulkCreateOrUpdateHarvest": { "type": "object", "properties": { "harvests": { "type": "array", "items": { "$ref": "#/components/schemas/BulkHarvestDetail" }, "nullable": true } }, "additionalProperties": false }, "BulkCreateOrUpdateHarvestResponse": { "type": "object", "properties": { "createdHarvestIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true }, "updatedHarvestIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true } }, "additionalProperties": false }, "BulkHarvestDetail": { "type": "object", "properties": { "harvestId": { "type": "integer", "format": "int32", "nullable": true }, "harvestName": { "type": "string", "nullable": true }, "harvestRoomId": { "type": "integer", "format": "int32" }, "harvestDate": { "type": "string", "format": "date-time", "nullable": true }, "strainId": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, "CalculationMethod": { "enum": [1, 2, 3, 4, 5, 6, 15], "type": "integer", "format": "int32" }, "CancelPreorderRequest": { "type": "object", "properties": { "orderId": { "type": "integer", "description": "Unique identifier of the pre-order to be canceled.", "format": "int32" }, "cancellationReason": { "type": "string", "description": "Required reason for canceling the order (used for business analytics and customer service).", "nullable": true } }, "additionalProperties": false, "description": "Request model for canceling existing customer pre-orders before fulfillment." }, "CannabinoidTerpeneValue": { "required": ["labResultName", "labResultUnitId", "value"], "type": "object", "properties": { "labResultName": { "minLength": 1, "type": "string", "description": "Name of the laboratory test result (e.g., \"THC\", \"CBD\", \"Limonene\") - must match predefined compound list." }, "value": { "type": "number", "description": "Measured value of the compound in the cannabis sample (decimal precision for accurate reporting).", "format": "double" }, "labResultUnitId": { "type": "integer", "description": "Unit identifier for the measurement (references LabResultUnit enum - mg/g, percentage, etc.).", "format": "int32" } }, "additionalProperties": false, "description": "Laboratory test result value model for cannabinoid and terpene measurements in cannabis products." }, "CartItemPrice": { "type": "object", "properties": { "productName": { "type": "string", "nullable": true }, "productId": { "type": "integer", "format": "int32" }, "quantity": { "type": "number", "format": "double" }, "subtotal": { "type": "number", "format": "double" }, "pricingTierAdjustment": { "type": "number", "format": "double", "nullable": true }, "discounts": { "type": "array", "items": { "$ref": "#/components/schemas/Discount" }, "nullable": true }, "tax": { "type": "number", "format": "double" } }, "additionalProperties": false }, "CartPrice": { "type": "object", "properties": { "cartItemPrices": { "type": "array", "items": { "$ref": "#/components/schemas/CartItemPrice" }, "nullable": true }, "subTotal": { "type": "number", "format": "double" }, "taxes": { "type": "number", "format": "double" }, "discount": { "type": "number", "format": "double" }, "total": { "type": "number", "format": "double" }, "originalTotal": { "type": "number", "format": "double" }, "roundedDifference": { "type": "number", "format": "double" } }, "additionalProperties": false }, "ChangeGrowthPhaseRequest": { "type": "object", "properties": { "plantIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "description": "Collection of LeafLogix plant IDs to update to the new growth phase", "nullable": true }, "growthPhase": { "type": "string", "description": "Target cultivation growth phase. Must be one of: `Propagation`, `Vegetative`, `Flowering`", "nullable": true }, "phaseStartDate": { "type": "string", "description": "Date when new growth phase begins (optional, defaults to current UTC time if not specified)", "format": "date-time", "nullable": true } }, "additionalProperties": false, "description": "Request model for updating the cultivation growth phase of cannabis plants to track development stages.\n\n**Growth Phase Management:**\n- Updates plant cultivation phase for proper development tracking\n- Supports bulk processing of multiple plants in single operation\n- Validates growth phase against allowed phase values\n- Automatically sets phase start date if not provided\n\n**Valid Growth Phases:**\n- `Propagation`: Initial plant development and cloning phase\n- `Vegetative`: Active vegetative growth before flowering initiation\n- `Flowering`: Reproductive growth phase leading to harvest\n\n**Phase Transition Rules:**\n- Phase start date defaults to current UTC time if not specified\n- Phase changes are logged for cultivation timeline tracking\n- Integration with external cultivation systems for environmental control" }, "ClosingReportCategorySummary": { "type": "object", "properties": { "category": { "type": "string", "description": "Product category name (e.g., \"Flower\", \"Edibles\", \"Concentrates\").", "nullable": true }, "categoryTotal": { "type": "number", "description": "Total net sales for the category (calculated property returning CategoryNetTotal).", "format": "double", "readOnly": true }, "categoryGrossTotal": { "type": "number", "description": "Gross sales total for the category before discounts (in USD).", "format": "double" }, "categoryDiscountTotal": { "type": "number", "description": "Total discount amount applied to products in this category (in USD).", "format": "double" }, "categoryNetTotal": { "type": "number", "description": "Net sales total for the category after discounts (in USD).", "format": "double" }, "categoryCost": { "type": "number", "description": "Total cost of goods sold for products in this category (in USD).", "format": "double" } }, "additionalProperties": false, "description": "Product category sales summary for cannabis retail closing reports and financial analysis." }, "ClosingReportCustomerTypeSummary": { "type": "object", "properties": { "customerType": { "type": "string", "description": "Customer type classification (e.g., \"Recreational\", \"Medical\", \"Industry\").", "nullable": true }, "total": { "type": "number", "description": "Total net sales for this customer type (calculated property returning NetTotal).", "format": "double", "readOnly": true }, "grossTotal": { "type": "number", "description": "Gross sales total for this customer type before discounts (in USD).", "format": "double" }, "netTotal": { "type": "number", "description": "Net sales total for this customer type after discounts (in USD).", "format": "double" }, "discountTotal": { "type": "number", "description": "Total discount amount applied to this customer type (in USD).", "format": "double" }, "customerTypeCost": { "type": "number", "description": "Total cost of goods sold for this customer type (in USD).", "format": "double" }, "cannabisSales": { "type": "number", "description": "Cannabis product sales total for this customer type (in USD).", "format": "double" }, "nonCannabisSales": { "type": "number", "description": "Non-cannabis product sales total for this customer type (accessories, etc.) (in USD).", "format": "double" } }, "additionalProperties": false, "description": "Customer type sales summary for cannabis retail closing reports and customer segment analysis." }, "ClosingReportOrderSourceSummary": { "type": "object", "properties": { "orderSource": { "type": "string", "description": "Order origination source (e.g., \"Website\", \"Mobile App\", \"Weedmaps\", \"Walk-In\").", "nullable": true }, "total": { "type": "number", "description": "Total net sales for this order source (calculated property returning NetTotal).", "format": "double", "readOnly": true }, "grossTotal": { "type": "number", "description": "Gross sales total for this order source before discounts (in USD).", "format": "double" }, "netTotal": { "type": "number", "description": "Net sales total for this order source after discounts (in USD).", "format": "double" }, "discountTotal": { "type": "number", "description": "Total discount amount applied to this order source (in USD).", "format": "double" }, "orderSourceCost": { "type": "number", "format": "double" } }, "additionalProperties": false, "description": "Order source sales summary for cannabis retail closing reports and marketing channel analysis." }, "ClosingReportOrderTypeSummary": { "type": "object", "properties": { "orderType": { "type": "string", "description": "Order fulfillment type (e.g., \"In-Store\", \"Pickup\", \"Delivery\", \"Curbside\").", "nullable": true }, "total": { "type": "number", "description": "Total net sales for this order type (calculated property returning NetTotal).", "format": "double", "readOnly": true }, "grossTotal": { "type": "number", "description": "Gross sales total for this order type before discounts (in USD).", "format": "double" }, "netTotal": { "type": "number", "description": "Net sales total for this order type after discounts (in USD).", "format": "double" }, "discountTotal": { "type": "number", "description": "Total discount amount applied to this order type (in USD).", "format": "double" }, "orderTypeCost": { "type": "number", "description": "Total cost of goods sold for this order type (in USD).", "format": "double" } }, "additionalProperties": false, "description": "Order type sales summary for cannabis retail closing reports and fulfillment channel analysis." }, "ClosingReportPayByBankBatchFileSums": { "type": "object", "properties": { "batchFileName": { "type": "string", "description": "Batch file name for payment processor identification and tracking.", "nullable": true }, "payByBankBatchFileAdjustmentAmount": { "type": "number", "description": "Adjustment amount for the batch file for financial reconciliation.", "format": "double" } }, "additionalProperties": false, "description": "Pay-by-Bank batch file summary for cannabis payment processing reconciliation." }, "ClosingReportPaymentSummary": { "type": "object", "properties": { "paymentType": { "type": "string", "description": "Payment method type (e.g., \"Cash\", \"Credit Card\", \"CanPay\", \"Hypur\").", "nullable": true }, "totalPaid": { "type": "number", "description": "Total amount paid using this payment method (in USD).", "format": "double" } }, "additionalProperties": false, "description": "Payment method summary for cannabis retail closing reports and financial reconciliation." }, "ClosingReportTaxRateSummary": { "type": "object", "properties": { "taxRate": { "type": "string", "description": "Tax rate name or type (e.g., \"State Excise Tax\", \"City Cannabis Tax\", \"Sales Tax\").", "nullable": true }, "totalTax": { "type": "number", "description": "Total tax amount collected for this tax rate (in USD).", "format": "double" } }, "additionalProperties": false, "description": "Tax rate summary for cannabis retail closing reports and tax liability tracking." }, "ClosingReportV2": { "type": "object", "properties": { "totalTips": { "type": "number", "description": "Total tips aggregated for the closing period for staff distribution.", "format": "double", "nullable": true, "readOnly": true }, "payByBankTips": { "type": "number", "description": "Tips processed through Pay-by-Bank system for electronic tip distribution.", "format": "double" }, "payByBankTransactionFees": { "type": "number", "description": "Transaction fees charged by Pay-by-Bank system for cost accounting.", "format": "double" }, "payByBankBatchFile": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportPayByBankBatchFileSums" }, "description": "Batch file summaries for Pay-by-Bank transaction reconciliation.", "nullable": true }, "feesDonations": { "type": "array", "items": { "$ref": "#/components/schemas/FeeDonation" }, "description": "Fees and donations collected during the closing period for compliance reporting.", "nullable": true }, "dutchiePayTips": { "type": "number", "description": "DutchiePay tips processed for cannabis payment integration.", "format": "double", "nullable": true, "readOnly": true }, "dutchiePayTotalAdjustmentAmount": { "type": "number", "description": "DutchiePay transaction adjustments for cannabis payment processing.", "format": "double", "nullable": true, "readOnly": true }, "dutchiePayBatchFileSums": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportPayByBankBatchFileSums" }, "description": "DutchiePay batch file summaries for cannabis payment reconciliation.", "nullable": true, "readOnly": true }, "grossSales": { "type": "number", "format": "double", "nullable": true }, "discount": { "type": "number", "format": "double", "nullable": true }, "loyalty": { "type": "number", "format": "double", "nullable": true }, "totalTax": { "type": "number", "format": "double", "nullable": true }, "cost": { "type": "number", "format": "double", "nullable": true }, "coupons": { "type": "number", "format": "double", "nullable": true }, "itemTotal": { "type": "number", "format": "double", "nullable": true }, "transactionCount": { "type": "integer", "format": "int32" }, "itemCount": { "type": "integer", "format": "int32" }, "customerCount": { "type": "integer", "format": "int32" }, "newCustomerCount": { "type": "integer", "format": "int32" }, "voidCount": { "type": "integer", "format": "int32" }, "voidTotal": { "type": "number", "format": "double", "nullable": true }, "returnTotal": { "type": "number", "format": "double", "nullable": true }, "startingBalance": { "type": "number", "format": "double", "nullable": true }, "endingBalance": { "type": "number", "format": "double", "nullable": true }, "deposits": { "type": "number", "format": "double", "nullable": true }, "adjustments": { "type": "number", "format": "double", "nullable": true }, "totalPayments": { "type": "number", "format": "double", "nullable": true }, "invoiceTotal": { "type": "number", "format": "double", "nullable": true }, "cannabisSales": { "type": "number", "format": "double", "nullable": true }, "nonCannabisSales": { "type": "number", "format": "double", "nullable": true }, "netSales": { "type": "number", "format": "double", "nullable": true }, "revenueFeesDonations": { "type": "number", "format": "double", "nullable": true }, "nonRevenueFeesDonations": { "type": "number", "format": "double", "nullable": true }, "rounding": { "type": "number", "format": "double", "nullable": true }, "totalIncome": { "type": "number", "format": "double", "nullable": true }, "averageCartNetSales": { "type": "number", "format": "double", "nullable": true }, "overShort": { "type": "number", "format": "double", "nullable": true, "readOnly": true }, "categorySummary": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportCategorySummary" }, "nullable": true }, "paymentSummary": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportPaymentSummary" }, "nullable": true }, "taxSummary": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportTaxRateSummary" }, "nullable": true }, "customerTypeSummary": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportCustomerTypeSummary" }, "nullable": true }, "orderTypeSummary": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportOrderTypeSummary" }, "nullable": true }, "orderSourceSummary": { "type": "array", "items": { "$ref": "#/components/schemas/ClosingReportOrderSourceSummary" }, "nullable": true } }, "additionalProperties": false, "description": "Enhanced closing report model for cannabis dispensary daily financial operations with payment processing integration." }, "ConvertBatchDetails": { "type": "object", "properties": { "batchId": { "type": "integer", "description": "Batch identifier for the plant batch being converted to mature growth phase.", "format": "int32" }, "serialNumbers": { "type": "array", "items": { "type": "string" }, "description": "Collection of individual plant serial numbers within the batch for state tracking compliance.", "nullable": true }, "batchStage": { "type": "string", "description": "Target growth stage for the batch conversion (e.g., \"Vegetative\", \"Flowering\").", "nullable": true }, "roomId": { "type": "integer", "description": "Destination room identifier for the converted batch location tracking.", "format": "int32" }, "tableId": { "type": "integer", "description": "Destination table identifier within the room for precise location tracking (optional).", "format": "int32", "nullable": true }, "dateCreated": { "type": "string", "description": "Date when the batch conversion was performed for cultivation timeline documentation.", "format": "date-time", "nullable": true } }, "additionalProperties": false, "description": "Detailed specification for converting individual plant batches during cultivation growth phase transitions." }, "ConvertImmatureBatchRequest": { "type": "object", "properties": { "batches": { "type": "array", "items": { "$ref": "#/components/schemas/ConvertBatchDetails" }, "description": "Collection of plant batches to be converted from immature to mature growth phases.", "nullable": true } }, "additionalProperties": false, "description": "Request model for converting immature plant batches to mature growth phases in cannabis cultivation operations." }, "ConvertImmaturePlantResponse": { "type": "object", "properties": { "convertedPlants": { "type": "array", "items": { "$ref": "#/components/schemas/CreatedMaturePlant" }, "description": "Collection of mature plants created from immature batch conversion.", "nullable": true } }, "additionalProperties": false, "description": "Response model for immature plant batch conversion operations containing converted mature plant identifiers." }, "ConvertImmaturePlantResponseApiResult": { "type": "object", "properties": { "result": { "type": "boolean" }, "message": { "type": "string", "nullable": true }, "data": { "$ref": "#/components/schemas/ConvertImmaturePlantResponse" } }, "additionalProperties": false }, "CreateAnonymousTransactionRequest": { "type": "object", "properties": { "transactionReference": { "type": "string", "description": "Optional reference identifier for the transaction (for external system integration).", "nullable": true } }, "additionalProperties": false, "description": "Request model for creating anonymous transactions for guest customer operations." }, "CreateImmaturePlantBatchResponse": { "type": "object", "properties": { "batches": { "type": "array", "items": { "$ref": "#/components/schemas/CreatedImmaturePlantBatch" }, "description": "Collection of created immature plant batches with associated plant identifiers.", "nullable": true } }, "additionalProperties": false, "description": "Response model for immature plant batch creation operations containing created batch and plant identifiers." }, "CreateImmaturePlantBatchResponseApiResult": { "type": "object", "properties": { "result": { "type": "boolean" }, "message": { "type": "string", "nullable": true }, "data": { "$ref": "#/components/schemas/CreateImmaturePlantBatchResponse" } }, "additionalProperties": false }, "CreateJournalEntryRequest": { "required": ["body", "customerId", "date", "subject"], "type": "object", "properties": { "customerId": { "type": "integer", "description": "The customer ID to create the journal entry for.", "format": "int32" }, "subject": { "minLength": 1, "type": "string", "description": "Brief title or summary of the journal entry." }, "body": { "minLength": 1, "type": "string", "description": "Detailed content and notes for the journal entry." }, "date": { "type": "string", "description": "Date and time when the journal entry should be dated.", "format": "date-time" } }, "additionalProperties": false, "description": "Request model for creating new customer journal entries with interaction details and notes." }, "CreateMatureBatchRequest": { "type": "object", "properties": { "batches": { "type": "array", "items": { "$ref": "#/components/schemas/MatureBatchDetails" }, "description": "Collection of mature plant batch specifications for bulk batch creation operations.", "nullable": true } }, "additionalProperties": false, "description": "Request model for creating mature plant batches in cannabis cultivation operations." }, "CreateMaturePlantsResponse": { "type": "object", "properties": { "createdPlants": { "type": "array", "items": { "$ref": "#/components/schemas/CreatedMaturePlant" }, "description": "Collection of mature plants created ready for flowering phase cultivation.", "nullable": true } }, "additionalProperties": false, "description": "Response model for mature plant batch creation operations containing created mature plant identifiers." }, "CreateMaturePlantsResponseApiResult": { "type": "object", "properties": { "result": { "type": "boolean" }, "message": { "type": "string", "nullable": true }, "data": { "$ref": "#/components/schemas/CreateMaturePlantsResponse" } }, "additionalProperties": false }, "CreateOrUpdateHarvest": { "type": "object", "properties": { "harvestId": { "type": "integer", "format": "int32", "nullable": true }, "harvestName": { "type": "string", "nullable": true }, "strainName": { "type": "string", "nullable": true }, "harvestRoomId": { "type": "integer", "format": "int32" }, "harvestDate": { "type": "string", "format": "date-time" } }, "additionalProperties": false }, "CreatePlantRequest": { "type": "object", "properties": { "serialNumber": { "type": "string", "nullable": true }, "plantGroupName": { "type": "string", "nullable": true }, "growthPhase": { "type": "string", "nullable": true }, "phaseStartDate": { "type": "string", "format": "date-time", "nullable": true }, "dateCreated": { "type": "string", "format": "date-time", "nullable": true }, "bornDate": { "type": "string", "format": "date-time", "nullable": true }, "strain": { "type": "string", "nullable": true }, "room": { "type": "string", "nullable": true }, "table": { "type": "string", "nullable": true }, "isMother": { "type": "boolean" }, "bypassStateIntegration": { "type": "boolean" } }, "additionalProperties": false }, "CreatePreOrderRequest": { "required": ["customerId"], "type": "object", "properties": { "customerId": { "type": "integer", "format": "int32" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/PreOrderItem" }, "nullable": true }, "redemptions": { "type": "array", "items": { "$ref": "#/components/schemas/PreOrderRedemption" }, "nullable": true }, "isDelivery": { "type": "boolean" }, "orderSource": { "type": "string", "nullable": true, "deprecated": true }, "orderType": { "type": "string", "nullable": true }, "deliveryStreet": { "type": "string", "nullable": true }, "deliveryStreet2": { "type": "string", "nullable": true }, "deliveryCity": { "type": "string", "nullable": true }, "deliveryState": { "type": "string", "nullable": true }, "deliveryPostalCode": { "type": "string", "nullable": true }, "idempotencyKey": { "type": "string", "nullable": true }, "notes": { "type": "string", "nullable": true }, "status": { "type": "string", "nullable": true }, "transactionReference": { "type": "string", "nullable": true }, "timeWindowStartDateUtc": { "type": "string", "format": "date-time", "nullable": true }, "timeWindowEndDateUtc": { "type": "string", "format": "date-time", "nullable": true }, "deliveryScheduleId": { "$ref": "#/components/schemas/DeliveryScheduleType" } }, "additionalProperties": false }, "CreateUpdatePurchaseOrderItemRequest": { "type": "object", "properties": { "productId": { "type": "integer", "format": "int32" }, "unitId": { "$ref": "#/components/schemas/Int32NullableOptional" }, "quantity": { "$ref": "#/components/schemas/Int32NullableOptional" }, "subtotal": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "tax": { "$ref": "#/components/schemas/DecimalNullableOptional" } }, "additionalProperties": false }, "CreateUpdatePurchaseOrderRequest": { "type": "object", "properties": { "purchaseOrderId": { "type": "integer", "format": "int32", "nullable": true }, "expectedArrivalDate": { "$ref": "#/components/schemas/DateTimeNullableOptional" }, "title": { "$ref": "#/components/schemas/StringOptional" }, "dateReceived": { "$ref": "#/components/schemas/DateTimeNullableOptional" }, "shippingInformation": { "$ref": "#/components/schemas/StringOptional" }, "vendorContact": { "$ref": "#/components/schemas/StringOptional" }, "status": { "$ref": "#/components/schemas/StringOptional" }, "vendorId": { "$ref": "#/components/schemas/Int32NullableOptional" }, "purchaseOrderNumber": { "$ref": "#/components/schemas/Int32NullableOptional" }, "purchaseOrderItems": { "type": "array", "items": { "$ref": "#/components/schemas/CreateUpdatePurchaseOrderItemRequest" }, "nullable": true } }, "additionalProperties": false }, "CreateUpdatePurchaseOrderResponse": { "type": "object", "properties": { "createdPurchaseOrderIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true }, "updatedPurchaseOrderIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true } }, "additionalProperties": false }, "CreateUpdatePurchaseOrdersRequest": { "type": "object", "properties": { "purchaseOrders": { "type": "array", "items": { "$ref": "#/components/schemas/CreateUpdatePurchaseOrderRequest" }, "nullable": true } }, "additionalProperties": false }, "CreatedImmaturePlantBatch": { "type": "object", "properties": { "batchId": { "type": "integer", "description": "Unique identifier assigned to the created immature plant batch.", "format": "int32" }, "plantIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "description": "Collection of unique plant identifiers created within this batch.", "nullable": true } }, "additionalProperties": false, "description": "Individual created immature plant batch containing batch identifier and associated plant IDs." }, "CreatedMaturePlant": { "type": "object", "properties": { "batchId": { "type": "integer", "format": "int32" }, "plantId": { "type": "integer", "format": "int32" }, "plantSerialNumber": { "type": "string", "nullable": true } }, "additionalProperties": false }, "Customer": { "type": "object", "properties": { "customerId": { "type": "integer", "description": "Unique internal identifier for the customer record.", "format": "int32" }, "uniqueId": { "type": "string", "description": "String representation of UniqueId for external API consumption.", "nullable": true, "readOnly": true }, "name": { "type": "string", "description": "Deprecated name field (use FirstName and LastName instead).", "nullable": true, "deprecated": true }, "firstName": { "type": "string", "description": "Customer's first name.", "nullable": true }, "lastName": { "type": "string", "description": "Customer's last name.", "nullable": true }, "middleName": { "type": "string", "description": "Customer's middle name.", "nullable": true }, "nameSuffix": { "type": "string", "description": "Name suffix (Jr., Sr., III, etc.).", "nullable": true }, "namePrefix": { "type": "string", "description": "Name prefix (Mr., Mrs., Dr., etc.).", "nullable": true }, "address1": { "type": "string", "description": "Primary street address line.", "nullable": true }, "address2": { "type": "string", "description": "Secondary address line (apartment, suite, etc.).", "nullable": true }, "city": { "type": "string", "description": "City name.", "nullable": true }, "state": { "type": "string", "description": "State or province.", "nullable": true }, "postalCode": { "type": "string", "description": "Postal or ZIP code.", "nullable": true }, "phone": { "type": "string", "description": "Primary phone number.", "nullable": true }, "cellPhone": { "type": "string", "description": "Cell phone number.", "nullable": true }, "emailAddress": { "type": "string", "description": "Email address.", "nullable": true }, "status": { "type": "string", "description": "Customer account status.", "nullable": true }, "mmjidNumber": { "type": "string", "description": "Medical marijuana identification number.", "nullable": true }, "mmjidExpirationDate": { "type": "string", "description": "Medical marijuana ID expiration date.", "format": "date-time", "nullable": true }, "lastModifiedDateUTC": { "type": "string", "description": "Last modification timestamp in UTC format.", "nullable": true }, "creationDate": { "type": "string", "description": "Customer record creation date.", "format": "date-time", "nullable": true }, "customerType": { "type": "string", "description": "Customer type classification.", "nullable": true }, "gender": { "type": "string", "description": "Customer's gender.", "nullable": true }, "driversLicenseHash": { "type": "string", "description": "SHA2_256 hash of the Driver License ID", "nullable": true }, "dateOfBirth": { "type": "string", "description": "Customer's date of birth.", "format": "date-time", "nullable": true }, "externalCustomerId": { "type": "string", "description": "External system customer identifier.", "nullable": true }, "createdByIntegrator": { "type": "string", "description": "Name of the integration system that created this customer.", "nullable": true }, "isAnonymous": { "type": "boolean", "description": "Indicates if this is an anonymous customer record." }, "referralSource": { "type": "string", "description": "How the customer heard about the dispensary.", "nullable": true }, "otherReferralSource": { "type": "string", "description": "Additional details about referral source when \"Other\" is selected.", "nullable": true }, "springBigMemberId": { "type": "integer", "description": "SpringBig loyalty system member identifier.", "format": "int32" }, "customIdentifier": { "type": "string", "description": "Custom identifier for external system integration.", "nullable": true }, "discountGroups": { "type": "array", "items": { "type": "string" }, "description": "Collection of active discount groups for this customer.", "nullable": true, "readOnly": true }, "createdAtLocation": { "type": "string", "description": "Location where this customer record was created.", "nullable": true }, "notes": { "type": "string", "description": "Additional notes about the customer.", "nullable": true }, "isLoyaltyMember": { "type": "boolean", "description": "Indicates if customer is enrolled in loyalty program.", "nullable": true }, "primaryQualifyingCondition": { "type": "string", "description": "Primary medical condition for medical marijuana patients.", "nullable": true }, "secondaryQualifyingConditions": { "type": "array", "items": { "type": "string" }, "description": "Additional medical conditions for medical marijuana patients.", "nullable": true }, "mergedIntoCustomerId": { "type": "integer", "description": "Customer ID this record was merged into (if applicable).", "format": "int32", "nullable": true }, "optedIntoMarketing": { "type": "boolean", "description": "Customer's marketing communication preference.", "nullable": true }, "loyaltyTier": { "type": "string", "description": "Customer's current loyalty program tier.", "nullable": true } }, "additionalProperties": false, "description": "Represents a customer profile with personal information, contact details, and cannabis compliance data." }, "CustomerSearchRequest": { "type": "object", "properties": { "lastName": { "type": "string", "description": "Customer's last name for name-based search matching.", "nullable": true }, "dateOfBirth": { "type": "string", "description": "Customer's date of birth for identity verification and precise matching.", "format": "date-time", "nullable": true }, "phone": { "type": "string", "description": "Customer's phone number for contact-based search matching.", "nullable": true }, "emailAddress": { "type": "string", "description": "Customer's email address for account-based search matching.", "nullable": true }, "mmjidNumber": { "type": "string", "description": "Medical marijuana identification number for regulatory compliance search.", "nullable": true }, "driversLicenseId": { "type": "string", "description": "Driver's license identifier for government ID-based search matching.", "nullable": true } }, "additionalProperties": false, "description": "Search criteria model for customer lookup operations with flexible matching options." }, "CustomerSearchResult": { "type": "object", "properties": { "matchType": { "type": "string", "description": "Indicates how the customer record was matched during the search operation.", "nullable": true }, "customerId": { "type": "integer", "description": "Unique internal identifier for the customer record.", "format": "int32" }, "uniqueId": { "type": "string", "description": "String representation of UniqueId for external API consumption.", "nullable": true, "readOnly": true }, "name": { "type": "string", "description": "Deprecated name field (use FirstName and LastName instead).", "nullable": true, "deprecated": true }, "firstName": { "type": "string", "description": "Customer's first name.", "nullable": true }, "lastName": { "type": "string", "description": "Customer's last name.", "nullable": true }, "middleName": { "type": "string", "description": "Customer's middle name.", "nullable": true }, "nameSuffix": { "type": "string", "description": "Name suffix (Jr., Sr., III, etc.).", "nullable": true }, "namePrefix": { "type": "string", "description": "Name prefix (Mr., Mrs., Dr., etc.).", "nullable": true }, "address1": { "type": "string", "description": "Primary street address line.", "nullable": true }, "address2": { "type": "string", "description": "Secondary address line (apartment, suite, etc.).", "nullable": true }, "city": { "type": "string", "description": "City name.", "nullable": true }, "state": { "type": "string", "description": "State or province.", "nullable": true }, "postalCode": { "type": "string", "description": "Postal or ZIP code.", "nullable": true }, "phone": { "type": "string", "description": "Primary phone number.", "nullable": true }, "cellPhone": { "type": "string", "description": "Cell phone number.", "nullable": true }, "emailAddress": { "type": "string", "description": "Email address.", "nullable": true }, "status": { "type": "string", "description": "Customer account status.", "nullable": true }, "mmjidNumber": { "type": "string", "description": "Medical marijuana identification number.", "nullable": true }, "mmjidExpirationDate": { "type": "string", "description": "Medical marijuana ID expiration date.", "format": "date-time", "nullable": true }, "lastModifiedDateUTC": { "type": "string", "description": "Last modification timestamp in UTC format.", "nullable": true }, "creationDate": { "type": "string", "description": "Customer record creation date.", "format": "date-time", "nullable": true }, "customerType": { "type": "string", "description": "Customer type classification.", "nullable": true }, "gender": { "type": "string", "description": "Customer's gender.", "nullable": true }, "driversLicenseHash": { "type": "string", "description": "SHA2_256 hash of the Driver License ID", "nullable": true }, "dateOfBirth": { "type": "string", "description": "Customer's date of birth.", "format": "date-time", "nullable": true }, "externalCustomerId": { "type": "string", "description": "External system customer identifier.", "nullable": true }, "createdByIntegrator": { "type": "string", "description": "Name of the integration system that created this customer.", "nullable": true }, "isAnonymous": { "type": "boolean", "description": "Indicates if this is an anonymous customer record." }, "referralSource": { "type": "string", "description": "How the customer heard about the dispensary.", "nullable": true }, "otherReferralSource": { "type": "string", "description": "Additional details about referral source when \"Other\" is selected.", "nullable": true }, "springBigMemberId": { "type": "integer", "description": "SpringBig loyalty system member identifier.", "format": "int32" }, "customIdentifier": { "type": "string", "description": "Custom identifier for external system integration.", "nullable": true }, "discountGroups": { "type": "array", "items": { "type": "string" }, "description": "Collection of active discount groups for this customer.", "nullable": true, "readOnly": true }, "createdAtLocation": { "type": "string", "description": "Location where this customer record was created.", "nullable": true }, "notes": { "type": "string", "description": "Additional notes about the customer.", "nullable": true }, "isLoyaltyMember": { "type": "boolean", "description": "Indicates if customer is enrolled in loyalty program.", "nullable": true }, "primaryQualifyingCondition": { "type": "string", "description": "Primary medical condition for medical marijuana patients.", "nullable": true }, "secondaryQualifyingConditions": { "type": "array", "items": { "type": "string" }, "description": "Additional medical conditions for medical marijuana patients.", "nullable": true }, "mergedIntoCustomerId": { "type": "integer", "description": "Customer ID this record was merged into (if applicable).", "format": "int32", "nullable": true }, "optedIntoMarketing": { "type": "boolean", "description": "Customer's marketing communication preference.", "nullable": true }, "loyaltyTier": { "type": "string", "description": "Customer's current loyalty program tier.", "nullable": true } }, "additionalProperties": false, "description": "Extended customer model that includes search match type information for customer lookup operations." }, "CustomerType": { "type": "object", "properties": { "id": { "type": "integer", "description": "Unique identifier for the customer type.", "format": "int32" }, "name": { "type": "string", "description": "Display name of the customer type.", "nullable": true }, "isMedical": { "type": "boolean", "description": "Indicates whether this customer type is for medical marijuana patients." }, "isRetail": { "type": "boolean", "description": "Indicates whether this customer type is for retail (adult-use) customers." } }, "additionalProperties": false, "description": "Represents a customer type classification for cannabis dispensary operations and compliance." }, "DateTimeNullableOptional": { "type": "string", "additionalProperties": false }, "DecimalNullableOptional": { "type": "number", "additionalProperties": false }, "DeleteImageRequest": { "required": ["imageId", "productId"], "type": "object", "properties": { "productId": { "type": "integer", "description": "The unique identifier of the product that owns the image to be deleted.", "format": "int32" }, "imageId": { "type": "integer", "description": "The unique identifier of the specific image to be deleted from the product.", "format": "int32" } }, "additionalProperties": false, "description": "Request model for deleting a product image through the product image management API." }, "DeliveryOrderStatus": { "type": "object", "properties": { "preOrderId": { "type": "integer", "format": "int32", "nullable": true }, "transactionId": { "type": "integer", "format": "int32" }, "status": { "type": "string", "nullable": true }, "orderDate": { "type": "string", "format": "date-time" }, "customerFirstName": { "type": "string", "nullable": true }, "customerLastName": { "type": "string", "nullable": true }, "customerId": { "type": "integer", "format": "int32" }, "orderType": { "type": "string", "nullable": true }, "orderSource": { "type": "string", "nullable": true }, "rejectedReason": { "type": "string", "nullable": true }, "total": { "type": "number", "format": "double", "nullable": true }, "subTotal": { "type": "number", "format": "double", "nullable": true }, "totalTax": { "type": "number", "format": "double", "nullable": true }, "streetAddress1": { "type": "string", "nullable": true }, "streetAddress2": { "type": "string", "nullable": true }, "city": { "type": "string", "nullable": true }, "deliveryState": { "type": "string", "nullable": true }, "postalCode": { "type": "string", "nullable": true }, "customerPhone": { "type": "string", "nullable": true }, "customerExpectedTimeStart": { "type": "string", "format": "date-time" }, "customerExpectedTimeEnd": { "type": "string", "format": "date-time" }, "dispatchDepartTime": { "type": "string", "format": "date-time" }, "dispatchArriveTime": { "type": "string", "format": "date-time" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/AllocatedDeliveryItem" }, "nullable": true }, "payments": { "type": "array", "items": { "$ref": "#/components/schemas/DeliveryPayment" }, "nullable": true }, "deliveryStatus": { "type": "string", "nullable": true } }, "additionalProperties": false }, "DeliveryPayment": { "type": "object", "properties": { "name": { "type": "string", "nullable": true }, "amount": { "type": "number", "format": "double" } }, "additionalProperties": false }, "DeliveryScheduleType": { "enum": [1, 2], "type": "integer", "format": "int32" }, "Discount": { "type": "object", "properties": { "name": { "type": "string", "nullable": true }, "amount": { "type": "number", "format": "double" }, "discountId": { "type": "integer", "format": "int32", "nullable": true } }, "additionalProperties": false }, "DiscountApiResponse": { "type": "object", "properties": { "id": { "type": "integer", "format": "int32", "nullable": true }, "externalId": { "type": "string", "nullable": true }, "validDateFrom": { "type": "string", "format": "date-time", "nullable": true }, "validDateTo": { "type": "string", "format": "date-time", "nullable": true }, "maxRedemptions": { "type": "integer", "format": "int32", "nullable": true }, "redemptionLimit": { "type": "integer", "format": "int32", "nullable": true }, "firstTimeCustomerOnly": { "$ref": "#/components/schemas/DiscountFirstTimeCustomer" }, "discountDescription": { "type": "string", "nullable": true }, "discountCode": { "type": "string", "nullable": true }, "applicationMethodId": { "$ref": "#/components/schemas/DiscountApplicationMethod" }, "applicationMethod": { "type": "string", "nullable": true, "readOnly": true }, "canStackAutomatically": { "type": "boolean" }, "onlineName": { "type": "string", "nullable": true }, "locationRestrictions": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true }, "restrictToGroupIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true }, "startTime": { "type": "object", "nullable": true }, "endTime": { "type": "object", "nullable": true }, "monday": { "type": "boolean", "nullable": true }, "tuesday": { "type": "boolean", "nullable": true }, "wednesday": { "type": "boolean", "nullable": true }, "thursday": { "type": "boolean", "nullable": true }, "friday": { "type": "boolean", "nullable": true }, "saturday": { "type": "boolean", "nullable": true }, "sunday": { "type": "boolean", "nullable": true }, "isActive": { "type": "boolean" }, "isBundledDiscount": { "type": "boolean" }, "constraints": { "type": "array", "items": { "$ref": "#/components/schemas/DiscountConstraintAPIResponse" }, "nullable": true }, "reward": { "$ref": "#/components/schemas/DiscountRewardAPIResponse" }, "menuDisplay": { "$ref": "#/components/schemas/DiscountMenuDisplayAPIResponse" }, "paymentRestrictions": { "$ref": "#/components/schemas/DiscountPaymentRestrictionAPIResponse" } }, "additionalProperties": false }, "DiscountApplicationMethod": { "enum": [1, 2, 3, 4, 5, 6], "type": "integer", "format": "int32" }, "DiscountConstraintAPIResponse": { "type": "object", "properties": { "discountConstraintId": { "type": "integer", "format": "int32", "nullable": true }, "discountId": { "type": "integer", "format": "int32" }, "thresholdMin": { "type": "number", "format": "double", "nullable": true }, "includeNonCannabis": { "type": "boolean" }, "thresholdTypeId": { "$ref": "#/components/schemas/DiscountThresholdType" }, "thresholdType": { "type": "string", "nullable": true, "readOnly": true }, "hasThreshold": { "type": "boolean", "readOnly": true }, "discountItemGroupTypeId": { "$ref": "#/components/schemas/DiscountItemGroupType" }, "itemGroupType": { "type": "string", "nullable": true, "readOnly": true }, "restrictions": { "type": "object", "additionalProperties": { "$ref": "#/components/schemas/IRestrictionAPIResponse" }, "nullable": true } }, "additionalProperties": false }, "DiscountFirstTimeCustomer": { "enum": [0, 1, 2], "type": "integer", "format": "int32" }, "DiscountGroup": { "type": "object", "properties": { "discountGroupId": { "type": "integer", "description": "Unique identifier for the discount group.", "format": "int32" }, "discountGroupName": { "type": "string", "description": "Display name of the discount group for management and organization.", "nullable": true } }, "additionalProperties": false, "description": "Discount group model for organizing and categorizing related discounts." }, "DiscountItemGroupType": { "enum": [5, 6], "type": "integer", "format": "int32" }, "DiscountMenuDisplayAPIResponse": { "type": "object", "properties": { "menuDisplayDescription": { "type": "string", "nullable": true }, "menuDisplayImageUrl": { "type": "string", "nullable": true }, "menuDisplayName": { "type": "string", "nullable": true }, "menuDisplayRank": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, "DiscountPaymentRestrictionAPIResponse": { "type": "object", "properties": { "payByBankSignupIncentive": { "type": "boolean" } }, "additionalProperties": false }, "DiscountRestriction": { "type": "object", "properties": { "ids": { "type": "array", "items": { "type": "integer", "format": "int32" }, "description": "Collection of entity identifiers subject to the restriction rule.", "nullable": true }, "isExclusion": { "type": "boolean", "description": "Indicates if this is an exclusion rule (true) or inclusion rule (false)." } }, "additionalProperties": false, "description": "Discount restriction model defining entity inclusion or exclusion rules for discount application." }, "DiscountRewardAPIResponse": { "type": "object", "properties": { "discountRewardId": { "type": "integer", "format": "int32", "nullable": true }, "discountId": { "type": "integer", "format": "int32" }, "calculationMethodId": { "$ref": "#/components/schemas/CalculationMethod" }, "calculationMethod": { "type": "string", "nullable": true, "readOnly": true }, "discountValue": { "type": "number", "format": "double" }, "includeNonCannabis": { "type": "boolean" }, "highestOrLowest": { "type": "string", "nullable": true }, "thresholdTypeId": { "$ref": "#/components/schemas/DiscountThresholdType" }, "thresholdType": { "type": "string", "nullable": true, "readOnly": true }, "hasThreshold": { "type": "boolean", "readOnly": true }, "itemGroupTypeId": { "$ref": "#/components/schemas/DiscountItemGroupType" }, "itemGroupType": { "type": "string", "nullable": true, "readOnly": true }, "thresholdMin": { "type": "number", "format": "double", "nullable": true }, "thresholdMax": { "type": "number", "format": "double", "nullable": true }, "applyToOnlyOneItem": { "type": "boolean" }, "restrictions": { "type": "object", "additionalProperties": { "$ref": "#/components/schemas/IRestrictionAPIResponse" }, "nullable": true } }, "additionalProperties": false }, "DiscountThresholdType": { "enum": [1, 2, 3], "type": "integer", "format": "int32" }, "DriverDetail": { "type": "object", "properties": { "driverId": { "type": "integer", "format": "int32" }, "name": { "type": "string", "nullable": true }, "stateId": { "type": "string", "nullable": true }, "driversLicense": { "type": "string", "nullable": true } }, "additionalProperties": false }, "EcomCustomerEdit": { "required": [ "address1", "city", "customerType", "firstName", "postalCode", "state", "status" ], "type": "object", "properties": { "customerId": { "type": "integer", "description": "When specified, it updates the record, if the ID exists\nnull / unspecified will create a new customer", "format": "int32", "nullable": true }, "uniqueId": { "type": "string", "description": "Unique identifier for external system integration.", "nullable": true }, "name": { "type": "string", "description": "Deprecated full name field (use FirstName and LastName instead).", "nullable": true, "deprecated": true }, "firstName": { "minLength": 1, "type": "string", "description": "Customer's first name (required)." }, "lastName": { "type": "string", "description": "Customer's last name.", "nullable": true }, "middleName": { "type": "string", "description": "Customer's middle name.", "nullable": true }, "nameSuffix": { "type": "string", "description": "Name suffix (Jr., Sr., III, etc.).", "nullable": true }, "namePrefix": { "type": "string", "description": "Name prefix (Mr., Mrs., Dr., etc.).", "nullable": true }, "address1": { "minLength": 1, "type": "string", "description": "Primary street address line (required)." }, "address2": { "type": "string", "description": "Secondary address line (apartment, suite, etc.).", "nullable": true }, "city": { "minLength": 1, "type": "string", "description": "City name (required)." }, "state": { "minLength": 1, "type": "string", "description": "State or province (required)." }, "postalCode": { "minLength": 1, "type": "string", "description": "Postal or ZIP code (required)." }, "phone": { "type": "string", "description": "Phone number.", "nullable": true }, "emailAddress": { "type": "string", "description": "Email address.", "nullable": true }, "status": { "minLength": 1, "type": "string", "description": "Active; Cancelled; Hold; Banned" }, "mmjidNumber": { "type": "string", "description": "Medical marijuana identification number.", "nullable": true }, "driversLicenseID": { "type": "string", "description": "Driver's license ID.", "nullable": true }, "driversLicenseExpiration": { "type": "string", "description": "Driver's license expiration date.", "format": "date-time", "nullable": true }, "mmjidExpirationDate": { "type": "string", "description": "Medical marijuana ID expiration date.", "format": "date-time", "nullable": true }, "customerType": { "minLength": 1, "type": "string", "description": "Customer type classification (required). Use CustomerTypes endpoint to retrieve active customer types for a given location." }, "dateOfBirth": { "type": "string", "description": "Customer's date of birth.", "format": "date-time", "nullable": true }, "externalCustomerId": { "type": "string", "description": "External system customer identifier.", "nullable": true }, "gender": { "type": "string", "description": "Customer's gender.", "nullable": true }, "idempotencyKey": { "type": "string", "description": "Optional idempotency key for duplicate prevention. When provided with a ConsumerKey header, ensures the same customer creation request is not processed multiple times.", "nullable": true }, "referralSource": { "type": "string", "description": "How the customer heard about the dispensary. Use ReferralSources endpoint to retrieve values.", "nullable": true }, "customIdentifier": { "type": "string", "description": "Custom identifier for external system integration.", "nullable": true }, "notes": { "type": "string", "description": "Additional notes about the customer.", "nullable": true }, "isLoyaltyMember": { "type": "boolean", "description": "Indicates if customer is enrolled in loyalty program.", "nullable": true } }, "additionalProperties": false, "description": "E-commerce customer data model for creating or updating customer profiles via API integration." }, "Employee": { "type": "object", "properties": { "userId": { "type": "integer", "format": "int32" }, "loginId": { "type": "string", "nullable": true }, "fullName": { "type": "string", "nullable": true }, "defaultLocation": { "type": "string", "nullable": true }, "status": { "type": "string", "nullable": true }, "stateId": { "type": "string", "nullable": true }, "mmjExpiration": { "type": "string", "format": "date-time" }, "permissionsLocation": { "type": "string", "nullable": true }, "groups": { "type": "string", "nullable": true } }, "additionalProperties": false }, "FeeDonation": { "type": "object", "properties": { "name": { "type": "string", "description": "Name of the fee or donation for identification and reporting purposes.", "nullable": true }, "cashValue": { "type": "number", "description": "Cash value of the fee or donation for financial accounting.", "format": "double" }, "isRevenue": { "type": "boolean", "description": "Flag indicating whether the fee or donation counts as revenue for accounting purposes." } }, "additionalProperties": false, "description": "Fee and donation tracking model for cannabis dispensary compliance and accounting." }, "FeeDonationInfo": { "type": "object", "properties": { "feeDonationId": { "type": "integer", "description": "Unique identifier for the specific fee or donation program.", "format": "int32" }, "description": { "type": "string", "description": "Description of the fee or donation for customer receipts and reporting.", "nullable": true }, "amount": { "type": "number", "description": "Amount of the fee or donation (in USD).", "format": "double" }, "isRevenue": { "type": "boolean", "description": "Indicates whether this fee counts as business revenue for accounting purposes." } }, "additionalProperties": false, "description": "Fee and donation information associated with cannabis retail transactions." }, "FinishOrUnfinishBatchDetails": { "type": "object", "properties": { "batchId": { "type": "integer", "format": "int32" }, "harvestCompletedOn": { "type": "string", "format": "date-time", "nullable": true } }, "additionalProperties": false }, "GuestListEntry": { "type": "object", "properties": { "name": { "type": "string", "nullable": true }, "checkinDateUTC": { "type": "string", "format": "date-time" }, "status": { "type": "string", "nullable": true }, "customerId": { "type": "integer", "format": "int32" }, "transactionId": { "type": "integer", "format": "int32" }, "transactionReferenceNumber": { "type": "string", "nullable": true }, "terminalName": { "type": "string", "nullable": true }, "customerType": { "type": "string", "nullable": true }, "phone": { "type": "string", "nullable": true }, "cellPhone": { "type": "string", "nullable": true }, "preOrderSource": { "type": "string", "nullable": true } }, "additionalProperties": false }, "Harvest": { "type": "object", "properties": { "harvestId": { "type": "integer", "format": "int32" }, "harvestName": { "type": "string", "nullable": true }, "harvestDate": { "type": "string", "format": "date-time" }, "harvestRoom": { "type": "string", "nullable": true }, "plantCount": { "type": "integer", "format": "int32" }, "plantWeight": { "type": "number", "format": "double", "nullable": true }, "wetWeight": { "type": "number", "format": "double", "nullable": true }, "wetWaste": { "type": "number", "format": "double", "nullable": true }, "dryBudWeight": { "type": "number", "format": "double", "nullable": true }, "dryShakeWeight": { "type": "number", "format": "double", "nullable": true }, "dryWaste": { "type": "number", "format": "double", "nullable": true }, "packageCount": { "type": "integer", "format": "int32" }, "packagedWeight": { "type": "number", "format": "double", "nullable": true }, "lastModifiedDateUTC": { "type": "string", "format": "date-time" }, "strainName": { "type": "string", "nullable": true } }, "additionalProperties": false }, "HarvestPlantRequest": { "type": "object", "properties": { "plants": { "type": "array", "items": { "$ref": "#/components/schemas/HarvestedPlant" }, "description": "Collection of plants to be harvested with optional weight measurements", "nullable": true }, "harvestId": { "type": "integer", "description": "Target harvest record ID for associating harvested plants", "format": "int32" }, "harvestedOn": { "type": "string", "description": "Date and time when harvest occurred (optional, defaults to current UTC time if not specified)", "format": "date-time", "nullable": true } }, "additionalProperties": false, "description": "Request model for moving cannabis plants from cultivation to harvest status with optional weight tracking.\n\n**Request Behavior:**\n- Moves specified plants from cultivation status to harvesting status\n- Supports bulk processing of multiple plants in single operation\n- Optional weight tracking for harvest yield management\n- Integrates with external cultivation systems when configured\n\n**Validation:**\n- All plant IDs must exist and be accessible to the authenticated location\n- Plants must be in valid status for harvesting (typically Active status)\n- Harvest ID must correspond to existing harvest record" }, "HarvestWasteDetail": { "type": "object", "properties": { "harvestId": { "type": "integer", "description": "Identifier for the harvest batch generating this waste.", "format": "int32" }, "wasteType": { "type": "string", "description": "Type or category of waste material from the harvest.", "nullable": true }, "wasteAmount": { "type": "number", "description": "Quantity of waste material generated from the harvest.", "format": "double" }, "unitId": { "type": "integer", "description": "Unit of measurement identifier for the waste amount.", "format": "int32" } }, "additionalProperties": false, "description": "Harvest waste detail model for tracking waste generated from specific harvest operations." }, "HarvestWasteDetailWaste": { "type": "object", "properties": { "wasteId": { "type": "integer", "description": "Unique identifier for the waste record (null for new waste creation).", "format": "int32", "nullable": true }, "referenceNo": { "type": "string", "description": "Reference number for waste tracking and documentation.", "nullable": true }, "comments": { "type": "string", "description": "Additional comments or notes about the waste disposal.", "nullable": true }, "wasteDate": { "type": "string", "description": "Date when the waste disposal occurred.", "format": "date-time", "nullable": true }, "wasteDetail": { "type": "array", "items": { "$ref": "#/components/schemas/HarvestWasteDetail" }, "description": "Collection of waste detail records containing specific item information.", "nullable": true }, "lspId": { "type": "integer", "description": "Licensed Service Provider identifier (internal use only).", "format": "int32", "nullable": true }, "locId": { "type": "integer", "description": "Location identifier (internal use only).", "format": "int32", "nullable": true }, "roomRequired": { "type": "boolean", "description": "Indicates if room identification is required for this waste type (internal use only).", "nullable": true }, "isBioTrack": { "type": "boolean", "description": "Indicates if this waste integrates with BioTrack system (internal use only).", "nullable": true } }, "additionalProperties": false, "description": "Generic waste record model containing waste disposal information and associated detail records for cannabis compliance and waste tracking." }, "HarvestedPlant": { "type": "object", "properties": { "plantId": { "type": "integer", "description": "Unique LeafLogix plant identifier for the plant being harvested", "format": "int32" }, "weight": { "type": "number", "description": "Optional harvest weight measurement (typically wet weight in grams)", "format": "double", "nullable": true } }, "additionalProperties": false, "description": "Individual plant harvest information with optional weight tracking for yield management.\n\n**Weight Tracking:**\n- Weight is optional but recommended for harvest yield analysis\n- Typically represents wet weight at time of harvest\n- Used for compliance reporting and operational analytics" }, "IRestrictionAPIResponse": { "type": "object", "properties": { "isExclusion": { "type": "boolean" } }, "additionalProperties": false }, "Int32IEnumerableOptional": { "type": "array", "additionalProperties": false }, "Int32NullableOptional": { "type": "integer", "additionalProperties": false }, "IntegratedPayment": { "type": "object", "properties": { "integrationType": { "type": "string", "description": "Type of integrated payment processor used for the transaction (e.g., \"CreditCard\", \"CanPay\", \"ACH\").", "nullable": true }, "integratedPaid": { "type": "number", "description": "Amount paid through the integrated payment system (in USD).", "format": "double" }, "externalPaymentId": { "type": "string", "description": "External payment identifier from the integrated payment processor for transaction tracking.", "nullable": true } }, "additionalProperties": false, "description": "Integrated payment processing information for cannabis transactions processed through connected payment systems." }, "InventoryDiscrepancy": { "type": "object", "properties": { "inventoryId": { "type": "integer", "format": "int32", "nullable": true }, "packageId": { "type": "string", "nullable": true }, "quantity": { "type": "number", "format": "double" }, "roomId": { "type": "integer", "format": "int32" }, "unitId": { "type": "integer", "format": "int32" }, "externalQuantity": { "type": "number", "format": "double" }, "externalUnitId": { "type": "integer", "format": "int32" }, "equivalentExternalQuantity": { "type": "number", "format": "double", "nullable": true }, "difference": { "type": "number", "format": "double", "readOnly": true }, "productName": { "type": "string", "nullable": true }, "room": { "type": "string", "nullable": true }, "externalRoom": { "type": "string", "nullable": true }, "batchModeQuantity": { "type": "number", "format": "double", "nullable": true }, "bioTrackCategoryName": { "type": "string", "nullable": true }, "externalBioTrackCategoryName": { "type": "string", "nullable": true }, "sku": { "type": "string", "nullable": true }, "unitErrorMsg": { "type": "string", "nullable": true }, "rooms": { "type": "array", "items": { "type": "string" }, "nullable": true }, "serialNumber": { "type": "string", "nullable": true } }, "additionalProperties": false }, "InventoryIntegrationReconResponse": { "type": "object", "properties": { "lastUpdated": { "type": "string", "format": "date-time", "nullable": true }, "discrepancies": { "type": "array", "items": { "$ref": "#/components/schemas/InventoryDiscrepancy" }, "nullable": true } }, "additionalProperties": false }, "InventoryItem": { "type": "object", "properties": { "unitWeightUnit": { "type": "string", "description": "Unit of measurement for unit weight, always \"g\" (grams).", "nullable": true }, "inventoryId": { "type": "integer", "description": "Unique inventory record identifier for this specific inventory item.", "format": "int32" }, "productId": { "type": "integer", "description": "Product identifier linking this inventory to the product catalog.", "format": "int32" }, "sku": { "type": "string", "description": "Stock Keeping Unit (SKU) code for inventory tracking and identification.", "nullable": true }, "productName": { "type": "string", "description": "Display name of the product for customer-facing applications.", "nullable": true }, "description": { "type": "string", "description": "Detailed product description including effects, characteristics, and usage information.", "nullable": true }, "categoryId": { "type": "integer", "description": "Category identifier for product classification (optional).", "format": "int32", "nullable": true }, "category": { "type": "string", "description": "Category name for product classification and filtering.", "nullable": true }, "imageUrl": { "type": "string", "description": "URL path to product image for display purposes.", "nullable": true }, "quantityAvailable": { "type": "number", "description": "Current available quantity for sale or transfer.", "format": "double" }, "quantityUnits": { "type": "string", "description": "Unit of measurement for the available quantity (e.g., \"g\", \"mg\", \"ea\").", "nullable": true }, "unitWeight": { "type": "number", "description": "Weight per unit in grams for dosing and compliance calculations.", "format": "double" }, "flowerEquivalent": { "type": "number", "description": "Flower equivalent amount in grams for compliance tracking.", "format": "double" }, "recFlowerEquivalent": { "type": "number", "description": "Recreational flower equivalent amount in grams (optional).", "format": "double", "nullable": true }, "flowerEquivalentUnits": { "type": "string", "description": "Unit of measurement for flower equivalent, always \"g\" (grams).", "nullable": true, "readOnly": true }, "batchId": { "type": "integer", "description": "Batch identifier for lot tracking and quality control.", "format": "int32" }, "batchName": { "type": "string", "description": "Human-readable batch name or lot number for tracking.", "nullable": true }, "packageId": { "type": "string", "description": "Package identifier for compliance tracking and traceability.", "nullable": true }, "packageStatus": { "type": "string", "description": "Current status of the package (e.g., \"Active\", \"Testing\", \"Quarantine\").", "nullable": true }, "unitPrice": { "type": "number", "description": "Base unit price for retail sales.", "format": "double" }, "medUnitPrice": { "type": "number", "description": "Medical program pricing (optional, different from retail).", "format": "double", "nullable": true }, "recUnitPrice": { "type": "number", "description": "Recreational program pricing (optional, different from medical).", "format": "double", "nullable": true }, "strainId": { "type": "integer", "description": "Strain identifier for cannabis products (optional).", "format": "int32", "nullable": true }, "strain": { "type": "string", "description": "Strain name for cannabis products.", "nullable": true }, "strainType": { "type": "string", "description": "Cannabis strain classification (Hybrid, Indica, Sativa, CBD).", "nullable": true }, "size": { "type": "string", "description": "Product size designation for packaging and dosing information.", "nullable": true }, "labResults": { "type": "array", "items": { "$ref": "#/components/schemas/LabResult" }, "description": "Collection of laboratory test results for this batch (included when includeLabResults=true).", "nullable": true }, "testedDate": { "type": "string", "description": "Date when laboratory testing was completed (optional).", "format": "date-time", "nullable": true }, "sampleDate": { "type": "string", "description": "Date when sample was collected for laboratory testing (optional).", "format": "date-time", "nullable": true }, "packagedDate": { "type": "string", "description": "Date when product was packaged for distribution (optional).", "format": "date-time", "nullable": true }, "manufacturingDate": { "type": "string", "description": "Date when product was manufactured or produced (optional).", "format": "date-time", "nullable": true }, "lastModifiedDateUtc": { "type": "string", "description": "Last modification timestamp in UTC for data synchronization.", "format": "date-time", "nullable": true }, "labTestStatus": { "type": "string", "description": "Current status of laboratory testing (e.g., \"Passed\", \"Failed\", \"Pending\").", "nullable": true }, "vendorId": { "type": "integer", "description": "Vendor identifier for the supplier of this inventory (optional).", "format": "int32", "nullable": true }, "vendor": { "type": "string", "description": "Vendor name for the supplier of this inventory.", "nullable": true }, "expirationDate": { "type": "string", "description": "Product expiration date for compliance and quality control (optional).", "format": "date-time", "nullable": true }, "roomQuantities": { "type": "array", "items": { "$ref": "#/components/schemas/InventoryRoomQuantity" }, "description": "Quantity breakdown by storage room/location (included when includeRoomQuantities=true).", "nullable": true }, "pricingTierName": { "type": "string", "description": "Pricing tier classification for bulk pricing strategies.", "nullable": true }, "alternateName": { "type": "string", "description": "Alternative product name for display purposes.", "nullable": true }, "tags": { "type": "array", "items": { "$ref": "#/components/schemas/InventoryTag" }, "description": "Collection of compliance tags associated with this inventory package.", "nullable": true }, "brandId": { "type": "integer", "description": "Brand identifier for branded products (optional).", "format": "int32", "nullable": true }, "brandName": { "type": "string", "description": "Brand name for branded products.", "nullable": true }, "medicalOnly": { "type": "boolean", "description": "Indicates if product is restricted to medical program only." }, "externalPackageId": { "type": "string", "description": "External compliance system ID (METRC or BioTrack) for regulatory tracking.", "nullable": true }, "producer": { "type": "string", "description": "Producer name for cultivation and manufacturing tracking.", "nullable": true }, "producerId": { "type": "integer", "description": "Producer identifier for cultivation and manufacturing tracking (optional).", "format": "int32", "nullable": true }, "lineage": { "type": "array", "items": { "$ref": "#/components/schemas/PackageLineage" }, "description": "Package lineage information for traceability and compliance tracking.", "nullable": true }, "potencyIndicator": { "type": "string", "description": "Potency classification indicator for dosing guidance.", "nullable": true }, "masterCategory": { "type": "string", "description": "Master category classification for product grouping.", "nullable": true }, "effectivePotencyMg": { "type": "number", "description": "Effective potency in milligrams for dosing calculations (optional).", "format": "double", "nullable": true }, "isCannabis": { "type": "boolean", "description": "Indicates if product contains cannabis or is cannabis-related." }, "packageNDC": { "type": "string", "description": "National Drug Code for pharmaceutical tracking (optional).", "nullable": true }, "labResultUrl": { "type": "string", "description": "URL to certificate of analysis or lab testing document.", "nullable": true } }, "additionalProperties": false, "description": "Inventory item model representing current stock and product details for available inventory." }, "InventoryRoomQuantity": { "type": "object", "properties": { "roomId": { "type": "integer", "description": "Room identifier for the storage location.", "format": "int32" }, "room": { "type": "string", "description": "Room name or description for the storage location.", "nullable": true }, "quantityAvailable": { "type": "number", "description": "Quantity of cannabis product available in this specific room location.", "format": "double" } }, "additionalProperties": false, "description": "Cannabis inventory quantity tracking model by room location for facility management and compliance." }, "InventorySnapshot": { "required": [ "inventoryId", "packageId", "product", "productId", "quantity", "room", "roomId", "sku", "snapshotDate", "unit", "unitId" ], "type": "object", "properties": { "sku": { "minLength": 1, "type": "string", "description": "Stock Keeping Unit (SKU) code for product identification." }, "product": { "minLength": 1, "type": "string", "description": "Product name as it existed at the snapshot date." }, "productId": { "type": "integer", "description": "Product identifier linking to the product catalog.", "format": "int32" }, "room": { "minLength": 1, "type": "string", "description": "Storage room name where inventory was located at snapshot time." }, "roomId": { "type": "integer", "description": "Storage room identifier for location tracking.", "format": "int32" }, "vendor": { "type": "string", "description": "Vendor name for the supplier of this inventory (optional).", "nullable": true }, "packageId": { "minLength": 1, "type": "string", "description": "Package identifier for compliance tracking and traceability." }, "batchName": { "type": "string", "description": "Batch name or lot number for quality tracking (optional).", "nullable": true }, "batchId": { "type": "integer", "description": "Batch identifier for lot tracking (optional).", "format": "int32", "nullable": true }, "quantity": { "type": "number", "description": "Inventory quantity as it existed at the snapshot date.", "format": "double" }, "totalCost": { "type": "number", "description": "Total cost value of the inventory quantity (optional).", "format": "double", "nullable": true }, "unit": { "minLength": 1, "type": "string", "description": "Unit of measurement for the quantity." }, "unitId": { "type": "integer", "description": "Unit identifier for the measurement type.", "format": "int32" }, "status": { "type": "string", "description": "Inventory status at the time of snapshot (e.g., \"Active\", \"Quarantine\").", "nullable": true }, "snapshotDate": { "type": "string", "description": "Date and time when this inventory snapshot was captured.", "format": "date-time" }, "inventoryId": { "type": "integer", "description": "Inventory record identifier linking to the specific inventory item.", "format": "int32" } }, "additionalProperties": false, "description": "Historical inventory snapshot model representing inventory levels at a specific point in time." }, "InventoryTag": { "type": "object", "properties": { "tagId": { "type": "integer", "format": "int32" }, "tagName": { "type": "string", "nullable": true }, "packageId": { "type": "string", "nullable": true } }, "additionalProperties": false }, "InventoryTransaction": { "required": ["inventoryTransactionId"], "type": "object", "properties": { "inventoryTransactionId": { "type": "integer", "description": "Unique identifier for the inventory transaction record.", "format": "int32" }, "transactionType": { "type": "string", "description": "Type of inventory transaction performed.\n**Options**: Move, Convert, Adjust, Combine, Receive, Change Product, Discontinue, Detail Update, Reconciliation, Create Package", "nullable": true }, "product": { "type": "string", "description": "Product name at the time of transaction.", "nullable": true }, "sku": { "type": "string", "description": "Stock Keeping Unit (SKU) code for the product.", "nullable": true }, "productId": { "type": "integer", "description": "Product identifier linking to the product catalog.", "format": "int32" }, "unit": { "type": "string", "description": "Unit of measurement for the transaction quantities.", "nullable": true }, "packageId": { "type": "string", "description": "Package identifier for compliance tracking and traceability.", "nullable": true }, "externalPackageId": { "type": "string", "description": "External package identifier from integrated compliance systems.", "nullable": true }, "batchId": { "type": "integer", "description": "Batch identifier for lot tracking (optional).", "format": "int32", "nullable": true }, "batchName": { "type": "string", "description": "Batch name or lot number for quality tracking (optional).", "nullable": true }, "quantity": { "type": "number", "description": "Transaction quantity for non-adjustment operations (Move, Convert, Receive, etc.).", "format": "double", "nullable": true }, "fromQuantity": { "type": "number", "description": "Original quantity before adjustment (used for Adjust transaction type).", "format": "double", "nullable": true }, "toQuantity": { "type": "number", "description": "New quantity after adjustment (used for Adjust transaction type).", "format": "double", "nullable": true }, "reason": { "type": "string", "description": "Reason for adjustment (used for Adjust transaction type).", "nullable": true }, "receiveInventoryHistoryId": { "type": "integer", "description": "Receive inventory history identifier for received inventory linkage (optional).", "format": "int32", "nullable": true }, "fromLocation": { "type": "string", "description": "Source location name for Move transactions.", "nullable": true }, "fromRoom": { "type": "string", "description": "Source room name for Move transactions.", "nullable": true }, "toLocation": { "type": "string", "description": "Destination location name for Move transactions.", "nullable": true }, "toRoom": { "type": "string", "description": "Destination room name for Move transactions.", "nullable": true }, "conversionTransactionID": { "type": "integer", "description": "Conversion transaction identifier for Convert operations (optional).", "format": "int32", "nullable": true }, "transactionBy": { "type": "string", "description": "Username or identifier of the person who performed the transaction.", "nullable": true }, "transactionDate": { "type": "string", "description": "Date and time when the transaction was performed.", "format": "date-time" }, "unitCost": { "type": "number", "description": "Unit cost of the package at the time of transaction (optional).", "format": "double", "nullable": true }, "purchaseOrderId": { "type": "integer", "description": "Purchase order identifier for received inventory linkage (optional).", "format": "int32", "nullable": true }, "inventoryId": { "type": "integer", "description": "Unique inventory item identifier affected by this transaction.", "format": "int32" } }, "additionalProperties": false, "description": "Inventory transaction record model representing historical inventory movement and modification operations." }, "JournalEntry": { "type": "object", "properties": { "journalEntryId": { "type": "integer", "description": "Unique identifier for the journal entry.", "format": "int32" }, "subject": { "type": "string", "description": "Brief title or summary of the journal entry.", "nullable": true }, "body": { "type": "string", "description": "Detailed content and notes for the journal entry.", "nullable": true }, "date": { "type": "string", "description": "Date and time when the journal entry was created or should be dated.", "format": "date-time" } }, "additionalProperties": false, "description": "Represents a customer journal entry containing notes and interaction history for customer service tracking." }, "LabResult": { "type": "object", "properties": { "labTest": { "type": "string", "description": "Name of the laboratory test performed (e.g., \"THC\", \"CBD\", \"Myrcene\", \"Total Aerobic Count\").", "nullable": true }, "value": { "type": "number", "description": "Numeric test result value (null if not detected or not applicable).", "format": "double", "nullable": true }, "labResultUnitId": { "$ref": "#/components/schemas/LabResultUnit" }, "labResultUnit": { "type": "string", "description": "Human-readable unit name corresponding to the LabResultUnitId.", "nullable": true, "readOnly": true } }, "additionalProperties": false, "description": "Laboratory testing result model for cannabis and cannabis product analysis." }, "LabResultUnit": { "enum": [1, 2, 3, 4, 5, 6], "type": "integer", "format": "int32" }, "LabResultUnitData": { "type": "object", "properties": { "labResultUnitId": { "type": "integer", "description": "Unique identifier for the lab result unit type.", "format": "int32" }, "labResultUnit": { "type": "string", "description": "Display name of the lab result unit (e.g., \"mg\", \"%\", \"mg/g\", \"ND\", \"LOQ\", \"Pass/Fail\").", "nullable": true } }, "additionalProperties": false, "description": "Laboratory result unit data model for cannabis testing measurements and reporting." }, "LineItemTaxInfo": { "type": "object", "properties": { "rateName": { "type": "string", "description": "Name of the tax rate applied (e.g., \"State Excise Tax\", \"City Cannabis Tax\", \"Sales Tax\").", "nullable": true }, "rate": { "type": "number", "description": "Tax rate as a decimal percentage (e.g., 0.0875 for 8.75% tax rate).", "format": "double" }, "amount": { "type": "number", "description": "Calculated tax amount applied to the line item (in USD).", "format": "double" }, "transactionItemId": { "type": "integer", "description": "Reference identifier linking this tax information back to the specific transaction line item.\nNot guaranteed to be unique outside of a single transaction.", "format": "int32", "readOnly": true } }, "additionalProperties": false, "description": "Tax information applied to individual transaction line items in cannabis retail operations." }, "Lineage": { "type": "object", "properties": { "lineageId": { "type": "integer", "description": "Unique identifier for the genetic lineage.", "format": "int32" }, "lineageName": { "type": "string", "description": "Display name for the genetic lineage (e.g., \"Indica\", \"Sativa\", \"Hybrid\").", "nullable": true } }, "additionalProperties": false, "description": "Cannabis genetic lineage model containing hereditary classification information for product categorization and genetic tracking." }, "LocationIdentity": { "type": "object", "properties": { "locationId": { "type": "integer", "description": "Unique identifier for the cannabis dispensary location.", "format": "int32" }, "lspId": { "type": "integer", "description": "Unique identifier for the parent company (LSP - Licensed Service Provider).", "format": "int32" }, "locationName": { "type": "string", "description": "Business name of the cannabis dispensary location.", "nullable": true }, "lspName": { "type": "string", "description": "Company name of the parent organization (Licensed Service Provider).", "nullable": true }, "address": { "type": "string", "description": "Primary street address of the dispensary location.", "nullable": true }, "address2": { "type": "string", "description": "Secondary address line (suite, unit, etc.) if applicable.", "nullable": true }, "city": { "type": "string", "description": "City where the dispensary is located.", "nullable": true }, "state": { "type": "string", "description": "State or province where the dispensary is licensed to operate.", "nullable": true }, "postalCode": { "type": "string", "description": "Postal code (ZIP code) for the dispensary location.", "nullable": true }, "licenseNumber": { "type": "string", "description": "State-issued cannabis business license number for regulatory compliance.", "nullable": true }, "doingBusinessAs": { "type": "string", "description": "\"Doing Business As\" name if different from the legal business name.", "nullable": true }, "shareCustomerProfiles": { "type": "boolean", "description": "Indicates whether customer profiles are shared across locations within the organization." }, "globalId": { "type": "string", "description": "Legacy global unique identifier for the location (deprecated).", "format": "uuid", "nullable": true, "deprecated": true }, "locationGlobalId": { "type": "string", "description": "Global unique identifier for the location across all systems and integrations.", "format": "uuid", "nullable": true }, "lspGlobalId": { "type": "string", "description": "Global unique identifier for the parent company (LSP) across all systems.", "format": "uuid", "nullable": true }, "region": { "type": "string", "description": "Regional identifier for compliance and API routing (internal use only).", "nullable": true }, "regionId": { "type": "string", "description": "Base64-encoded SHA256 hash of the region identifier for secure regional routing.", "nullable": true, "readOnly": true } }, "additionalProperties": false, "description": "Location identity model containing complete location and parent company information for API key verification and context identification." }, "LocationMapping": { "type": "object", "properties": { "locationName": { "type": "string", "description": "Name of the location where the discount applies.", "nullable": true } }, "additionalProperties": false, "description": "Location mapping model for associating discounts with specific business locations." }, "LocationProductOverride": { "type": "object", "properties": { "productId": { "type": "integer", "format": "int32" }, "price": { "type": "number", "format": "double", "nullable": true }, "recPrice": { "type": "number", "format": "double", "nullable": true }, "cost": { "type": "number", "format": "double", "nullable": true }, "onlineAvailable": { "type": "boolean", "nullable": true }, "posAvailable": { "type": "boolean", "nullable": true }, "maxPurchasable": { "type": "number", "format": "double", "nullable": true }, "lowInventoryThreshold": { "type": "number", "format": "double", "nullable": true }, "customMetadata": { "type": "string", "nullable": true } }, "additionalProperties": false }, "LocationProductOverrideRequest": { "type": "object", "properties": { "productId": { "type": "integer", "description": "Product identifier for the product being configured with location-specific overrides.", "format": "int32" }, "price": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "recPrice": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "cost": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "onlineAvailable": { "$ref": "#/components/schemas/BooleanNullableOptional" }, "posAvailable": { "$ref": "#/components/schemas/BooleanNullableOptional" }, "maxPurchasable": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "lowInventoryThreshold": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "customMetadata": { "$ref": "#/components/schemas/StringOptional" } }, "additionalProperties": false }, "LocationResponse": { "type": "object", "properties": { "locationName": { "type": "string", "nullable": true }, "locId": { "type": "integer", "format": "int32" }, "licenseNumber": { "type": "string", "nullable": true }, "outcome": { "type": "string", "nullable": true, "readOnly": true }, "outcomeId": { "type": "integer", "format": "int32", "readOnly": true }, "broadcastedTo": { "type": "string", "nullable": true }, "errorDetail": { "type": "string", "nullable": true } }, "additionalProperties": false }, "LoyaltySnapshot": { "type": "object", "properties": { "customerId": { "type": "integer", "description": "Unique identifier for the customer in the loyalty program.\nLinks this loyalty snapshot to the specific customer account.", "format": "int32" }, "loyaltyBalance": { "type": "number", "description": "Current available loyalty points balance for the customer.\nRepresents points that can be redeemed for rewards or discounts.", "format": "double" }, "loyaltySpent": { "type": "number", "description": "Total loyalty points redeemed/spent by the customer over their lifetime.\nHistorical record of all point redemptions and rewards claimed.", "format": "double" }, "loyaltyEarned": { "type": "number", "description": "Total loyalty points earned by the customer over their lifetime.\nHistorical record of all points awarded through purchases and activities.", "format": "double" } }, "additionalProperties": false, "description": "Represents a customer's loyalty program balance and activity snapshot for reporting purposes.\n\nContains current point balances and historical activity for individual customers within the\nloyalty program. Used for daily balance reporting, customer service inquiries, and loyalty\nprogram analytics. Data reflects nightly batch processing and may not include real-time changes." }, "ManualPayment": { "type": "object", "properties": { "manualPaymentProcessorName": { "type": "string", "description": "Name of the manual payment processor or handling method (e.g., \"Cash\", \"Check\", \"Money Order\").", "nullable": true }, "manualPaid": { "type": "number", "description": "Amount paid through the manual payment method (in USD).", "format": "double" } }, "additionalProperties": false, "description": "Manual payment information for cannabis transactions processed outside integrated payment systems." }, "MatureBatchDetails": { "type": "object", "properties": { "batchId": { "type": "integer", "description": "Batch identifier for the mature plant batch being created.", "format": "int32" }, "serialNumbers": { "type": "array", "items": { "type": "string" }, "description": "Collection of individual plant serial numbers within the mature batch for state tracking compliance.", "nullable": true }, "batchStage": { "type": "string", "description": "Growth stage designation for the mature batch (e.g., \"Vegetative\", \"Flowering\").", "nullable": true }, "roomId": { "type": "integer", "description": "Room identifier for the mature batch location assignment.", "format": "int32" }, "tableId": { "type": "integer", "description": "Table identifier within the room for precise location tracking (optional).", "format": "int32", "nullable": true }, "dateCreated": { "type": "string", "description": "Date when the mature batch was created for cultivation timeline documentation.", "format": "date-time", "nullable": true } }, "additionalProperties": false, "description": "Detailed specification for creating individual mature plant batches with compliance tracking information." }, "MovePlantRequest": { "type": "object", "properties": { "plantIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "description": "Collection of LeafLogix plant IDs to move to the target room", "nullable": true }, "roomId": { "type": "integer", "description": "Target cultivation room ID within the same facility where plants will be moved", "format": "int32" }, "tableId": { "type": "integer", "description": "Optional table ID within the target room for precise plant positioning (optional)", "format": "int32", "nullable": true } }, "additionalProperties": false, "description": "Request model for moving cannabis plants to a different cultivation room or table within the same facility.\n\n**Movement Behavior:**\n- Moves specified plants to target room within same facility\n- Optional table assignment for precise cultivation area management\n- Validates target room belongs to same facility for security\n- Automatically updates plant cultivation stage if room has associated stage\n\n**Facility Restrictions:**\n- Target room must belong to same facility as requesting user\n- Cross-facility plant movements are prohibited for security and compliance\n- All plant IDs must be accessible to the authenticated location\n\n**Integration:**\n- Movement synchronized with external cultivation systems when configured\n- Supports cultivation workflow automation and environmental optimization" }, "ObjectWaste": { "type": "object", "properties": { "wasteId": { "type": "integer", "description": "Unique identifier for the waste record (null for new waste creation).", "format": "int32", "nullable": true }, "referenceNo": { "type": "string", "description": "Reference number for waste tracking and documentation.", "nullable": true }, "comments": { "type": "string", "description": "Additional comments or notes about the waste disposal.", "nullable": true }, "wasteDate": { "type": "string", "description": "Date when the waste disposal occurred.", "format": "date-time", "nullable": true }, "wasteDetail": { "type": "array", "items": { "type": "object" }, "description": "Collection of waste detail records containing specific item information.", "nullable": true }, "lspId": { "type": "integer", "description": "Licensed Service Provider identifier (internal use only).", "format": "int32", "nullable": true }, "locId": { "type": "integer", "description": "Location identifier (internal use only).", "format": "int32", "nullable": true }, "roomRequired": { "type": "boolean", "description": "Indicates if room identification is required for this waste type (internal use only).", "nullable": true }, "isBioTrack": { "type": "boolean", "description": "Indicates if this waste integrates with BioTrack system (internal use only).", "nullable": true } }, "additionalProperties": false, "description": "Generic waste record model containing waste disposal information and associated detail records for cannabis compliance and waste tracking." }, "PackageLineage": { "type": "object", "properties": { "packageId": { "type": "string", "description": "Package identifier for the current package in the lineage chain.", "nullable": true }, "antecedentPackageDistance": { "type": "integer", "description": "Number of generations between current package and antecedent package in the lineage chain.", "format": "int32" }, "antecedentIsHarvest": { "type": "boolean", "description": "Flag indicating whether the antecedent package originated from a harvest operation." }, "batchName": { "type": "string", "description": "Batch name for the current package for lot tracking and quality control.", "nullable": true }, "antecedentBatchName": { "type": "string", "description": "Batch name of the antecedent package for lineage and quality tracking.", "nullable": true } }, "additionalProperties": false, "description": "Package lineage tracking model for cannabis product traceability and regulatory compliance." }, "Plant": { "type": "object", "properties": { "plantId": { "type": "integer", "format": "int32" }, "serialNumber": { "type": "string", "nullable": true }, "growthPhase": { "type": "string", "nullable": true }, "type": { "type": "string", "nullable": true }, "harvestedWeight": { "type": "number", "format": "double", "nullable": true }, "status": { "type": "string", "nullable": true }, "plantCount": { "type": "integer", "format": "int32", "nullable": true }, "isMother": { "type": "boolean" }, "motherPlantId": { "type": "integer", "format": "int32", "nullable": true }, "plantedOn": { "type": "string", "format": "date-time", "nullable": true }, "addedToHarvestOn": { "type": "string", "format": "date-time", "nullable": true }, "harvestDate": { "type": "string", "format": "date-time", "nullable": true }, "destroyedDate": { "type": "string", "format": "date-time", "nullable": true }, "plantGroupName": { "type": "string", "nullable": true }, "strain": { "type": "string", "nullable": true }, "room": { "type": "string", "nullable": true }, "table": { "type": "string", "nullable": true }, "vegetationStartedOn": { "type": "string", "format": "date-time", "nullable": true }, "vegetationEndedOn": { "type": "string", "format": "date-time", "nullable": true }, "floweringStartedOn": { "type": "string", "format": "date-time", "nullable": true }, "floweringEndedOn": { "type": "string", "format": "date-time", "nullable": true }, "currentPhaseStartDate": { "type": "string", "format": "date-time", "nullable": true }, "lastModifiedDate": { "type": "string", "format": "date-time", "nullable": true }, "daysInCurrentPhase": { "type": "integer", "format": "int32", "nullable": true }, "floweringRoom": { "type": "string", "nullable": true }, "floweringTable": { "type": "string", "nullable": true }, "vegetationRoom": { "type": "string", "nullable": true }, "vegetationTable": { "type": "string", "nullable": true }, "daysInFlowering": { "type": "integer", "format": "int32", "nullable": true }, "daysInVegetation": { "type": "integer", "format": "int32", "nullable": true }, "batchId": { "type": "integer", "format": "int32" }, "harvestId": { "type": "integer", "format": "int32", "readOnly": true } }, "additionalProperties": false }, "PlantWasteDetail": { "type": "object", "properties": { "plantId": { "type": "integer", "description": "Identifier for the plant generating this waste.", "format": "int32" }, "wasteType": { "type": "string", "description": "Type or category of waste material from the plant.", "nullable": true }, "wasteAmount": { "type": "number", "description": "Quantity of waste material generated from the plant.", "format": "double" }, "unitId": { "type": "integer", "description": "Unit of measurement identifier for the waste amount.", "format": "int32" } }, "additionalProperties": false, "description": "Plant waste detail model for tracking waste generated from specific plant disposal operations." }, "PlantWasteDetailWaste": { "type": "object", "properties": { "wasteId": { "type": "integer", "description": "Unique identifier for the waste record (null for new waste creation).", "format": "int32", "nullable": true }, "referenceNo": { "type": "string", "description": "Reference number for waste tracking and documentation.", "nullable": true }, "comments": { "type": "string", "description": "Additional comments or notes about the waste disposal.", "nullable": true }, "wasteDate": { "type": "string", "description": "Date when the waste disposal occurred.", "format": "date-time", "nullable": true }, "wasteDetail": { "type": "array", "items": { "$ref": "#/components/schemas/PlantWasteDetail" }, "description": "Collection of waste detail records containing specific item information.", "nullable": true }, "lspId": { "type": "integer", "description": "Licensed Service Provider identifier (internal use only).", "format": "int32", "nullable": true }, "locId": { "type": "integer", "description": "Location identifier (internal use only).", "format": "int32", "nullable": true }, "roomRequired": { "type": "boolean", "description": "Indicates if room identification is required for this waste type (internal use only).", "nullable": true }, "isBioTrack": { "type": "boolean", "description": "Indicates if this waste integrates with BioTrack system (internal use only).", "nullable": true } }, "additionalProperties": false, "description": "Generic waste record model containing waste disposal information and associated detail records for cannabis compliance and waste tracking." }, "PostImmatureBatchRequest": { "type": "object", "properties": { "batches": { "type": "array", "items": { "$ref": "#/components/schemas/BatchDetails" }, "description": "Collection of immature plant batch specifications for bulk batch creation operations.", "nullable": true } }, "additionalProperties": false, "description": "Request model for creating immature plant batches in cannabis cultivation operations." }, "PreOrderItem": { "required": ["productId", "quantity"], "type": "object", "properties": { "productId": { "type": "integer", "format": "int32" }, "quantity": { "type": "number", "format": "double" } }, "additionalProperties": false }, "PreOrderRedemption": { "required": ["redemptionId", "redemptionType"], "type": "object", "properties": { "productId": { "type": "integer", "format": "int32", "nullable": true }, "redemptionType": { "minLength": 1, "type": "string" }, "redemptionId": { "minLength": 1, "type": "string" }, "redemptionDescription": { "type": "string", "nullable": true }, "redemptionCallbackUrl": { "type": "string", "nullable": true } }, "additionalProperties": false }, "PreOrderRedemptionIEnumerableOptional": { "type": "array", "additionalProperties": false }, "PreOrderStatus": { "type": "object", "properties": { "preOrderId": { "type": "integer", "format": "int32" }, "status": { "type": "string", "nullable": true }, "transactionId": { "type": "integer", "format": "int32", "nullable": true }, "orderDate": { "type": "string", "format": "date-time" }, "customerFirstName": { "type": "string", "nullable": true }, "customerLastName": { "type": "string", "nullable": true }, "customerId": { "type": "integer", "format": "int32" }, "orderType": { "type": "string", "nullable": true }, "orderSource": { "type": "string", "nullable": true }, "rejectedReason": { "type": "string", "nullable": true }, "isCancellable": { "type": "boolean" }, "isUpdateable": { "type": "boolean" }, "total": { "type": "number", "format": "double", "nullable": true }, "subTotal": { "type": "number", "format": "double", "nullable": true }, "totalTax": { "type": "number", "format": "double", "nullable": true }, "sourceSystem": { "type": "string", "nullable": true }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/AllocatedPreOrderItem" }, "nullable": true } }, "additionalProperties": false }, "PrecartItem": { "type": "object", "properties": { "productId": { "type": "integer", "format": "int32" }, "quantity": { "type": "number", "format": "double" } }, "additionalProperties": false }, "PriceCartRequest": { "type": "object", "properties": { "cart": { "type": "array", "items": { "$ref": "#/components/schemas/PrecartItem" }, "description": "Collection of products in the customer's shopping cart with quantities and specifications.", "nullable": true }, "customerTypeId": { "type": "integer", "description": "Customer type identifier for pricing tier and discount eligibility (e.g., medical, recreational).", "format": "int32", "nullable": true }, "customerId": { "type": "integer", "description": "Unique customer identifier for personalized pricing and loyalty program benefits.", "format": "int32", "nullable": true }, "deliveryStreet": { "type": "string", "description": "Primary street address for delivery orders (used for tax calculation and delivery fee estimation).", "nullable": true }, "deliveryStreet2": { "type": "string", "description": "Secondary address information (apartment, suite, unit number) for delivery orders.", "nullable": true }, "deliveryCity": { "type": "string", "description": "City name for delivery address (used for tax jurisdiction determination).", "nullable": true }, "deliveryState": { "type": "string", "description": "State or province for delivery address (used for tax calculation and compliance verification).", "nullable": true }, "deliveryPostalCode": { "type": "string", "description": "Postal or ZIP code for delivery address (used for precise tax calculation and delivery zones).", "nullable": true }, "isDelivery": { "type": "boolean", "description": "Indicates whether this is a delivery order (true) or pickup order (false) for tax and fee calculation." } }, "additionalProperties": false, "description": "Request model for calculating pricing, taxes, and discounts for a customer's shopping cart before creating a pre-order." }, "PriceEstimates": { "type": "object", "properties": { "discountAmount": { "type": "number", "format": "double" }, "taxAmount": { "type": "number", "format": "double" }, "feeAmount": { "type": "number", "format": "double" }, "subtotal": { "type": "number", "format": "double" }, "grandTotal": { "type": "number", "format": "double" } }, "additionalProperties": false }, "PricingDetail": { "type": "object", "properties": { "medPrice": { "type": "number", "description": "Medical cannabis patient pricing (typically lower due to tax benefits and patient programs).", "format": "double", "nullable": true }, "recPrice": { "type": "number", "description": "Recreational adult-use cannabis pricing (standard retail pricing with full taxes).", "format": "double", "nullable": true }, "pricingTierName": { "type": "string", "description": "Pricing tier name for customer segmentation (e.g., \"Standard\", \"VIP\", \"Bulk\", \"Employee\").", "nullable": true } }, "additionalProperties": false, "description": "Pricing detail information for cannabis products with medical and recreational pricing tiers." }, "PricingTier": { "type": "object", "properties": { "pricingTierId": { "type": "integer", "format": "int32" }, "pricingTierName": { "type": "string", "nullable": true } }, "additionalProperties": false }, "PricingTierData": { "type": "object", "properties": { "startWeight": { "type": "number", "format": "double", "nullable": true }, "endWeight": { "type": "number", "format": "double", "nullable": true }, "price": { "type": "number", "format": "double" }, "medicalPrice": { "type": "number", "format": "double" } }, "additionalProperties": false }, "Producer": { "type": "object", "properties": { "producerId": { "type": "integer", "description": "Unique identifier for the producer.", "format": "int32" }, "producerName": { "type": "string", "description": "Display name of the producer for product attribution and branding.", "nullable": true } }, "additionalProperties": false, "description": "Producer identification model containing basic producer information for product attribution and reference data needs." }, "ProductCategory": { "type": "object", "properties": { "productCategoryId": { "type": "integer", "description": "Unique identifier for the product category.", "format": "int32" }, "productCategoryName": { "type": "string", "description": "Display name of the product category (e.g., \"Flower\", \"Edibles\", \"Concentrates\").", "nullable": true }, "masterCategory": { "type": "string", "description": "Higher-level master category classification for broader product grouping.", "nullable": true } }, "additionalProperties": false, "description": "Product category model containing cannabis product classification information for menu organization and product management." }, "ProductDetail": { "type": "object", "properties": { "productId": { "type": "integer", "format": "int32" }, "sku": { "type": "string", "nullable": true }, "internalName": { "type": "string", "nullable": true }, "productName": { "type": "string", "nullable": true }, "description": { "type": "string", "nullable": true }, "masterCategory": { "type": "string", "nullable": true }, "categoryId": { "type": "integer", "format": "int32", "nullable": true }, "category": { "type": "string", "nullable": true }, "imageUrl": { "type": "string", "nullable": true }, "imageUrls": { "type": "array", "items": { "type": "string" }, "nullable": true }, "strainId": { "type": "integer", "format": "int32", "nullable": true }, "strain": { "type": "string", "nullable": true }, "strainType": { "type": "string", "nullable": true }, "size": { "type": "string", "nullable": true }, "netWeight": { "type": "number", "format": "double", "nullable": true }, "netWeightUnitId": { "type": "integer", "format": "int32", "nullable": true }, "netWeightUnit": { "type": "string", "nullable": true, "readOnly": true }, "brandId": { "type": "integer", "format": "int32", "nullable": true }, "brandName": { "type": "string", "nullable": true }, "vendorId": { "type": "integer", "format": "int32", "nullable": true }, "vendorName": { "type": "string", "nullable": true }, "isCannabis": { "type": "boolean" }, "isActive": { "type": "boolean" }, "isCoupon": { "type": "boolean" }, "thcContent": { "type": "number", "format": "double", "nullable": true }, "thcContentUnit": { "type": "string", "nullable": true }, "cbdContent": { "type": "number", "format": "double", "nullable": true }, "cbdContentUnit": { "type": "string", "nullable": true }, "productGrams": { "type": "number", "format": "double", "nullable": true }, "flowerEquivalent": { "type": "number", "format": "double", "nullable": true }, "recFlowerEquivalent": { "type": "number", "format": "double", "nullable": true }, "price": { "type": "number", "format": "double", "nullable": true }, "medPrice": { "type": "number", "format": "double", "nullable": true }, "recPrice": { "type": "number", "format": "double", "nullable": true }, "unitCost": { "type": "number", "format": "double", "nullable": true }, "unitType": { "type": "string", "nullable": true }, "onlineTitle": { "type": "string", "nullable": true }, "onlineDescription": { "type": "string", "nullable": true }, "onlineProduct": { "type": "boolean", "nullable": true, "readOnly": true }, "posProducts": { "type": "boolean", "nullable": true }, "pricingTier": { "type": "integer", "format": "int32", "nullable": true }, "onlineAvailable": { "type": "boolean", "nullable": true }, "lowInventoryThreshold": { "type": "number", "format": "double", "nullable": true }, "pricingTierName": { "type": "string", "nullable": true }, "pricingTierDescription": { "type": "string", "nullable": true }, "pricingTierData": { "type": "array", "items": { "$ref": "#/components/schemas/PricingTierData" }, "nullable": true }, "flavor": { "type": "string", "nullable": true }, "alternateName": { "type": "string", "nullable": true }, "lineageName": { "type": "string", "nullable": true }, "distillationName": { "type": "string", "nullable": true }, "maxPurchaseablePerTransaction": { "type": "number", "format": "double", "nullable": true }, "tags": { "type": "array", "items": { "$ref": "#/components/schemas/ProductTag" }, "nullable": true }, "effects": { "type": "array", "items": { "$ref": "#/components/schemas/ProductEffect" }, "nullable": true }, "dosage": { "type": "string", "nullable": true }, "instructions": { "type": "string", "nullable": true }, "allergens": { "type": "string", "nullable": true }, "standardAllergens": { "$ref": "#/components/schemas/StandardAllergensDetails" }, "defaultUnit": { "type": "string", "nullable": true }, "producerId": { "type": "integer", "format": "int32", "nullable": true }, "producerName": { "type": "string", "nullable": true }, "createdDate": { "type": "string", "format": "date-time", "nullable": true }, "isMedicalOnly": { "type": "boolean" }, "lastModifiedDateUTC": { "type": "string", "format": "date-time", "nullable": true }, "grossWeight": { "type": "number", "format": "double", "nullable": true }, "isTaxable": { "type": "boolean", "nullable": true }, "taxCategories": { "type": "array", "items": { "type": "string" }, "nullable": true }, "upc": { "type": "string", "nullable": true }, "regulatoryCategory": { "type": "string", "nullable": true }, "ndc": { "type": "string", "nullable": true }, "daysSupply": { "type": "number", "format": "double", "nullable": true }, "illinoisTaxCategory": { "type": "string", "nullable": true, "readOnly": true }, "externalCategory": { "type": "string", "nullable": true }, "externalId": { "type": "string", "nullable": true }, "syncExternally": { "type": "boolean" }, "regulatoryName": { "type": "string", "nullable": true }, "broadcastedResponses": { "$ref": "#/components/schemas/BroadcastedResponses" }, "administrationMethod": { "type": "string", "nullable": true }, "unitCBDContentDose": { "type": "number", "format": "double", "nullable": true }, "unitTHCContentDose": { "type": "number", "format": "double", "nullable": true }, "oilVolume": { "type": "number", "format": "double", "nullable": true }, "ingredientList": { "type": "string", "nullable": true }, "expirationDays": { "type": "integer", "format": "int32", "nullable": true }, "abbreviation": { "type": "string", "nullable": true }, "isTestProduct": { "type": "boolean" }, "isFinished": { "type": "boolean" }, "allowAutomaticDiscounts": { "type": "boolean" }, "servingSize": { "type": "string", "nullable": true }, "servingSizePerUnit": { "type": "integer", "format": "int32", "nullable": true }, "isNutrient": { "type": "boolean" }, "approvalDateUTC": { "type": "string", "format": "date-time", "nullable": true }, "ecomCategory": { "type": "string", "nullable": true }, "ecomSubcategory": { "type": "string", "nullable": true }, "customMetadata": { "type": "string", "nullable": true } }, "additionalProperties": false }, "ProductDetailUpload": { "required": ["productName", "sku"], "type": "object", "properties": { "productId": { "type": "integer", "description": "The unique identifier for a product in the system.\n\n**IMPORTANT**: This field determines whether a product is created or updated:\n- To CREATE a new product: Omit this field or set to null\n- To UPDATE an existing product: You MUST provide the ProductId of the existing product", "format": "int32", "nullable": true }, "sku": { "minLength": 1, "type": "string", "description": "Product SKU - REQUIRED for CREATE operations" }, "productName": { "minLength": 1, "type": "string", "description": "Product Name - REQUIRED for CREATE operations" }, "description": { "type": "string", "description": "Deprecated in favor of AlternateName", "nullable": true }, "alternateName": { "type": "string", "nullable": true }, "masterCategory": { "type": "string", "nullable": true }, "category": { "type": "string", "nullable": true }, "strain": { "type": "string", "nullable": true }, "strainType": { "type": "string", "description": "Strain type of the specified strain.\nUsed to disambiguate strains, if duplicates exist.\nIf no duplicates exist in the location's strain list, this field is not useful.\nIf duplicates DO exist and this field is not specified, the strain will be chosen by the first one created.", "nullable": true, "example": "123" }, "size": { "type": "string", "nullable": true }, "netWeight": { "type": "number", "format": "double", "nullable": true }, "netWeightUnit": { "type": "string", "description": "Optional. Abbreviation of the unit of the product's net weight.", "nullable": true }, "grossWeight": { "type": "number", "format": "double", "nullable": true }, "brandName": { "type": "string", "nullable": true }, "vendorName": { "type": "string", "nullable": true }, "isCannabis": { "type": "boolean" }, "isActive": { "type": "boolean" }, "thcContent": { "type": "number", "format": "double", "nullable": true }, "thcContentUnit": { "type": "string", "description": "mg; %; mg/g; n.d.", "nullable": true }, "cbdContent": { "type": "number", "format": "double", "nullable": true }, "cbdContentUnit": { "type": "string", "description": "mg; %; mg/g; n.d.", "nullable": true }, "productGrams": { "type": "number", "format": "double", "nullable": true }, "flowerEquivalent": { "type": "number", "format": "double", "nullable": true }, "recFlowerEquivalent": { "type": "number", "format": "double", "nullable": true }, "price": { "type": "number", "format": "double", "nullable": true }, "unitCost": { "type": "number", "format": "double", "nullable": true }, "unitType": { "type": "string", "nullable": true }, "onlineTitle": { "type": "string", "nullable": true }, "onlineDescription": { "type": "string", "nullable": true }, "onlineProduct": { "type": "boolean", "nullable": true }, "posProducts": { "type": "boolean", "nullable": true }, "tags": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true }, "defaultUnit": { "type": "string", "nullable": true }, "isMedicalOnly": { "type": "boolean", "nullable": true }, "isTaxable": { "type": "boolean", "nullable": true }, "regulatoryCategory": { "type": "string", "nullable": true }, "ndc": { "type": "string", "nullable": true }, "daysSupply": { "type": "number", "format": "double", "nullable": true }, "illinoisTaxCategory": { "type": "string", "nullable": true }, "externalCategory": { "type": "string", "nullable": true }, "externalId": { "$ref": "#/components/schemas/StringOptional" }, "syncExternally": { "type": "boolean", "nullable": true }, "bypassExternalUpdate": { "type": "boolean", "nullable": true }, "administrationMethod": { "$ref": "#/components/schemas/StringOptional" }, "unitCBDContentDose": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "unitTHCContentDose": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "oilVolume": { "$ref": "#/components/schemas/DecimalNullableOptional" }, "ingredientList": { "$ref": "#/components/schemas/StringOptional" }, "expirationDays": { "$ref": "#/components/schemas/Int32NullableOptional" }, "abbreviation": { "$ref": "#/components/schemas/StringOptional" }, "isTestProduct": { "$ref": "#/components/schemas/BooleanOptional" }, "isFinished": { "$ref": "#/components/schemas/BooleanOptional" }, "allowAutomaticDiscounts": { "$ref": "#/components/schemas/BooleanOptional" }, "servingSize": { "$ref": "#/components/schemas/StringOptional" }, "servingSizePerUnit": { "$ref": "#/components/schemas/Int32NullableOptional" }, "isNutrient": { "$ref": "#/components/schemas/BooleanOptional" }, "approvalDateUTC": { "$ref": "#/components/schemas/DateTimeNullableOptional" }, "customMetadata": { "$ref": "#/components/schemas/StringOptional" }, "taxCategories": { "type": "array", "items": { "type": "string" }, "description": "List of strings of tax categories that the product belongs to.", "nullable": true }, "pricingDetails": { "$ref": "#/components/schemas/PricingDetail" }, "userName": { "type": "string", "description": "UserName of the user making the product change\nThis will be used when authorizing with traceability systems (METRC/BioTrack) - if not included or NULL is specified, the traceability integration's \"master key\" will be used, if possible.\nThis field is only relevant if the request is setting SyncExternally to true", "nullable": true }, "instructions": { "type": "string", "nullable": true }, "upc": { "type": "string", "nullable": true }, "regulatoryName": { "$ref": "#/components/schemas/StringOptional" }, "broadcast": { "$ref": "#/components/schemas/BooleanOptional" } }, "additionalProperties": false, "description": "Product upload model for creating and updating products.\n\n⚠️ **DATA LOSS WARNING**: Most fields will be overwritten with null/zero if not provided.\n**RECOMMENDED**: Use GET /products first, modify needed fields, then POST the complete object." }, "ProductEffect": { "type": "object", "properties": { "effectId": { "type": "integer", "format": "int32" }, "effectName": { "type": "string", "nullable": true }, "productId": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, "ProductTag": { "type": "object", "properties": { "tagId": { "type": "integer", "format": "int32" }, "tagName": { "type": "string", "nullable": true }, "productId": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, "PublishedDiscount": { "type": "object", "properties": { "discountId": { "type": "integer", "description": "Unique identifier for the discount.", "format": "int32" }, "discountName": { "type": "string", "description": "Display name of the discount for customer-facing applications.", "nullable": true }, "discountAmount": { "type": "number", "description": "Monetary discount amount or percentage value.", "format": "double" }, "discountCode": { "type": "string", "description": "Promotional code required to apply the discount (optional).", "nullable": true }, "discountType": { "type": "string", "description": "Type classification of the discount (e.g., percentage, fixed amount).", "nullable": true }, "discountMethod": { "type": "string", "description": "Method used to apply the discount (e.g., automatic, code required).", "nullable": true }, "isActive": { "type": "boolean", "description": "Indicates if the discount is currently active and available." }, "validFrom": { "type": "string", "description": "Start date and time when discount becomes valid (UTC converted from Eastern Time).", "format": "date-time", "nullable": true }, "validUntil": { "type": "string", "description": "End date and time when discount expires (UTC converted from Eastern Time).", "format": "date-time", "nullable": true }, "thresholdType": { "type": "string", "description": "Type of threshold requirement for discount eligibility (optional).", "nullable": true }, "minimumItemsRequired": { "type": "number", "description": "Minimum number of qualifying items required for discount application (optional).", "format": "double", "nullable": true }, "maximumItemsAllowed": { "type": "number", "description": "Maximum number of items that can receive the discount (optional).", "format": "double", "nullable": true }, "maximumUsageCount": { "type": "number", "description": "Maximum number of times this discount can be used (optional).", "format": "double", "nullable": true }, "includeNonCannabis": { "type": "boolean", "description": "Indicates if discount applies to non-cannabis products." }, "firstTimeCustomerOnly": { "type": "boolean", "description": "Indicates if discount is restricted to first-time customers only." }, "stackOnOtherDiscounts": { "type": "boolean", "description": "Indicates if discount can be combined with other discounts." }, "weeklyRecurrenceInfo": { "$ref": "#/components/schemas/WeeklyRecurrenceInfo" }, "products": { "$ref": "#/components/schemas/DiscountRestriction" }, "productCategories": { "$ref": "#/components/schemas/DiscountRestriction" }, "brands": { "$ref": "#/components/schemas/DiscountRestriction" }, "vendors": { "$ref": "#/components/schemas/DiscountRestriction" }, "strains": { "$ref": "#/components/schemas/DiscountRestriction" }, "tiers": { "$ref": "#/components/schemas/DiscountRestriction" }, "tags": { "$ref": "#/components/schemas/DiscountRestriction" }, "inventoryTags": { "$ref": "#/components/schemas/DiscountRestriction" }, "customerTypes": { "$ref": "#/components/schemas/DiscountRestriction" }, "discountGroups": { "type": "array", "items": { "$ref": "#/components/schemas/DiscountGroup" }, "description": "Associated discount groups for bundling and organization (loaded conditionally).", "nullable": true } }, "additionalProperties": false, "description": "Published discount model containing complete discount configuration and constraint information for customer-facing applications." }, "PurchaseOrderData": { "type": "object", "properties": { "purchaseOrderId": { "type": "integer", "format": "int32" }, "expectedArrivalDate": { "type": "string", "format": "date-time", "nullable": true }, "title": { "type": "string", "nullable": true }, "dateReceived": { "type": "string", "format": "date-time", "nullable": true }, "dateSubmitted": { "type": "string", "format": "date-time", "nullable": true }, "shippingInformation": { "type": "string", "nullable": true }, "vendorId": { "type": "integer", "format": "int32" }, "vendorName": { "type": "string", "nullable": true }, "vendorContact": { "type": "string", "nullable": true }, "status": { "type": "string", "nullable": true }, "purchaseOrderNumber": { "type": "integer", "format": "int32" }, "createdByUser": { "type": "string", "nullable": true }, "dateCreated": { "type": "string", "format": "date-time", "nullable": true }, "purchaseOrderItems": { "type": "array", "items": { "$ref": "#/components/schemas/PurchaseOrderItemDetail" }, "nullable": true } }, "additionalProperties": false }, "PurchaseOrderItemDetail": { "type": "object", "properties": { "purchaseOrderId": { "type": "integer", "format": "int32" }, "purchaseOrderItemId": { "type": "integer", "format": "int32" }, "productId": { "type": "integer", "format": "int32" }, "productName": { "type": "string", "nullable": true }, "quantity": { "type": "integer", "format": "int32" }, "unitId": { "type": "integer", "format": "int32" }, "unitName": { "type": "string", "nullable": true }, "unitNameAbbreviation": { "type": "string", "nullable": true }, "subtotal": { "type": "number", "format": "double" }, "tax": { "type": "number", "format": "double" } }, "additionalProperties": false }, "ReceiveInventoryItemSave": { "required": ["productId", "quantity"], "type": "object", "properties": { "productId": { "type": "integer", "description": "Product identifier for the cannabis product being received into inventory (required).", "format": "int32" }, "quantity": { "type": "number", "description": "Quantity of the product being received into inventory (required).", "format": "double" }, "unitType": { "type": "string", "description": "Unit type for the received quantity (qty; ml; g; Gal; L; lb; mg; oz; fl oz; kg).", "nullable": true }, "flowerEquivalent": { "type": "number", "description": "Flower equivalent weight for regulatory compliance and limit calculations.", "format": "double", "nullable": true }, "recFlowerEquivalent": { "type": "number", "description": "Recreational flower equivalent weight for regulatory compliance tracking.", "format": "double", "nullable": true }, "vendorId": { "type": "integer", "description": "Vendor identifier for supply chain tracking and vendor management.", "format": "int32", "nullable": true }, "roomId": { "type": "integer", "description": "Room identifier for facility location assignment and space management.", "format": "int32", "nullable": true }, "packageId": { "type": "string", "description": "Package identifier from state tracking system for compliance documentation.", "nullable": true }, "lot": { "type": "string", "description": "Lot number for batch tracking and quality control management.", "nullable": true }, "cost": { "type": "number", "description": "Unit cost for inventory valuation and cost accounting.", "format": "double", "nullable": true }, "price": { "type": "number", "description": "General retail price for the received inventory item.", "format": "double", "nullable": true }, "recPrice": { "type": "number", "description": "Recreational market price for dual-license operations.", "format": "double", "nullable": true }, "tax": { "type": "number", "description": "Tax amount for financial compliance and tax reporting.", "format": "double", "nullable": true }, "expirationDate": { "type": "string", "description": "Product expiration date for inventory rotation and compliance management.", "format": "date-time", "nullable": true }, "tags": { "type": "array", "items": { "type": "integer", "format": "int32" }, "description": "Collection of tag identifiers for product categorization and organization.", "nullable": true }, "cultivationTax": { "type": "number", "description": "Cultivation tax amount for cannabis-specific tax compliance.", "format": "double", "nullable": true }, "tableId": { "type": "integer", "description": "Table identifier within the room for precise location tracking.", "format": "int32", "nullable": true }, "sourceAllocatedInventoryId": { "type": "integer", "description": "Source allocated inventory identifier for traceability and audit trails.", "format": "int32", "nullable": true }, "totalPackageCost": { "type": "number", "description": "Total package cost for comprehensive cost allocation and accounting.", "format": "double", "nullable": true }, "getMetrcLabResults": { "type": "boolean", "description": "Flag to retrieve lab results from Metrc for compliance integration.", "nullable": true }, "productName": { "type": "string", "description": "Product name for inventory identification and display purposes.", "nullable": true }, "packagingDate": { "type": "string", "description": "Date when the product was packaged for shelf life tracking.", "format": "date-time", "nullable": true }, "manufacturingDate": { "type": "string", "description": "Date when the product was manufactured for quality control tracking.", "format": "date-time", "nullable": true }, "producerId": { "type": "integer", "description": "Producer identifier for supply chain tracking and compliance documentation.", "format": "int32", "nullable": true }, "externalPackageId": { "type": "string", "description": "External package identifier for cross-system integration and tracking.", "nullable": true }, "potencyIndicator": { "type": "string", "description": "Potency indicator for product strength classification and customer information.", "nullable": true } }, "additionalProperties": false, "description": "Request model for receiving and recording new cannabis inventory items into the facility management system." }, "ReceiveInventorySave": { "required": ["deliveredOn"], "type": "object", "properties": { "vendorId": { "type": "integer", "description": "Vendor identifier for the supplier (optional, can be resolved from VendorLicense).", "format": "int32", "nullable": true }, "deliveredBy": { "type": "string", "description": "Name of the person who delivered the inventory shipment.", "nullable": true }, "deliveredOn": { "type": "string", "description": "Date and time when the inventory was delivered (required).", "format": "date-time" }, "vendorLicense": { "type": "string", "description": "Vendor license code for compliance tracking and vendor identification.", "nullable": true }, "transactionId": { "type": "string", "description": "External transaction reference ID for tracking and reconciliation.", "nullable": true }, "orderTitle": { "type": "string", "description": "Descriptive title for the receive order for identification purposes.", "nullable": true }, "externalId": { "type": "string", "description": "External system ID for preventing duplicate receives (must be unique).", "nullable": true }, "note": { "type": "string", "description": "Additional notes or comments about the receive transaction.", "nullable": true }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/ReceiveInventoryItemSave" }, "description": "Collection of inventory items being received in this transaction.", "nullable": true }, "receiveIntoInventory": { "type": "boolean", "description": "Indicates whether to immediately process items into inventory (true) or save as draft (false).", "nullable": true }, "userId": { "type": "integer", "description": "User ID for processing the receive (required when ReceiveIntoInventory=true).", "format": "int32", "nullable": true }, "userName": { "type": "string", "description": "Username for processing the receive (alternative to UserId, required when ReceiveIntoInventory=true).", "nullable": true } }, "additionalProperties": false, "description": "Request model for creating inventory receive orders for incoming transfers, purchase orders, or direct inventory additions." }, "ReceivedInventory": { "type": "object", "properties": { "receiveInventoryHistoryId": { "type": "integer", "description": "Unique identifier for the receive inventory transaction.", "format": "int32" }, "title": { "type": "string", "description": "Descriptive title for the receive order for identification purposes.", "nullable": true }, "status": { "type": "string", "description": "Current processing status of the receive order (e.g., \"Pending\", \"Completed\", \"Failed\").", "nullable": true }, "failureMessage": { "type": "string", "description": "Error message if the receive order failed processing (optional).", "nullable": true }, "deliveredOn": { "type": "string", "description": "Date and time when the inventory was delivered by the vendor (optional).", "format": "date-time", "nullable": true }, "addedOn": { "type": "string", "description": "Date and time when the receive order was created in the system (optional).", "format": "date-time", "nullable": true }, "vendor": { "type": "string", "description": "Name of the vendor who supplied the inventory.", "nullable": true }, "vendorLicense": { "type": "string", "description": "Vendor license code for compliance tracking and verification.", "nullable": true }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/ReceivedInventoryItem" }, "description": "Collection of inventory items included in this receive order.", "nullable": true } }, "additionalProperties": false, "description": "Received inventory record model representing completed or pending inventory receive orders and their processing status." }, "ReceivedInventoryItem": { "type": "object", "properties": { "product": { "type": "string", "description": "Product name for inventory item identification and display.", "nullable": true }, "sku": { "type": "string", "description": "Stock Keeping Unit (SKU) for product identification and retail operations.", "nullable": true }, "productId": { "type": "integer", "description": "Product identifier for database references and system integration.", "format": "int32", "nullable": true }, "type": { "type": "string", "description": "Product type classification for cannabis product categorization.", "nullable": true }, "quantity": { "type": "number", "description": "Quantity of the received inventory item for stock tracking.", "format": "double" }, "unitAbbreviation": { "type": "string", "description": "Unit abbreviation for quantity measurement display (e.g., \"g\", \"oz\", \"ml\").", "nullable": true }, "unit": { "type": "string", "description": "Full unit name for quantity measurement (e.g., \"grams\", \"ounces\", \"milliliters\").", "nullable": true }, "unitCost": { "type": "number", "description": "Cost per unit for inventory valuation and financial accounting.", "format": "double" }, "unitTax": { "type": "number", "description": "Tax amount per unit for cannabis tax compliance and reporting.", "format": "double" }, "totalCost": { "type": "number", "description": "Total cost for the received inventory item including all taxes and fees.", "format": "double" }, "packageId": { "type": "string", "description": "Package identifier from state tracking system for compliance documentation.", "nullable": true }, "externalPackageId": { "type": "string", "description": "External package identifier for cross-system tracking and integration.", "nullable": true }, "batchName": { "type": "string", "description": "Batch name for lot tracking and quality control management.", "nullable": true }, "batchId": { "type": "integer", "description": "Batch identifier for database references and batch tracking.", "format": "int32", "nullable": true }, "room": { "type": "string", "description": "Room name for facility location identification and display.", "nullable": true }, "roomId": { "type": "integer", "description": "Room identifier for database references and location tracking.", "format": "int32", "nullable": true } }, "additionalProperties": false, "description": "Response model representing received cannabis inventory items with complete tracking and financial information." }, "RegisterAdjustment": { "type": "object", "properties": { "adjustmentId": { "type": "integer", "description": "Unique identifier for the register adjustment transaction.\nPrimary key for tracking and referencing specific adjustment records.", "format": "int32" }, "adjustmentType": { "type": "string", "description": "Type of register adjustment being performed.\nCommon values include \"Adjustment\", \"Close Out\", \"Deposit\", \"Withdrawal\", \"Cash Drop\".", "nullable": true }, "adjustmentAmount": { "type": "number", "description": "Dollar amount of the register adjustment (positive or negative).\nPositive values indicate cash added to register, negative values indicate cash removed.", "format": "double" }, "adjustedBy": { "type": "string", "description": "Name of the employee who performed the register adjustment.\nUsed for accountability and audit trail purposes.", "nullable": true }, "adjustedOn": { "type": "string", "description": "Date and time when the register adjustment was performed (optional).\nTimestamp for audit trail and reconciliation purposes.", "format": "date-time", "nullable": true }, "terminalName": { "type": "string", "description": "Name of the register/terminal where the adjustment occurred.\nIdentifies which physical register or point-of-sale terminal was adjusted.", "nullable": true }, "terminalId": { "type": "integer", "description": "Unique identifier for the register/terminal where the adjustment occurred.\nNumeric identifier for the specific point-of-sale terminal.", "format": "int32" }, "adjustedByEmployeeId": { "type": "integer", "description": "Employee ID of the staff member who performed the adjustment.\nNumeric identifier linking to the employee record for accountability.", "format": "int32" }, "adjustmentReason": { "type": "string", "description": "Reason code or description for why the adjustment was made.\nProvides business justification for the cash adjustment.", "nullable": true }, "comment": { "type": "string", "description": "Additional comments or notes about the register adjustment (optional).\nFree-text field for additional details or explanations.", "nullable": true } }, "additionalProperties": false, "description": "Represents a register cash adjustment transaction record for financial reconciliation and audit trails.\n\nRegister adjustments include manual cash corrections, deposits, withdrawals, close-outs, and other\ncash management activities that affect register balances. Each adjustment maintains a complete\naudit trail with employee accountability and reason tracking." }, "RegisterCashSummary": { "type": "object", "properties": { "terminalName": { "type": "string", "description": "Name of the register/terminal for which this cash summary applies.\nIdentifies the specific point-of-sale terminal or register location.", "nullable": true }, "startingBalance": { "type": "number", "description": "Starting cash balance for the register at the beginning of the period.\nBase amount of cash in the register before any transactions occurred.", "format": "double" }, "endingBalance": { "type": "number", "description": "Ending cash balance for the register at the end of the period.\nFinal amount of cash in the register after all transactions and adjustments.", "format": "double" }, "sales": { "type": "number", "description": "Total cash sales processed through the register during the period.\nIncludes all cash payments received for customer transactions.", "format": "double" }, "returns": { "type": "number", "description": "Total cash refunds and returns processed during the period.\nRepresents cash paid out to customers for returned merchandise.", "format": "double" }, "deposits": { "type": "number", "description": "Total cash deposits added to the register during the period.\nIncludes cash added to the register for operational purposes.", "format": "double" }, "adjustments": { "type": "number", "description": "Total register adjustments (positive or negative) made during the period.\nIncludes manual cash corrections, withdrawals, and balancing entries.", "format": "double" }, "overShort": { "type": "number", "description": "Cash variance (over or short) compared to expected register balance.\nPositive values indicate cash overage, negative values indicate shortage.", "format": "double" } }, "additionalProperties": false, "description": "Represents a comprehensive cash flow summary for a specific register terminal.\n\nThis model provides real-time cash reconciliation data including starting balances,\ntransaction activity, and variance calculations for cash management and balancing\npurposes. Used for end-of-shift reconciliation and cash discrepancy identification." }, "RegisterTransaction": { "type": "object", "properties": { "registerTransactionId": { "type": "integer", "description": "Unique identifier for the register transaction record.\nPrimary key for tracking and referencing specific transaction activities.", "format": "int32" }, "transactionType": { "type": "string", "description": "Type of register transaction being recorded.\nExamples include \"Sale\", \"Adjustment\", \"Close Out\", \"Deposit\", \"Withdrawal\", \"Return\", \"Payment\".", "nullable": true }, "transactionAmount": { "type": "number", "description": "Dollar amount of the register transaction (positive or negative).\nRepresents the financial impact of the transaction on register balances.", "format": "double" }, "transactionBy": { "type": "string", "description": "Name of the employee who processed the register transaction.\nUsed for accountability and performance tracking.", "nullable": true }, "transactionDateUTC": { "type": "string", "description": "Date and time when the register transaction occurred in UTC (optional).\nTimestamp for audit trail and financial reconciliation purposes.", "format": "date-time", "nullable": true }, "transactionId": { "type": "integer", "description": "Reference to the associated business transaction ID (optional).\nLinks register activity to customer sales transactions when applicable.", "format": "int32", "nullable": true }, "terminalName": { "type": "string", "description": "Name of the register/terminal where the transaction was processed.\nIdentifies which physical register or point-of-sale terminal handled the transaction.", "nullable": true }, "terminalId": { "type": "integer", "description": "Unique identifier for the register/terminal where the transaction occurred.\nNumeric identifier for the specific point-of-sale terminal.", "format": "int32" }, "transactionByEmployeeId": { "type": "integer", "description": "Employee ID of the staff member who processed the transaction.\nNumeric identifier linking to the employee record for accountability tracking.", "format": "int32" }, "adjustmentReason": { "type": "string", "description": "Reason code or description for adjustment transactions (optional).\nProvides business justification when the transaction is an adjustment or correction.", "nullable": true }, "comment": { "type": "string", "description": "Additional comments or notes about the register transaction (optional).\nFree-text field for additional context or explanations.", "nullable": true } }, "additionalProperties": false, "description": "Represents a comprehensive register transaction record including sales, adjustments, and cash management activities.\n\nThis model encompasses all types of register activity including customer sales transactions, cash adjustments,\npayment processing, register maintenance, and operational activities. Each transaction maintains complete\naudit trails with employee accountability and detailed financial information." }, "RegulatoryCategory": { "type": "object", "properties": { "regulatoryCategoryId": { "type": "integer", "description": "Unique identifier for the regulatory category.", "format": "int32" }, "regulatoryCategoryName": { "type": "string", "description": "Display name of the regulatory category as defined by state cannabis regulations.", "nullable": true } }, "additionalProperties": false, "description": "Regulatory category model containing state-mandated product classification information for cannabis compliance and reporting." }, "ReportingDiscountDetail": { "type": "object", "properties": { "isAvailableOnline": { "type": "boolean", "description": "Indicates if discount is available for online/e-commerce ordering." }, "applicationMethod": { "type": "string", "description": "Method used to apply the discount in the system.", "nullable": true }, "externalId": { "type": "string", "description": "External system identifier for integration mapping.", "nullable": true }, "requireManagerApproval": { "type": "boolean", "description": "Indicates if discount application requires manager approval." }, "isDeleted": { "type": "boolean", "description": "Indicates if discount has been marked as deleted." }, "appliesToLocations": { "type": "array", "items": { "$ref": "#/components/schemas/LocationMapping" }, "description": "Collection of location mappings where this discount applies.", "nullable": true }, "discountId": { "type": "integer", "description": "Unique identifier for the discount.", "format": "int32" }, "discountName": { "type": "string", "description": "Display name of the discount for customer-facing applications.", "nullable": true }, "discountAmount": { "type": "number", "description": "Monetary discount amount or percentage value.", "format": "double" }, "discountCode": { "type": "string", "description": "Promotional code required to apply the discount (optional).", "nullable": true }, "discountType": { "type": "string", "description": "Type classification of the discount (e.g., percentage, fixed amount).", "nullable": true }, "discountMethod": { "type": "string", "description": "Method used to apply the discount (e.g., automatic, code required).", "nullable": true }, "isActive": { "type": "boolean", "description": "Indicates if the discount is currently active and available." }, "validFrom": { "type": "string", "description": "Start date and time when discount becomes valid (UTC converted from Eastern Time).", "format": "date-time", "nullable": true }, "validUntil": { "type": "string", "description": "End date and time when discount expires (UTC converted from Eastern Time).", "format": "date-time", "nullable": true }, "thresholdType": { "type": "string", "description": "Type of threshold requirement for discount eligibility (optional).", "nullable": true }, "minimumItemsRequired": { "type": "number", "description": "Minimum number of qualifying items required for discount application (optional).", "format": "double", "nullable": true }, "maximumItemsAllowed": { "type": "number", "description": "Maximum number of items that can receive the discount (optional).", "format": "double", "nullable": true }, "maximumUsageCount": { "type": "number", "description": "Maximum number of times this discount can be used (optional).", "format": "double", "nullable": true }, "includeNonCannabis": { "type": "boolean", "description": "Indicates if discount applies to non-cannabis products." }, "firstTimeCustomerOnly": { "type": "boolean", "description": "Indicates if discount is restricted to first-time customers only." }, "stackOnOtherDiscounts": { "type": "boolean", "description": "Indicates if discount can be combined with other discounts." }, "weeklyRecurrenceInfo": { "$ref": "#/components/schemas/WeeklyRecurrenceInfo" }, "products": { "$ref": "#/components/schemas/DiscountRestriction" }, "productCategories": { "$ref": "#/components/schemas/DiscountRestriction" }, "brands": { "$ref": "#/components/schemas/DiscountRestriction" }, "vendors": { "$ref": "#/components/schemas/DiscountRestriction" }, "strains": { "$ref": "#/components/schemas/DiscountRestriction" }, "tiers": { "$ref": "#/components/schemas/DiscountRestriction" }, "tags": { "$ref": "#/components/schemas/DiscountRestriction" }, "inventoryTags": { "$ref": "#/components/schemas/DiscountRestriction" }, "customerTypes": { "$ref": "#/components/schemas/DiscountRestriction" }, "discountGroups": { "type": "array", "items": { "$ref": "#/components/schemas/DiscountGroup" }, "description": "Associated discount groups for bundling and organization (loaded conditionally).", "nullable": true } }, "additionalProperties": false, "description": "Extended discount model with additional reporting and administrative properties for internal operations." }, "ReportingInventoryItem": { "type": "object", "properties": { "unitWeightUnit": { "type": "string", "description": "Unit of measurement for unit weight, always \"g\" (grams).", "nullable": true }, "unitCost": { "type": "number", "description": "Unit cost of the inventory item for cost of goods sold calculations (in USD).", "format": "double", "nullable": true }, "allocatedQuantity": { "type": "number", "description": "Quantity of inventory allocated to orders or transfers but not yet fulfilled.", "format": "double", "nullable": true }, "inventoryId": { "type": "integer", "description": "Unique inventory record identifier for this specific inventory item.", "format": "int32" }, "productId": { "type": "integer", "description": "Product identifier linking this inventory to the product catalog.", "format": "int32" }, "sku": { "type": "string", "description": "Stock Keeping Unit (SKU) code for inventory tracking and identification.", "nullable": true }, "productName": { "type": "string", "description": "Display name of the product for customer-facing applications.", "nullable": true }, "description": { "type": "string", "description": "Detailed product description including effects, characteristics, and usage information.", "nullable": true }, "categoryId": { "type": "integer", "description": "Category identifier for product classification (optional).", "format": "int32", "nullable": true }, "category": { "type": "string", "description": "Category name for product classification and filtering.", "nullable": true }, "imageUrl": { "type": "string", "description": "URL path to product image for display purposes.", "nullable": true }, "quantityAvailable": { "type": "number", "description": "Current available quantity for sale or transfer.", "format": "double" }, "quantityUnits": { "type": "string", "description": "Unit of measurement for the available quantity (e.g., \"g\", \"mg\", \"ea\").", "nullable": true }, "unitWeight": { "type": "number", "description": "Weight per unit in grams for dosing and compliance calculations.", "format": "double" }, "flowerEquivalent": { "type": "number", "description": "Flower equivalent amount in grams for compliance tracking.", "format": "double" }, "recFlowerEquivalent": { "type": "number", "description": "Recreational flower equivalent amount in grams (optional).", "format": "double", "nullable": true }, "flowerEquivalentUnits": { "type": "string", "description": "Unit of measurement for flower equivalent, always \"g\" (grams).", "nullable": true, "readOnly": true }, "batchId": { "type": "integer", "description": "Batch identifier for lot tracking and quality control.", "format": "int32" }, "batchName": { "type": "string", "description": "Human-readable batch name or lot number for tracking.", "nullable": true }, "packageId": { "type": "string", "description": "Package identifier for compliance tracking and traceability.", "nullable": true }, "packageStatus": { "type": "string", "description": "Current status of the package (e.g., \"Active\", \"Testing\", \"Quarantine\").", "nullable": true }, "unitPrice": { "type": "number", "description": "Base unit price for retail sales.", "format": "double" }, "medUnitPrice": { "type": "number", "description": "Medical program pricing (optional, different from retail).", "format": "double", "nullable": true }, "recUnitPrice": { "type": "number", "description": "Recreational program pricing (optional, different from medical).", "format": "double", "nullable": true }, "strainId": { "type": "integer", "description": "Strain identifier for cannabis products (optional).", "format": "int32", "nullable": true }, "strain": { "type": "string", "description": "Strain name for cannabis products.", "nullable": true }, "strainType": { "type": "string", "description": "Cannabis strain classification (Hybrid, Indica, Sativa, CBD).", "nullable": true }, "size": { "type": "string", "description": "Product size designation for packaging and dosing information.", "nullable": true }, "labResults": { "type": "array", "items": { "$ref": "#/components/schemas/LabResult" }, "description": "Collection of laboratory test results for this batch (included when includeLabResults=true).", "nullable": true }, "testedDate": { "type": "string", "description": "Date when laboratory testing was completed (optional).", "format": "date-time", "nullable": true }, "sampleDate": { "type": "string", "description": "Date when sample was collected for laboratory testing (optional).", "format": "date-time", "nullable": true }, "packagedDate": { "type": "string", "description": "Date when product was packaged for distribution (optional).", "format": "date-time", "nullable": true }, "manufacturingDate": { "type": "string", "description": "Date when product was manufactured or produced (optional).", "format": "date-time", "nullable": true }, "lastModifiedDateUtc": { "type": "string", "description": "Last modification timestamp in UTC for data synchronization.", "format": "date-time", "nullable": true }, "labTestStatus": { "type": "string", "description": "Current status of laboratory testing (e.g., \"Passed\", \"Failed\", \"Pending\").", "nullable": true }, "vendorId": { "type": "integer", "description": "Vendor identifier for the supplier of this inventory (optional).", "format": "int32", "nullable": true }, "vendor": { "type": "string", "description": "Vendor name for the supplier of this inventory.", "nullable": true }, "expirationDate": { "type": "string", "description": "Product expiration date for compliance and quality control (optional).", "format": "date-time", "nullable": true }, "roomQuantities": { "type": "array", "items": { "$ref": "#/components/schemas/InventoryRoomQuantity" }, "description": "Quantity breakdown by storage room/location (included when includeRoomQuantities=true).", "nullable": true }, "pricingTierName": { "type": "string", "description": "Pricing tier classification for bulk pricing strategies.", "nullable": true }, "alternateName": { "type": "string", "description": "Alternative product name for display purposes.", "nullable": true }, "tags": { "type": "array", "items": { "$ref": "#/components/schemas/InventoryTag" }, "description": "Collection of compliance tags associated with this inventory package.", "nullable": true }, "brandId": { "type": "integer", "description": "Brand identifier for branded products (optional).", "format": "int32", "nullable": true }, "brandName": { "type": "string", "description": "Brand name for branded products.", "nullable": true }, "medicalOnly": { "type": "boolean", "description": "Indicates if product is restricted to medical program only." }, "externalPackageId": { "type": "string", "description": "External compliance system ID (METRC or BioTrack) for regulatory tracking.", "nullable": true }, "producer": { "type": "string", "description": "Producer name for cultivation and manufacturing tracking.", "nullable": true }, "producerId": { "type": "integer", "description": "Producer identifier for cultivation and manufacturing tracking (optional).", "format": "int32", "nullable": true }, "lineage": { "type": "array", "items": { "$ref": "#/components/schemas/PackageLineage" }, "description": "Package lineage information for traceability and compliance tracking.", "nullable": true }, "potencyIndicator": { "type": "string", "description": "Potency classification indicator for dosing guidance.", "nullable": true }, "masterCategory": { "type": "string", "description": "Master category classification for product grouping.", "nullable": true }, "effectivePotencyMg": { "type": "number", "description": "Effective potency in milligrams for dosing calculations (optional).", "format": "double", "nullable": true }, "isCannabis": { "type": "boolean", "description": "Indicates if product contains cannabis or is cannabis-related." }, "packageNDC": { "type": "string", "description": "National Drug Code for pharmaceutical tracking (optional).", "nullable": true }, "labResultUrl": { "type": "string", "description": "URL to certificate of analysis or lab testing document.", "nullable": true } }, "additionalProperties": false, "description": "Extended inventory item model for financial reporting with cost and allocation data." }, "RetagPlantRequest": { "type": "object", "properties": { "plantId": { "type": "integer", "description": "Plant identifier for the cannabis plant being retagged with a new serial number.", "format": "int32" }, "serialNumber": { "type": "string", "description": "New serial number for the plant identification tag replacement.", "nullable": true } }, "additionalProperties": false, "description": "Request model for retagging cannabis plants with new serial numbers for compliance and tracking updates." }, "RetireImmaturePlantsDetails": { "type": "object", "properties": { "batchId": { "type": "integer", "description": "Batch identifier for the plant batch containing plants to be retired.", "format": "int32" }, "countToRetire": { "type": "integer", "description": "Number of plants to retire from the specified batch.", "format": "int32" }, "reasonCode": { "type": "string", "description": "Standardized reason code for the plant retirement (e.g., \"DISEASE\", \"PEST\", \"POOR_HEALTH\", \"CONTAMINATION\").", "nullable": true }, "retireDate": { "type": "string", "description": "Date when the plants were retired for cultivation timeline documentation.", "format": "date-time", "nullable": true } }, "additionalProperties": false, "description": "Detailed specification for retiring immature plants from cultivation batches with compliance documentation." }, "RetireImmaturePlantsRequest": { "type": "object", "properties": { "plants": { "type": "array", "items": { "$ref": "#/components/schemas/RetireImmaturePlantsDetails" }, "description": "Collection of plant retirement specifications for batch processing of plant removals.", "nullable": true } }, "additionalProperties": false, "description": "Request model for retiring immature cannabis plants due to loss, contamination, or quality issues." }, "RetirePlantRequest": { "type": "object", "properties": { "plantIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true }, "reasonId": { "type": "integer", "format": "int32", "nullable": true }, "reasonCode": { "type": "string", "nullable": true }, "wasteType": { "type": "string", "nullable": true }, "roomId": { "type": "integer", "format": "int32" }, "wasteWeight": { "type": "number", "format": "double", "nullable": true }, "comment": { "type": "string", "nullable": true }, "wastePackageId": { "type": "string", "nullable": true }, "wasteDate": { "type": "string", "format": "date-time", "nullable": true }, "plantWeight": { "type": "number", "format": "double", "nullable": true }, "plantWeightUnitId": { "type": "integer", "format": "int32", "nullable": true }, "wasteMaterial": { "type": "string", "nullable": true }, "wasteReason": { "type": "string", "nullable": true }, "wasteMethod": { "type": "string", "nullable": true }, "reasonNote": { "type": "string", "nullable": true }, "emptyCloneGroup": { "type": "boolean" } }, "additionalProperties": false }, "Room": { "type": "object", "properties": { "roomId": { "type": "integer", "description": "Unique identifier for the cultivation room or facility area.\n**Required for updates, null/0 for new room creation.**", "format": "int32", "nullable": true }, "roomName": { "type": "string", "description": "Human-readable name for room identification and cultivation tracking.\n**Required for both create and update operations.**", "nullable": true }, "isQuarantineRoom": { "type": "boolean", "description": "Indicates if this room is designated for quarantine operations and compliance isolation." }, "isVaultRoom": { "type": "boolean", "description": "Indicates if this room is designated as a secure vault for valuable inventory storage." }, "isWaitingRoom": { "type": "boolean", "description": "Indicates if this room is designated as a customer waiting area." }, "isSalesFloor": { "type": "boolean", "description": "Indicates if this room is designated as the main sales floor for customer transactions." }, "isPOSRoom": { "type": "boolean", "description": "Indicates if this room is designated for point-of-sale operations and transactions." }, "isInventoryRoom": { "type": "boolean", "description": "Indicates if this room is designated for inventory storage and management." }, "isPreOrderRoom": { "type": "boolean", "description": "Indicates if this room is designated for pre-order fulfillment operations." }, "isEcommerceRoom": { "type": "boolean", "description": "Indicates if this room is designated for e-commerce order processing and fulfillment." } }, "additionalProperties": false, "description": "Cultivation room model containing facility area configuration information for cannabis operations and facility management." }, "RoomWaste": { "type": "object", "properties": { "wasteId": { "type": "integer", "description": "Unique identifier for the waste record.", "format": "int32", "nullable": true }, "referenceNo": { "type": "string", "description": "Reference number for waste tracking and documentation.", "nullable": true }, "comments": { "type": "string", "description": "Additional comments or notes about the waste disposal.", "nullable": true }, "wasteDate": { "type": "string", "description": "Date when the waste disposal occurred.", "format": "date-time", "nullable": true }, "wasteType": { "type": "string", "description": "Type or category of waste material being disposed.", "nullable": true }, "roomId": { "type": "integer", "description": "Identifier for the room or facility area where waste originated.", "format": "int32" }, "wasteAmount": { "type": "number", "description": "Quantity of waste material being disposed.", "format": "double" }, "unitId": { "type": "integer", "description": "Unit of measurement identifier for the waste amount.", "format": "int32" } }, "additionalProperties": false, "description": "Room-based waste record model for facility waste disposal tracking and compliance documentation." }, "SavedReceive": { "type": "object", "properties": { "receiveInventoryHistoryId": { "type": "integer", "description": "Unique identifier for the created receive inventory transaction.", "format": "int32" } }, "additionalProperties": false, "description": "Response model for successful inventory receive order creation operations." }, "SetImageRequest": { "required": ["base64Image", "fileName", "productId"], "type": "object", "properties": { "productId": { "type": "integer", "description": "The unique identifier of the product to associate the image with.", "format": "int32" }, "base64Image": { "minLength": 1, "type": "string", "description": "Base64-encoded string representation of the image file data." }, "fileName": { "minLength": 1, "type": "string", "description": "Original filename of the image including file extension for proper handling." }, "image": { "type": "string", "description": "Computed property that converts the Base64Image string to byte array for processing.", "format": "byte", "nullable": true, "readOnly": true }, "fileType": { "$ref": "#/components/schemas/UploadFileType" } }, "additionalProperties": false, "description": "Request model for setting a product image through the product image management API." }, "SetImageResponse": { "type": "object", "properties": { "imageId": { "type": "integer", "description": "Unique identifier assigned to the uploaded image for tracking and reference.", "format": "int32" }, "imageUrl": { "type": "string", "description": "Public URL where the uploaded image can be accessed and displayed.", "nullable": true } }, "additionalProperties": false, "description": "Response model for successful product image upload operations." }, "Severity": { "enum": [0, 1, 2], "type": "integer", "format": "int32" }, "Size": { "type": "object", "properties": { "sizeId": { "type": "integer", "description": "Unique identifier for the product size configuration.", "format": "int32" }, "sizeName": { "type": "string", "description": "Display name for the product size.", "nullable": true }, "description": { "type": "string", "description": "Detailed description of the product size and its usage.", "nullable": true } }, "additionalProperties": false, "description": "Represents a product size configuration for cannabis products within an organization." }, "SplitBatchDetails": { "type": "object", "properties": { "newBatchName": { "type": "string", "nullable": true }, "batchId": { "type": "integer", "format": "int32" }, "location": { "type": "string", "nullable": true }, "strain": { "type": "string", "nullable": true }, "quantity": { "type": "integer", "format": "int32" }, "splitDate": { "type": "string", "format": "date-time", "nullable": true } }, "additionalProperties": false }, "SplitImmaturePlantResult": { "type": "object", "properties": { "batch": { "type": "array", "items": { "$ref": "#/components/schemas/SplitImmaturePlantResultDetail" }, "nullable": true }, "plant": { "type": "array", "items": { "$ref": "#/components/schemas/SplitImmaturePlantResultDetail" }, "nullable": true } }, "additionalProperties": false }, "SplitImmaturePlantResultApiResult": { "type": "object", "properties": { "result": { "type": "boolean" }, "message": { "type": "string", "nullable": true }, "data": { "$ref": "#/components/schemas/SplitImmaturePlantResult" } }, "additionalProperties": false }, "SplitImmaturePlantResultDetail": { "type": "object", "properties": { "batchId": { "type": "integer", "format": "int32" }, "batchPlantCount": { "type": "integer", "format": "int32" }, "newBatchId": { "type": "integer", "format": "int32" }, "newBatchPlantCount": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, "SplitImmaturePlantsRequest": { "type": "object", "properties": { "batch": { "type": "array", "items": { "$ref": "#/components/schemas/SplitBatchDetails" }, "description": "Collection of batch split specifications for dividing immature plant batches into smaller groups.", "nullable": true }, "plant": { "type": "array", "items": { "$ref": "#/components/schemas/SplitPlantDetails" }, "description": "Collection of individual plant split specifications for precise cultivation management.", "nullable": true } }, "additionalProperties": false, "description": "Request model for splitting immature cannabis plant batches and individual plants for cultivation optimization." }, "SplitPlantDetails": { "type": "object", "properties": { "batchId": { "type": "integer", "format": "int32" }, "location": { "type": "string", "nullable": true }, "strain": { "type": "string", "nullable": true }, "quantity": { "type": "integer", "format": "int32" }, "splitDate": { "type": "string", "format": "date-time", "nullable": true } }, "additionalProperties": false }, "StandardAllergensDetails": { "type": "object", "properties": { "milk": { "type": "boolean" }, "eggs": { "type": "boolean" }, "fish": { "type": "boolean" }, "peanuts": { "type": "boolean" }, "treeNuts": { "type": "boolean" }, "sesame": { "type": "boolean" }, "shellfish": { "type": "boolean" }, "soybeans": { "type": "boolean" }, "wheat": { "type": "boolean" } }, "additionalProperties": false }, "StrainDetail": { "type": "object", "properties": { "strainId": { "type": "integer", "description": "Unique identifier for the strain", "format": "int32" }, "strainName": { "type": "string", "description": "Name of the cannabis strain", "nullable": true }, "strainDescription": { "type": "string", "description": "Detailed description of the strain's characteristics and effects", "nullable": true }, "strainAbbreviation": { "type": "string", "description": "Short name or code for the strain", "nullable": true }, "strainType": { "type": "string", "description": "Classification type of the strain. Valid values: `Indica`, `Sativa`, `Hybrid`, `CBD`", "nullable": true }, "externalId": { "type": "string", "description": "External system identifier for third-party integration", "nullable": true } }, "additionalProperties": false, "description": "Cannabis strain information with genetic and classification details for product categorization and cultivation tracking." }, "StringIEnumerableOptional": { "type": "array", "additionalProperties": false }, "StringOptional": { "type": "string", "additionalProperties": false }, "SuccessResult": { "type": "object", "properties": { "result": { "type": "boolean" }, "message": { "type": "string", "nullable": true }, "data": { "type": "object", "nullable": true } }, "additionalProperties": false }, "Table": { "type": "object", "properties": { "tableId": { "type": "integer", "format": "int32", "nullable": true }, "tableName": { "type": "string", "nullable": true } }, "additionalProperties": false }, "Tag": { "type": "object", "properties": { "tagName": { "type": "string", "nullable": true }, "tagId": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, "TaxSummaryInfo": { "type": "object", "properties": { "rateName": { "type": "string", "description": "Name of the tax type being summarized (e.g., \"State Excise Tax\", \"Sales Tax\").", "nullable": true }, "amount": { "type": "number", "description": "Total tax amount for this tax type across all transaction items (in USD).", "format": "double" } }, "additionalProperties": false, "description": "Summary tax information aggregated across transaction items for reporting and receipt generation." }, "Terminal": { "type": "object", "properties": { "terminalId": { "type": "integer", "description": "Unique identifier for the point-of-sale terminal.", "format": "int32" }, "terminalName": { "type": "string", "description": "Human-readable name for terminal identification and assignment.", "nullable": true } }, "additionalProperties": false, "description": "Point-of-sale terminal model containing terminal identification information for retail operations and transaction processing." }, "Transaction": { "type": "object", "properties": { "transactionId": { "type": "integer", "format": "int32" }, "customerId": { "type": "integer", "format": "int32" }, "employeeId": { "type": "integer", "format": "int32" }, "transactionDate": { "type": "string", "format": "date-time" }, "voidDate": { "type": "string", "format": "date-time", "nullable": true }, "isVoid": { "type": "boolean" }, "subtotal": { "type": "number", "format": "double" }, "totalDiscount": { "type": "number", "format": "double" }, "totalBeforeTax": { "type": "number", "format": "double", "readOnly": true }, "tax": { "type": "number", "format": "double" }, "tipAmount": { "type": "number", "format": "double", "nullable": true }, "total": { "type": "number", "format": "double" }, "paid": { "type": "number", "format": "double" }, "changeDue": { "type": "number", "format": "double" }, "totalItems": { "type": "integer", "format": "int32" }, "terminalName": { "type": "string", "nullable": true }, "checkInDate": { "type": "string", "format": "date-time", "nullable": true }, "invoiceNumber": { "type": "string", "nullable": true }, "isTaxInclusive": { "type": "boolean" }, "transactionType": { "type": "string", "description": "Will have one of the following values: Retail, Transfer, WholesaleOrder", "nullable": true }, "loyaltyEarned": { "type": "number", "description": "Loyalty points earned on this transaction (can be negative if it's a return)", "format": "double", "nullable": true }, "loyaltySpent": { "type": "number", "description": "Loyalty points spent on this transaction (can be negative if it's a return)", "format": "double", "nullable": true }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/TransactionItem" }, "nullable": true }, "discounts": { "type": "array", "items": { "$ref": "#/components/schemas/AppliedDiscount" }, "nullable": true, "readOnly": true }, "lastModifiedDateUTC": { "type": "string", "format": "date-time" }, "cashPaid": { "type": "number", "format": "double", "nullable": true }, "debitPaid": { "type": "number", "format": "double", "nullable": true }, "electronicPaid": { "type": "number", "format": "double", "nullable": true }, "electronicPaymentMethod": { "type": "string", "nullable": true }, "checkPaid": { "type": "number", "format": "double", "nullable": true }, "creditPaid": { "type": "number", "format": "double", "nullable": true }, "giftPaid": { "type": "number", "format": "double", "nullable": true }, "mmapPaid": { "type": "number", "format": "double", "nullable": true }, "prePaymentAmount": { "type": "number", "format": "double", "nullable": true }, "revenueFeesAndDonations": { "type": "number", "format": "double", "nullable": true }, "nonRevenueFeesAndDonations": { "type": "number", "format": "double", "nullable": true }, "feesAndDonations": { "type": "array", "items": { "$ref": "#/components/schemas/FeeDonationInfo" }, "nullable": true }, "taxSummary": { "type": "array", "items": { "$ref": "#/components/schemas/TaxSummaryInfo" }, "nullable": true, "readOnly": true }, "returnOnTransactionId": { "type": "integer", "format": "int32", "nullable": true }, "adjustmentForTransactionId": { "type": "integer", "format": "int32", "nullable": true }, "orderType": { "type": "string", "nullable": true }, "wasPreOrdered": { "type": "boolean" }, "orderSource": { "type": "string", "nullable": true }, "orderMethod": { "type": "string", "nullable": true }, "invoiceName": { "type": "string", "nullable": true }, "isReturn": { "type": "boolean", "readOnly": true }, "authCode": { "type": "string", "nullable": true }, "customerTypeId": { "type": "integer", "format": "int32" }, "isMedical": { "type": "boolean" }, "orderIds": { "type": "array", "items": { "type": "integer", "format": "int32" }, "nullable": true }, "totalCredit": { "type": "number", "format": "double" }, "completedByUser": { "type": "string", "nullable": true }, "responsibleForSaleUserId": { "type": "integer", "format": "int32" }, "transactionDateLocalTime": { "type": "string", "format": "date-time" }, "estTimeArrivalLocal": { "type": "string", "format": "date-time", "nullable": true }, "estDeliveryDateLocal": { "type": "string", "format": "date-time", "nullable": true, "readOnly": true }, "referenceId": { "type": "string", "nullable": true }, "manualPayments": { "type": "array", "items": { "$ref": "#/components/schemas/ManualPayment" }, "nullable": true }, "manualPaid": { "type": "number", "format": "double", "nullable": true }, "integratedPayments": { "type": "array", "items": { "$ref": "#/components/schemas/IntegratedPayment" }, "nullable": true }, "integratedPaid": { "type": "number", "format": "double", "nullable": true } }, "additionalProperties": false, "description": "Complete cannabis retail transaction model representing all aspects of cannabis sales operations." }, "TransactionItem": { "type": "object", "properties": { "transactionId": { "type": "integer", "description": "Parent transaction identifier linking this item to the overall transaction.", "format": "int32" }, "productId": { "type": "integer", "description": "Product identifier for the purchased cannabis product.", "format": "int32" }, "totalPrice": { "type": "number", "description": "Total price for this line item including all taxes and discounts (in USD).", "format": "double" }, "quantity": { "type": "number", "description": "Quantity of the product purchased (units based on product type - grams, pieces, etc.).", "format": "double" }, "unitPrice": { "type": "number", "description": "Unit price per individual item before taxes and discounts (in USD).", "format": "double" }, "unitCost": { "type": "number", "description": "Cost basis of the product for internal accounting and margin calculations (in USD).", "format": "double", "nullable": true }, "packageId": { "type": "string", "description": "State tracking system package identifier for regulatory compliance (seed-to-sale tracking).", "nullable": true }, "sourcePackageId": { "type": "string", "description": "Original source package identifier for product lineage tracking in state systems.", "nullable": true }, "totalDiscount": { "type": "number", "description": "Total discount amount applied to this line item (in USD).", "format": "double" }, "inventoryId": { "type": "integer", "description": "Inventory record identifier for the specific product inventory being sold.", "format": "int32" }, "unitId": { "type": "integer", "description": "Unit type identifier defining how the product is measured and sold.", "format": "int32" }, "unitWeight": { "type": "number", "description": "Weight of the product unit in grams (calculated for flower products with UnitId = 1).", "format": "double", "nullable": true, "readOnly": true }, "unitWeightUnit": { "type": "string", "description": "Unit of measurement for product weight (always \"g\" for grams).", "nullable": true, "readOnly": true }, "flowerEquivalent": { "type": "number", "description": "Flower equivalent weight for concentrate products in grams (for regulatory compliance).", "format": "double", "nullable": true }, "flowerEquivalentUnit": { "type": "string", "description": "Unit of measurement for flower equivalent (always \"g\" for grams).", "nullable": true, "readOnly": true }, "discounts": { "type": "array", "items": { "$ref": "#/components/schemas/AppliedDiscount" }, "description": "Collection of discounts applied to this transaction item.", "nullable": true }, "taxes": { "type": "array", "items": { "$ref": "#/components/schemas/LineItemTaxInfo" }, "description": "Collection of taxes applied to this transaction item.", "nullable": true }, "returnDate": { "type": "string", "description": "Date when this item was returned (null if not returned).", "format": "date-time", "nullable": true }, "isReturned": { "type": "boolean", "description": "Indicates whether this transaction item has been returned.", "readOnly": true }, "returnedByTransactionId": { "type": "integer", "description": "Transaction identifier of the return transaction that processed this item's return.", "format": "int32", "nullable": true }, "returnReason": { "type": "string", "description": "Reason provided for returning this item (e.g., \"Defective\", \"Customer Dissatisfaction\").", "nullable": true }, "batchName": { "type": "string", "description": "Cultivation batch name for product traceability and regulatory compliance.", "nullable": true }, "transactionItemId": { "type": "integer", "description": "Reference identifier to tie child items to parent items within a transaction.\nNot guaranteed to be unique outside of a single transaction.", "format": "int32", "readOnly": true }, "vendor": { "type": "string", "description": "Vendor or supplier name for the product.", "nullable": true }, "isCoupon": { "type": "boolean", "description": "Indicates whether this item represents a coupon or promotional discount rather than a physical product." } }, "additionalProperties": false, "description": "Individual line item within a cannabis retail transaction containing product, pricing, and compliance information." }, "Unit": { "type": "object", "properties": { "unitId": { "type": "integer", "description": "Unique identifier for the measurement unit.", "format": "int32" }, "unitName": { "type": "string", "description": "Full name of the measurement unit (e.g., \"Grams\", \"Ounces\", \"Pounds\").", "nullable": true }, "abbreviation": { "type": "string", "description": "Short abbreviation for the unit (e.g., \"g\", \"oz\", \"lb\").", "nullable": true }, "unitTypeId": { "type": "integer", "description": "Unit type classification identifier linking to measurement category.", "format": "int32" } }, "additionalProperties": false, "description": "Measurement unit model for cannabis product tracking and inventory management." }, "UnitType": { "type": "object", "properties": { "unitTypeId": { "type": "integer", "description": "Unique identifier for the unit type category.", "format": "int32" }, "unitTypeName": { "type": "string", "description": "Display name of the unit type category (e.g., \"Weight\", \"Volume\", \"Quantity\").", "nullable": true }, "unitTypeAbbreivation": { "type": "string", "description": "Short abbreviation for the unit type (e.g., \"Wgt\", \"Vol\", \"Qty\").", "nullable": true } }, "additionalProperties": false, "description": "Unit type classification model for organizing measurement units by category." }, "UpdateBatchLabResultsRequest": { "required": ["batchName"], "type": "object", "properties": { "batchName": { "minLength": 1, "type": "string", "description": "Name of the batch to update with laboratory test results (required)." }, "sampleWeight": { "type": "number", "description": "Weight of the laboratory sample used for testing (in grams).", "format": "double", "nullable": true }, "labResults": { "type": "array", "items": { "$ref": "#/components/schemas/CannabinoidTerpeneValue" }, "description": "Collection of laboratory test results including cannabinoids and terpenes.", "nullable": true } }, "additionalProperties": false, "description": "Request model for updating laboratory test results for a specific batch by batch name." }, "UpdateBatchRequest": { "type": "object", "properties": { "batchName": { "type": "string", "nullable": true }, "roomId": { "type": "integer", "format": "int32", "nullable": true }, "strainId": { "type": "integer", "format": "int32", "nullable": true } }, "additionalProperties": false }, "UpdateDeliveryRouteDetailRequest": { "type": "object", "properties": { "transactionId": { "type": "integer", "description": "Delivery transaction identifier to update (required).", "format": "int32" }, "driverId": { "type": "integer", "description": "Primary driver identifier for delivery assignment (optional).", "format": "int32", "nullable": true }, "driverId2": { "type": "integer", "description": "Secondary driver identifier for delivery assignment (optional).", "format": "int32", "nullable": true }, "vehicleId": { "type": "integer", "description": "Vehicle identifier for delivery assignment (optional).", "format": "int32", "nullable": true }, "route": { "type": "string", "description": "Route information or delivery notes (optional).", "nullable": true }, "status": { "type": "string", "description": "Delivery status update (optional).", "nullable": true } }, "additionalProperties": false, "description": "Request model for updating delivery route details including vehicle assignments, driver assignments, and delivery status." }, "UpdateJournalEntryRequest": { "required": ["body", "date", "journalEntryId", "subject"], "type": "object", "properties": { "journalEntryId": { "type": "integer", "description": "The ID of the existing journal entry to update.", "format": "int32" }, "subject": { "minLength": 1, "type": "string", "description": "Updated title or summary for the journal entry." }, "body": { "minLength": 1, "type": "string", "description": "Updated detailed content and notes for the journal entry." }, "date": { "type": "string", "description": "Updated date and time when the journal entry should be dated.", "format": "date-time" } }, "additionalProperties": false, "description": "Request model for updating existing customer journal entries with modified content and details." }, "UpdatePackageTagsRequest": { "required": ["tags"], "type": "object", "properties": { "packageIds": { "$ref": "#/components/schemas/StringIEnumerableOptional" }, "inventoryIds": { "$ref": "#/components/schemas/Int32IEnumerableOptional" }, "tags": { "type": "array", "items": { "type": "string" }, "description": "Required collection of tags to apply to the specified packages (required)." } }, "additionalProperties": false }, "UpdatePlantDetails": { "type": "object", "properties": { "plantId": { "type": "integer", "format": "int32" }, "serialNumber": { "$ref": "#/components/schemas/StringOptional" }, "dateCreated": { "$ref": "#/components/schemas/DateTimeNullableOptional" }, "bornDate": { "$ref": "#/components/schemas/DateTimeNullableOptional" }, "isMother": { "$ref": "#/components/schemas/BooleanNullableOptional" }, "strainId": { "$ref": "#/components/schemas/Int32NullableOptional" }, "roomId": { "$ref": "#/components/schemas/Int32NullableOptional" }, "tableId": { "$ref": "#/components/schemas/Int32NullableOptional" }, "batchId": { "$ref": "#/components/schemas/Int32NullableOptional" } }, "additionalProperties": false }, "UpdatePlantsRequest": { "type": "object", "properties": { "plants": { "type": "array", "items": { "$ref": "#/components/schemas/UpdatePlantDetails" }, "nullable": true } }, "additionalProperties": false }, "UpdatePreOrderRequest": { "type": "object", "properties": { "orderId": { "type": "integer", "format": "int32" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/PreOrderItem" }, "nullable": true }, "isDelivery": { "type": "boolean" }, "orderSource": { "type": "string", "nullable": true, "deprecated": true }, "deliveryStreet": { "type": "string", "nullable": true }, "deliveryCity": { "type": "string", "nullable": true }, "deliveryState": { "type": "string", "nullable": true }, "deliveryPostalCode": { "type": "string", "nullable": true }, "deliveryScheduleId": { "$ref": "#/components/schemas/DeliveryScheduleType" }, "notes": { "type": "string", "nullable": true }, "redemptions": { "$ref": "#/components/schemas/PreOrderRedemptionIEnumerableOptional" }, "customerId": { "type": "integer", "format": "int32" }, "deliveryStreet2": { "type": "string", "nullable": true }, "timeWindowStartDateUtc": { "type": "string", "format": "date-time", "nullable": true }, "timeWindowEndDateUtc": { "type": "string", "format": "date-time", "nullable": true } }, "additionalProperties": false }, "UpdateStrain": { "required": ["strainDescription", "strainName"], "type": "object", "properties": { "strainId": { "type": "integer", "description": "Unique identifier for strain updates.\n- **For CREATE**: Omit this field, set to null, or set to 0\n- **For UPDATE**: Provide the existing strain's ID", "format": "int32", "nullable": true }, "strainName": { "minLength": 1, "type": "string", "description": "Name of the cannabis strain (required for creation)" }, "strainDescription": { "minLength": 1, "type": "string", "description": "Detailed description of the strain's characteristics and effects.\n**REQUIRED** - Cannot be null or empty for both create and update operations." }, "abbreviation": { "type": "string", "description": "Short name or code for the strain (optional)", "nullable": true }, "strainType": { "type": "string", "description": "Classification type of the strain (optional).\n**Must be one of**: `Indica`, `Sativa`, `Hybrid`, `CBD`\nIf provided, value will be validated against allowed strain types.", "nullable": true }, "externalId": { "type": "string", "description": "External system identifier for third-party integration (optional).\nUseful for synchronizing with cultivation management systems.", "nullable": true }, "broadcast": { "$ref": "#/components/schemas/BooleanOptional" } }, "additionalProperties": false, "description": "Request model for creating or updating cannabis strain information.\n\n**Create vs Update Behavior:**\n- **CREATE**: When `StrainId` is null, 0, or omitted, a new strain record will be created\n- **UPDATE**: When `StrainId` is provided with a valid strain ID, the existing strain will be updated\n\n**Sparse Update Behavior:**\n- **Provided fields**: Will overwrite existing values with provided data\n- **Omitted fields**: Will preserve existing values (no data loss for updates)\n- **Special handling**: `StrainDescription` is always required and cannot be null" }, "UploadFileType": { "enum": [0, 1, 2, 3, 4, 5], "type": "integer", "format": "int32" }, "ValidationFailure": { "type": "object", "properties": { "propertyName": { "type": "string", "nullable": true }, "errorMessage": { "type": "string", "nullable": true }, "attemptedValue": { "type": "object", "nullable": true }, "customState": { "type": "object", "nullable": true }, "severity": { "$ref": "#/components/schemas/Severity" }, "errorCode": { "type": "string", "nullable": true }, "formattedMessagePlaceholderValues": { "type": "object", "additionalProperties": { "type": "object", "nullable": true }, "nullable": true } }, "additionalProperties": false }, "ValidationResult": { "type": "object", "properties": { "isValid": { "type": "boolean", "readOnly": true }, "errors": { "type": "array", "items": { "$ref": "#/components/schemas/ValidationFailure" }, "nullable": true }, "ruleSetsExecuted": { "type": "array", "items": { "type": "string" }, "nullable": true } }, "additionalProperties": false }, "VehicleDetail": { "type": "object", "properties": { "vehicleId": { "type": "integer", "format": "int32" }, "make": { "type": "string", "nullable": true }, "model": { "type": "string", "nullable": true }, "modelYear": { "type": "string", "nullable": true }, "color": { "type": "string", "nullable": true }, "licensePlate": { "type": "string", "nullable": true }, "vin": { "type": "string", "nullable": true } }, "additionalProperties": false }, "Vendor": { "type": "object", "properties": { "vendorId": { "type": "integer", "description": "Unique identifier for the vendor in the system (null for new vendor creation).", "format": "int32", "nullable": true }, "vendorName": { "type": "string", "description": "Official business name of the vendor as registered with regulatory authorities.", "nullable": true }, "address": { "type": "string", "description": "Street address of the vendor's business location.", "nullable": true }, "city": { "type": "string", "description": "City where the vendor's business is located.", "nullable": true }, "state": { "type": "string", "description": "State or province where the vendor's business is located.", "nullable": true }, "postalCode": { "type": "string", "description": "Postal or ZIP code for the vendor's business address.", "nullable": true }, "licenseNumber": { "type": "string", "description": "Cannabis business license number issued by state regulatory authorities.", "nullable": true }, "contactName": { "type": "string", "description": "Name of the primary business contact for this vendor.", "nullable": true }, "contactEmail": { "type": "string", "description": "Email address for business communications with the vendor.", "nullable": true }, "contactPhone": { "type": "string", "description": "Phone number for business communications with the vendor.", "nullable": true } }, "additionalProperties": false, "description": "Vendor information model for cannabis supply chain and compliance management." }, "WasteSummary": { "type": "object", "properties": { "roomWaste": { "type": "array", "items": { "$ref": "#/components/schemas/RoomWaste" }, "description": "Collection of room-based waste disposal records.", "nullable": true }, "harvestWaste": { "type": "array", "items": { "$ref": "#/components/schemas/ObjectWaste" }, "description": "Collection of harvest-based waste disposal records.", "nullable": true }, "plantWaste": { "type": "array", "items": { "$ref": "#/components/schemas/ObjectWaste" }, "description": "Collection of plant-based waste disposal records.", "nullable": true } }, "additionalProperties": false, "description": "Comprehensive waste summary model containing all waste types for facility waste management and regulatory reporting." }, "WeeklyRecurrenceInfo": { "type": "object", "properties": { "startTime": { "type": "string", "description": "Daily start time when discount becomes available (optional).", "format": "date-span", "nullable": true }, "endTime": { "type": "string", "description": "Daily end time when discount expires (optional).", "format": "date-span", "nullable": true }, "appliesOnMonday": { "type": "boolean", "description": "Indicates if discount is available on Mondays." }, "appliesOnTuesday": { "type": "boolean", "description": "Indicates if discount is available on Tuesdays." }, "appliesOnWednesday": { "type": "boolean", "description": "Indicates if discount is available on Wednesdays." }, "appliesOnThursday": { "type": "boolean", "description": "Indicates if discount is available on Thursdays." }, "appliesOnFriday": { "type": "boolean", "description": "Indicates if discount is available on Fridays." }, "appliesOnSaturday": { "type": "boolean", "description": "Indicates if discount is available on Saturdays." }, "appliesOnSunday": { "type": "boolean", "description": "Indicates if discount is available on Sundays." } }, "additionalProperties": false, "description": "Weekly recurring schedule model defining time-based availability patterns for discount application." } }, "securitySchemes": { "basicAuth": { "type": "http", "description": "**API Key Authentication Required**\r\n\r\n**How to Authenticate:**\r\n1. Use HTTP Basic Authentication\r\n2. Username: Your API key\r\n3. Password: Leave empty\r\n4. Header format: `Authorization: Basic `\r\n\r\n**Example:**\r\n- API Key: `your-api-key-here`\r\n- Header: `Authorization: Basic eW91ci1hcGkta2V5LWhlcmU6`\r\n\r\n**All endpoints require authentication** - requests without valid API keys will receive `401 Unauthorized` responses.", "scheme": "basic" } } }, "security": [ { "basicAuth": [] } ] } ================================================ FILE: specs/3.0.x/enum-escape.json ================================================ { "openapi": "3.0.2", "info": { "title": "OpenAPI 3.0.2 enum escape example", "version": "1" }, "components": { "schemas": { "Foo": { "type": "object", "properties": { "foo": { "enum": ["foo'bar", "foo\"bar"], "type": "string" } } }, "Bar": { "enum": ["foo'bar", "foo\"bar"], "type": "string" } } } } ================================================ FILE: specs/3.0.x/enum-inline.json ================================================ { "openapi": "3.0.3", "info": { "title": "OpenAPI 3.0.3 enum inline example", "version": "1" }, "components": { "schemas": { "Foo": { "properties": { "type": { "enum": ["foo", "bar", "FooBar", "fooBar", "foo bar"], "type": "string" } }, "type": "object" } } } } ================================================ FILE: specs/3.0.x/enum-names-values.json ================================================ { "openapi": "3.0.2", "info": { "title": "OpenAPI 3.0.2 enum names values example", "version": "1" }, "components": { "schemas": { "1-10": { "enum": ["1-10", "11-20"], "type": "string" }, "myFoo": { "enum": ["myFoo", "myBar"], "type": "string" }, "MyFoo": { "enum": ["MyFoo", "MyBar"], "type": "string" }, "Foo": { "enum": ["foo", "bar", null, "", true, false], "nullable": true, "type": "string" }, "Numbers": { "enum": [100, 200, 300, -100, -200, -300], "type": "number" }, "Arrays": { "enum": [["foo"], ["bar"], ["baz"]], "type": "array" } } } } ================================================ FILE: specs/3.0.x/enum-null.json ================================================ { "openapi": "3.0.2", "info": { "title": "OpenAPI 3.0.2 enum null example", "version": "1" }, "components": { "schemas": { "Foo": { "enum": ["foo", "bar", null], "nullable": true, "type": "string" }, "Bar": { "enum": ["foo", "bar", null], "type": "string" }, "Baz": { "enum": ["foo", "bar"], "nullable": true, "type": "string" } } } } ================================================ FILE: specs/3.0.x/exclude-deprecated.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 exclude deprecated example version: 1 paths: /foo: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Foo' required: true responses: '200': description: OK /bar: post: deprecated: true requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Bar' required: true responses: '200': description: OK components: schemas: Foo: type: string Bar: deprecated: true type: string ================================================ FILE: specs/3.0.x/external-shared.json ================================================ { "components": { "schemas": { "ExternalSharedModel": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" } }, "required": ["id"] }, "ExternalSharedModelWithUuid": { "type": "string", "format": "uuid" }, "ExternalNested": { "type": "object", "properties": { "inner": { "type": "object", "properties": { "deep": { "type": "string" } } } } }, "ExternalNestedNumeric": { "type": "object", "properties": { "0": { "type": "object", "properties": { "1": { "type": "string" } } } } } } } } ================================================ FILE: specs/3.0.x/external.yaml ================================================ openapi: 3.0.0 info: title: OpenAPI 3.0 external example version: 1 # Paths using external references paths: /external-model: get: summary: Get external model parameters: - $ref: '#/components/parameters/ExternalIdParam' - $ref: '#/components/parameters/ExternalUuidParam' responses: '200': $ref: '#/components/responses/ExternalModelResponse' '400': $ref: '#/components/responses/ExternalUuidResponse' post: summary: Create external model requestBody: $ref: '#/components/requestBodies/ExternalModelBody' responses: '201': $ref: '#/components/responses/ExternalModelResponse' '422': $ref: '#/components/responses/ExternalUnionResponse' /external-uuid: get: summary: Get external UUID parameters: - $ref: '#/components/parameters/ExternalUuidParam' responses: '200': $ref: '#/components/responses/ExternalUuidResponse' put: summary: Update external UUID requestBody: $ref: '#/components/requestBodies/ExternalUuidBody' responses: '200': $ref: '#/components/responses/ExternalUuidResponse' /external-nested: get: summary: Get external nested object parameters: - $ref: '#/components/parameters/ExternalDeepParam' responses: '200': $ref: '#/components/responses/ExternalNestedResponse' post: summary: Create external nested object requestBody: $ref: '#/components/requestBodies/ExternalNestedBody' responses: '201': $ref: '#/components/responses/ExternalNestedResponse' /external-mixed: get: summary: Get mixed external data parameters: - $ref: '#/components/parameters/ExternalIdParam' - $ref: '#/components/parameters/ExternalUuidParam' - $ref: '#/components/parameters/ExternalDeepParam' - $ref: '#/components/parameters/ExternalNumericParam' responses: '200': $ref: '#/components/responses/ExternalArrayResponse' post: summary: Create mixed external data requestBody: $ref: '#/components/requestBodies/ExternalMixedBody' responses: '201': $ref: '#/components/responses/ExternalModelResponse' /external-array: get: summary: Get array of external models responses: '200': $ref: '#/components/responses/ExternalArrayResponse' post: summary: Create array of external models requestBody: content: application/json: schema: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' required: true responses: '201': $ref: '#/components/responses/ExternalArrayResponse' /external-union: get: summary: Get union of external types responses: '200': $ref: '#/components/responses/ExternalUnionResponse' post: summary: Create union of external types requestBody: content: application/json: schema: oneOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/components/schemas/ExternalNested' required: true responses: '201': $ref: '#/components/responses/ExternalUnionResponse' /external-properties/{id}: get: summary: Get external properties parameters: - name: id in: path required: true schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' - name: uuid in: query schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - name: deep in: header schema: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' responses: '200': content: application/json: schema: type: object properties: id: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' name: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/name' uuid: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' deep: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' numeric: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' components: schemas: # Basic external schema references (multiple uses of each type) ExternalSchemaA: description: External schema (A) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalSchemaB: description: External schema (B) - second use of ExternalSharedModel $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalSchemaC: description: External schema (C) - third use of ExternalSharedModel $ref: './external-shared.json#/components/schemas/ExternalSharedModel' # Path-based references using /path syntax ExternalSchemaPathA: description: External schema via path reference (A) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalSchemaPathB: description: External schema via path reference (B) - second use $ref: './external-shared.json#/components/schemas/ExternalSharedModel' # UUID type references (multiple uses) ExternalSchemaPropertyA: description: External schema property (A) type: object properties: uuid1: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalSchemaPropertyB: description: External schema property (B) - second use of UUID type: object properties: uuid2: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalSchemaPropertyC: description: External schema property (C) - third use of UUID type: object properties: uuid3: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # Duplicate refs in same schema ExternalSchemaPropertyD: description: External schema property with duplicate refs (D) type: object properties: uuid4: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' uuid5: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # External property references ExternalSchemaExternalProp: description: External schema property via external property ref (id) type: object properties: id3: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' id4: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' # Alias references ExternalSchemaExternalPropAlias: description: Alias to external property via component property ref type: object properties: id5: $ref: '#/components/schemas/ExternalSchemaExternalProp/properties/id3' id6: $ref: '#/components/schemas/ExternalSchemaExternalProp/properties/id4' # Nested property references (multiple uses) ExternalDoubleNestedProp: description: External double nested prop via property ref type: object properties: deep1: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' deep2: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' # Numeric property references (multiple uses) ExternalDoubleNestedNumeric: description: External double nested numeric properties type: object properties: numeric1: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' numeric2: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' # Complex nested object references ExternalNestedObjectA: description: External nested object reference (A) $ref: './external-shared.json#/components/schemas/ExternalNested' ExternalNestedObjectB: description: External nested object reference (B) - second use $ref: './external-shared.json#/components/schemas/ExternalNested' # Numeric nested object references ExternalNestedNumericObjectA: description: External numeric nested object reference (A) $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' ExternalNestedNumericObjectB: description: External numeric nested object reference (B) - second use $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' # Mixed property references ExternalMixedProperties: description: Mixed external property references type: object properties: id7: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' name1: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/name' uuid6: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' deep3: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' numeric3: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' # Array of external references ExternalArraySchema: description: Array containing external references type: object properties: items: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' uuidItems: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # Union types with external references ExternalUnionSchema: description: Union type with external references oneOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # AllOf with external references ExternalAllOfSchema: description: AllOf with external references allOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - type: object properties: additional: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # AnyOf with external references ExternalAnyOfSchema: description: AnyOf with external references anyOf: - $ref: './external-shared.json#/components/schemas/ExternalNested' - $ref: './external-shared.json#/components/schemas/ExternalNested' - $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' - $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' # Parameters using external references parameters: ExternalIdParam: name: id in: path required: true schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' ExternalUuidParam: name: uuid in: query schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalDeepParam: name: deep in: header schema: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' ExternalNumericParam: name: numeric in: query schema: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' # Request bodies using external references requestBodies: ExternalModelBody: description: Request body using external model required: true content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalUuidBody: description: Request body using external UUID content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalNestedBody: description: Request body using external nested object content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalNested' ExternalMixedBody: description: Request body with mixed external properties content: application/json: schema: type: object properties: id: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' name: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/name' uuid: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' deep: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' # Responses using external references responses: ExternalModelResponse: description: Response using external model content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalUuidResponse: description: Response using external UUID content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalNestedResponse: description: Response using external nested object content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalNested' ExternalArrayResponse: description: Response with array of external models content: application/json: schema: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalUnionResponse: description: Response with union of external types content: application/json: schema: oneOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/components/schemas/ExternalNested' # Headers using external references headers: ExternalIdHeader: description: Header using external ID property schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' ExternalUuidHeader: description: Header using external UUID schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalDeepHeader: description: Header using external deep property schema: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' ================================================ FILE: specs/3.0.x/full.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 example version: '1' servers: - url: http://localhost:3000/base paths: /api/v{api-version}/no+tag: tags: [] get: operationId: export patch: responses: default: description: OK post: operationId: import requestBody: required: true content: application/json: schema: type: object oneOf: - $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' - $ref: '#/components/schemas/ModelWithArrayReadOnlyAndWriteOnly' responses: '200': description: Success content: application/json; type=collection: schema: $ref: '#/components/schemas/Model-From.Zendesk' default: description: Default success response content: application/json: schema: $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' put: operationId: foo+Wow responses: default: description: OK /api/v{api-version}/simple/$count: get: tags: - Simple operationId: api/v{version}/ODataController/$count responses: '200': description: Success content: application/json; type=collection: schema: $ref: '#/components/schemas/Model-From.Zendesk' /api/v{api-version}/simple:operation: get: parameters: - description: foo in method in: path name: foo_param required: true schema: type: string responses: '200': description: Response is a simple number content: application/json: schema: type: number default: description: Default error response content: application/json: schema: $ref: '#/components/schemas/ModelWithBoolean' /api/v{api-version}/simple: get: tags: - Simple operationId: GetCallWithoutParametersAndResponse put: tags: - Simple operationId: PutCallWithoutParametersAndResponse post: tags: - Simple operationId: PostCallWithoutParametersAndResponse delete: tags: - Simple operationId: DeleteCallWithoutParametersAndResponse options: tags: - Simple operationId: OptionsCallWithoutParametersAndResponse head: tags: - Simple operationId: HeadCallWithoutParametersAndResponse patch: tags: - Simple operationId: PatchCallWithoutParametersAndResponse /api/v{api-version}/foo/{foo_param}/bar/{BarParam}: delete: tags: - Parameters operationId: deleteFoo parameters: - description: foo in method in: path name: foo_param required: true schema: type: string - description: bar in method in: path name: BarParam required: true schema: type: string - description: Parameter with illegal characters name: x-Foo-Bar in: header required: true content: application/json: schema: $ref: '#/components/schemas/ModelWithString' parameters: - description: foo in global parameters in: path name: foo_param required: true schema: type: string - description: bar in global parameters in: path name: BarParam required: true schema: type: string /api/v{api-version}/descriptions: post: tags: - Descriptions operationId: CallWithDescriptions parameters: - description: |- Testing multiline comments in string: First line Second line Fourth line name: parameterWithBreaks in: query schema: type: string - description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work' name: parameterWithBackticks in: query schema: type: string - description: "Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work" name: parameterWithSlashes in: query schema: type: string - description: 'Testing expression placeholders in string: ${expression} should work' name: parameterWithExpressionPlaceholders in: query schema: type: string - description: 'Testing quotes in string: ''single quote'''''' and "double quotes""" should work' name: parameterWithQuotes in: query schema: type: string - description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work' name: parameterWithReservedCharacters in: query schema: type: string /api/v{api-version}/parameters/deprecated: post: tags: - Deprecated deprecated: true operationId: DeprecatedCall parameters: - deprecated: true description: This parameter is deprecated name: parameter in: header required: true schema: nullable: true allOf: - $ref: '#/components/schemas/DeprecatedModel' /api/v{api-version}/parameters/{parameterPath}: post: tags: - Parameters operationId: CallWithParameters parameters: - description: This is the parameter that goes into the header name: parameterHeader in: header required: true schema: nullable: true type: string - required: false schema: $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' name: foo_ref_enum in: query - required: true schema: allOf: - $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' name: foo_all_of_enum in: query - description: This is the parameter that goes into the query params name: cursor in: query required: true schema: nullable: true type: string - description: This is the parameter that goes into the cookie name: parameterCookie in: cookie required: true schema: nullable: true type: string - description: This is the parameter that goes into the path name: parameterPath in: path required: true schema: nullable: true type: string - description: api-version should be required in standalone clients name: api-version in: path required: true schema: nullable: true type: string requestBody: description: This is the parameter that goes into the body required: true content: application/json: schema: nullable: true properties: {} type: object /api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}: post: tags: - Parameters operationId: CallWithWeirdParameterNames parameters: - description: This is the parameter that goes into the path name: parameter.path.1 in: path required: false schema: nullable: false type: string - description: This is the parameter that goes into the path name: parameter-path-2 in: path required: false schema: nullable: false type: string - description: This is the parameter that goes into the path name: PARAMETER-PATH-3 in: path required: false schema: nullable: false type: string - description: This is the parameter with a reserved keyword name: default in: query required: false schema: nullable: false type: string - description: This is the parameter that goes into the request header name: parameter.header in: header required: true schema: nullable: true type: string - description: This is the parameter that goes into the request query params name: parameter-query in: query required: true schema: nullable: true type: string - description: This is the parameter that goes into the cookie name: PARAMETER-COOKIE in: cookie required: true schema: nullable: true type: string - description: api-version should be required in standalone clients name: api-version in: path required: true schema: nullable: true type: string requestBody: description: This is the parameter that goes into the body required: true content: application/json: schema: nullable: true allOf: - $ref: '#/components/schemas/ModelWithString' /api/v{api-version}/parameters: get: tags: - Parameters operationId: GetCallWithOptionalParam parameters: - description: This is an optional parameter name: page in: query required: false schema: type: number requestBody: description: This is a required parameter required: true content: application/json: schema: $ref: '#/components/schemas/ModelWithOneOfEnum' post: tags: - Parameters operationId: PostCallWithOptionalParam parameters: - description: This is a required parameter name: parameter in: query required: true schema: $ref: '#/components/schemas/Pageable' requestBody: description: This is an optional parameter required: false content: application/json: schema: properties: offset: nullable: true required: true type: number type: object responses: '200': description: Response is a simple number content: application/json: schema: type: number '204': description: Success /api/v{api-version}/requestBody: post: tags: - RequestBody parameters: - $ref: '#/components/parameters/SimpleParameter' requestBody: $ref: '#/components/requestBodies/SimpleRequestBody' /api/v{api-version}/formData: post: tags: - FormData parameters: - $ref: '#/components/parameters/SimpleParameter' requestBody: $ref: '#/components/requestBodies/SimpleFormData' /api/v{api-version}/defaults: get: tags: - Defaults operationId: CallWithDefaultParameters parameters: - description: This is a simple string with default value name: parameterString in: query schema: nullable: true type: string default: Hello World! - description: This is a simple number with default value name: parameterNumber in: query schema: nullable: true type: number default: 123 - description: This is a simple boolean with default value name: parameterBoolean in: query schema: nullable: true type: boolean default: true - description: This is a simple enum with default value name: parameterEnum in: query schema: enum: - Success - Warning - Error default: 0 - description: This is a simple model with default value name: parameterModel in: query schema: nullable: true allOf: - $ref: '#/components/schemas/ModelWithString' default: prop: Hello World! post: tags: - Defaults operationId: CallWithDefaultOptionalParameters parameters: - description: This is a simple string that is optional with default value name: parameterString in: query required: false schema: type: string default: Hello World! - description: This is a simple number that is optional with default value name: parameterNumber in: query required: false schema: type: number default: 123 - description: This is a simple boolean that is optional with default value name: parameterBoolean in: query required: false schema: type: boolean default: true - description: This is a simple enum that is optional with default value name: parameterEnum in: query required: false schema: enum: - Success - Warning - Error default: 0 - description: This is a simple model that is optional with default value name: parameterModel in: query required: false schema: $ref: '#/components/schemas/ModelWithString' default: prop: Hello World! put: tags: - Defaults operationId: CallToTestOrderOfParams parameters: - description: This is a optional string with default name: parameterOptionalStringWithDefault in: query required: false schema: type: string default: Hello World! - description: This is a optional string with empty default name: parameterOptionalStringWithEmptyDefault in: query required: false schema: type: string default: '' - description: This is a optional string with no default name: parameterOptionalStringWithNoDefault in: query required: false schema: type: string - description: This is a string with default name: parameterStringWithDefault in: query required: true schema: type: string default: Hello World! - description: This is a string with empty default name: parameterStringWithEmptyDefault in: query required: true schema: type: string default: '' - description: This is a string with no default name: parameterStringWithNoDefault in: query required: true schema: type: string - description: This is a string that can be null with no default name: parameterStringNullableWithNoDefault in: query required: false schema: type: string nullable: true - description: This is a string that can be null with default name: parameterStringNullableWithDefault in: query required: false schema: type: string nullable: true default: null /api/v{api-version}/duplicate: delete: tags: - Duplicate operationId: DuplicateName get: tags: - Duplicate operationId: DuplicateName2 post: tags: - Duplicate operationId: DuplicateName3 put: tags: - Duplicate operationId: DuplicateName4 /api/v{api-version}/no-content: get: tags: - NoContent operationId: CallWithNoContentResponse responses: '204': description: Success /api/v{api-version}/multiple-tags/response-and-no-content: get: tags: - Response - NoContent operationId: CallWithResponseAndNoContentResponse responses: '200': description: Response is a simple number content: application/json: schema: type: number '204': description: Success /api/v{api-version}/multiple-tags/a: get: tags: - MultipleTags1 - MultipleTags2 operationId: DummyA responses: '200': content: application/json: schema: $ref: '#/components/schemas/400' /api/v{api-version}/multiple-tags/b: get: tags: - MultipleTags1 - MultipleTags2 - MultipleTags3 operationId: DummyB responses: '204': description: Success /api/v{api-version}/response: get: tags: - Response operationId: CallWithResponse responses: default: content: application/json: schema: $ref: '#/components/schemas/import' post: tags: - Response operationId: CallWithDuplicateResponses responses: '200': description: Message for 200 response content: application/json: schema: allOf: - $ref: '#/components/schemas/ModelWithBoolean' - $ref: '#/components/schemas/ModelWithInteger' '201': description: Message for 201 response content: application/json: schema: $ref: '#/components/schemas/ModelWithString' '202': description: Message for 202 response content: application/json: schema: $ref: '#/components/schemas/ModelWithString' '500': description: Message for 500 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '501': description: Message for 501 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '502': description: Message for 502 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' default: description: Default error response content: application/json: schema: $ref: '#/components/schemas/ModelWithBoolean' 4XX: description: Message for 4XX errors content: application/json: schema: $ref: '#/components/schemas/DictionaryWithArray' put: tags: - Response operationId: CallWithResponses responses: '200': description: Message for 200 response content: application/json: schema: type: object properties: '@namespace.string': type: string readOnly: true '@namespace.integer': type: integer readOnly: true value: type: array items: $ref: '#/components/schemas/ModelWithString' readOnly: true '201': description: Message for 201 response content: application/json: schema: $ref: '#/components/schemas/ModelThatExtends' '202': description: Message for 202 response content: application/json: schema: $ref: '#/components/schemas/ModelThatExtendsExtends' '500': description: Message for 500 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '501': description: Message for 501 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '502': description: Message for 502 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' default: description: Message for default response content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' /api/v{api-version}/collectionFormat: get: tags: - CollectionFormat operationId: CollectionFormat parameters: - description: This is an array parameter that is sent as csv format (comma-separated values) name: parameterArrayCSV in: query required: true schema: nullable: true type: array items: type: string collectionFormat: csv - description: This is an array parameter that is sent as ssv format (space-separated values) name: parameterArraySSV in: query required: true schema: nullable: true type: array items: type: string collectionFormat: ssv - description: This is an array parameter that is sent as tsv format (tab-separated values) name: parameterArrayTSV in: query required: true schema: nullable: true type: array items: type: string collectionFormat: tsv - description: This is an array parameter that is sent as pipes format (pipe-separated values) name: parameterArrayPipes in: query required: true schema: nullable: true type: array items: type: string collectionFormat: pipes - description: This is an array parameter that is sent as multi format (multiple parameter instances) name: parameterArrayMulti in: query required: true schema: nullable: true type: array items: type: string collectionFormat: multi /api/v{api-version}/types: get: tags: - Types operationId: Types parameters: - description: This is a number parameter name: parameterNumber in: query required: true schema: type: number default: 123 - description: This is a string parameter name: parameterString in: query required: true schema: type: string default: default nullable: true - description: This is a boolean parameter name: parameterBoolean in: query required: true schema: type: boolean default: true nullable: true - description: This is an object parameter name: parameterObject in: query required: true schema: type: object default: null nullable: true - description: This is an array parameter name: parameterArray in: query required: true schema: type: array items: type: string nullable: true - description: This is a dictionary parameter name: parameterDictionary in: query required: true schema: type: object items: type: string nullable: true - description: This is an enum parameter name: parameterEnum in: query required: true schema: enum: - Success - Warning - Error nullable: true - description: This is a number parameter name: id in: path schema: type: integer format: int32 responses: '200': description: Response is a simple number content: application/json: schema: type: number '201': description: Response is a simple string content: application/json: schema: type: string '202': description: Response is a simple boolean content: application/json: schema: type: boolean '203': description: Response is a simple object content: application/json: schema: type: object /api/v{api-version}/upload: post: tags: - Upload operationId: UploadFile parameters: - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: string nullable: true requestBody: content: application/x-www-form-urlencoded: description: Supply a file reference for upload schema: format: binary type: string required: true responses: '200': content: application/json: schema: type: boolean /api/v{api-version}/file/{id}: get: tags: - FileResponse operationId: FileResponse parameters: - name: id in: path required: true schema: type: string - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: string responses: '200': description: Success content: audio/*: schema: format: binary type: string video/*: schema: format: binary type: string /api/v{api-version}/complex: get: tags: - Complex operationId: ComplexTypes parameters: - description: Parameter containing object name: parameterObject in: query required: true schema: type: object properties: first: type: object properties: second: type: object properties: third: type: string - description: Parameter containing reference name: parameterReference in: query required: true schema: $ref: '#/components/schemas/ModelWithString' responses: '200': description: Successful response content: application/json: schema: type: array items: $ref: '#/components/schemas/ModelWithString' '400': description: 400 `server` error '500': description: 500 server error /api/v{api-version}/multipart: post: tags: - multipart operationId: MultipartRequest requestBody: content: multipart/form-data: schema: type: object properties: content: type: string format: binary data: allOf: - $ref: '#/components/schemas/ModelWithString' nullable: true encoding: content: style: form data: style: form get: tags: - multipart operationId: MultipartResponse responses: '200': description: OK content: multipart/mixed: schema: type: object properties: file: type: string format: binary metadata: type: object properties: foo: type: string bar: type: string /api/v{api-version}/complex/{id}: put: tags: - Complex operationId: ComplexParams parameters: - name: id in: path required: true schema: type: integer format: int32 - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: string requestBody: content: application/json-patch+json: schema: required: - key - name - parameters - type type: object properties: key: maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ type: string nullable: true readOnly: true name: maxLength: 255 type: string nullable: true enabled: type: boolean default: true type: enum: - Monkey - Horse - Bird type: string readOnly: true listOfModels: type: array items: $ref: '#/components/schemas/ModelWithString' nullable: true listOfStrings: type: array items: type: string nullable: true parameters: type: object oneOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' user: type: object properties: id: type: integer format: int32 readOnly: true name: type: string nullable: true readOnly: true readOnly: true responses: '200': description: Success content: application/json; type=collection: schema: $ref: '#/components/schemas/ModelWithString' /api/v{api-version}/header: post: tags: - Header operationId: CallWithResultFromHeader responses: '200': description: Successful response headers: operation-location: schema: type: string '400': description: 400 server error '500': description: 500 server error /api/v{api-version}/error: post: tags: - Error operationId: testErrorCode parameters: - description: Status code to return name: status in: query required: true schema: type: integer responses: '200': description: 'Custom message: Successful response' '500': description: 'Custom message: Internal Server Error' '501': description: 'Custom message: Not Implemented' '502': description: 'Custom message: Bad Gateway' '503': description: 'Custom message: Service Unavailable' /api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串: post: tags: - Non-Ascii-æøåÆØÅöôêÊ operationId: nonAsciiæøåÆØÅöôêÊ字符串 parameters: - description: Dummy input param name: nonAsciiParamæøåÆØÅöôêÊ in: query required: true schema: type: integer responses: '200': description: Successful response content: application/json: schema: type: array items: $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' put: tags: - Non-Ascii-æøåÆØÅöôêÊ summary: Login User operationId: putWithFormUrlEncoded requestBody: content: application/x-www-form-urlencoded: schema: $ref: '#/components/schemas/ArrayWithStrings' required: true components: requestBodies: SimpleRequestBody: x-body-name: foo description: A reusable request body required: false content: application/json: schema: $ref: '#/components/schemas/ModelWithString' SimpleFormData: description: A reusable request body required: false content: multipart/form-data: schema: $ref: '#/components/schemas/ModelWithString' parameters: SimpleParameter: description: This is a reusable parameter name: parameter in: query required: false schema: type: string x-Foo-Bar: description: Parameter with illegal characters name: x-Foo-Bar in: header required: true content: application/json: schema: $ref: '#/components/schemas/ModelWithString' schemas: ExternalRefA: description: External ref to shared model (A) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalRefB: description: External ref to shared model (B) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' '400': description: Model with number-only name type: string camelCaseCommentWithBreaks: description: |- Testing multiline comments in string: First line Second line Fourth line type: integer CommentWithBreaks: description: |- Testing multiline comments in string: First line Second line Fourth line type: integer CommentWithBackticks: description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work' type: integer CommentWithBackticksAndQuotes: description: 'Testing backticks and quotes in string: `backticks`, ''quotes'', "double quotes" and ```multiple backticks``` should work' type: integer CommentWithSlashes: description: "Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work" type: integer CommentWithExpressionPlaceholders: description: 'Testing expression placeholders in string: ${expression} should work' type: integer CommentWithQuotes: description: 'Testing quotes in string: ''single quote'''''' and "double quotes""" should work' type: integer CommentWithReservedCharacters: description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work' type: integer SimpleInteger: description: This is a simple number type: integer SimpleBoolean: description: This is a simple boolean type: boolean SimpleString: description: This is a simple string type: string NonAsciiStringæøåÆØÅöôêÊ字符串: description: A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) type: string SimpleFile: description: This is a simple file format: binary type: string SimpleReference: description: This is a simple reference allOf: - $ref: '#/components/schemas/ModelWithString' SimpleStringWithPattern: description: This is a simple string type: string nullable: true maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ EnumWithStrings: description: This is a simple enum with strings enum: - Success - Warning - Error - "'Single Quote'" - '"Double Quotes"' - 'Non-ascii: øæåôöØÆÅÔÖ字符串' EnumWithReplacedCharacters: enum: - "'Single Quote'" - '"Double Quotes"' - øæåôöØÆÅÔÖ字符串 - 3.1 - '' type: string EnumWithNumbers: description: This is a simple enum with numbers enum: - 1 - 2 - 3 - 1.1 - 1.2 - 1.3 - 100 - 200 - 300 - -100 - -200 - -300 - -1.1 - -1.2 - -1.3 default: 200 EnumFromDescription: description: Success=1,Warning=2,Error=3 type: number EnumWithExtensions: description: This is a simple enum with numbers enum: - 200 - 400 - 500 x-enum-varnames: - CUSTOM_SUCCESS - CUSTOM_WARNING - CUSTOM_ERROR x-enum-descriptions: - Used when the status of something is successful - Used when the status of something has a warning - Used when the status of something has an error EnumWithXEnumNames: enum: - 0 - 1 - 2 x-enumNames: - zero - one - two ArrayWithNumbers: description: This is a simple array with numbers type: array items: type: integer ArrayWithBooleans: description: This is a simple array with booleans type: array items: type: boolean ArrayWithStrings: description: This is a simple array with strings type: array items: type: string default: - test ArrayWithReferences: description: This is a simple array with references type: array items: $ref: '#/components/schemas/ModelWithString' ArrayWithArray: description: This is a simple array containing an array type: array items: type: array items: $ref: '#/components/schemas/ModelWithString' ArrayWithProperties: description: This is a simple array with properties type: array items: type: object properties: 16x16: $ref: '#/components/schemas/camelCaseCommentWithBreaks' bar: type: string ArrayWithAnyOfProperties: description: This is a simple array with any of properties type: array items: anyOf: - type: object properties: foo: type: string default: test - type: object properties: bar: type: string AnyOfAnyAndNull: type: object properties: data: anyOf: - {} - nullable: true AnyOfArrays: description: This is a simple array with any of properties type: object properties: results: items: anyOf: - type: object properties: foo: type: string - type: object properties: bar: type: string type: array DictionaryWithString: description: This is a string dictionary type: object additionalProperties: type: string DictionaryWithPropertiesAndAdditionalProperties: type: object properties: foo: type: number bar: type: boolean additionalProperties: type: string DictionaryWithReference: description: This is a string reference type: object additionalProperties: $ref: '#/components/schemas/ModelWithString' DictionaryWithArray: description: This is a complex dictionary type: object additionalProperties: type: array items: $ref: '#/components/schemas/ModelWithString' DictionaryWithDictionary: description: This is a string dictionary type: object additionalProperties: type: object additionalProperties: type: string DictionaryWithProperties: description: This is a complex dictionary type: object additionalProperties: type: object properties: foo: type: string bar: type: string ModelWithInteger: description: This is a model with one number property type: object properties: prop: description: This is a simple number property type: integer ModelWithBoolean: description: This is a model with one boolean property type: object properties: prop: description: This is a simple boolean property type: boolean ModelWithString: description: This is a model with one string property type: object properties: prop: description: This is a simple string property type: string ModelWithStringError: description: This is a model with one string property type: object properties: prop: description: This is a simple string property type: string Model-From.Zendesk: description: "`Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comment\ s-to-tickets)" type: string ModelWithNullableString: description: This is a model with one string property type: object required: - nullableRequiredProp1 - nullableRequiredProp2 properties: nullableProp1: description: This is a simple string property type: string nullable: true nullableRequiredProp1: description: This is a simple string property type: string nullable: true nullableProp2: description: This is a simple string property nullable: true type: string nullableRequiredProp2: description: This is a simple string property nullable: true type: string foo_bar-enum: description: This is a simple enum with strings enum: - Success - Warning - Error - ØÆÅ字符串 ModelWithEnum: description: This is a model with one enum type: object properties: foo_bar-enum: description: This is a simple enum with strings enum: - Success - Warning - Error - ØÆÅ字符串 statusCode: description: These are the HTTP error code enums enum: - '100' - 200 FOO - 300 FOO_BAR - 400 foo-bar - 500 foo.bar - 600 foo&bar bool: description: Simple boolean enum type: boolean enum: - true ModelWithEnumWithHyphen: description: This is a model with one enum with escaped name type: object properties: foo-bar-baz-qux: type: string enum: - '3.0' title: Foo-Bar-Baz-Qux default: '3.0' ModelWithEnumFromDescription: description: This is a model with one enum type: object properties: test: type: integer description: Success=1,Warning=2,Error=3 ModelWithNestedEnums: description: This is a model with nested enums type: object properties: dictionaryWithEnum: type: object additionalProperties: enum: - Success - Warning - Error dictionaryWithEnumFromDescription: type: object additionalProperties: type: integer description: Success=1,Warning=2,Error=3 arrayWithEnum: type: array items: enum: - Success - Warning - Error arrayWithDescription: type: array items: type: integer description: Success=1,Warning=2,Error=3 foo_bar-enum: description: This is a simple enum with strings enum: - Success - Warning - Error - ØÆÅ字符串 ModelWithReference: description: This is a model with one property containing a reference type: object properties: prop: $ref: '#/components/schemas/ModelWithProperties' ModelWithArrayReadOnlyAndWriteOnly: description: This is a model with one property containing an array type: object properties: prop: type: array items: $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' propWithFile: type: array items: format: binary type: string propWithNumber: type: array items: type: number ModelWithArray: description: This is a model with one property containing an array type: object properties: prop: type: array items: $ref: '#/components/schemas/ModelWithString' propWithFile: type: array items: format: binary type: string propWithNumber: type: array items: type: number ModelWithDictionary: description: This is a model with one property containing a dictionary type: object properties: prop: type: object additionalProperties: type: string DeprecatedModel: deprecated: true description: This is a deprecated model with a deprecated property type: object properties: prop: deprecated: true description: This is a deprecated property type: string ModelWithCircularReference: description: This is a model with one property containing a circular reference type: object properties: prop: $ref: '#/components/schemas/ModelWithCircularReference' CompositionWithOneOf: description: This is a model with one property with a 'one of' relationship type: object properties: propA: type: object oneOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithOneOfAnonymous: description: This is a model with one property with a 'one of' relationship where the options are not $ref type: object properties: propA: type: object oneOf: - description: Anonymous object type type: object properties: propA: type: string - description: Anonymous string type type: string - description: Anonymous integer type type: integer ModelCircle: description: Circle type: object required: - kind properties: kind: type: string radius: type: number ModelSquare: description: Square type: object required: - kind properties: kind: type: string sideLength: type: number CompositionWithOneOfDiscriminator: description: This is a model with one property with a 'one of' relationship where the options are not $ref type: object oneOf: - $ref: '#/components/schemas/ModelCircle' - $ref: '#/components/schemas/ModelSquare' discriminator: propertyName: kind mapping: circle: '#/components/schemas/ModelCircle' square: '#/components/schemas/ModelSquare' CompositionWithAnyOf: description: This is a model with one property with a 'any of' relationship type: object properties: propA: type: object anyOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithAnyOfAnonymous: description: This is a model with one property with a 'any of' relationship where the options are not $ref type: object properties: propA: type: object anyOf: - description: Anonymous object type type: object properties: propA: type: string - description: Anonymous string type type: string - description: Anonymous integer type type: integer CompositionWithNestedAnyAndTypeNull: description: This is a model with nested 'any of' property with a type null type: object properties: propA: type: object anyOf: - items: nullable: true allOf: - $ref: '#/components/schemas/ModelWithDictionary' type: array - items: nullable: true allOf: - $ref: '#/components/schemas/ModelWithArray' type: array 3e-num_1Период: enum: - Bird - Dog type: string ConstValue: enum: - ConstValue type: string CompositionWithNestedAnyOfAndNull: description: This is a model with one property with a 'any of' relationship where the options are not $ref type: object properties: propA: nullable: true allOf: - items: anyOf: - $ref: '#/components/schemas/3e-num_1Период' - $ref: '#/components/schemas/ConstValue' type: array title: Scopes CompositionWithOneOfAndNullable: description: This is a model with one property with a 'one of' relationship type: object properties: propA: nullable: true type: object oneOf: - type: object properties: boolean: type: boolean - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithOneOfAndSimpleDictionary: description: This is a model that contains a simple dictionary within composition type: object properties: propA: oneOf: - type: boolean - type: object additionalProperties: type: number CompositionWithOneOfAndSimpleArrayDictionary: description: This is a model that contains a dictionary of simple arrays within composition type: object properties: propA: oneOf: - type: boolean - type: object additionalProperties: type: array items: type: boolean CompositionWithOneOfAndComplexArrayDictionary: description: This is a model that contains a dictionary of complex arrays (composited) within composition type: object properties: propA: oneOf: - type: boolean - type: object additionalProperties: type: array items: oneOf: - type: number - type: string CompositionWithAllOfAndNullable: description: This is a model with one property with a 'all of' relationship type: object properties: propA: nullable: true type: object allOf: - type: object properties: boolean: type: boolean - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithAnyOfAndNullable: description: This is a model with one property with a 'any of' relationship type: object properties: propA: nullable: true type: object anyOf: - type: object properties: boolean: type: boolean - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionBaseModel: description: This is a base model with two simple optional properties type: object properties: firstName: type: string lastname: type: string CompositionExtendedModel: description: This is a model that extends the base model type: object allOf: - $ref: '#/components/schemas/CompositionBaseModel' properties: age: type: number required: - firstName - lastname - age ModelWithProperties: description: This is a model with one nested property type: object required: - required - requiredAndReadOnly - requiredAndNullable properties: required: type: string requiredAndReadOnly: type: string readOnly: true requiredAndNullable: type: string nullable: true string: type: string number: type: number boolean: type: boolean reference: $ref: '#/components/schemas/ModelWithString' property with space: type: string default: type: string try: type: string '@namespace.string': type: string readOnly: true '@namespace.integer': type: integer readOnly: true ModelWithNestedProperties: description: This is a model with one nested property type: object required: - first properties: first: type: object required: - second readOnly: true nullable: true properties: second: type: object required: - third readOnly: true nullable: true properties: third: type: string required: true readOnly: true nullable: true ModelWithDuplicateProperties: description: This is a model with duplicated properties type: object properties: prop: $ref: '#/components/schemas/ModelWithString' ModelWithOrderedProperties: description: This is a model with ordered properties type: object properties: zebra: type: string apple: type: string hawaii: type: string ModelWithDuplicateImports: description: This is a model with duplicated imports type: object properties: propA: $ref: '#/components/schemas/ModelWithString' propB: $ref: '#/components/schemas/ModelWithString' propC: $ref: '#/components/schemas/ModelWithString' ModelThatExtends: description: This is a model that extends another model type: object allOf: - $ref: '#/components/schemas/ModelWithString' - type: object properties: propExtendsA: type: string propExtendsB: $ref: '#/components/schemas/ModelWithString' ModelThatExtendsExtends: description: This is a model that extends another model type: object allOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelThatExtends' - type: object properties: propExtendsC: type: string propExtendsD: $ref: '#/components/schemas/ModelWithString' ModelWithPattern: description: This is a model that contains a some patterns type: object required: - key - name properties: key: maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ type: string name: maxLength: 255 type: string enabled: type: boolean readOnly: true modified: type: string format: date-time readOnly: true id: type: string pattern: ^\d{2}-\d{3}-\d{4}$ text: type: string pattern: ^\w+$ patternWithSingleQuotes: type: string pattern: ^[a-zA-Z0-9']*$ patternWithNewline: type: string pattern: aaa\nbbb patternWithBacktick: type: string pattern: aaa`bbb patternWithUnicode: type: string pattern: ^\p{L}+$ File: required: - mime type: object properties: id: title: Id type: string readOnly: true minLength: 1 updated_at: title: Updated at type: string format: date-time readOnly: true created_at: title: Created at type: string format: date-time readOnly: true mime: title: Mime type: string maxLength: 24 minLength: 1 file: title: File type: string readOnly: true format: uri default: type: object properties: name: type: string Pageable: type: object properties: page: minimum: 0 type: integer format: int32 default: 0 size: minimum: 1 type: integer format: int32 sort: type: array items: type: string FreeFormObjectWithoutAdditionalProperties: description: This is a free-form object without additionalProperties. type: object FreeFormObjectWithAdditionalPropertiesEqTrue: description: 'This is a free-form object with additionalProperties: true.' type: object additionalProperties: true FreeFormObjectWithAdditionalPropertiesEqEmptyObject: description: 'This is a free-form object with additionalProperties: {}.' type: object additionalProperties: {} ModelWithConst: type: object properties: String: enum: - String type: string number: enum: - 0 type: number 'null': nullable: true withType: enum: - Some string type: string ModelWithAdditionalPropertiesEqTrue: description: 'This is a model with one property and additionalProperties: true' type: object properties: prop: description: This is a simple string property type: string additionalProperties: true NestedAnyOfArraysNullable: properties: nullableArray: nullable: true allOf: - items: anyOf: - type: string - type: boolean type: array type: object CompositionWithOneOfAndProperties: type: object oneOf: - type: object required: - foo properties: foo: $ref: '#/components/parameters/SimpleParameter' additionalProperties: false - type: object required: - bar properties: bar: $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' additionalProperties: false required: - baz - qux properties: baz: type: integer format: uint16 minimum: 0 nullable: true qux: type: integer format: uint8 minimum: 0 NullableObject: description: An object that can be null nullable: true type: object properties: foo: type: string default: null CharactersInDescription: type: string description: Some % character ModelWithNullableObject: type: object properties: data: $ref: '#/components/schemas/NullableObject' ModelWithAdditionalPropertiesRef: type: object description: An object with additional properties that can be null additionalProperties: nullable: true allOf: - $ref: '#/components/schemas/NullableObject' ModelWithOneOfEnum: oneOf: - type: object required: - foo properties: foo: type: string enum: - Bar - type: object required: - foo properties: foo: type: string enum: - Baz - type: object required: - foo properties: foo: type: string enum: - Qux - type: object required: - content - foo properties: content: type: string format: date-time foo: type: string enum: - Quux - type: object required: - content - foo properties: content: type: array items: type: string format: date-time maxItems: 2 minItems: 2 foo: type: string enum: - Corge ModelWithNestedArrayEnumsDataFoo: enum: - foo - bar type: string ModelWithNestedArrayEnumsDataBar: enum: - baz - qux type: string ModelWithNestedArrayEnumsData: type: object properties: foo: type: array items: $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' bar: type: array items: $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataBar' ModelWithNestedArrayEnums: type: object properties: array_strings: type: array items: type: string data: allOf: - $ref: '#/components/schemas/ModelWithNestedArrayEnumsData' ModelWithNestedCompositionEnums: type: object properties: foo: allOf: - $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' ModelWithReadOnlyAndWriteOnly: type: object required: - foo - bar - baz properties: foo: type: string bar: readOnly: true type: string baz: type: string writeOnly: true ModelWithConstantSizeArray: type: array items: type: number minItems: 2 maxItems: 2 ModelWithAnyOfConstantSizeArray: type: array items: oneOf: - type: number - type: string minItems: 3 maxItems: 3 ModelWithPrefixItemsConstantSizeArray: type: array items: oneOf: - $ref: '#/components/schemas/ModelWithInteger' - type: number - type: string ModelWithAnyOfConstantSizeArrayNullable: type: array items: oneOf: - type: number nullable: true - type: string minItems: 3 maxItems: 3 ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions: type: array items: oneOf: - type: number - $ref: '#/components/schemas/import' minItems: 2 maxItems: 2 ModelWithAnyOfConstantSizeArrayAndIntersect: type: array items: allOf: - type: number - type: string minItems: 2 maxItems: 2 ModelWithNumericEnumUnion: type: object properties: value: type: number description: Период enum: - -10 - -1 - 0 - 1 - 3 - 6 - 12 ModelWithBackticksInDescription: description: Some description with `back ticks` type: object properties: template: type: string description: >- The template `that` should be used for parsing and importing the contents of the CSV file.

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    
                [
                  {
                    "resourceType": "Asset",
                    "identifier": {
                      "name": "${1}",
                      "domain": {
                        "name": "${2}",
                        "community": {
                          "name": "Some Community"
                        }
                      }
                    },
                    "attributes" : {
                      "00000000-0000-0000-0000-000000003115" : [ {
                        "value" : "${3}"
                      } ],
                      "00000000-0000-0000-0000-000000000222" : [ {
                        "value" : "${4}"
                      } ]
                    }
                  }
                ]
    
                
    ModelWithOneOfAndProperties: type: object oneOf: - $ref: '#/components/parameters/SimpleParameter' - $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' required: - baz - qux properties: baz: type: integer format: uint16 minimum: 0 nullable: true qux: type: integer format: uint8 minimum: 0 ParameterSimpleParameterUnused: description: Model used to test deduplication strategy (unused) type: string PostServiceWithEmptyTagResponse: description: Model used to test deduplication strategy type: string PostServiceWithEmptyTagResponse2: description: Model used to test deduplication strategy type: string DeleteFooData: description: Model used to test deduplication strategy type: string DeleteFooData2: description: Model used to test deduplication strategy type: string import: description: Model with restricted keyword name type: string SchemaWithFormRestrictedKeys: properties: description: type: string x-enum-descriptions: type: string x-enum-varnames: type: string x-enumNames: type: string title: type: string object: type: object properties: description: type: string x-enum-descriptions: type: string x-enum-varnames: type: string x-enumNames: type: string title: type: string array: type: array items: type: object properties: description: type: string x-enum-descriptions: type: string x-enum-varnames: type: string x-enumNames: type: string title: type: string io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions: description: This schema was giving PascalCase transformations a hard time properties: preconditions: allOf: - $ref: '#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions' description: Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. type: object io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions: description: This schema was giving PascalCase transformations a hard time properties: resourceVersion: description: Specifies the target ResourceVersion type: string uid: description: Specifies the target UID. type: string type: object AdditionalPropertiesUnknownIssue: type: object properties: {} additionalProperties: anyOf: - type: string - type: number AdditionalPropertiesUnknownIssue2: type: object additionalProperties: anyOf: - type: string - type: number AdditionalPropertiesUnknownIssue3: type: object allOf: - type: string - type: object required: - entries properties: entries: type: object additionalProperties: $ref: '#/components/schemas/AdditionalPropertiesUnknownIssue' AdditionalPropertiesIntegerIssue: type: object required: - value properties: value: type: integer additionalProperties: type: integer OneOfAllOfIssue: oneOf: - allOf: - oneOf: - $ref: '#/components/schemas/ConstValue' - $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' - $ref: '#/components/schemas/3e-num_1Период' - $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' Generic.Schema.Duplicate.Issue`1[System.Boolean]: type: object properties: item: type: boolean error: type: string nullable: true hasError: type: boolean readOnly: true data: type: object properties: {} additionalProperties: false additionalProperties: false Generic.Schema.Duplicate.Issue`1[System.String]: type: object properties: item: type: string nullable: true error: type: string nullable: true hasError: type: boolean readOnly: true additionalProperties: false ================================================ FILE: specs/3.0.x/internal-name-conflict.json ================================================ { "openapi": "3.0.4", "info": { "title": "OpenAPI 3.0.4 internal name conflict example", "version": "1" }, "paths": { "/foo": { "get": { "operationId": "create__", "responses": { "200": { "description": "OK" } } }, "patch": { "operationId": "create_", "responses": { "200": { "description": "OK" } } }, "post": { "operationId": "create", "responses": { "200": { "description": "OK" } } } } } } ================================================ FILE: specs/3.0.x/invalid/operationId-unique.yaml ================================================ openapi: 3.0.4 info: title: Invalid OpenAPI 3.0.4 operationId unique example version: 1 paths: /foo: get: operationId: foo responses: '200': content: '*/*': schema: type: string description: OK post: operationId: foo responses: '200': content: '*/*': schema: type: string description: OK ================================================ FILE: specs/3.0.x/invalid/servers-array.yaml ================================================ openapi: 3.0.4 info: title: Invalid OpenAPI 3.0.4 servers array example version: 1 servers: foo: bar ================================================ FILE: specs/3.0.x/invalid/servers-entry.yaml ================================================ openapi: 3.0.4 info: title: Invalid OpenAPI 3.0.4 servers entry example version: 1 servers: - foo ================================================ FILE: specs/3.0.x/invalid/servers-required.yaml ================================================ openapi: 3.0.4 info: title: Invalid OpenAPI 3.0.4 servers required example version: 1 servers: - description: missing url ================================================ FILE: specs/3.0.x/operation-204.json ================================================ { "openapi": "3.0.0", "info": { "title": "OpenAPI 3.0.0 operation 204 example", "version": "1" }, "paths": { "/foo": { "post": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "string" } } } }, "204": { "description": "Created" } } } } } } ================================================ FILE: specs/3.0.x/orpc.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 oRPC example version: 1 paths: /users: get: tags: - users operationId: getUsers summary: Get all users parameters: - name: limit in: query description: Maximum number of users to return required: false schema: type: integer default: 10 - name: offset in: query description: Number of users to skip required: false schema: type: integer default: 0 responses: '200': description: List of users content: application/json: schema: type: array items: $ref: '#/components/schemas/User' post: tags: - users operationId: createUser summary: Create a new user requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateUserInput' responses: '201': description: User created content: application/json: schema: $ref: '#/components/schemas/User' /users/{userId}: get: tags: - users operationId: getUserById summary: Get a user by ID parameters: - name: userId in: path description: User ID required: true schema: type: string responses: '200': description: User found content: application/json: schema: $ref: '#/components/schemas/User' put: tags: - users operationId: updateUser summary: Update a user parameters: - name: userId in: path description: User ID required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/UpdateUserInput' responses: '200': description: User updated content: application/json: schema: $ref: '#/components/schemas/User' delete: tags: - users operationId: deleteUser summary: Delete a user parameters: - name: userId in: path description: User ID required: true schema: type: string - name: X-Request-Id in: header description: Request ID for tracing required: false schema: type: string responses: '204': description: User deleted /posts: get: tags: - posts operationId: getPosts summary: Get all posts parameters: - name: authorId in: query description: Filter by author ID required: false schema: type: string - name: status in: query description: Filter by status required: false schema: type: string enum: - draft - published - archived responses: '200': description: List of posts content: application/json: schema: type: array items: $ref: '#/components/schemas/Post' post: tags: - posts operationId: createPost summary: Create a new post parameters: - name: X-Author-Id in: header description: Author ID required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreatePostInput' responses: '201': description: Post created content: application/json: schema: $ref: '#/components/schemas/Post' /posts/{postId}: get: tags: - posts operationId: getPostById summary: Get a post by ID parameters: - name: postId in: path description: Post ID required: true schema: type: string - name: includeComments in: query description: Include comments in response required: false schema: type: boolean default: false responses: '200': description: Post found content: application/json: schema: $ref: '#/components/schemas/Post' components: schemas: User: type: object required: - id - email - name properties: id: type: string email: type: string format: email name: type: string createdAt: type: string format: date-time CreateUserInput: type: object required: - email - name properties: email: type: string format: email name: type: string password: type: string minLength: 8 UpdateUserInput: type: object properties: email: type: string format: email name: type: string Post: type: object required: - id - title - content - authorId properties: id: type: string title: type: string content: type: string authorId: type: string status: type: string enum: - draft - published - archived createdAt: type: string format: date-time CreatePostInput: type: object required: - title - content properties: title: type: string content: type: string status: type: string enum: - draft - published default: draft ================================================ FILE: specs/3.0.x/parameter-explode-false.json ================================================ { "openapi": "3.0.0", "info": { "title": "OpenAPI 3.0.0 parameter explode false example", "version": "1" }, "paths": { "/foo": { "post": { "parameters": [ { "name": "foo", "in": "query", "explode": false, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "default": { "description": "OK" } } } } } } ================================================ FILE: specs/3.0.x/ref-deep.yaml ================================================ openapi: 3.0.0 info: title: OpenAPI 3.0.0 ref deep example version: '1' paths: /foo: get: responses: '200': description: OK content: application/json: schema: type: array items: type: object properties: foo: type: integer bar: type: string post: responses: '200': description: OK content: application/json: schema: type: object properties: foo: $ref: '#/paths/~1foo/get/responses/200/content/application~1json/schema/items' bar: type: string components: schemas: Foo: type: object properties: foo: type: array items: type: object properties: baz: type: string bar: type: array items: type: object properties: baz: type: string Bar: type: object properties: foo: type: array items: $ref: '#/components/schemas/Foo/properties/foo/items' bar: type: array items: $ref: '#/components/schemas/Foo/properties/bar/items' ================================================ FILE: specs/3.0.x/ref-duplicate-url.yaml ================================================ openapi: 3.0.3 info: title: OpenAPI 3.0.3 $ref duplicate URL example version: 1 paths: /a: get: responses: default: description: OK content: application/json: schema: $ref: './enum-escape.json#/components/schemas/Foo' /b: get: responses: default: description: OK content: application/json: schema: $ref: './enum-escape.json#/components/schemas/Foo' ================================================ FILE: specs/3.0.x/sdk-instance.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 sdk instance example version: 1 paths: /foo: get: tags: - fooBaz responses: '200': content: '*/*': schema: type: string description: OK post: tags: - fooBaz operationId: foo.-post responses: '200': content: '*/*': schema: type: string description: OK put: tags: - fooBaz operationId: /foo/-put/ responses: '200': content: '*/*': schema: type: string description: OK /foo/bar: get: tags: - barBaz responses: '200': content: '*/*': schema: type: string description: OK post: tags: - fooBaz - barBaz operationId: foo.bar.post responses: '200': content: '*/*': schema: type: string description: OK put: tags: - fooBaz - barBaz operationId: /foo/bar/put/ responses: '200': content: '*/*': schema: type: string description: OK ================================================ FILE: specs/3.0.x/sdk-method-class-conflict.yaml ================================================ openapi: 3.0.4 info: title: Internal API description: Internal API version: 1.0-0.0.0 paths: /api/v1/accounting-companies: post: tags: - AccountingCompanies requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/xml: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' text/plain: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/json-patch+json: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' text/json: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' application/*+json: schema: $ref: '#/components/schemas/AccountingCompanyCreateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/xml: schema: $ref: '#/components/schemas/AccountingCompany' text/plain: schema: $ref: '#/components/schemas/AccountingCompany' application/octet-stream: schema: $ref: '#/components/schemas/AccountingCompany' text/json: schema: $ref: '#/components/schemas/AccountingCompany' /api/v1/accounting-companies/{id}: post: tags: - AccountingCompanies parameters: - name: id in: path required: true schema: type: integer format: int32 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/xml: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' text/plain: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' text/json: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' application/*+json: schema: $ref: '#/components/schemas/AccountingCompanyUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompany' application/xml: schema: $ref: '#/components/schemas/AccountingCompany' text/plain: schema: $ref: '#/components/schemas/AccountingCompany' application/octet-stream: schema: $ref: '#/components/schemas/AccountingCompany' text/json: schema: $ref: '#/components/schemas/AccountingCompany' delete: tags: - AccountingCompanies parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK /api/v1/odata/AccountingCompanies: get: tags: - AccountingCompanies operationId: api/v{version:apiVersion}/odata/AccountingCompanies parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/xml: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' text/plain: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' text/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' /api/v1/odata/AccountingCompanies/$count: get: tags: - AccountingCompanies operationId: api/v{version:apiVersion}/odata/AccountingCompanies/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/xml: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' text/plain: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' text/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompany' /api/v1/accounting-company-memberships: put: tags: - AccountingCompanyMemberships requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/xml: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' text/plain: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/json-patch+json: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' text/json: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' application/*+json: schema: $ref: '#/components/schemas/AccountingCompanyMembershipUpsertDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/xml: schema: $ref: '#/components/schemas/AccountingCompanyMembership' text/plain: schema: $ref: '#/components/schemas/AccountingCompanyMembership' application/octet-stream: schema: $ref: '#/components/schemas/AccountingCompanyMembership' text/json: schema: $ref: '#/components/schemas/AccountingCompanyMembership' /api/v1/accounting-company-memberships/{id}: delete: tags: - AccountingCompanyMemberships parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK /api/v1/odata/AccountingCompanyMemberships: get: tags: - AccountingCompanyMemberships operationId: api/v{version:apiVersion}/odata/AccountingCompanyMemberships parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/xml: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' text/plain: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' text/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' /api/v1/odata/AccountingCompanyMemberships/$count: get: tags: - AccountingCompanyMemberships operationId: api/v{version:apiVersion}/odata/AccountingCompanyMemberships/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/xml: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' text/plain: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' text/json: schema: type: array items: $ref: '#/components/schemas/AccountingCompanyMembership' /api/v1/bank-accounts: put: tags: - BankAccounts requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/xml: schema: $ref: '#/components/schemas/BankAccountUpsertDto' text/plain: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/json-patch+json: schema: $ref: '#/components/schemas/BankAccountUpsertDto' text/json: schema: $ref: '#/components/schemas/BankAccountUpsertDto' application/*+json: schema: $ref: '#/components/schemas/BankAccountUpsertDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BankAccount' application/json: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BankAccount' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BankAccount' application/xml: schema: $ref: '#/components/schemas/BankAccount' text/plain: schema: $ref: '#/components/schemas/BankAccount' application/octet-stream: schema: $ref: '#/components/schemas/BankAccount' text/json: schema: $ref: '#/components/schemas/BankAccount' /api/v1/bank-accounts/{id}: delete: tags: - BankAccounts parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK /api/v1/odata/BankAccounts: get: tags: - BankAccounts operationId: api/v{version:apiVersion}/odata/BankAccounts parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/xml: schema: type: array items: $ref: '#/components/schemas/BankAccount' text/plain: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BankAccount' text/json: schema: type: array items: $ref: '#/components/schemas/BankAccount' /api/v1/odata/BankAccounts/$count: get: tags: - BankAccounts operationId: api/v{version:apiVersion}/odata/BankAccounts/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/xml: schema: type: array items: $ref: '#/components/schemas/BankAccount' text/plain: schema: type: array items: $ref: '#/components/schemas/BankAccount' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BankAccount' text/json: schema: type: array items: $ref: '#/components/schemas/BankAccount' /api/v1/business-accountant-assignments: put: tags: - BusinessAccountantAssignments requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/xml: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' text/plain: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/json-patch+json: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' text/json: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' application/*+json: schema: $ref: '#/components/schemas/BusinessAccountantAssignmentUpsert' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/xml: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' text/plain: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' application/octet-stream: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' text/json: schema: $ref: '#/components/schemas/BusinessAccountantAssignment' /api/v1/business-accountant-assignments/{id}: delete: tags: - BusinessAccountantAssignments parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK /api/v1/odata/BusinessAccountantAssignments: get: tags: - BusinessAccountantAssignments operationId: api/v{version:apiVersion}/odata/BusinessAccountantAssignments parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/xml: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' text/plain: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' text/json: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' /api/v1/odata/BusinessAccountantAssignments/$count: get: tags: - BusinessAccountantAssignments operationId: api/v{version:apiVersion}/odata/BusinessAccountantAssignments/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/xml: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' text/plain: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' text/json: schema: type: array items: $ref: '#/components/schemas/BusinessAccountantAssignment' /api/v1/business-documents/{id}/raw: get: tags: - BusinessDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK '204': description: No Content /api/v1/business-documents: post: tags: - BusinessDocuments requestBody: content: multipart/form-data: schema: required: - BusinessId - DocumentName - DocumentTypeId - File - TaskId type: object properties: BusinessId: type: integer format: int32 DocumentTypeId: type: integer format: int32 File: type: string format: binary DocumentName: maxLength: 255 type: string TaskId: type: integer format: int64 encoding: BusinessId: style: form DocumentTypeId: style: form File: style: form DocumentName: style: form TaskId: style: form responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: $ref: '#/components/schemas/DocumentBusiness' /api/v1/business-documents/{id}: put: tags: - BusinessDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/xml: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' text/plain: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' text/json: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' application/*+json: schema: $ref: '#/components/schemas/BusinessDocumentUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: $ref: '#/components/schemas/DocumentBusiness' delete: tags: - BusinessDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: $ref: '#/components/schemas/DocumentBusiness' /api/v1/business-documents/{id}/approve: post: tags: - BusinessDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: $ref: '#/components/schemas/DocumentBusiness' /api/v1/business-documents/{id}/unapprove: post: tags: - BusinessDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: $ref: '#/components/schemas/DocumentBusiness' /api/v1/business-documents/{id}/move-to-personal: post: tags: - BusinessDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK /api/v1/business-documents/{id}/move-to-business: post: tags: - BusinessDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/xml: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' text/plain: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/json-patch+json: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' text/json: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' application/*+json: schema: $ref: '#/components/schemas/BusinessDocumentMoveToBusinessDocumentsDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: $ref: '#/components/schemas/DocumentBusiness' /api/v1/odata/BusinessDocumentActivities: get: tags: - BusinessDocuments operationId: api/v{version:apiVersion}/odata/BusinessDocumentActivities parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' /api/v1/odata/BusinessDocumentActivities/$count: get: tags: - BusinessDocuments operationId: api/v{version:apiVersion}/odata/BusinessDocumentActivities/$count parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusinessActivity' /api/v1/odata/BusinessDocuments: get: tags: - BusinessDocuments operationId: api/v{version:apiVersion}/odata/BusinessDocuments parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' /api/v1/odata/BusinessDocuments/$count: get: tags: - BusinessDocuments operationId: api/v{version:apiVersion}/odata/BusinessDocuments/$count parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' /api/v1/odata/BusinessDocumentsSummaries: get: tags: - BusinessDocumentsSummaries operationId: api/v{version:apiVersion}/odata/BusinessDocumentsSummaries parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/xml: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' text/plain: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' text/json: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' deprecated: true /api/v1/odata/BusinessDocumentsSummaries/$count: get: tags: - BusinessDocumentsSummaries operationId: api/v{version:apiVersion}/odata/BusinessDocumentsSummaries/$count parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/xml: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' text/plain: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' text/json: schema: type: array items: $ref: '#/components/schemas/BusinessDocumentsSummary' deprecated: true /api/v1/businesses/{id}/document-types-summary: get: tags: - Businesses parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentTypesSummary' /api/v1/businesses: post: tags: - Businesses requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessCreateDto' application/xml: schema: $ref: '#/components/schemas/BusinessCreateDto' text/plain: schema: $ref: '#/components/schemas/BusinessCreateDto' application/json-patch+json: schema: $ref: '#/components/schemas/BusinessCreateDto' text/json: schema: $ref: '#/components/schemas/BusinessCreateDto' application/*+json: schema: $ref: '#/components/schemas/BusinessCreateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/xml: schema: $ref: '#/components/schemas/Business' text/plain: schema: $ref: '#/components/schemas/Business' application/octet-stream: schema: $ref: '#/components/schemas/Business' text/json: schema: $ref: '#/components/schemas/Business' /api/v1/businesses/{id}: put: tags: - Businesses parameters: - name: id in: path required: true schema: type: integer format: int32 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/xml: schema: $ref: '#/components/schemas/BusinessUpdateDto' text/plain: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/BusinessUpdateDto' text/json: schema: $ref: '#/components/schemas/BusinessUpdateDto' application/*+json: schema: $ref: '#/components/schemas/BusinessUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/xml: schema: $ref: '#/components/schemas/Business' text/plain: schema: $ref: '#/components/schemas/Business' application/octet-stream: schema: $ref: '#/components/schemas/Business' text/json: schema: $ref: '#/components/schemas/Business' delete: tags: - Businesses parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK /api/v1/businesses/{id}/contact: put: tags: - Businesses parameters: - name: id in: path required: true schema: type: integer format: int32 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/xml: schema: $ref: '#/components/schemas/BusinessChangeContactDto' text/plain: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/json-patch+json: schema: $ref: '#/components/schemas/BusinessChangeContactDto' text/json: schema: $ref: '#/components/schemas/BusinessChangeContactDto' application/*+json: schema: $ref: '#/components/schemas/BusinessChangeContactDto' responses: '200': description: OK /api/v1/businesses/{id}/disconnect: post: tags: - Businesses parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/xml: schema: $ref: '#/components/schemas/Business' text/plain: schema: $ref: '#/components/schemas/Business' application/octet-stream: schema: $ref: '#/components/schemas/Business' text/json: schema: $ref: '#/components/schemas/Business' /api/v1/odata/Businesses: get: tags: - Businesses operationId: api/v{version:apiVersion}/odata/Businesses parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/xml: schema: type: array items: $ref: '#/components/schemas/Business' text/plain: schema: type: array items: $ref: '#/components/schemas/Business' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Business' text/json: schema: type: array items: $ref: '#/components/schemas/Business' /api/v1/odata/Businesses/$count: get: tags: - Businesses operationId: api/v{version:apiVersion}/odata/Businesses/$count parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Business' application/xml: schema: type: array items: $ref: '#/components/schemas/Business' text/plain: schema: type: array items: $ref: '#/components/schemas/Business' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Business' text/json: schema: type: array items: $ref: '#/components/schemas/Business' /api/v1/odata/Businesses({key}): get: tags: - Businesses operationId: api/v{version:apiVersion}/odata/Businesses({key}) parameters: - name: key in: query schema: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/xml: schema: $ref: '#/components/schemas/Business' text/plain: schema: $ref: '#/components/schemas/Business' application/octet-stream: schema: $ref: '#/components/schemas/Business' text/json: schema: $ref: '#/components/schemas/Business' /api/v1/odata/Businesses/{key}: get: tags: - Businesses operationId: api/v{version:apiVersion}/odata/Businesses/{key} parameters: - name: key in: query schema: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Business' application/json: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Business' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Business' application/xml: schema: $ref: '#/components/schemas/Business' text/plain: schema: $ref: '#/components/schemas/Business' application/octet-stream: schema: $ref: '#/components/schemas/Business' text/json: schema: $ref: '#/components/schemas/Business' /api/v1/business-memberships: put: tags: - BusinessesMemberships requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/xml: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' text/plain: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/json-patch+json: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' text/json: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' application/*+json: schema: $ref: '#/components/schemas/BusinessMembershipUpsertDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/xml: schema: $ref: '#/components/schemas/BusinessMembershipDto' text/plain: schema: $ref: '#/components/schemas/BusinessMembershipDto' application/octet-stream: schema: $ref: '#/components/schemas/BusinessMembershipDto' text/json: schema: $ref: '#/components/schemas/BusinessMembershipDto' /api/v1/odata/BusinessSummaries: get: tags: - BusinessSummaries operationId: api/v{version:apiVersion}/odata/BusinessSummaries parameters: - name: role in: query schema: type: string - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/xml: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' text/plain: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' text/json: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' /api/v1/odata/BusinessSummaries/$count: get: tags: - BusinessSummaries operationId: api/v{version:apiVersion}/odata/BusinessSummaries/$count parameters: - name: role in: query schema: type: string - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/xml: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' text/plain: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' text/json: schema: type: array items: $ref: '#/components/schemas/BusinessSummary' /api/v1/counterparties: post: tags: - Counterparties requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/xml: schema: $ref: '#/components/schemas/CounterpartyCreateDto' text/plain: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/json-patch+json: schema: $ref: '#/components/schemas/CounterpartyCreateDto' text/json: schema: $ref: '#/components/schemas/CounterpartyCreateDto' application/*+json: schema: $ref: '#/components/schemas/CounterpartyCreateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/xml: schema: $ref: '#/components/schemas/Counterparty' text/plain: schema: $ref: '#/components/schemas/Counterparty' application/octet-stream: schema: $ref: '#/components/schemas/Counterparty' text/json: schema: $ref: '#/components/schemas/Counterparty' /api/v1/counterparties/{id}: patch: tags: - Counterparties parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/xml: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' text/plain: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' text/json: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' application/*+json: schema: $ref: '#/components/schemas/CounterpartyUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Counterparty' application/json: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Counterparty' application/xml: schema: $ref: '#/components/schemas/Counterparty' text/plain: schema: $ref: '#/components/schemas/Counterparty' application/octet-stream: schema: $ref: '#/components/schemas/Counterparty' text/json: schema: $ref: '#/components/schemas/Counterparty' delete: tags: - Counterparties parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK /api/v1/odata/Counterparties: get: tags: - Counterparties operationId: api/v{version:apiVersion}/odata/Counterparties parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/xml: schema: type: array items: $ref: '#/components/schemas/Counterparty' text/plain: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Counterparty' text/json: schema: type: array items: $ref: '#/components/schemas/Counterparty' /api/v1/odata/Counterparties/$count: get: tags: - Counterparties operationId: api/v{version:apiVersion}/odata/Counterparties/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/xml: schema: type: array items: $ref: '#/components/schemas/Counterparty' text/plain: schema: type: array items: $ref: '#/components/schemas/Counterparty' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Counterparty' text/json: schema: type: array items: $ref: '#/components/schemas/Counterparty' /api/v1/data-box-credentials: put: tags: - DataBoxCredentials requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/xml: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' text/plain: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/json-patch+json: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' text/json: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' application/*+json: schema: $ref: '#/components/schemas/DataBoxCredentialsUpsertDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DataBoxCredentials' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DataBoxCredentials' application/xml: schema: $ref: '#/components/schemas/DataBoxCredentials' text/plain: schema: $ref: '#/components/schemas/DataBoxCredentials' application/octet-stream: schema: $ref: '#/components/schemas/DataBoxCredentials' text/json: schema: $ref: '#/components/schemas/DataBoxCredentials' /api/v1/data-box-credentials/{id}: delete: tags: - DataBoxCredentials parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK /api/v1/odata/DataBoxCredentials: get: tags: - DataBoxCredentials operationId: api/v{version:apiVersion}/odata/DataBoxCredentials parameters: - name: includePassword in: query schema: type: boolean - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/xml: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' text/plain: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' text/json: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' /api/v1/odata/DataBoxCredentials/$count: get: tags: - DataBoxCredentials operationId: api/v{version:apiVersion}/odata/DataBoxCredentials/$count parameters: - name: includePassword in: query schema: type: boolean - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/xml: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' text/plain: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' text/json: schema: type: array items: $ref: '#/components/schemas/DataBoxCredentials' /api/dev: get: tags: - Dev responses: '200': description: OK /api/dev/reseed-db: get: tags: - Dev responses: '200': description: OK /api/dev/db-reset: get: tags: - Dev responses: '200': description: OK /api/dev/db/reset: get: tags: - Dev responses: '200': description: OK /api/dev/db/create: get: tags: - Dev responses: '200': description: OK /api/dev/db/touch: get: tags: - Dev responses: '200': description: OK /api/dev/seed: get: tags: - Dev responses: '200': description: OK /api/dev/seed-all: get: tags: - Dev responses: '200': description: OK /api/dev/seed-prod: get: tags: - Dev responses: '200': description: OK /api/dev/job/process-recurring-tasks: get: tags: - Dev parameters: - name: refDay in: query schema: type: string format: date responses: '200': description: OK /api/dev/notifications/send-test: get: tags: - Dev parameters: - name: userId in: query schema: type: integer format: int32 default: 1 responses: '200': description: OK /api/dev/confirm-email: get: tags: - Dev parameters: - name: email in: query schema: type: string format: email responses: '200': description: OK /api/dev/email/send-test: get: tags: - Dev parameters: - name: to in: query schema: type: string - name: subject in: query schema: type: string - name: message in: query schema: type: string responses: '200': description: OK /api/v1/notifications/device-tokens: put: tags: - DeviceTokens requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/xml: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' text/plain: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/json-patch+json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' text/json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' application/*+json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenUpsertDto' responses: '200': description: OK delete: tags: - DeviceTokens requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/xml: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' text/plain: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/json-patch+json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' text/json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' application/*+json: schema: $ref: '#/components/schemas/NotificationsDeviceTokenDeleteDto' responses: '200': description: OK /api/v1/odata/DocumentTypes: get: tags: - DocumentTypes operationId: api/v{version:apiVersion}/odata/DocumentTypes parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentType' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentType' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentType' /api/v1/odata/DocumentTypes/$count: get: tags: - DocumentTypes operationId: api/v{version:apiVersion}/odata/DocumentTypes/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentType' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentType' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentType' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentType' /api/v1/feedback: post: tags: - Feedback requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/xml: schema: $ref: '#/components/schemas/SendFeedbackRequest' text/plain: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/json-patch+json: schema: $ref: '#/components/schemas/SendFeedbackRequest' text/json: schema: $ref: '#/components/schemas/SendFeedbackRequest' application/*+json: schema: $ref: '#/components/schemas/SendFeedbackRequest' responses: '200': description: OK /api/v1/invitations: post: tags: - Invitations requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationCreateDto' application/xml: schema: $ref: '#/components/schemas/InvitationCreateDto' text/plain: schema: $ref: '#/components/schemas/InvitationCreateDto' application/json-patch+json: schema: $ref: '#/components/schemas/InvitationCreateDto' text/json: schema: $ref: '#/components/schemas/InvitationCreateDto' application/*+json: schema: $ref: '#/components/schemas/InvitationCreateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/xml: schema: $ref: '#/components/schemas/Invitation' text/plain: schema: $ref: '#/components/schemas/Invitation' application/octet-stream: schema: $ref: '#/components/schemas/Invitation' text/json: schema: $ref: '#/components/schemas/Invitation' /api/v1/invitations/{id}/accept: post: tags: - Invitations parameters: - name: id in: path required: true schema: type: integer format: int32 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/xml: schema: $ref: '#/components/schemas/InvitationAcceptDto' text/plain: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/json-patch+json: schema: $ref: '#/components/schemas/InvitationAcceptDto' text/json: schema: $ref: '#/components/schemas/InvitationAcceptDto' application/*+json: schema: $ref: '#/components/schemas/InvitationAcceptDto' responses: '200': description: OK /api/v1/invitations/{id}/reject: post: tags: - Invitations parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK /api/v1/invitations/{id}: delete: tags: - Invitations parameters: - name: id in: path required: true schema: type: integer format: int32 responses: '200': description: OK patch: tags: - Invitations parameters: - name: id in: path required: true schema: type: integer format: int32 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/xml: schema: $ref: '#/components/schemas/InvitationUpdateDto' text/plain: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/InvitationUpdateDto' text/json: schema: $ref: '#/components/schemas/InvitationUpdateDto' application/*+json: schema: $ref: '#/components/schemas/InvitationUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Invitation' application/json: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invitation' application/xml: schema: $ref: '#/components/schemas/Invitation' text/plain: schema: $ref: '#/components/schemas/Invitation' application/octet-stream: schema: $ref: '#/components/schemas/Invitation' text/json: schema: $ref: '#/components/schemas/Invitation' /api/v1/odata/Invitations: get: tags: - Invitations operationId: api/v{version:apiVersion}/odata/Invitations parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/xml: schema: type: array items: $ref: '#/components/schemas/Invitation' text/plain: schema: type: array items: $ref: '#/components/schemas/Invitation' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Invitation' text/json: schema: type: array items: $ref: '#/components/schemas/Invitation' /api/v1/odata/Invitations/$count: get: tags: - Invitations operationId: api/v{version:apiVersion}/odata/Invitations/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invitation' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invitation' application/xml: schema: type: array items: $ref: '#/components/schemas/Invitation' text/plain: schema: type: array items: $ref: '#/components/schemas/Invitation' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Invitation' text/json: schema: type: array items: $ref: '#/components/schemas/Invitation' /api/v1/invoices: post: tags: - Invoices requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/xml: schema: $ref: '#/components/schemas/InvoiceCreateDto' text/plain: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/json-patch+json: schema: $ref: '#/components/schemas/InvoiceCreateDto' text/json: schema: $ref: '#/components/schemas/InvoiceCreateDto' application/*+json: schema: $ref: '#/components/schemas/InvoiceCreateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/xml: schema: $ref: '#/components/schemas/Invoice' text/plain: schema: $ref: '#/components/schemas/Invoice' application/octet-stream: schema: $ref: '#/components/schemas/Invoice' text/json: schema: $ref: '#/components/schemas/Invoice' /api/v1/invoices/{id}: patch: tags: - Invoices parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/xml: schema: $ref: '#/components/schemas/InvoiceUpdateDto' text/plain: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/InvoiceUpdateDto' text/json: schema: $ref: '#/components/schemas/InvoiceUpdateDto' application/*+json: schema: $ref: '#/components/schemas/InvoiceUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/xml: schema: $ref: '#/components/schemas/Invoice' text/plain: schema: $ref: '#/components/schemas/Invoice' application/octet-stream: schema: $ref: '#/components/schemas/Invoice' text/json: schema: $ref: '#/components/schemas/Invoice' delete: tags: - Invoices parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK /api/v1/invoices/{id}/preview: get: tags: - Invoices parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK /api/v1/invoices/{id}/send: post: tags: - Invoices parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSendDto' application/xml: schema: $ref: '#/components/schemas/InvoiceSendDto' text/plain: schema: $ref: '#/components/schemas/InvoiceSendDto' application/json-patch+json: schema: $ref: '#/components/schemas/InvoiceSendDto' text/json: schema: $ref: '#/components/schemas/InvoiceSendDto' application/*+json: schema: $ref: '#/components/schemas/InvoiceSendDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/xml: schema: $ref: '#/components/schemas/Invoice' text/plain: schema: $ref: '#/components/schemas/Invoice' application/octet-stream: schema: $ref: '#/components/schemas/Invoice' text/json: schema: $ref: '#/components/schemas/Invoice' /api/v1/invoices/{id}/snapshot: post: tags: - Invoices parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Invoice' application/json: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Invoice' application/xml: schema: $ref: '#/components/schemas/Invoice' text/plain: schema: $ref: '#/components/schemas/Invoice' application/octet-stream: schema: $ref: '#/components/schemas/Invoice' text/json: schema: $ref: '#/components/schemas/Invoice' /api/v1/odata/Invoices: get: tags: - Invoices operationId: api/v{version:apiVersion}/odata/Invoices parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/xml: schema: type: array items: $ref: '#/components/schemas/Invoice' text/plain: schema: type: array items: $ref: '#/components/schemas/Invoice' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Invoice' text/json: schema: type: array items: $ref: '#/components/schemas/Invoice' /api/v1/odata/Invoices/$count: get: tags: - Invoices operationId: api/v{version:apiVersion}/odata/Invoices/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Invoice' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Invoice' application/xml: schema: type: array items: $ref: '#/components/schemas/Invoice' text/plain: schema: type: array items: $ref: '#/components/schemas/Invoice' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Invoice' text/json: schema: type: array items: $ref: '#/components/schemas/Invoice' /api/v1/invoice-settings: put: tags: - InvoiceSettings requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/xml: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' text/plain: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/json-patch+json: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' text/json: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' application/*+json: schema: $ref: '#/components/schemas/InvoiceSettingUpsertDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/InvoiceSetting' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/InvoiceSetting' application/xml: schema: $ref: '#/components/schemas/InvoiceSetting' text/plain: schema: $ref: '#/components/schemas/InvoiceSetting' application/octet-stream: schema: $ref: '#/components/schemas/InvoiceSetting' text/json: schema: $ref: '#/components/schemas/InvoiceSetting' /api/v1/odata/InvoiceSettings: get: tags: - InvoiceSettings operationId: api/v{version:apiVersion}/odata/InvoiceSettings parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/xml: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' text/plain: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' text/json: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' /api/v1/odata/InvoiceSettings/$count: get: tags: - InvoiceSettings operationId: api/v{version:apiVersion}/odata/InvoiceSettings/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/xml: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' text/plain: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' text/json: schema: type: array items: $ref: '#/components/schemas/InvoiceSetting' /api/v1/odata/Licenses: get: tags: - Licenses operationId: api/v{version:apiVersion}/odata/Licenses parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/xml: schema: type: array items: $ref: '#/components/schemas/LicenseDto' text/plain: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/LicenseDto' text/json: schema: type: array items: $ref: '#/components/schemas/LicenseDto' /api/v1/odata/Licenses/$count: get: tags: - Licenses operationId: api/v{version:apiVersion}/odata/Licenses/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/xml: schema: type: array items: $ref: '#/components/schemas/LicenseDto' text/plain: schema: type: array items: $ref: '#/components/schemas/LicenseDto' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/LicenseDto' text/json: schema: type: array items: $ref: '#/components/schemas/LicenseDto' /api/v1/notifications/test: post: tags: - Notifications requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/xml: schema: $ref: '#/components/schemas/NotificationsTestSendDto' text/plain: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/json-patch+json: schema: $ref: '#/components/schemas/NotificationsTestSendDto' text/json: schema: $ref: '#/components/schemas/NotificationsTestSendDto' application/*+json: schema: $ref: '#/components/schemas/NotificationsTestSendDto' responses: '200': description: OK /api/v1/personal-documents/{id}/raw: get: tags: - PersonalDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK '204': description: No Content /api/v1/personal-documents: post: tags: - PersonalDocuments requestBody: content: multipart/form-data: schema: required: - DocumentName - File type: object properties: File: type: string format: binary DocumentName: maxLength: 255 type: string encoding: File: style: form DocumentName: style: form responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/xml: schema: $ref: '#/components/schemas/DocumentPersonal' text/plain: schema: $ref: '#/components/schemas/DocumentPersonal' application/octet-stream: schema: $ref: '#/components/schemas/DocumentPersonal' text/json: schema: $ref: '#/components/schemas/DocumentPersonal' /api/v1/personal-documents/{id}/move-to-business: post: tags: - PersonalDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/xml: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' text/plain: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/json-patch+json: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' text/json: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' application/*+json: schema: $ref: '#/components/schemas/DocumentPersonalMoveToBusinessDocumentsDto' responses: '200': description: OK /api/v1/personal-documents/{id}: delete: tags: - PersonalDocuments parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/DocumentPersonal' application/xml: schema: $ref: '#/components/schemas/DocumentPersonal' text/plain: schema: $ref: '#/components/schemas/DocumentPersonal' application/octet-stream: schema: $ref: '#/components/schemas/DocumentPersonal' text/json: schema: $ref: '#/components/schemas/DocumentPersonal' /api/v1/personal-documents/summary: get: tags: - PersonalDocuments responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/xml: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' text/plain: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/octet-stream: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' text/json: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' /api/v1/odata/PersonalDocuments: get: tags: - PersonalDocuments operationId: api/v{version:apiVersion}/odata/PersonalDocuments parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' /api/v1/odata/PersonalDocuments/$count: get: tags: - PersonalDocuments operationId: api/v{version:apiVersion}/odata/PersonalDocuments/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentPersonal' /api/v1/recurring-tasks: post: tags: - RecurringTasks requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/xml: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' text/plain: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/json-patch+json: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' text/json: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' application/*+json: schema: $ref: '#/components/schemas/RecurringTaskCreateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/xml: schema: $ref: '#/components/schemas/RecurringTask' text/plain: schema: $ref: '#/components/schemas/RecurringTask' application/octet-stream: schema: $ref: '#/components/schemas/RecurringTask' text/json: schema: $ref: '#/components/schemas/RecurringTask' /api/v1/recurring-tasks/{id}: patch: tags: - RecurringTasks parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/xml: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' text/plain: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' text/json: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' application/*+json: schema: $ref: '#/components/schemas/RecurringTaskUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/RecurringTask' application/json: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/RecurringTask' application/xml: schema: $ref: '#/components/schemas/RecurringTask' text/plain: schema: $ref: '#/components/schemas/RecurringTask' application/octet-stream: schema: $ref: '#/components/schemas/RecurringTask' text/json: schema: $ref: '#/components/schemas/RecurringTask' delete: tags: - RecurringTasks parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK /api/v1/odata/RecurringTasks: get: tags: - RecurringTasks operationId: api/v{version:apiVersion}/odata/RecurringTasks parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/xml: schema: type: array items: $ref: '#/components/schemas/RecurringTask' text/plain: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/RecurringTask' text/json: schema: type: array items: $ref: '#/components/schemas/RecurringTask' /api/v1/odata/RecurringTasks/$count: get: tags: - RecurringTasks operationId: api/v{version:apiVersion}/odata/RecurringTasks/$count parameters: - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/xml: schema: type: array items: $ref: '#/components/schemas/RecurringTask' text/plain: schema: type: array items: $ref: '#/components/schemas/RecurringTask' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/RecurringTask' text/json: schema: type: array items: $ref: '#/components/schemas/RecurringTask' /: get: tags: - Root responses: '200': description: OK /api/v1/tasks: post: tags: - Tasks requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TasksCreateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TasksCreateDto' application/xml: schema: $ref: '#/components/schemas/TasksCreateDto' text/plain: schema: $ref: '#/components/schemas/TasksCreateDto' application/json-patch+json: schema: $ref: '#/components/schemas/TasksCreateDto' text/json: schema: $ref: '#/components/schemas/TasksCreateDto' application/*+json: schema: $ref: '#/components/schemas/TasksCreateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/xml: schema: type: array items: $ref: '#/components/schemas/Task' text/plain: schema: type: array items: $ref: '#/components/schemas/Task' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Task' text/json: schema: type: array items: $ref: '#/components/schemas/Task' /api/v1/tasks/{id}: put: tags: - Tasks parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskUpdateDto' application/xml: schema: $ref: '#/components/schemas/TaskUpdateDto' text/plain: schema: $ref: '#/components/schemas/TaskUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/TaskUpdateDto' text/json: schema: $ref: '#/components/schemas/TaskUpdateDto' application/*+json: schema: $ref: '#/components/schemas/TaskUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/xml: schema: $ref: '#/components/schemas/Task' text/plain: schema: $ref: '#/components/schemas/Task' application/octet-stream: schema: $ref: '#/components/schemas/Task' text/json: schema: $ref: '#/components/schemas/Task' /api/v1/tasks/{id}/submit: post: tags: - Tasks parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskSubmitDto' application/xml: schema: $ref: '#/components/schemas/TaskSubmitDto' text/plain: schema: $ref: '#/components/schemas/TaskSubmitDto' application/json-patch+json: schema: $ref: '#/components/schemas/TaskSubmitDto' text/json: schema: $ref: '#/components/schemas/TaskSubmitDto' application/*+json: schema: $ref: '#/components/schemas/TaskSubmitDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/xml: schema: $ref: '#/components/schemas/Task' text/plain: schema: $ref: '#/components/schemas/Task' application/octet-stream: schema: $ref: '#/components/schemas/Task' text/json: schema: $ref: '#/components/schemas/Task' /api/v1/tasks/{id}/approve: post: tags: - Tasks parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/xml: schema: $ref: '#/components/schemas/Task' text/plain: schema: $ref: '#/components/schemas/Task' application/octet-stream: schema: $ref: '#/components/schemas/Task' text/json: schema: $ref: '#/components/schemas/Task' /api/v1/tasks/{id}/reject: post: tags: - Tasks parameters: - name: id in: path required: true schema: type: integer format: int64 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/TaskRejectDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/TaskRejectDto' application/xml: schema: $ref: '#/components/schemas/TaskRejectDto' text/plain: schema: $ref: '#/components/schemas/TaskRejectDto' application/json-patch+json: schema: $ref: '#/components/schemas/TaskRejectDto' text/json: schema: $ref: '#/components/schemas/TaskRejectDto' application/*+json: schema: $ref: '#/components/schemas/TaskRejectDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/xml: schema: $ref: '#/components/schemas/Task' text/plain: schema: $ref: '#/components/schemas/Task' application/octet-stream: schema: $ref: '#/components/schemas/Task' text/json: schema: $ref: '#/components/schemas/Task' /api/v1/tasks/{id}/comments: get: tags: - Tasks parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/xml: schema: type: array items: $ref: '#/components/schemas/TaskComment' text/plain: schema: type: array items: $ref: '#/components/schemas/TaskComment' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/TaskComment' text/json: schema: type: array items: $ref: '#/components/schemas/TaskComment' /api/v1/tasks/{id}/documents: get: tags: - Tasks parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/xml: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' text/plain: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' text/json: schema: type: array items: $ref: '#/components/schemas/DocumentBusiness' /api/v1/odata/Tasks: get: tags: - Tasks operationId: api/v{version:apiVersion}/odata/Tasks parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/xml: schema: type: array items: $ref: '#/components/schemas/Task' text/plain: schema: type: array items: $ref: '#/components/schemas/Task' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Task' text/json: schema: type: array items: $ref: '#/components/schemas/Task' /api/v1/odata/Tasks/$count: get: tags: - Tasks operationId: api/v{version:apiVersion}/odata/Tasks/$count parameters: - name: accountants in: query schema: type: array items: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string - name: filter in: query description: 'Restricts the set of items returned. The maximum number of expressions is 100. The allowed functions are: allfunctions.' schema: type: string - name: orderby in: query description: Specifies the order in which items are returned. The maximum number of expressions is 5. schema: type: string - name: top in: query description: Limits the number of items returned from a collection. The maximum value is 100. schema: type: integer format: int32 - name: skip in: query description: Excludes the specified number of items of the queried collection from the result. schema: type: integer format: int32 - name: count in: query description: Indicates whether the total count of items within a collection are returned in the result. schema: type: boolean default: false responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: type: array items: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: type: array items: $ref: '#/components/schemas/Task' application/xml: schema: type: array items: $ref: '#/components/schemas/Task' text/plain: schema: type: array items: $ref: '#/components/schemas/Task' application/octet-stream: schema: type: array items: $ref: '#/components/schemas/Task' text/json: schema: type: array items: $ref: '#/components/schemas/Task' /api/v1/odata/Tasks({key}): get: tags: - Tasks operationId: api/v{version:apiVersion}/odata/Tasks({key}) parameters: - name: key in: query schema: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/xml: schema: $ref: '#/components/schemas/Task' text/plain: schema: $ref: '#/components/schemas/Task' application/octet-stream: schema: $ref: '#/components/schemas/Task' text/json: schema: $ref: '#/components/schemas/Task' /api/v1/odata/Tasks/{key}: get: tags: - Tasks operationId: api/v{version:apiVersion}/odata/Tasks/{key} parameters: - name: key in: query schema: type: integer format: int32 - name: select in: query description: Limits the properties returned in the result. schema: type: string - name: expand in: query description: Indicates the related entities to be represented inline. The maximum depth is 2. schema: type: string responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/Task' application/json: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/Task' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/Task' application/xml: schema: $ref: '#/components/schemas/Task' text/plain: schema: $ref: '#/components/schemas/Task' application/octet-stream: schema: $ref: '#/components/schemas/Task' text/json: schema: $ref: '#/components/schemas/Task' /api/v1/user/register: post: tags: - User requestBody: content: application/json: schema: $ref: '#/components/schemas/RegisterRequest' required: true responses: '200': description: OK '400': description: Bad Request content: application/problem+json: schema: $ref: '#/components/schemas/HttpValidationProblemDetails' /api/v1/user/login: post: tags: - User parameters: - name: useCookies in: query schema: type: boolean - name: useSessionCookies in: query schema: type: boolean requestBody: content: application/json: schema: $ref: '#/components/schemas/LoginRequest' required: true responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/AccessTokenResponse' /api/v1/user/refresh: post: tags: - User requestBody: content: application/json: schema: $ref: '#/components/schemas/RefreshRequest' required: true responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/AccessTokenResponse' /api/v1/user/confirmEmail: get: tags: - User operationId: MapIdentityApi-/api/v{version:apiVersion}/user/confirmEmail parameters: - name: userId in: query required: true schema: type: string - name: code in: query required: true schema: type: string - name: changedEmail in: query schema: type: string responses: '200': description: OK /api/v1/user/resendConfirmationEmail: post: tags: - User requestBody: content: application/json: schema: $ref: '#/components/schemas/ResendConfirmationEmailRequest' required: true responses: '200': description: OK /api/v1/user/forgotPassword: post: tags: - User requestBody: content: application/json: schema: $ref: '#/components/schemas/ForgotPasswordRequest' required: true responses: '200': description: OK '400': description: Bad Request content: application/problem+json: schema: $ref: '#/components/schemas/HttpValidationProblemDetails' /api/v1/user/resetPassword: post: tags: - User requestBody: content: application/json: schema: $ref: '#/components/schemas/ResetPasswordRequest' required: true responses: '200': description: OK '400': description: Bad Request content: application/problem+json: schema: $ref: '#/components/schemas/HttpValidationProblemDetails' /api/v1/user/manage/2fa: post: tags: - User requestBody: content: application/json: schema: $ref: '#/components/schemas/TwoFactorRequest' required: true responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/TwoFactorResponse' '400': description: Bad Request content: application/problem+json: schema: $ref: '#/components/schemas/HttpValidationProblemDetails' '404': description: Not Found /api/v1/user/manage/info: get: tags: - User responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/InfoResponse' '400': description: Bad Request content: application/problem+json: schema: $ref: '#/components/schemas/HttpValidationProblemDetails' '404': description: Not Found post: tags: - User requestBody: content: application/json: schema: $ref: '#/components/schemas/InfoRequest' required: true responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/InfoResponse' '400': description: Bad Request content: application/problem+json: schema: $ref: '#/components/schemas/HttpValidationProblemDetails' '404': description: Not Found /api/v1/user/logout: post: tags: - User requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: {} application/json;odata.metadata=minimal;odata.streaming=false: schema: {} application/json;odata.metadata=minimal: schema: {} application/json;odata.metadata=full;odata.streaming=true: schema: {} application/json;odata.metadata=full;odata.streaming=false: schema: {} application/json;odata.metadata=full: schema: {} application/json;odata.metadata=none;odata.streaming=true: schema: {} application/json;odata.metadata=none;odata.streaming=false: schema: {} application/json;odata.metadata=none: schema: {} application/json;odata.streaming=true: schema: {} application/json;odata.streaming=false: schema: {} application/json: schema: {} application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: {} application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: {} application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: {} application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: {} application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: {} application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: {} application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: {} application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: {} application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: {} application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: {} application/json;odata.metadata=full;IEEE754Compatible=false: schema: {} application/json;odata.metadata=full;IEEE754Compatible=true: schema: {} application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: {} application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: {} application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: {} application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: {} application/json;odata.metadata=none;IEEE754Compatible=false: schema: {} application/json;odata.metadata=none;IEEE754Compatible=true: schema: {} application/json;odata.streaming=true;IEEE754Compatible=false: schema: {} application/json;odata.streaming=true;IEEE754Compatible=true: schema: {} application/json;odata.streaming=false;IEEE754Compatible=false: schema: {} application/json;odata.streaming=false;IEEE754Compatible=true: schema: {} application/json;IEEE754Compatible=false: schema: {} application/json;IEEE754Compatible=true: schema: {} application/xml: schema: {} text/plain: schema: {} application/json-patch+json: schema: {} text/json: schema: {} application/*+json: schema: {} responses: '200': description: OK /api/v1/user/documents-summary: get: tags: - User responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/xml: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' text/plain: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' application/octet-stream: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' text/json: schema: $ref: '#/components/schemas/PersonalDocumentsSummary' deprecated: true /api/v1/user: delete: tags: - User responses: '200': description: OK /api/v1/users/me: get: tags: - Users responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/xml: schema: $ref: '#/components/schemas/User' text/plain: schema: $ref: '#/components/schemas/User' application/octet-stream: schema: $ref: '#/components/schemas/User' text/json: schema: $ref: '#/components/schemas/User' /api/v1/users/{id}: patch: tags: - Users parameters: - name: id in: path required: true schema: type: integer format: int32 requestBody: content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/UserUpdateDto' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/UserUpdateDto' application/xml: schema: $ref: '#/components/schemas/UserUpdateDto' text/plain: schema: $ref: '#/components/schemas/UserUpdateDto' application/json-patch+json: schema: $ref: '#/components/schemas/UserUpdateDto' text/json: schema: $ref: '#/components/schemas/UserUpdateDto' application/*+json: schema: $ref: '#/components/schemas/UserUpdateDto' responses: '200': description: OK content: application/json;odata.metadata=minimal;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=true: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=false: schema: $ref: '#/components/schemas/User' application/json: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=minimal;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=full;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.metadata=none;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=true;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=true;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=false;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;odata.streaming=false;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/json;IEEE754Compatible=false: schema: $ref: '#/components/schemas/User' application/json;IEEE754Compatible=true: schema: $ref: '#/components/schemas/User' application/xml: schema: $ref: '#/components/schemas/User' text/plain: schema: $ref: '#/components/schemas/User' application/octet-stream: schema: $ref: '#/components/schemas/User' text/json: schema: $ref: '#/components/schemas/User' components: schemas: AccessTokenResponse: required: - accessToken - expiresIn - refreshToken type: object properties: tokenType: type: string readOnly: true accessToken: type: string expiresIn: type: integer format: int64 refreshToken: type: string additionalProperties: false AccountingCompany: required: - country - id - identificationNumber - name type: object properties: id: type: integer format: int32 name: type: string identificationNumber: type: string countryCode: type: string deprecated: true country: $ref: '#/components/schemas/Country' additionalProperties: false AccountingCompanyCreateDto: required: - identificationNumber - name type: object properties: name: minLength: 1 type: string identificationNumber: minLength: 1 type: string additionalProperties: false AccountingCompanyMembership: required: - accountingCompanyId - accountingCompanyName - id - roleName - userFullName - userId type: object properties: id: type: integer format: int32 accountingCompanyId: type: integer format: int32 accountingCompanyName: type: string userId: type: integer format: int32 userFullName: type: string roleName: type: string additionalProperties: false AccountingCompanyMembershipUpsertDto: required: - accountingCompanyId - email - roleName type: object properties: accountingCompanyId: type: integer format: int32 email: minLength: 1 type: string format: email roleName: minLength: 1 type: string additionalProperties: false AccountingCompanyUpdateDto: required: - identificationNumber - name type: object properties: name: minLength: 1 type: string identificationNumber: minLength: 1 type: string additionalProperties: false AddressDto: required: - city - country - postalCode - street type: object properties: street: maxLength: 100 type: string city: maxLength: 50 type: string postalCode: maxLength: 20 type: string country: maxLength: 60 type: string additionalProperties: false AnnualInvoicesCount: enum: - Tens - Hundred - Thousands - TenThousands - HundredThousands type: string BankAccount: required: - accountNumber - bankCode - businessId - createdAt - currency - iban - id - swift type: object properties: id: type: integer format: int64 businessId: type: integer format: int64 accountNumber: type: string bankCode: type: string swift: type: string iban: type: string currency: $ref: '#/components/schemas/Currency' createdAt: type: string format: date-time updatedAt: type: string format: date-time nullable: true additionalProperties: false BankAccountUpsertDto: required: - accountNumber - bankCode - businessId - currency - iban - swift type: object properties: businessId: type: integer format: int32 accountNumber: maxLength: 20 minLength: 1 type: string bankCode: maxLength: 10 minLength: 1 type: string swift: maxLength: 11 minLength: 1 type: string iban: maxLength: 34 minLength: 1 type: string currency: $ref: '#/components/schemas/Currency' additionalProperties: false Business: required: - accountingCompany - contactPerson - country - deletedAt - fullAddress - id - identificationNumber - name - vatNumber type: object properties: id: type: integer format: int32 name: type: string identificationNumber: type: string vatNumber: type: string nullable: true country: $ref: '#/components/schemas/Country' countryCode: type: string deprecated: true deletedAt: type: string format: date-time nullable: true fullAddress: type: string nullable: true accountingCompany: $ref: '#/components/schemas/BusinessAccountingCompany' contactPerson: $ref: '#/components/schemas/BusinessContactPerson' additionalProperties: false BusinessAccountantAssignment: required: - accountantId - accountantName - businessId - businessName - id type: object properties: id: type: integer format: int32 businessId: type: integer format: int32 businessName: type: string accountantId: type: integer format: int32 accountantName: type: string additionalProperties: false BusinessAccountantAssignmentUpsert: required: - accountantId - businessId type: object properties: businessId: type: integer format: int32 accountantId: type: integer format: int32 additionalProperties: false BusinessAccountingCompany: required: - id - name type: object properties: id: type: integer format: int32 name: type: string additionalProperties: false BusinessAresAddress: required: - city - houseNumber - postalCode - street type: object properties: street: type: string houseNumber: maximum: 2147483647 minimum: 1 type: integer format: int32 guidanceNumber: maximum: 2147483647 minimum: 1 type: integer format: int32 nullable: true city: type: string postalCode: maximum: 2147483647 minimum: 1 type: integer format: int32 additionalProperties: false BusinessChangeContactDto: required: - userId type: object properties: userId: type: integer format: int32 nullable: true additionalProperties: false BusinessContactPerson: required: - email - fullName - id - phoneNumber type: object properties: id: type: integer format: int32 fullName: type: string email: type: string nullable: true phoneNumber: type: string nullable: true additionalProperties: false BusinessCreateDto: required: - identificationNumber - name type: object properties: name: minLength: 1 type: string identificationNumber: minLength: 1 type: string vatNumber: type: string nullable: true address: $ref: '#/components/schemas/BusinessAresAddress' additionalProperties: false BusinessDocumentMoveToBusinessDocumentsDto: required: - businessId type: object properties: businessId: type: integer format: int32 documentTypeId: type: integer format: int32 nullable: true additionalProperties: false BusinessDocumentUpdateDto: required: - documentTypeId - name type: object properties: name: maxLength: 255 type: string nullable: true documentTypeId: type: integer format: int32 nullable: true additionalProperties: false BusinessDocumentsSummary: required: - documentsCount - documentsSize - id - lastUploadAt - maxStorageSize - name type: object properties: id: type: integer format: int32 name: type: string documentsCount: type: integer format: int32 documentsSize: type: integer format: int64 lastUploadAt: type: string format: date-time nullable: true maxStorageSize: type: integer format: int64 additionalProperties: false BusinessMembershipDto: required: - businessId - businessName - id - roleId - roleName - userFullName - userId type: object properties: id: type: integer format: int32 userId: type: integer format: int32 userFullName: type: string businessId: type: integer format: int32 businessName: type: string roleId: type: integer format: int32 roleName: type: string additionalProperties: false BusinessMembershipUpsertDto: required: - businessId - email - roleName type: object properties: businessId: type: integer format: int32 email: minLength: 1 type: string format: email roleName: minLength: 1 type: string additionalProperties: false BusinessSummary: required: - documentsCount - documentsSize - id - lastUploadAt - name - pendingDocumentsCount - pendingTasksCount type: object properties: id: type: integer format: int32 name: type: string documentsCount: type: integer format: int32 documentsSize: type: integer format: int64 lastUploadAt: type: string format: date-time nullable: true maxStorageSize: type: integer format: int64 deprecated: true pendingTasksCount: type: integer format: int32 pendingDocumentsCount: type: integer format: int32 additionalProperties: false BusinessUpdateDto: required: - identificationNumber - name type: object properties: name: minLength: 1 type: string identificationNumber: minLength: 1 type: string vatNumber: minLength: 1 type: string nullable: true address: $ref: '#/components/schemas/BusinessAresAddress' additionalProperties: false Counterparty: required: - address - businessId - createdAt - email - id - identificationNumber - isFavourite - name - privateNote - vatNumber type: object properties: id: type: integer format: int64 businessId: type: integer format: int64 name: type: string identificationNumber: type: string nullable: true vatNumber: type: string nullable: true address: $ref: '#/components/schemas/AddressDto' email: type: string nullable: true privateNote: type: string nullable: true isFavourite: type: boolean nullable: true createdAt: type: string format: date-time updatedAt: type: string format: date-time nullable: true additionalProperties: false CounterpartyCreateDto: required: - address - businessId - email - identificationNumber - name - vatNumber type: object properties: businessId: type: integer format: int64 identificationNumber: maxLength: 31 minLength: 0 type: string name: maxLength: 255 minLength: 0 type: string vatNumber: maxLength: 31 minLength: 0 type: string nullable: true address: $ref: '#/components/schemas/AddressDto' email: maxLength: 320 minLength: 0 type: string format: email nullable: true privateNote: maxLength: 1024 minLength: 0 type: string nullable: true isFavourite: type: boolean nullable: true additionalProperties: false CounterpartyUpdateDto: type: object properties: identificationNumber: maxLength: 31 minLength: 0 type: string nullable: true name: maxLength: 255 minLength: 0 type: string nullable: true vatNumber: maxLength: 31 minLength: 0 type: string nullable: true address: $ref: '#/components/schemas/AddressDto' email: maxLength: 320 minLength: 0 type: string format: email nullable: true privateNote: maxLength: 1024 minLength: 0 type: string nullable: true isFavourite: type: boolean nullable: true additionalProperties: false Country: enum: - Czechia - Slovakia type: string CreateInvoiceClientDto: required: - counterpartyId type: object properties: counterpartyId: type: integer format: int64 additionalProperties: false Currency: enum: - CZK - EUR - USD - GBP type: string DataBoxCredentials: required: - businessId - businessName - password - userId - username type: object properties: id: type: integer format: int32 username: type: string password: type: string nullable: true businessId: type: integer format: int32 businessName: type: string userId: type: integer format: int32 additionalProperties: false DataBoxCredentialsUpsertDto: required: - businessId - password - username type: object properties: businessId: type: integer format: int32 username: maxLength: 50 type: string nullable: true password: maxLength: 50 type: string nullable: true additionalProperties: false DocumentAction: enum: - Uploaded type: string DocumentBusiness: required: - approvedAt - approverFullName - approverId - businessId - businessName - documentName - documentTypeId - documentTypeName - extension - id - originalFileName - size - taskId - uploadedAt - uploaderId type: object properties: id: type: integer format: int64 name: type: string deprecated: true documentName: type: string originalFileName: type: string extension: type: string nullable: true size: type: integer format: int64 businessId: type: integer format: int64 nullable: true businessName: type: string nullable: true documentTypeId: type: integer format: int64 documentTypeName: type: string approvedAt: type: string format: date-time nullable: true approverId: type: integer format: int32 nullable: true approverFullName: type: string nullable: true taskId: type: integer format: int64 nullable: true uploadedAt: type: string format: date-time uploaderId: type: integer format: int32 nullable: true deletedAt: type: string format: date-time nullable: true additionalProperties: false DocumentBusinessActivity: required: - action - businessId - businessName - documentId - documentName - happenedAt - performedByUserFullName - performedByUserId type: object properties: documentId: type: integer format: int64 documentName: type: string businessId: type: integer format: int64 businessName: type: string action: $ref: '#/components/schemas/DocumentAction' happenedAt: type: string format: date-time performedByUserId: type: integer format: int32 nullable: true performedByUserFullName: type: string nullable: true additionalProperties: false DocumentPersonal: required: - extension - id - name - size - userFullName - userId type: object properties: id: type: integer format: int64 name: type: string extension: type: string nullable: true size: type: integer format: int64 userId: type: integer format: int64 userFullName: type: string uploadedAt: type: string format: date-time deletedAt: type: string format: date-time nullable: true additionalProperties: false DocumentPersonalMoveToBusinessDocumentsDto: required: - businessId type: object properties: businessId: type: integer format: int32 documentTypeId: type: integer format: int32 additionalProperties: false DocumentType: required: - id - name type: object properties: id: type: integer format: int64 name: type: string additionalProperties: false DocumentTypesSummary: required: - documentsCount - documentTypeId - documentTypeName type: object properties: documentTypeId: type: integer format: int32 documentTypeName: type: string documentsCount: type: integer format: int32 additionalProperties: false FeedbackType: enum: - Feedback - Bug type: string ForgotPasswordRequest: required: - email type: object properties: email: type: string additionalProperties: false HttpValidationProblemDetails: type: object properties: type: type: string nullable: true title: type: string nullable: true status: type: integer format: int32 nullable: true detail: type: string nullable: true instance: type: string nullable: true errors: type: object additionalProperties: type: array items: type: string additionalProperties: {} InfoRequest: type: object properties: newEmail: type: string nullable: true newPassword: type: string nullable: true oldPassword: type: string nullable: true additionalProperties: false InfoResponse: required: - email - isEmailConfirmed type: object properties: email: type: string isEmailConfirmed: type: boolean additionalProperties: false Invitation: required: - accountingCompanyName - email - expiresAt - id - status type: object properties: id: type: integer format: int32 accountingCompanyName: type: string status: $ref: '#/components/schemas/InvitationStatus' expiresAt: type: string format: date-time email: type: string additionalProperties: false InvitationAcceptDto: required: - businessId type: object properties: businessId: type: integer format: int32 additionalProperties: false InvitationCreateDto: required: - accountingCompanyId - email type: object properties: accountingCompanyId: type: integer format: int32 email: maxLength: 320 minLength: 1 type: string format: email additionalProperties: false InvitationStatus: enum: - Pending - Expired - Rejected type: string InvitationUpdateDto: type: object properties: email: type: string format: email nullable: true additionalProperties: false Invoice: required: - bankAccount - businessId - client - constantSymbol - createdAt - currency - dueAt - footerNote - hideBankAccount - id - issuedAt - lines - noteBeforeLines - number - paymentMethod - reversedVatCharge - sentAt - snapshotAt - status - supplier - taxPointAt - totalPriceExcludingVat - totalPriceIncludingVat - totalVatAmount - type - updatedAt - variableSymbol type: object properties: id: type: integer format: int64 businessId: type: integer format: int64 supplier: $ref: '#/components/schemas/InvoiceSupplier' client: $ref: '#/components/schemas/InvoiceClient' bankAccount: $ref: '#/components/schemas/InvoiceBankAccount' hideBankAccount: type: boolean type: $ref: '#/components/schemas/InvoiceType' number: type: string status: $ref: '#/components/schemas/InvoiceStatus' paymentMethod: $ref: '#/components/schemas/PaymentMethod' currency: $ref: '#/components/schemas/Currency' reversedVatCharge: type: boolean variableSymbol: type: string nullable: true constantSymbol: type: string nullable: true issuedAt: type: string format: date dueAt: type: string format: date taxPointAt: type: string format: date nullable: true sentAt: type: string format: date-time nullable: true snapshotAt: type: string format: date-time nullable: true noteBeforeLines: type: string nullable: true lines: type: array items: $ref: '#/components/schemas/InvoiceLine' footerNote: type: string nullable: true totalPriceExcludingVat: type: number format: double totalVatAmount: type: number format: double totalPriceIncludingVat: type: number format: double createdAt: type: string format: date-time updatedAt: type: string format: date-time nullable: true additionalProperties: false InvoiceBankAccount: required: - accountNumber - bankCode - currency - iban - swift type: object properties: swift: type: string iban: type: string accountNumber: type: string bankCode: type: string currency: $ref: '#/components/schemas/Currency' additionalProperties: false InvoiceBankAccountUpdateDto: required: - accountNumber - bankCode - currency - iban - swift type: object properties: swift: type: string iban: type: string accountNumber: type: string bankCode: type: string currency: $ref: '#/components/schemas/Currency' additionalProperties: false InvoiceClient: required: - address - counterpartyId - deliveryAddress - deliveryName - email - identificationNumber - name - registrationNumber - vatNumber type: object properties: id: type: integer format: int64 nullable: true deprecated: true counterpartyId: type: integer format: int64 nullable: true name: type: string registrationNumber: type: string nullable: true identificationNumber: type: string nullable: true vatNumber: type: string nullable: true email: type: string nullable: true address: $ref: '#/components/schemas/InvoiceClientAddress' deliveryName: type: string nullable: true deliveryAddress: $ref: '#/components/schemas/InvoiceClientDeliveryAddress' additionalProperties: false InvoiceClientAddress: required: - city - country - postalCode - street type: object properties: street: maxLength: 100 type: string city: maxLength: 50 type: string postalCode: maxLength: 20 type: string country: maxLength: 60 type: string additionalProperties: false InvoiceClientDeliveryAddress: required: - city - country - postalCode - street type: object properties: street: maxLength: 100 type: string city: maxLength: 50 type: string postalCode: maxLength: 20 type: string country: maxLength: 60 type: string additionalProperties: false InvoiceCreateDto: required: - businessId - client - dueAt - hideBankAccount - issuedAt - lines - number - paymentMethod - reversedVatCharge - status - taxPointAt - type type: object properties: client: $ref: '#/components/schemas/CreateInvoiceClientDto' type: $ref: '#/components/schemas/InvoiceType' number: maxLength: 50 minLength: 1 type: string status: $ref: '#/components/schemas/InvoiceStatus' paymentMethod: $ref: '#/components/schemas/PaymentMethod' hideBankAccount: type: boolean reversedVatCharge: type: boolean variableSymbol: maxLength: 10 type: string nullable: true constantSymbol: maxLength: 4 type: string nullable: true issuedAt: type: string format: date dueAt: type: string format: date taxPointAt: type: string format: date noteBeforeLines: maxLength: 2048 type: string nullable: true lines: type: array items: $ref: '#/components/schemas/InvoiceLineCreateDto' footerNote: maxLength: 2048 type: string nullable: true businessId: type: integer format: int32 additionalProperties: false InvoiceLine: required: - description - quantity - totalPriceExcludingVat - totalPriceIncludingVat - unit - unitPrice - vatAmount - vatRate type: object properties: id: type: integer format: int64 description: type: string quantity: type: number format: double unit: type: string unitPrice: type: number format: double vatRate: type: number format: double totalPriceExcludingVat: type: number format: double vatAmount: type: number format: double totalPriceIncludingVat: type: number format: double additionalProperties: false InvoiceLineCreateDto: required: - description - quantity - unit - unitPrice - vatRate type: object properties: description: maxLength: 500 minLength: 1 type: string quantity: type: number format: double unit: maxLength: 20 minLength: 1 type: string unitPrice: type: number format: double vatRate: maximum: 100 minimum: 0 type: number format: double additionalProperties: false InvoiceLineUpdateDto: required: - description - id - quantity - unit - unitPrice - vatRate type: object properties: id: type: integer format: int64 nullable: true description: maxLength: 500 minLength: 1 type: string quantity: type: number format: double unit: maxLength: 20 minLength: 1 type: string unitPrice: type: number format: double vatRate: type: number format: double additionalProperties: false InvoiceSendDto: required: - customRecipientEmail - message type: object properties: customRecipientEmail: type: string format: email nullable: true message: type: string additionalProperties: false InvoiceSetting: required: - businessId - createdAt - isVatPayer - numberingSetting - template type: object properties: businessId: type: integer format: int64 isVatPayer: type: boolean template: $ref: '#/components/schemas/InvoiceTemplate' bankAccount: $ref: '#/components/schemas/InvoiceSettingsBankAccount' numberingSetting: $ref: '#/components/schemas/NumberingSetting' createdAt: type: string format: date-time updatedAt: type: string format: date-time nullable: true additionalProperties: false InvoiceSettingUpsertDto: required: - businessId - isVatPayer - numberingSetting - template type: object properties: businessId: type: integer format: int32 isVatPayer: type: boolean template: $ref: '#/components/schemas/InvoiceTemplateUpsertDto' bankAccount: $ref: '#/components/schemas/InvoiceSettingsBankAccountUpsertDto' numberingSetting: $ref: '#/components/schemas/NumberingSettingUpsertDto' additionalProperties: false InvoiceSettingsBankAccount: required: - accountNumber - bankCode - businessId - createdAt - currency - iban - id - number - swift type: object properties: id: type: integer format: int64 businessId: type: integer format: int64 number: type: string deprecated: true accountNumber: type: string bankCode: type: string swift: type: string iban: type: string currency: $ref: '#/components/schemas/Currency' createdAt: type: string format: date-time updatedAt: type: string format: date-time nullable: true additionalProperties: false InvoiceSettingsBankAccountUpsertDto: required: - accountNumber - bankCode - currency - iban - swift type: object properties: accountNumber: minLength: 1 type: string bankCode: minLength: 1 type: string swift: minLength: 1 type: string iban: minLength: 1 type: string currency: $ref: '#/components/schemas/Currency' additionalProperties: false InvoiceStatus: enum: - Draft - Issued - Paid - Overdue - Cancelled - Snapshot type: string InvoiceSupplier: required: - address - identificationNumber - name - registrationNumber - vatNumber type: object properties: name: type: string registrationNumber: type: string identificationNumber: type: string vatNumber: type: string nullable: true address: $ref: '#/components/schemas/InvoiceSupplierAddress' additionalProperties: false InvoiceSupplierAddress: required: - city - country - postalCode - street type: object properties: street: maxLength: 100 type: string city: maxLength: 50 type: string postalCode: maxLength: 20 type: string country: maxLength: 60 type: string additionalProperties: false InvoiceTemplate: required: - currency - footerText - textBeforeLines type: object properties: currency: $ref: '#/components/schemas/Currency' textBeforeLines: type: string nullable: true footerText: type: string nullable: true additionalProperties: false InvoiceTemplateUpsertDto: required: - currency - footerText - textBeforeLines type: object properties: currency: $ref: '#/components/schemas/Currency' textBeforeLines: maxLength: 2048 minLength: 0 type: string nullable: true footerText: maxLength: 2048 minLength: 0 type: string nullable: true additionalProperties: false InvoiceType: enum: - Regular - Corrective - Advance type: string InvoiceUpdateClientDto: required: - address - counterpartyId - deliveryAddress - deliveryName - email - name - registrationNumber - vatNumber type: object properties: counterpartyId: type: integer format: int64 nullable: true name: maxLength: 255 type: string nullable: true registrationNumber: maxLength: 31 type: string nullable: true vatNumber: maxLength: 31 type: string nullable: true email: maxLength: 320 type: string format: email nullable: true address: $ref: '#/components/schemas/AddressDto' deliveryName: maxLength: 255 type: string nullable: true deliveryAddress: $ref: '#/components/schemas/AddressDto' additionalProperties: false InvoiceUpdateDto: required: - bankAccount - client - constantSymbol - currency - dueAt - footerNote - hideBankAccount - issuedAt - lines - noteBeforeLines - number - paymentMethod - reversedVatCharge - status - taxPointAt - type - variableSymbol type: object properties: client: $ref: '#/components/schemas/InvoiceUpdateClientDto' bankAccount: $ref: '#/components/schemas/InvoiceBankAccountUpdateDto' hideBankAccount: type: boolean nullable: true type: $ref: '#/components/schemas/InvoiceType' number: maxLength: 50 type: string nullable: true status: $ref: '#/components/schemas/InvoiceStatus' paymentMethod: $ref: '#/components/schemas/PaymentMethod' currency: $ref: '#/components/schemas/Currency' reversedVatCharge: type: boolean nullable: true variableSymbol: maxLength: 10 type: string nullable: true constantSymbol: maxLength: 4 type: string nullable: true issuedAt: type: string format: date nullable: true dueAt: type: string format: date nullable: true taxPointAt: type: string format: date nullable: true noteBeforeLines: maxLength: 2048 type: string nullable: true lines: type: array items: $ref: '#/components/schemas/InvoiceLineUpdateDto' nullable: true footerNote: maxLength: 2048 type: string nullable: true additionalProperties: false LicenseDto: required: - businessId - id - maxBusinessMembersCount - maxBusinessStorageSize - maxContactsCount - tierId - tierName type: object properties: id: type: integer format: int32 tierId: type: integer format: int32 tierName: type: string businessId: type: integer format: int32 nullable: true maxStorageSize: type: integer format: int64 deprecated: true maxBusinessStorageSize: type: integer format: int64 maxBusinessMembersCount: type: integer format: int32 maxContactsCount: type: integer format: int32 additionalProperties: false LoginRequest: required: - email - password type: object properties: email: type: string password: type: string twoFactorCode: type: string nullable: true twoFactorRecoveryCode: type: string nullable: true additionalProperties: false NotificationsDeviceTokenDeleteDto: required: - token type: object properties: token: maxLength: 511 minLength: 1 type: string additionalProperties: false NotificationsDeviceTokenUpsertDto: required: - provider - token type: object properties: provider: $ref: '#/components/schemas/PushNotificationsProvider' token: maxLength: 511 minLength: 1 type: string additionalProperties: false NotificationsTestSendDto: required: - token type: object properties: token: type: string nullable: true additionalProperties: false NumberingSetting: required: - annualInvoicesCount - businessId - createdAt - format - id - isMonthIncluded - lastExternalInvoiceSequenceNumber - sequencePosition - useHyphen - yearFormat type: object properties: id: type: integer format: int64 businessId: type: integer format: int64 yearFormat: $ref: '#/components/schemas/YearFormat' isMonthIncluded: type: boolean useHyphen: type: boolean prefix: type: string nullable: true suffix: type: string nullable: true sequencePosition: $ref: '#/components/schemas/SequencePosition' annualInvoicesCount: $ref: '#/components/schemas/AnnualInvoicesCount' format: type: string lastExternalInvoiceSequenceNumber: type: integer format: int32 nullable: true createdAt: type: string format: date-time updatedAt: type: string format: date-time nullable: true additionalProperties: false NumberingSettingUpsertDto: required: - annualInvoicesCount - isMonthIncluded - prefix - sequencePosition - suffix - useHyphen - yearFormat type: object properties: yearFormat: $ref: '#/components/schemas/YearFormat' isMonthIncluded: type: boolean useHyphen: type: boolean prefix: maxLength: 15 minLength: 0 type: string nullable: true suffix: maxLength: 15 minLength: 0 type: string nullable: true sequencePosition: $ref: '#/components/schemas/SequencePosition' annualInvoicesCount: $ref: '#/components/schemas/AnnualInvoicesCount' lastExternalInvoiceSequenceNumber: maximum: 2147483647 minimum: 1 type: integer format: int32 nullable: true additionalProperties: false PaymentMethod: enum: - Cash - BankTransfer type: string PersonalDocumentsSummary: required: - documentsCount - documentsSize - maxStorageSize type: object properties: documentsCount: type: integer format: int32 documentsSize: type: integer format: int64 maxStorageSize: type: integer format: int64 additionalProperties: false PushNotificationsProvider: enum: - 1 - 2 type: integer format: int32 RecurrenceType: enum: - Daily - Weekly - Monthly - Yearly type: string RecurringTask: required: - accountantFullName - accountantId - accountingCompanyId - accountingCompanyName - businesses - details - documentTypeId - documentTypeName - executeAt - id - interval - isActive - period - title type: object properties: id: type: integer format: int64 title: type: string details: type: string accountingCompanyId: type: integer format: int32 accountingCompanyName: type: string accountantId: type: integer format: int32 nullable: true accountantFullName: type: string nullable: true recurrenceType: $ref: '#/components/schemas/RecurrenceType' period: $ref: '#/components/schemas/RecurrenceType' interval: maximum: 2147483647 minimum: 1 type: integer format: int32 executeAt: type: string format: date isActive: type: boolean businesses: type: array items: $ref: '#/components/schemas/RecurringTaskBusiness' documentTypeId: type: integer format: int32 documentTypeName: type: string additionalProperties: false RecurringTaskBusiness: required: - id - name type: object properties: id: type: integer format: int64 name: type: string additionalProperties: false RecurringTaskCreateDto: required: - accountingCompanyId - businessIds - details - documentTypeId - firstTaskDueAt - recurrenceType - title type: object properties: title: maxLength: 255 minLength: 1 type: string details: maxLength: 4096 minLength: 1 type: string recurrenceType: $ref: '#/components/schemas/RecurrenceType' interval: maximum: 2147483647 minimum: 1 type: integer format: int32 firstTaskDueAt: type: string format: date accountingCompanyId: type: integer format: int32 businessIds: type: array items: type: integer format: int32 documentTypeId: type: integer format: int32 additionalProperties: false RecurringTaskUpdateDto: type: object properties: title: maxLength: 255 type: string nullable: true details: maxLength: 4096 type: string nullable: true isActive: type: boolean nullable: true recurrenceType: $ref: '#/components/schemas/RecurrenceType' interval: maximum: 2147483647 minimum: 1 type: integer format: int32 nullable: true nextTasksCreateAt: type: string format: date nullable: true documentTypeId: type: integer format: int32 nullable: true additionalProperties: false RefreshRequest: required: - refreshToken type: object properties: refreshToken: type: string additionalProperties: false RegisterRequest: required: - email - password type: object properties: email: type: string password: type: string additionalProperties: false ResendConfirmationEmailRequest: required: - email type: object properties: email: type: string additionalProperties: false ResetPasswordRequest: required: - email - newPassword - resetCode type: object properties: email: type: string resetCode: type: string newPassword: type: string additionalProperties: false SendFeedbackRequest: required: - message - platform - subject - type type: object properties: type: $ref: '#/components/schemas/FeedbackType' subject: maxLength: 200 minLength: 0 type: string message: maxLength: 5000 minLength: 0 type: string platform: maxLength: 50 minLength: 0 type: string deviceInfo: maxLength: 500 minLength: 0 type: string nullable: true appVersion: maxLength: 50 minLength: 0 type: string nullable: true traceId: maxLength: 100 minLength: 0 type: string nullable: true additionalProperties: false SequencePosition: enum: - Start - End type: string Task: required: - businessId - businessName - details - documentTypeId - documentTypeName - dueAt - id - status - title type: object properties: id: type: integer format: int64 title: type: string details: type: string dueAt: type: string format: date status: $ref: '#/components/schemas/TaskStatus' businessId: type: integer format: int32 businessName: type: string documentTypeId: type: integer format: int32 documentTypeName: type: string additionalProperties: false TaskComment: required: - authorFullName - authorId - content - createdAt - id - taskId type: object properties: id: type: integer format: int64 taskId: type: integer format: int64 nullable: true content: type: string authorId: type: integer format: int32 nullable: true authorFullName: type: string nullable: true createdAt: type: string format: date-time additionalProperties: false TaskRejectDto: required: - reason type: object properties: reason: minLength: 1 type: string additionalProperties: false TaskStatus: enum: - PendingClient - PendingAccountant - Completed - Canceled type: string TaskSubmitDto: required: - answer type: object properties: answer: maxLength: 4096 type: string nullable: true additionalProperties: false TaskUpdateDto: required: - details - dueAt - title type: object properties: title: minLength: 1 type: string details: minLength: 1 type: string dueAt: type: string format: date documentTypeId: type: integer format: int32 nullable: true additionalProperties: false TasksCreateDto: required: - businessIds - details - dueAt - title type: object properties: businessIds: type: array items: type: integer format: int32 documentTypeId: type: integer format: int32 title: minLength: 1 type: string details: minLength: 1 type: string dueAt: type: string format: date additionalProperties: false TwoFactorRequest: type: object properties: enable: type: boolean nullable: true twoFactorCode: type: string nullable: true resetSharedKey: type: boolean resetRecoveryCodes: type: boolean forgetMachine: type: boolean additionalProperties: false TwoFactorResponse: required: - isMachineRemembered - isTwoFactorEnabled - recoveryCodesLeft - sharedKey type: object properties: sharedKey: type: string recoveryCodesLeft: type: integer format: int32 recoveryCodes: type: array items: type: string nullable: true isTwoFactorEnabled: type: boolean isMachineRemembered: type: boolean additionalProperties: false User: required: - email - emailConfirmed - fullName - id - isAccountant - phoneNumber type: object properties: id: type: integer format: int32 email: type: string nullable: true emailConfirmed: type: boolean fullName: type: string phoneNumber: type: string nullable: true isAccountant: type: boolean additionalProperties: false UserUpdateDto: type: object properties: firstName: minLength: 1 type: string nullable: true lastName: minLength: 1 type: string nullable: true phoneNumber: type: string format: tel nullable: true additionalProperties: false YearFormat: enum: - Full - Short type: string ================================================ FILE: specs/3.0.x/sdk-nested-classes.yaml ================================================ openapi: 3.0.3 info: title: OpenAPI 3.0 sdk nested classes example version: 1.0.0 description: Test schema for nested class generation with various operationId patterns servers: - url: https://api.example.com/v1 paths: /business/providers/domains: get: tags: - business - providers - domains operationId: business.providers.domains.get responses: '200': description: OK content: '*/*': schema: type: string post: tags: - providers - domains - business operationId: business.providers.domains.post responses: '200': description: OK content: '*/*': schema: type: string put: tags: - domains responses: '200': description: OK content: '*/*': schema: type: string /locations/businesses: get: tags: - locations - business operationId: business.get responses: '200': description: OK content: '*/*': schema: type: string /locations: get: tags: - locations operationId: get responses: '200': description: OK content: '*/*': schema: type: string ================================================ FILE: specs/3.0.x/security-api-key.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 security api key example version: '1' paths: /foo: get: responses: '200': description: OK security: - foo: [] /bar: get: responses: '200': description: OK security: - bar: [] components: securitySchemes: foo: in: query name: foo type: apiKey bar: in: cookie name: bar type: apiKey ================================================ FILE: specs/3.0.x/security-http-bearer.json ================================================ { "openapi": "3.0.4", "info": { "title": "OpenAPI 3.0.4 security bearer example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK" } }, "security": [ { "foo": [] } ] } } }, "components": { "securitySchemes": { "foo": { "bearerFormat": "JWT", "scheme": "bearer", "type": "http" } } } } ================================================ FILE: specs/3.0.x/security-oauth2.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 security oauth2 example version: '1' paths: /foo: get: responses: '200': description: OK security: - foo: [] components: securitySchemes: foo: flows: authorizationCode: authorizationUrl: '/' tokenUrl: '/' scopes: {} clientCredentials: tokenUrl: '/' scopes: {} implicit: authorizationUrl: '/' scopes: {} password: scopes: {} tokenUrl: '/' type: 'oauth2' ================================================ FILE: specs/3.0.x/security-open-id-connect.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 security OpenID Connect example version: '1' paths: /foo: get: responses: '200': description: OK security: - foo: [] components: securitySchemes: foo: openIdConnectUrl: 'https://example.com/.well-known/openid-configuration' type: 'openIdConnect' ================================================ FILE: specs/3.0.x/servers.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 servers example version: 1 servers: - url: https://foo.com/v1 description: foo - url: /v1 paths: /foo: get: responses: '200': content: '*/*': schema: type: string description: OK ================================================ FILE: specs/3.0.x/transformers-all-of.yaml ================================================ openapi: 3.0.1 info: title: OpenAPI 3.0.1 transformers all of example version: 1 paths: /foo: get: responses: '200': content: '*/*': schema: $ref: '#/components/schemas/Foo' description: OK components: schemas: Foo: type: object properties: foo: type: array items: $ref: '#/components/schemas/Bar' required: - foo Bar: type: object properties: foo: type: array items: oneOf: - $ref: '#/components/schemas/Baz' bar: type: string enum: - foo - bar - baz required: - foo - bar Baz: type: object allOf: - $ref: '#/components/schemas/Qux' - type: object properties: foo: format: int32 type: integer bar: format: date-time type: string baz: type: string enum: - foo - bar - baz qux: format: int32 type: integer required: - foo - bar - baz - qux Qux: type: object discriminator: propertyName: id properties: foo: type: integer format: int32 bar: type: number baz: format: date-time type: string id: type: string required: - foo - bar - id ================================================ FILE: specs/3.0.x/transformers-allof-response-wrapper.json ================================================ { "openapi": "3.0.0", "info": { "title": "Test Paginated Response", "version": "1.0.0" }, "components": { "schemas": { "PaginatedResponse": { "type": "object", "properties": { "meta": { "type": "object", "properties": { "page": { "type": "number" }, "limit": { "type": "number" }, "total": { "type": "number" }, "totalPages": { "type": "number" } } } } }, "RepositorySecret": { "type": "object", "properties": { "id": { "type": "number" }, "name": { "type": "string" }, "createdAt": { "format": "date-time", "type": "string" }, "updatedAt": { "format": "date-time", "type": "string" } }, "required": ["id", "name", "createdAt", "updatedAt"] } } }, "paths": { "/secrets": { "get": { "operationId": "listSecrets", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "title": "PaginatedResponseRepositorySecret", "allOf": [ { "$ref": "#/components/schemas/PaginatedResponse" }, { "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/RepositorySecret" } } } } ] } } } } } } }, "/secrets/{id}": { "post": { "operationId": "createSecret", "responses": { "201": { "description": "Created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RepositorySecret" } } } } } } } }, "servers": [ { "url": "{protocol}://specs", "variables": { "protocol": { "default": "https", "enum": ["http", "https"] } } } ] } ================================================ FILE: specs/3.0.x/transformers-any-of-null.json ================================================ { "openapi": "3.0.3", "info": { "title": "OpenAPI 3.0.3 transformers any of null example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Foo" } } } } } } } }, "/polls": { "get": { "operationId": "getPoll", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Poll" } } } } } } }, "/polls/nullable": { "get": { "operationId": "getNullablePoll", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "anyOf": [ { "$ref": "#/components/schemas/Poll" } ], "nullable": true } } } } } } } }, "components": { "schemas": { "Poll": { "type": "object", "properties": { "id": { "type": "integer" }, "createdAt": { "type": "string", "format": "date-time" } }, "required": ["id", "createdAt"] }, "Foo": { "type": "object", "properties": { "foo": { "type": "string", "format": "date-time" }, "bar": { "anyOf": [ { "type": "string", "nullable": true, "format": "date-time" } ] }, "requiredBaz": { "anyOf": [ { "type": "string", "nullable": true, "format": "date-time" } ] } }, "required": ["requiredBaz"] } } } } ================================================ FILE: specs/3.0.x/transformers-array.json ================================================ { "openapi": "3.0.1", "info": { "title": "OpenAPI 3.0.1 transformers array example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "foo": { "type": "array", "items": { "type": "object", "properties": { "baz": { "type": "string", "format": "date-time" } }, "required": ["baz"] } } }, "required": ["foo"] } } } } } } } } } ================================================ FILE: specs/3.0.x/transformers-recursive.json ================================================ { "openapi": "3.0.3", "info": { "title": "Recursive Schema Test", "version": "1.0.0" }, "paths": { "/tree": { "get": { "operationId": "getTree", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/TreeNode" } } } } } } } } }, "components": { "schemas": { "TreeNode": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "createdAt": { "type": "string", "format": "date-time" }, "children": { "type": "array", "items": { "$ref": "#/components/schemas/TreeNode" } } } } } } } ================================================ FILE: specs/3.0.x/transforms-read-write.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 transforms read write example version: 1 paths: /foo-read-write: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/FooReadWrite' required: true responses: '200': content: '*/*': schema: $ref: '#/components/schemas/FooReadWrite' description: OK /foo-read: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/FooRead' required: true responses: '200': content: '*/*': schema: $ref: '#/components/schemas/FooRead' description: OK /foo-write: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/FooWrite' required: true responses: '200': content: '*/*': schema: $ref: '#/components/schemas/FooWrite' description: OK components: schemas: FooReadWrite: allOf: - $ref: '#/components/schemas/BarRead' - type: object properties: foo: writeOnly: true type: string FooRead: allOf: - $ref: '#/components/schemas/BarRead' - type: object properties: foo: readOnly: true type: string FooWrite: allOf: - $ref: '#/components/schemas/BarWrite' - type: object properties: foo: writeOnly: true type: string BarRead: anyOf: - $ref: '#/components/schemas/Baz' - type: object properties: bar: readOnly: true type: string BarWrite: anyOf: - $ref: '#/components/schemas/Baz' - type: object properties: bar: writeOnly: true type: string Baz: type: object properties: baz: type: string QuxAllRead: type: object properties: baz: readOnly: true type: string Quux: type: object properties: baz: type: array items: $ref: '#/components/schemas/Baz' qux: $ref: '#/components/schemas/QuxAllRead' Corge: type: object properties: foo: type: object properties: baz: type: boolean writeOnly: true bar: type: object properties: baz: type: boolean readOnly: true ================================================ FILE: specs/3.0.x/transforms-schemas-name-collision.yaml ================================================ openapi: 3.0.3 info: title: Schema Name Collision Test version: 1.0.0 paths: /test: get: responses: '200': description: Success content: application/json: schema: type: object properties: user1: $ref: '#/components/schemas/User_v1_User' user2: $ref: '#/components/schemas/User' user3: $ref: '#/components/schemas/User_v2_User' components: schemas: User_v1_User: type: object properties: id: type: string version: type: string enum: ['v1'] User: type: object properties: name: type: string User_v2_User: type: object properties: email: type: string version: type: string enum: ['v2'] ================================================ FILE: specs/3.0.x/transforms-schemas-name.yaml ================================================ openapi: 3.0.3 info: title: Schema Name Transform Test version: 1.0.0 paths: /users: get: summary: Get users responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/User_v1_0_0_User' /posts: post: summary: Create post requestBody: content: application/json: schema: $ref: '#/components/schemas/Post_v2_1_3_Post' responses: '201': description: Created content: application/json: schema: $ref: '#/components/schemas/Post_v2_1_3_Post' components: schemas: User_v1_0_0_User: type: object properties: id: type: string name: type: string profile: $ref: '#/components/schemas/UserProfile_v1_0_0_UserProfile' UserProfile_v1_0_0_UserProfile: type: object properties: bio: type: string avatar: type: string Post_v2_1_3_Post: type: object properties: id: type: string title: type: string author: $ref: '#/components/schemas/User_v1_0_0_User' comments: type: array items: $ref: '#/components/schemas/Comment_v1_5_2_Comment' Comment_v1_5_2_Comment: type: object properties: id: type: string text: type: string author: $ref: '#/components/schemas/User_v1_0_0_User' ================================================ FILE: specs/3.0.x/type-format.yaml ================================================ openapi: 3.0.4 info: title: OpenAPI 3.0.4 type format example version: 1 paths: /foo: post: responses: '200': description: OK content: 'application/json': schema: $ref: '#/components/schemas/Foo' components: schemas: Foo: type: object properties: bar: type: integer foo: default: 0 format: int64 type: integer id: type: string format: typeid example: 'user_123' required: - id - foo Bar: type: object required: - foo properties: foo: type: integer additionalProperties: type: integer ================================================ FILE: specs/3.0.x/type-invalid.json ================================================ { "openapi": "3.0.0", "info": { "title": "OpenAPI 3.0.0 type invalid example", "version": "1" }, "components": { "schemas": { "Foo": { "type": "invalid" } } } } ================================================ FILE: specs/3.0.x/validators.json ================================================ { "openapi": "3.0.4", "info": { "title": "OpenAPI 3.0.4 validators example", "version": "1" }, "components": { "schemas": { "Foo": { "default": null, "nullable": true, "properties": { "foo": { "pattern": "^\\d{3}-\\d{2}-\\d{4}$", "type": "string" }, "bar": { "$ref": "#/components/schemas/Bar" }, "baz": { "items": { "$ref": "#/components/schemas/Foo" }, "type": "array" }, "qux": { "default": 0, "exclusiveMinimum": true, "minimum": 0, "type": "integer" } }, "type": "object" }, "Bar": { "properties": { "foo": { "$ref": "#/components/schemas/Foo" } }, "type": "object" }, "Baz": { "default": "baz", "pattern": "foo\\nbar", "readOnly": true, "type": "string" } } } } ================================================ FILE: specs/3.1.x/additional-properties-false.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 additional properties false example", "version": "1" }, "components": { "schemas": { "Foo": { "required": ["foo"], "type": "object", "properties": { "foo": { "type": "string" } }, "additionalProperties": false }, "Bar": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "type": "object", "additionalProperties": false } ] }, "Baz": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "required": ["bar"], "type": "object", "properties": { "bar": { "type": "string" } }, "additionalProperties": false } ] } } } } ================================================ FILE: specs/3.1.x/additional-properties-true.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 additional properties true example", "version": "1" }, "components": { "schemas": { "Foo": { "required": ["foo"], "type": "object", "properties": { "foo": { "type": "string" } }, "additionalProperties": true }, "Bar": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "type": "object", "additionalProperties": true } ] }, "Baz": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "required": ["bar"], "type": "object", "properties": { "bar": { "type": "string" } }, "additionalProperties": true } ] }, "Qux": { "type": "object", "additionalProperties": {} } } } } ================================================ FILE: specs/3.1.x/additional-properties-undefined.json ================================================ { "openapi": "3.1.1", "info": { "title": "OpenAPI 3.1.1 additional properties undefined example", "version": "1" }, "components": { "schemas": { "Foo": { "properties": { "foo": { "type": "object" } }, "required": ["foo"], "type": "object" } } } } ================================================ FILE: specs/3.1.x/additional-properties.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 additional properties example version: '1' components: schemas: ObjectWithAdditionalPropertiesString: type: object properties: headers: type: object additionalProperties: type: string ObjectOnlyAdditionalPropertiesString: type: object additionalProperties: type: string ObjectOnlyAdditionalPropertiesNumber: type: object additionalProperties: type: number ObjectOnlyAdditionalPropertiesBoolean: type: object additionalProperties: type: boolean ObjectWithPropertiesAndAdditionalPropertiesNumber: type: object properties: id: type: string count: type: integer additionalProperties: type: number ObjectWithAdditionalPropertiesObject: type: object properties: metadata: type: object additionalProperties: type: object properties: value: type: string ObjectOnlyAdditionalPropertiesObject: type: object additionalProperties: type: object properties: name: type: string ObjectWithAdditionalPropertiesFalse: type: object properties: id: type: string count: type: integer additionalProperties: false ObjectWithNestedAdditionalPropertiesFalse: type: object properties: membership: type: object properties: status: type: string enum: [approved, declined, pending] calendar_membership_tier_id: type: string additionalProperties: false ================================================ FILE: specs/3.1.x/array-items-all-of.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 array items allOf example version: '1' components: schemas: ArrayWithAllOfObjects: type: array items: allOf: - type: object properties: id: type: integer - type: object properties: name: type: string ArrayWithAllOfPrimitives: type: array items: allOf: - type: number - type: string ArrayWithAllOfRefs: type: array items: allOf: - $ref: '#/components/schemas/BaseModel' - type: object properties: extra: type: string BaseModel: type: object properties: id: type: integer createdAt: type: string format: date-time ================================================ FILE: specs/3.1.x/array-items-one-of-length-1.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 array items oneOf length 1 example version: '1' components: schemas: Foo: type: object properties: foo: type: array items: oneOf: - $ref: '#/components/schemas/Bar' maxItems: 2147483647 minItems: 1 Bar: type: string ================================================ FILE: specs/3.1.x/array-nested-one-of.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 array nested one of example version: 1 components: schemas: Foo: oneOf: - type: array items: oneOf: - type: object properties: foo: type: string bar: type: string - type: object properties: baz: type: string qux: type: string - type: array items: type: object properties: foo: type: string bar: type: string ================================================ FILE: specs/3.1.x/body-nested-array.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 body nested array example version: 1 paths: /foo: post: requestBody: content: 'multipart/form-data': schema: properties: foo: items: items: type: integer type: array type: array required: - foo type: object required: true responses: '200': description: OK ================================================ FILE: specs/3.1.x/body-response-text-plain.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 body response text plain example version: 1 paths: /foo: post: requestBody: content: 'text/plain': schema: type: string required: true responses: '200': description: OK content: text/plain: schema: type: string ================================================ FILE: specs/3.1.x/case.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 case example version: '1' paths: /foo: get: parameters: - description: 'original name: fooBar' in: query name: fooBar required: true schema: type: string - description: 'original name: BarBaz' in: query name: BarBaz required: true schema: type: string - description: 'original name: qux_quux' in: query name: qux_quux required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/Foo' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Foo' '201': description: OK content: application/json: schema: $ref: '#/components/schemas/201' components: schemas: '201': description: 'original name: 201' type: number Foo: description: 'original name: Foo' properties: fooBar: description: 'original name: fooBar' $ref: '#/components/schemas/foo_bar' BarBaz: description: 'original name: BarBaz' $ref: '#/components/schemas/Foo' qux_quux: description: 'original name: qux_quux' properties: fooBar: description: 'original name: fooBar' $ref: '#/components/schemas/fooBar' BarBaz: description: 'original name: BarBaz' $ref: '#/components/schemas/FooBar' qux_quux: description: 'original name: qux_quux' type: boolean required: - fooBar - BarBaz - qux_quux type: object required: - fooBar - BarBaz - qux_quux type: object foo_bar: description: 'original name: foo_bar' type: boolean fooBar: description: 'original name: fooBar' type: number FooBar: description: 'original name: FooBar' type: string ================================================ FILE: specs/3.1.x/components-request-bodies.json ================================================ { "openapi": "3.1.1", "info": { "title": "OpenAPI 3.1.1 components request bodies example", "version": "1" }, "paths": { "/foo": { "post": { "requestBody": { "$ref": "#/components/requestBodies/Foo" }, "responses": { "200": { "description": "OK" } } } } }, "components": { "requestBodies": { "Foo": { "description": "Foo", "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "page": { "type": "number" } } } } } } } } } ================================================ FILE: specs/3.1.x/const-values.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 const values example version: '1' components: schemas: NumberNoFormat: type: number const: 42.5 IntegerNoFormat: type: integer const: -1 NumberInt8: type: number format: int8 const: 100 NumberInt16: type: number format: int16 const: 1000 NumberInt32: type: number format: int32 const: 100000 NumberInt64: type: number format: int64 const: 1000000000000 NumberUint8: type: number format: uint8 const: 200 NumberUint16: type: number format: uint16 const: 50000 NumberUint32: type: number format: uint32 const: 3000000000 NumberUint64: type: number format: uint64 const: 18000000000000000000 IntegerInt8: type: integer format: int8 const: -100 IntegerInt16: type: integer format: int16 const: -1000 IntegerInt32: type: integer format: int32 const: -100000 IntegerInt64: type: integer format: int64 const: -1000000000000 IntegerUint8: type: integer format: uint8 const: 255 IntegerUint16: type: integer format: uint16 const: 65535 IntegerUint32: type: integer format: uint32 const: 4294967295 IntegerUint64: type: integer format: uint64 const: 1000000000000 StringInt64: type: string format: int64 const: '-9223372036854775808' StringUint64: type: string format: uint64 const: '18446744073709551615' StringInt64n: type: string format: int64 const: '-9223372036854775808n' StringUint64n: type: string format: uint64 const: '18446744073709551615n' ================================================ FILE: specs/3.1.x/const.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 const example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "const": "First line.\n\nSecond line.\n\nPS: I love you.", "type": "string" } } } } } } } } } ================================================ FILE: specs/3.1.x/content-binary.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 content binary example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "content": { "image/png": { "schema": { "type": "string", "contentMediaType": "image/png", "contentEncoding": "base64" } } } } } } }, "/bar": { "get": { "responses": { "200": { "content": { "application/zip": {} } } } } } } } ================================================ FILE: specs/3.1.x/content-media-type.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 contentMediaType example version: '1' paths: /upload: post: operationId: uploadFile requestBody: content: multipart/form-data: schema: $ref: '#/components/schemas/FileUploadRequest' responses: '200': description: OK /upload-typed: post: operationId: uploadFileTyped requestBody: content: multipart/form-data: schema: $ref: '#/components/schemas/FileUploadRequestTyped' responses: '200': description: OK components: schemas: FileUploadRequest: type: object required: - file properties: file: contentMediaType: application/octet-stream description: Binary file content FileUploadRequestTyped: type: object required: - file properties: file: type: string contentMediaType: application/octet-stream description: Binary file content with explicit string type ================================================ FILE: specs/3.1.x/content-types.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 content types example version: '1' paths: /foo: get: responses: '200': description: OK content: text/plain: schema: type: string application/json: schema: type: string text/json: schema: type: string ================================================ FILE: specs/3.1.x/defaults-with-ref-and-anyof.json ================================================ { "openapi": "3.1.0", "info": { "title": "Defaults with $ref and anyOf", "version": "1.0.0" }, "paths": {}, "components": { "schemas": { "AudioFormat": { "type": "string", "enum": ["pcm_16bit_44.1khz", "pcm_16bit_24khz"] }, "Language": { "type": "string", "enum": ["en", "es", "fr"] }, "NestedConfig": { "type": "object", "properties": { "model": { "type": "string", "default": "gpt-4" }, "temperature": { "type": "number", "default": 1 } }, "required": ["model", "temperature"] }, "TestSchema": { "type": "object", "properties": { "primitiveDefault": { "type": "number", "default": 42 }, "refWithPrimitiveDefault": { "$ref": "#/components/schemas/AudioFormat", "default": "pcm_16bit_44.1khz" }, "refWithObjectDefault": { "$ref": "#/components/schemas/NestedConfig", "default": { "model": "gpt-4", "temperature": 1 } }, "anyOfWithNullDefault": { "anyOf": [{ "type": "number" }, { "type": "null" }], "default": null }, "anyOfWithRefAndNullDefault": { "anyOf": [{ "$ref": "#/components/schemas/Language" }, { "type": "null" }], "default": null }, "optionalAnyOfWithDefault": { "anyOf": [{ "type": "string" }, { "type": "null" }], "default": null } }, "required": [ "primitiveDefault", "refWithPrimitiveDefault", "refWithObjectDefault", "anyOfWithNullDefault", "anyOfWithRefAndNullDefault" ] } } } } ================================================ FILE: specs/3.1.x/discriminator-all-of.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 discriminator all of example version: 1 components: schemas: Foo: type: object required: - id properties: id: type: string discriminator: propertyName: id Bar: allOf: - $ref: '#/components/schemas/Foo' - type: object properties: bar: type: string Baz: allOf: - $ref: '#/components/schemas/Foo' - type: object properties: baz: type: string Qux: allOf: - $ref: '#/components/schemas/Foo' - type: object properties: qux: type: boolean FooMapped: type: object required: - id properties: id: type: string discriminator: propertyName: id mapping: bar: '#/components/schemas/BarMapped' baz: '#/components/schemas/BazMapped' BarMapped: allOf: - $ref: '#/components/schemas/FooMapped' - type: object properties: bar: type: string BazMapped: allOf: - $ref: '#/components/schemas/FooMapped' - type: object properties: baz: type: string QuxMapped: allOf: - $ref: '#/components/schemas/FooMapped' - type: object properties: qux: type: boolean FooUnion: oneOf: - $ref: '#/components/schemas/BarUnion' - $ref: '#/components/schemas/BazUnion' discriminator: propertyName: id mapping: bar: '#/components/schemas/BarUnion' baz: '#/components/schemas/BazUnion' BarUnion: type: object properties: id: type: string bar: type: string BazUnion: type: object properties: id: type: string baz: type: string QuxExtend: # this is a schema that extends the FooUnion schema allOf: - $ref: '#/components/schemas/FooUnion' ================================================ FILE: specs/3.1.x/discriminator-allof-inline.json ================================================ { "openapi": "3.1.0", "info": { "title": "Discriminator allOf inline schema mapping", "version": "1.0.0", "description": "Reproduces a bug where a schema extending a parent whose allOf contains both a $ref (with a discriminator that doesn't map the child) and an inline schema (with a discriminator that does map the child) gets the wrong discriminator value. The inline discriminator mapping should win, not the $ref discriminator fallback." }, "paths": { "/foos": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/Bar" }, { "$ref": "#/components/schemas/Baz" }, { "$ref": "#/components/schemas/Qux" } ] } } } } } } } }, "components": { "schemas": { "Foo": { "required": ["$type"], "type": "object", "properties": { "$type": { "type": "string" }, "foo": { "type": "string" } }, "discriminator": { "propertyName": "$type", "mapping": { "FooBar": "#/components/schemas/Bar", "FooBaz": "#/components/schemas/Baz" } } }, "Bar": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "required": ["$type"], "type": "object", "properties": { "$type": { "type": "string" }, "bar": { "type": "string" } }, "discriminator": { "propertyName": "$type", "mapping": { "BarQux": "#/components/schemas/Qux" } } } ] }, "Baz": { "allOf": [ { "$ref": "#/components/schemas/Foo" }, { "type": "object", "properties": { "baz": { "type": "string" } } } ] }, "Qux": { "allOf": [ { "$ref": "#/components/schemas/Bar" }, { "type": "object", "properties": { "qux": { "type": "string" } } } ] } } } } ================================================ FILE: specs/3.1.x/discriminator-allof-nested.json ================================================ { "openapi": "3.1.0", "info": { "title": "Minimal Polymorphic Discriminator Reproduction", "version": "1.0.0", "description": "Demonstrates an issue where TypeScript type generation results in wrong discriminator for nested allOf inheritance with discriminators at multiple levels." }, "paths": { "/cars": { "get": { "summary": "Get cars", "responses": { "200": { "description": "List of cars", "content": { "application/json": { "schema": { "type": "array", "items": { "oneOf": [ { "$ref": "#/components/schemas/CarDto" }, { "$ref": "#/components/schemas/VolvoDto" } ] } } } } } } } } }, "components": { "schemas": { "VehicleDto": { "type": "object", "required": ["$type", "id"], "properties": { "$type": { "type": "string" }, "id": { "type": "integer" } }, "discriminator": { "propertyName": "$type", "mapping": { "Car": "#/components/schemas/CarDto", "Volvo": "#/components/schemas/VolvoDto" } } }, "CarDto": { "allOf": [ { "$ref": "#/components/schemas/VehicleDto" }, { "type": "object", "required": ["modelName"], "properties": { "modelName": { "type": "string" } } } ] }, "VolvoDto": { "allOf": [ { "$ref": "#/components/schemas/CarDto" }, { "type": "object", "required": ["seatbeltCount"], "properties": { "seatbeltCount": { "type": "integer" } } } ] } } } } ================================================ FILE: specs/3.1.x/discriminator-any-of.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 discriminator any of example version: 1 components: schemas: Foo: anyOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' discriminator: propertyName: type Baz: allOf: - $ref: '#/components/schemas/Qux' Bar: allOf: - $ref: '#/components/schemas/Qux' Spæcial: allOf: - $ref: '#/components/schemas/Qux' Qux: type: object properties: id: type: string type: $ref: '#/components/schemas/Quux' required: - id - type Quux: enum: - Bar - Baz type: string Quuz: anyOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/Spæcial' discriminator: propertyName: type mapping: bar: '#/components/schemas/Bar' baz: '#/components/schemas/Baz' 'non-ascii': '#/components/schemas/Spæcial' ================================================ FILE: specs/3.1.x/discriminator-mapped-many.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 discriminator mapped many example version: 1 components: schemas: Foo: oneOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/Spæcial' discriminator: propertyName: foo mapping: one: '#/components/schemas/Bar' two: '#/components/schemas/Bar' three: '#/components/schemas/Baz' four: '#/components/schemas/Spæcial' Bar: type: object properties: foo: type: string enum: - one - two Baz: type: object properties: foo: type: string enum: - three Spæcial: type: object properties: foo: type: string enum: - four ================================================ FILE: specs/3.1.x/discriminator-non-string.yaml ================================================ openapi: 3.1.0 info: title: Non-string discriminator test version: 1 components: schemas: # --- Boolean discriminator (oneOf) --- BooleanOneOf: oneOf: - $ref: '#/components/schemas/AutoConfig' - $ref: '#/components/schemas/CustomConfig' discriminator: propertyName: use_custom mapping: 'False': '#/components/schemas/AutoConfig' 'True': '#/components/schemas/CustomConfig' AutoConfig: type: object required: - use_custom - auto_setting properties: use_custom: type: boolean const: false auto_setting: type: string CustomConfig: type: object required: - use_custom - custom_value properties: use_custom: type: boolean const: true custom_value: type: integer # --- Boolean discriminator (anyOf) --- BooleanAnyOf: anyOf: - $ref: '#/components/schemas/AutoConfig' - $ref: '#/components/schemas/CustomConfig' discriminator: propertyName: use_custom mapping: 'False': '#/components/schemas/AutoConfig' 'True': '#/components/schemas/CustomConfig' # --- Integer discriminator (oneOf) --- IntegerOneOf: oneOf: - $ref: '#/components/schemas/TypeOne' - $ref: '#/components/schemas/TypeTwo' discriminator: propertyName: type_id mapping: '1': '#/components/schemas/TypeOne' '2': '#/components/schemas/TypeTwo' TypeOne: type: object required: - type_id - one_data properties: type_id: type: integer const: 1 one_data: type: string TypeTwo: type: object required: - type_id - two_data properties: type_id: type: integer const: 2 two_data: type: string # --- Number (float) discriminator (oneOf) --- NumberOneOf: oneOf: - $ref: '#/components/schemas/VersionAlpha' - $ref: '#/components/schemas/VersionBeta' discriminator: propertyName: version mapping: '1.0': '#/components/schemas/VersionAlpha' '2.5': '#/components/schemas/VersionBeta' VersionAlpha: type: object required: - version - alpha_field properties: version: type: number const: 1.0 alpha_field: type: string VersionBeta: type: object required: - version - beta_field properties: version: type: number const: 2.5 beta_field: type: string # --- Integer discriminator (allOf) --- IntegerAllOfBase: type: object required: - kind properties: kind: type: integer discriminator: propertyName: kind mapping: '1': '#/components/schemas/IntegerAllOfChildA' '2': '#/components/schemas/IntegerAllOfChildB' IntegerAllOfChildA: allOf: - $ref: '#/components/schemas/IntegerAllOfBase' - type: object required: - child_a_field properties: child_a_field: type: string IntegerAllOfChildB: allOf: - $ref: '#/components/schemas/IntegerAllOfBase' - type: object required: - child_b_field properties: child_b_field: type: string # --- 3.1.x-specific: discriminator property with type array (e.g. nullable integer) --- NullableIntegerOneOf: oneOf: - $ref: '#/components/schemas/NullableVariantX' - $ref: '#/components/schemas/NullableVariantY' discriminator: propertyName: tag mapping: '10': '#/components/schemas/NullableVariantX' '20': '#/components/schemas/NullableVariantY' NullableVariantX: type: object required: - tag - x_data properties: tag: type: - integer - 'null' const: 10 x_data: type: string NullableVariantY: type: object required: - tag - y_data properties: tag: type: - integer - 'null' const: 20 y_data: type: string ================================================ FILE: specs/3.1.x/discriminator-object-self-mapped.json ================================================ { "openapi": "3.1.0", "info": { "title": "Discriminator object schema with self mapping", "version": "1.0.0", "description": "Ensures a concrete schema with a discriminator mapping to itself gets a literal discriminator value instead of falling back to string." }, "paths": { "/blog-posts": { "get": { "summary": "Get blog posts", "responses": { "200": { "description": "List of blog posts", "content": { "application/json": { "schema": { "type": "array", "items": { "oneOf": [ { "$ref": "#/components/schemas/BlogPostDto" }, { "$ref": "#/components/schemas/BlogPostWithImageDto" } ] } } } } } } } } }, "components": { "schemas": { "BlogPostDto": { "type": "object", "required": ["$type", "id", "title"], "properties": { "$type": { "type": "string" }, "id": { "type": "integer" }, "title": { "type": "string" } }, "discriminator": { "propertyName": "$type", "mapping": { "BlogPost": "#/components/schemas/BlogPostDto", "BlogPostWithImage": "#/components/schemas/BlogPostWithImageDto" } } }, "BlogPostWithImageDto": { "allOf": [ { "$ref": "#/components/schemas/BlogPostDto" }, { "type": "object", "required": ["imageUrl"], "properties": { "imageUrl": { "type": "string" } } } ] } } } } ================================================ FILE: specs/3.1.x/discriminator-one-of-read-write.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 discriminator one of with read/write example version: 1 paths: /pets: post: requestBody: content: application/json: schema: $ref: '#/components/schemas/CreatePetRequest' required: true responses: '200': content: application/json: schema: $ref: '#/components/schemas/CreatePetResponse' description: OK components: schemas: AnimalPayload: type: object required: - typeDiscriminator properties: typeDiscriminator: type: string discriminator: propertyName: typeDiscriminator mapping: dog: '#/components/schemas/DogPayload' cat: '#/components/schemas/CatPayload' DogPayload: allOf: - $ref: '#/components/schemas/AnimalPayload' - type: object required: - breed - canFetch - displayBreed properties: breed: type: string canFetch: type: boolean displayBreed: type: string readOnly: true CatPayload: allOf: - $ref: '#/components/schemas/AnimalPayload' - type: object required: - breed - livesRemaining - displayBreed properties: breed: type: string livesRemaining: type: integer displayBreed: type: string readOnly: true CreatePetRequest: type: object required: - name - animal properties: name: type: string animal: oneOf: - $ref: '#/components/schemas/DogPayload' - $ref: '#/components/schemas/CatPayload' discriminator: propertyName: typeDiscriminator mapping: dog: '#/components/schemas/DogPayload' cat: '#/components/schemas/CatPayload' CreatePetResponse: type: object required: - id - name - animal properties: id: type: string name: type: string animal: oneOf: - $ref: '#/components/schemas/DogPayload' - $ref: '#/components/schemas/CatPayload' discriminator: propertyName: typeDiscriminator mapping: dog: '#/components/schemas/DogPayload' cat: '#/components/schemas/CatPayload' ================================================ FILE: specs/3.1.x/discriminator-one-of.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 discriminator one of example version: 1 components: schemas: Foo: oneOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' discriminator: propertyName: type Baz: allOf: - $ref: '#/components/schemas/Qux' Bar: allOf: - $ref: '#/components/schemas/Qux' Spæcial: allOf: - $ref: '#/components/schemas/Qux' Qux: type: object properties: id: type: string type: $ref: '#/components/schemas/Quux' required: - id - type Quux: enum: - Bar - Baz type: string Quuz: oneOf: - $ref: '#/components/schemas/Bar' - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/Spæcial' discriminator: propertyName: type mapping: bar: '#/components/schemas/Bar' baz: '#/components/schemas/Baz' 'non-ascii': '#/components/schemas/Spæcial' ================================================ FILE: specs/3.1.x/duplicate-null.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.0.0" }, "components": { "schemas": { "WeirdEnum": { "description": "should not produce duplicate null", "oneOf": [ { "type": "string", "enum": [""] }, { "type": ["string", "null"] }, { "type": "null" } ] } } } } ================================================ FILE: specs/3.1.x/enum-escape.json ================================================ { "openapi": "3.1.1", "info": { "title": "OpenAPI 3.1.1 enum escape example", "version": "1" }, "components": { "schemas": { "Foo": { "type": "object", "properties": { "foo": { "enum": ["foo'bar", "foo\"bar"], "type": "string" } } }, "Bar": { "enum": ["foo'bar", "foo\"bar"], "type": "string" } } } } ================================================ FILE: specs/3.1.x/enum-inline.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 enum inline example version: '1' paths: /foo: get: responses: '200': description: OK content: application/json: schema: type: object properties: foo: type: string enum: - foo - bar - FooBar - fooBar - foo bar post: responses: '200': description: 'OK' content: application/json: schema: type: object properties: foo: type: string enum: - baz put: responses: '200': description: 'OK' content: application/json: schema: $ref: '#/components/schemas/Baz' components: schemas: Foo: properties: type: enum: - foo - bar type: string type: object Bar: properties: type: $ref: '#/components/schemas/Baz' type: object Baz: enum: - qux - quux type: string ================================================ FILE: specs/3.1.x/enum-names-values.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 enum names values example version: '1' components: schemas: 1-10: enum: - 1-10 - 11-20 type: string myFoo: enum: - myFoo - myBar type: string MyFoo: enum: - MyFoo - MyBar type: string Foo: enum: - foo - bar - null - '' - true - false type: - string - 'null' Numbers: enum: - 100 - 200 - 300 - -100 - -200 - -300 type: number Arrays: enum: - - foo - - bar - - baz type: array MyFooRef: type: object properties: foo: type: array items: $ref: '#/components/schemas/MyFoo' ================================================ FILE: specs/3.1.x/enum-null.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 enum null example", "version": "1" }, "components": { "schemas": { "Foo": { "enum": ["foo", "bar", null], "type": ["string", "null"] }, "Bar": { "enum": ["foo", "bar", null], "type": "string" }, "Baz": { "enum": ["foo", "bar"], "type": ["string", "null"] } } } } ================================================ FILE: specs/3.1.x/exclude-deprecated.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 exclude deprecated example version: 1 paths: /foo: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Foo' required: true responses: '200': description: OK /bar: post: deprecated: true requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Bar' required: true responses: '200': description: OK components: schemas: Foo: type: string Bar: deprecated: true type: string ================================================ FILE: specs/3.1.x/external-shared.json ================================================ { "components": { "schemas": { "ExternalSharedModel": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" } }, "required": ["id"] }, "ExternalSharedModelWithUuid": { "type": "string", "format": "uuid" }, "ExternalNested": { "type": "object", "properties": { "inner": { "type": "object", "properties": { "deep": { "type": "string" } } } } }, "ExternalNestedNumeric": { "type": "object", "properties": { "0": { "type": "object", "properties": { "1": { "type": "string" } } } } } } } } ================================================ FILE: specs/3.1.x/external.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 external example version: 1 # Paths using external references paths: /external-model: get: summary: Get external model parameters: - $ref: '#/components/parameters/ExternalIdParam' - $ref: '#/components/parameters/ExternalUuidParam' responses: '200': $ref: '#/components/responses/ExternalModelResponse' '400': $ref: '#/components/responses/ExternalUuidResponse' post: summary: Create external model requestBody: $ref: '#/components/requestBodies/ExternalModelBody' responses: '201': $ref: '#/components/responses/ExternalModelResponse' '422': $ref: '#/components/responses/ExternalUnionResponse' /external-uuid: get: summary: Get external UUID parameters: - $ref: '#/components/parameters/ExternalUuidParam' responses: '200': $ref: '#/components/responses/ExternalUuidResponse' put: summary: Update external UUID requestBody: $ref: '#/components/requestBodies/ExternalUuidBody' responses: '200': $ref: '#/components/responses/ExternalUuidResponse' /external-nested: get: summary: Get external nested object parameters: - $ref: '#/components/parameters/ExternalDeepParam' responses: '200': $ref: '#/components/responses/ExternalNestedResponse' post: summary: Create external nested object requestBody: $ref: '#/components/requestBodies/ExternalNestedBody' responses: '201': $ref: '#/components/responses/ExternalNestedResponse' /external-mixed: get: summary: Get mixed external data parameters: - $ref: '#/components/parameters/ExternalIdParam' - $ref: '#/components/parameters/ExternalUuidParam' - $ref: '#/components/parameters/ExternalDeepParam' - $ref: '#/components/parameters/ExternalNumericParam' responses: '200': $ref: '#/components/responses/ExternalArrayResponse' post: summary: Create mixed external data requestBody: $ref: '#/components/requestBodies/ExternalMixedBody' responses: '201': $ref: '#/components/responses/ExternalModelResponse' /external-array: get: summary: Get array of external models responses: '200': $ref: '#/components/responses/ExternalArrayResponse' post: summary: Create array of external models requestBody: content: application/json: schema: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' required: true responses: '201': $ref: '#/components/responses/ExternalArrayResponse' /external-union: get: summary: Get union of external types responses: '200': $ref: '#/components/responses/ExternalUnionResponse' post: summary: Create union of external types requestBody: content: application/json: schema: oneOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/components/schemas/ExternalNested' required: true responses: '201': $ref: '#/components/responses/ExternalUnionResponse' /external-properties/{id}: get: summary: Get external properties parameters: - name: id in: path required: true schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' - name: uuid in: query schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - name: deep in: header schema: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' responses: '200': content: application/json: schema: type: object properties: id: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' name: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/name' uuid: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' deep: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' numeric: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' components: schemas: # Basic external schema references (multiple uses of each type) ExternalSchemaA: description: External schema (A) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalSchemaB: description: External schema (B) - second use of ExternalSharedModel $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalSchemaC: description: External schema (C) - third use of ExternalSharedModel $ref: './external-shared.json#/components/schemas/ExternalSharedModel' # Path-based references using /path syntax ExternalSchemaPathA: description: External schema via path reference (A) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalSchemaPathB: description: External schema via path reference (B) - second use $ref: './external-shared.json#/components/schemas/ExternalSharedModel' # UUID type references (multiple uses) ExternalSchemaPropertyA: description: External schema property (A) type: object properties: uuid1: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalSchemaPropertyB: description: External schema property (B) - second use of UUID type: object properties: uuid2: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalSchemaPropertyC: description: External schema property (C) - third use of UUID type: object properties: uuid3: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # Duplicate refs in same schema ExternalSchemaPropertyD: description: External schema property with duplicate refs (D) type: object properties: uuid4: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' uuid5: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # External property references ExternalSchemaExternalProp: description: External schema property via external property ref (id) type: object properties: id3: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' id4: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' # Alias references ExternalSchemaExternalPropAlias: description: Alias to external property via component property ref type: object properties: id5: $ref: '#/components/schemas/ExternalSchemaExternalProp/properties/id3' id6: $ref: '#/components/schemas/ExternalSchemaExternalProp/properties/id4' # Nested property references (multiple uses) ExternalDoubleNestedProp: description: External double nested prop via property ref type: object properties: deep1: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' deep2: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' # Numeric property references (multiple uses) ExternalDoubleNestedNumeric: description: External double nested numeric properties type: object properties: numeric1: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' numeric2: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' # Complex nested object references ExternalNestedObjectA: description: External nested object reference (A) $ref: './external-shared.json#/components/schemas/ExternalNested' ExternalNestedObjectB: description: External nested object reference (B) - second use $ref: './external-shared.json#/components/schemas/ExternalNested' # Numeric nested object references ExternalNestedNumericObjectA: description: External numeric nested object reference (A) $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' ExternalNestedNumericObjectB: description: External numeric nested object reference (B) - second use $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' # Mixed property references ExternalMixedProperties: description: Mixed external property references type: object properties: id7: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' name1: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/name' uuid6: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' deep3: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' numeric3: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' # Array of external references ExternalArraySchema: description: Array containing external references type: object properties: items: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' uuidItems: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # Union types with external references ExternalUnionSchema: description: Union type with external references oneOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # AllOf with external references ExternalAllOfSchema: description: AllOf with external references allOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - type: object properties: additional: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' # AnyOf with external references ExternalAnyOfSchema: description: AnyOf with external references anyOf: - $ref: './external-shared.json#/components/schemas/ExternalNested' - $ref: './external-shared.json#/components/schemas/ExternalNested' - $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' - $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric' # Parameters using external references parameters: ExternalIdParam: name: id in: path required: true schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' ExternalUuidParam: name: uuid in: query schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalDeepParam: name: deep in: header schema: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' ExternalNumericParam: name: numeric in: query schema: $ref: './external-shared.json#/components/schemas/ExternalNestedNumeric/properties/0/properties/1' # Request bodies using external references requestBodies: ExternalModelBody: description: Request body using external model required: true content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalUuidBody: description: Request body using external UUID content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalNestedBody: description: Request body using external nested object content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalNested' ExternalMixedBody: description: Request body with mixed external properties content: application/json: schema: type: object properties: id: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' name: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/name' uuid: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' deep: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' # Responses using external references responses: ExternalModelResponse: description: Response using external model content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalUuidResponse: description: Response using external UUID content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalNestedResponse: description: Response using external nested object content: application/json: schema: $ref: './external-shared.json#/components/schemas/ExternalNested' ExternalArrayResponse: description: Response with array of external models content: application/json: schema: type: array items: $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalUnionResponse: description: Response with union of external types content: application/json: schema: oneOf: - $ref: './external-shared.json#/components/schemas/ExternalSharedModel' - $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' - $ref: './external-shared.json#/components/schemas/ExternalNested' # Headers using external references headers: ExternalIdHeader: description: Header using external ID property schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModel/properties/id' ExternalUuidHeader: description: Header using external UUID schema: $ref: './external-shared.json#/components/schemas/ExternalSharedModelWithUuid' ExternalDeepHeader: description: Header using external deep property schema: $ref: './external-shared.json#/components/schemas/ExternalNested/properties/inner/properties/deep' ================================================ FILE: specs/3.1.x/formats.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 formats example version: '1' components: schemas: NumberNoFormat: type: number NumberInt8: type: number format: int8 NumberInt16: type: number format: int16 NumberInt32: type: number format: int32 NumberInt64: type: number format: int64 NumberUint8: type: number format: uint8 NumberUint16: type: number format: uint16 NumberUint32: type: number format: uint32 NumberUint64: type: number format: uint64 IntegerNoFormat: type: integer IntegerInt8: type: integer format: int8 IntegerInt16: type: integer format: int16 IntegerInt32: type: integer format: int32 IntegerInt64: type: integer format: int64 IntegerUint8: type: integer format: uint8 IntegerUint16: type: integer format: uint16 IntegerUint32: type: integer format: uint32 IntegerUint64: type: integer format: uint64 StringInt64: type: string format: int64 StringUint64: type: string format: uint64 ================================================ FILE: specs/3.1.x/full.yaml ================================================ openapi: 3.1.0 info: title: swagger version: v1.0 servers: - url: http://localhost:3000/base paths: /api/v{api-version}/no+tag: tags: [] get: operationId: export patch: responses: default: description: OK post: operationId: import requestBody: required: true content: application/json: schema: type: object oneOf: - $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' - $ref: '#/components/schemas/ModelWithArrayReadOnlyAndWriteOnly' responses: '200': description: Success content: application/json; type=collection: schema: $ref: '#/components/schemas/Model-From.Zendesk' default: description: Default success response content: application/json: schema: $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' put: operationId: foo+Wow responses: default: description: OK /api/v{api-version}/simple/$count: get: tags: - Simple operationId: api/v{version}/ODataController/$count responses: '200': description: Success content: application/json; type=collection: schema: $ref: '#/components/schemas/Model-From.Zendesk' /api/v{api-version}/simple:operation: get: parameters: - description: foo in method in: path name: foo_param required: true schema: oneOf: - type: string - format: uuid type: string responses: '200': description: Response is a simple number content: application/json: schema: type: number default: description: Default error response content: application/json: schema: $ref: '#/components/schemas/ModelWithBoolean' /api/v{api-version}/simple: get: tags: - Simple operationId: GetCallWithoutParametersAndResponse put: tags: - Simple operationId: PutCallWithoutParametersAndResponse post: tags: - Simple operationId: PostCallWithoutParametersAndResponse delete: tags: - Simple operationId: DeleteCallWithoutParametersAndResponse options: tags: - Simple operationId: OptionsCallWithoutParametersAndResponse head: tags: - Simple operationId: HeadCallWithoutParametersAndResponse patch: tags: - Simple operationId: PatchCallWithoutParametersAndResponse /api/v{api-version}/foo/{foo_param}/bar/{BarParam}: delete: tags: - Parameters operationId: deleteFoo parameters: - description: foo in method in: path name: foo_param required: true schema: type: string - description: bar in method in: path name: BarParam required: true schema: type: string - description: Parameter with illegal characters name: x-Foo-Bar in: header required: true content: application/json: schema: $ref: '#/components/schemas/ModelWithString' parameters: - description: foo in global parameters in: path name: foo_param required: true schema: type: string - description: bar in global parameters in: path name: BarParam required: true schema: type: string /api/v{api-version}/descriptions: post: tags: - Descriptions operationId: CallWithDescriptions parameters: - description: |- Testing multiline comments in string: First line Second line Fourth line name: parameterWithBreaks in: query schema: type: string - description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work' name: parameterWithBackticks in: query schema: type: string - description: "Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work" name: parameterWithSlashes in: query schema: type: string - description: 'Testing expression placeholders in string: ${expression} should work' name: parameterWithExpressionPlaceholders in: query schema: type: string - description: 'Testing quotes in string: ''single quote'''''' and "double quotes""" should work' name: parameterWithQuotes in: query schema: type: string - description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work' name: parameterWithReservedCharacters in: query schema: type: string /api/v{api-version}/parameters/deprecated: post: tags: - Deprecated deprecated: true operationId: DeprecatedCall parameters: - deprecated: true description: This parameter is deprecated name: parameter in: header required: true schema: oneOf: - $ref: '#/components/schemas/DeprecatedModel' - type: 'null' /api/v{api-version}/parameters/{parameterPath}: post: tags: - Parameters operationId: CallWithParameters parameters: - description: This is the parameter that goes into the header name: parameterHeader in: header required: true schema: type: - string - 'null' - required: false schema: $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' name: foo_ref_enum in: query - required: true schema: allOf: - $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' name: foo_all_of_enum in: query - description: This is the parameter that goes into the query params name: cursor in: query required: true schema: type: - string - 'null' - description: This is the parameter that goes into the cookie name: parameterCookie in: cookie required: true schema: type: - string - 'null' - description: This is the parameter that goes into the path name: parameterPath in: path required: true schema: type: - string - 'null' - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: - string - 'null' requestBody: description: This is the parameter that goes into the body required: true content: application/json: schema: properties: {} type: - object - 'null' /api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}: post: tags: - Parameters operationId: CallWithWeirdParameterNames parameters: - description: This is the parameter that goes into the path name: parameter.path.1 in: path required: false schema: type: string - description: This is the parameter that goes into the path name: parameter-path-2 in: path required: false schema: type: string - description: This is the parameter that goes into the path name: PARAMETER-PATH-3 in: path required: false schema: type: string - description: This is the parameter with a reserved keyword name: default in: query required: false schema: type: string - description: This is the parameter that goes into the request header name: parameter.header in: header required: true schema: type: - string - 'null' - description: This is the parameter that goes into the request query params name: parameter-query in: query required: true schema: type: - string - 'null' - description: This is the parameter that goes into the cookie name: PARAMETER-COOKIE in: cookie required: true schema: type: - string - 'null' - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: - string - 'null' requestBody: description: This is the parameter that goes into the body required: true content: application/json: schema: oneOf: - $ref: '#/components/schemas/ModelWithString' - type: 'null' /api/v{api-version}/parameters: get: tags: - Parameters operationId: GetCallWithOptionalParam parameters: - description: This is an optional parameter name: page in: query required: false schema: type: number requestBody: description: This is a required parameter required: true content: application/json: schema: $ref: '#/components/schemas/ModelWithOneOfEnum' post: tags: - Parameters operationId: PostCallWithOptionalParam parameters: - description: This is a required parameter name: parameter in: query required: true schema: $ref: '#/components/schemas/Pageable' requestBody: description: This is an optional parameter required: false content: application/json: schema: properties: offset: required: true type: - number - 'null' type: object responses: '200': description: Response is a simple number content: application/json: schema: type: number '204': description: Success /api/v{api-version}/requestBody: post: tags: - RequestBody parameters: - $ref: '#/components/parameters/SimpleParameter' requestBody: $ref: '#/components/requestBodies/SimpleRequestBody' /api/v{api-version}/formData: post: tags: - FormData parameters: - $ref: '#/components/parameters/SimpleParameter' requestBody: $ref: '#/components/requestBodies/SimpleFormData' /api/v{api-version}/defaults: get: tags: - Defaults operationId: CallWithDefaultParameters parameters: - description: This is a simple string with default value name: parameterString in: query schema: default: Hello World! type: - string - 'null' - description: This is a simple number with default value name: parameterNumber in: query schema: default: 123 type: - number - 'null' - description: This is a simple boolean with default value name: parameterBoolean in: query schema: default: true type: - boolean - 'null' - description: This is a simple enum with default value name: parameterEnum in: query schema: enum: - Success - Warning - Error default: 0 - description: This is a simple model with default value name: parameterModel in: query schema: oneOf: - $ref: '#/components/schemas/ModelWithString' default: prop: Hello World! - type: 'null' post: tags: - Defaults operationId: CallWithDefaultOptionalParameters parameters: - description: This is a simple string that is optional with default value name: parameterString in: query required: false schema: type: string default: Hello World! - description: This is a simple number that is optional with default value name: parameterNumber in: query required: false schema: type: number default: 123 - description: This is a simple boolean that is optional with default value name: parameterBoolean in: query required: false schema: type: boolean default: true - description: This is a simple enum that is optional with default value name: parameterEnum in: query required: false schema: enum: - Success - Warning - Error default: 0 - description: This is a simple model that is optional with default value name: parameterModel in: query required: false schema: $ref: '#/components/schemas/ModelWithString' default: prop: Hello World! put: tags: - Defaults operationId: CallToTestOrderOfParams parameters: - description: This is a optional string with default name: parameterOptionalStringWithDefault in: query required: false schema: type: string default: Hello World! - description: This is a optional string with empty default name: parameterOptionalStringWithEmptyDefault in: query required: false schema: type: string default: '' - description: This is a optional string with no default name: parameterOptionalStringWithNoDefault in: query required: false schema: type: string - description: This is a string with default name: parameterStringWithDefault in: query required: true schema: type: string default: Hello World! - description: This is a string with empty default name: parameterStringWithEmptyDefault in: query required: true schema: type: string default: '' - description: This is a string with no default name: parameterStringWithNoDefault in: query required: true schema: type: string - description: This is a string that can be null with no default name: parameterStringNullableWithNoDefault in: query required: false schema: type: - string - 'null' - description: This is a string that can be null with default name: parameterStringNullableWithDefault in: query required: false schema: default: null type: - string - 'null' /api/v{api-version}/duplicate: delete: tags: - Duplicate - Duplicate operationId: DuplicateName get: tags: - Duplicate operationId: DuplicateName2 post: tags: - Duplicate operationId: DuplicateName3 put: tags: - Duplicate operationId: DuplicateName4 /api/v{api-version}/no-content: get: tags: - noContent operationId: CallWithNoContentResponse responses: '204': description: Success /api/v{api-version}/multiple-tags/response-and-no-content: get: tags: - Response - NoContent operationId: CallWithResponseAndNoContentResponse responses: '200': description: Response is a simple number content: application/json: schema: type: number '204': description: Success /api/v{api-version}/multiple-tags/a: get: tags: - MultipleTags1 - MultipleTags2 operationId: DummyA responses: '200': content: application/json: schema: $ref: '#/components/schemas/400' /api/v{api-version}/multiple-tags/b: get: tags: - MultipleTags1 - MultipleTags2 - MultipleTags3 operationId: DummyB responses: '204': description: Success /api/v{api-version}/response: get: tags: - Response operationId: CallWithResponse responses: default: content: application/json: schema: $ref: '#/components/schemas/import' post: tags: - Response operationId: CallWithDuplicateResponses responses: '200': description: Message for 200 response content: application/json: schema: allOf: - $ref: '#/components/schemas/ModelWithBoolean' - $ref: '#/components/schemas/ModelWithInteger' '201': description: Message for 201 response content: application/json: schema: $ref: '#/components/schemas/ModelWithString' '202': description: Message for 202 response content: application/json: schema: $ref: '#/components/schemas/ModelWithString' '500': description: Message for 500 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '501': description: Message for 501 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '502': description: Message for 502 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' default: description: Default error response content: application/json: schema: $ref: '#/components/schemas/ModelWithBoolean' 4XX: description: Message for 4XX errors content: application/json: schema: $ref: '#/components/schemas/DictionaryWithArray' put: tags: - Response operationId: CallWithResponses responses: '200': description: Message for 200 response content: application/json: schema: type: object properties: '@namespace.string': type: string readOnly: true '@namespace.integer': type: integer readOnly: true value: type: array items: $ref: '#/components/schemas/ModelWithString' readOnly: true '201': description: Message for 201 response content: application/json: schema: $ref: '#/components/schemas/ModelThatExtends' '202': description: Message for 202 response content: application/json: schema: $ref: '#/components/schemas/ModelThatExtendsExtends' '500': description: Message for 500 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '501': description: Message for 501 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' '502': description: Message for 502 error content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' default: description: Message for default response content: application/json: schema: $ref: '#/components/schemas/ModelWithStringError' /api/v{api-version}/collectionFormat: get: tags: - CollectionFormat operationId: CollectionFormat parameters: - description: This is an array parameter that is sent as csv format (comma-separated values) name: parameterArrayCSV in: query required: true schema: type: - array - 'null' items: type: string collectionFormat: csv - description: This is an array parameter that is sent as ssv format (space-separated values) name: parameterArraySSV in: query required: true schema: type: - array - 'null' items: type: string collectionFormat: ssv - description: This is an array parameter that is sent as tsv format (tab-separated values) name: parameterArrayTSV in: query required: true schema: type: - array - 'null' items: type: string collectionFormat: tsv - description: This is an array parameter that is sent as pipes format (pipe-separated values) name: parameterArrayPipes in: query required: true schema: type: - array - 'null' items: type: string collectionFormat: pipes - description: This is an array parameter that is sent as multi format (multiple parameter instances) name: parameterArrayMulti in: query required: true schema: type: - array - 'null' items: type: string collectionFormat: multi /api/v{api-version}/types: get: tags: - Types operationId: Types parameters: - description: This is a number parameter name: parameterNumber in: query required: true schema: type: number default: 123 - description: This is a string parameter name: parameterString in: query required: true schema: type: - string - 'null' default: default - description: This is a boolean parameter name: parameterBoolean in: query required: true schema: type: - boolean - 'null' default: true - description: This is an object parameter name: parameterObject in: query required: true schema: type: - object - 'null' default: null - description: This is an array parameter name: parameterArray in: query required: true schema: type: - array - 'null' items: type: string - description: This is a dictionary parameter name: parameterDictionary in: query required: true schema: type: - object - 'null' items: type: string - description: This is an enum parameter name: parameterEnum in: query required: true schema: oneOf: - enum: - Success - Warning - Error - type: 'null' - description: This is a number parameter name: id in: path schema: type: integer format: int32 responses: '200': description: Response is a simple number content: application/json: schema: type: number '201': description: Response is a simple string content: application/json: schema: type: string '202': description: Response is a simple boolean content: application/json: schema: type: boolean '203': description: Response is a simple object content: application/json: schema: type: object /api/v{api-version}/upload: post: tags: - Upload operationId: UploadFile parameters: - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: - string - 'null' requestBody: content: application/x-www-form-urlencoded: description: Supply a file reference for upload schema: format: binary type: string required: true responses: '200': content: application/json: schema: type: boolean /api/v{api-version}/file/{id}: get: tags: - FileResponse operationId: FileResponse parameters: - name: id in: path required: true schema: type: string - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: string responses: '200': description: Success content: audio/*: schema: format: binary type: string video/*: schema: format: binary type: string /api/v{api-version}/complex: get: tags: - Complex operationId: ComplexTypes parameters: - description: Parameter containing object name: parameterObject in: query required: true schema: type: object properties: first: type: object properties: second: type: object properties: third: type: string - description: Parameter containing reference name: parameterReference in: query required: true schema: $ref: '#/components/schemas/ModelWithString' responses: '200': description: Successful response content: application/json: schema: type: array items: $ref: '#/components/schemas/ModelWithString' '400': description: 400 `server` error '500': description: 500 server error /api/v{api-version}/multipart: post: tags: - multipart operationId: MultipartRequest requestBody: content: multipart/form-data: schema: type: object properties: content: type: string format: binary data: oneOf: - $ref: '#/components/schemas/ModelWithString' - type: 'null' encoding: content: style: form data: style: form get: tags: - multipart operationId: MultipartResponse responses: '200': description: OK content: multipart/mixed: schema: type: object properties: file: type: string format: binary metadata: type: object properties: foo: type: string bar: type: string /api/v{api-version}/complex/{id}: put: tags: - Complex operationId: ComplexParams parameters: - name: id in: path required: true schema: type: integer format: int32 - description: api-version should be required in standalone clients name: api-version in: path required: true schema: type: string requestBody: content: application/json-patch+json: schema: required: - key - name - parameters - type type: object properties: key: maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ type: - string - 'null' readOnly: true name: maxLength: 255 type: - string - 'null' enabled: type: boolean default: true type: enum: - Monkey - Horse - Bird type: string readOnly: true listOfModels: type: - array - 'null' items: $ref: '#/components/schemas/ModelWithString' listOfStrings: type: - array - 'null' items: type: string parameters: type: object oneOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' user: type: object properties: id: type: integer format: int32 readOnly: true name: type: - string - 'null' readOnly: true readOnly: true responses: '200': description: Success content: application/json; type=collection: schema: $ref: '#/components/schemas/ModelWithString' /api/v{api-version}/header: post: tags: - Header operationId: CallWithResultFromHeader responses: '200': description: Successful response headers: operation-location: schema: type: string '400': description: 400 server error '500': description: 500 server error /api/v{api-version}/error: post: tags: - Error operationId: testErrorCode parameters: - description: Status code to return name: status in: query required: true schema: type: integer responses: '200': description: 'Custom message: Successful response' '500': description: 'Custom message: Internal Server Error' '501': description: 'Custom message: Not Implemented' '502': description: 'Custom message: Bad Gateway' '503': description: 'Custom message: Service Unavailable' /api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串: post: tags: - Non-Ascii-æøåÆØÅöôêÊ operationId: nonAsciiæøåÆØÅöôêÊ字符串 parameters: - description: Dummy input param name: nonAsciiParamæøåÆØÅöôêÊ in: query required: true schema: type: integer responses: '200': description: Successful response content: application/json: schema: type: array items: $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' put: tags: - Non-Ascii-æøåÆØÅöôêÊ summary: Login User operationId: putWithFormUrlEncoded requestBody: content: application/x-www-form-urlencoded: schema: $ref: '#/components/schemas/ArrayWithStrings' required: true components: requestBodies: SimpleRequestBody: x-body-name: foo description: A reusable request body required: false content: application/json: schema: $ref: '#/components/schemas/ModelWithString' SimpleFormData: description: A reusable request body required: false content: multipart/form-data: schema: $ref: '#/components/schemas/ModelWithString' parameters: SimpleParameter: description: This is a reusable parameter name: parameter in: query required: false schema: type: string x-Foo-Bar: description: Parameter with illegal characters name: x-Foo-Bar in: header required: true content: application/json: schema: $ref: '#/components/schemas/ModelWithString' schemas: ExternalRefA: description: External ref to shared model (A) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' ExternalRefB: description: External ref to shared model (B) $ref: './external-shared.json#/components/schemas/ExternalSharedModel' '400': description: Model with number-only name type: string camelCaseCommentWithBreaks: description: |- Testing multiline comments in string: First line Second line Fourth line type: integer CommentWithBreaks: description: |- Testing multiline comments in string: First line Second line Fourth line type: integer CommentWithBackticks: description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work' type: integer CommentWithBackticksAndQuotes: description: 'Testing backticks and quotes in string: `backticks`, ''quotes'', "double quotes" and ```multiple backticks``` should work' type: integer CommentWithSlashes: description: "Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work" type: integer CommentWithExpressionPlaceholders: description: 'Testing expression placeholders in string: ${expression} should work' type: integer CommentWithQuotes: description: 'Testing quotes in string: ''single quote'''''' and "double quotes""" should work' type: integer CommentWithReservedCharacters: description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work' type: integer SimpleInteger: description: This is a simple number type: integer SimpleBoolean: description: This is a simple boolean type: boolean SimpleString: description: This is a simple string type: string NonAsciiStringæøåÆØÅöôêÊ字符串: description: A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) type: string SimpleFile: description: This is a simple file format: binary type: string SimpleReference: description: This is a simple reference $ref: '#/components/schemas/ModelWithString' SimpleStringWithPattern: description: This is a simple string maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ type: - string - 'null' EnumWithStrings: description: This is a simple enum with strings enum: - Success - Warning - Error - "'Single Quote'" - '"Double Quotes"' - 'Non-ascii: øæåôöØÆÅÔÖ字符串' EnumWithReplacedCharacters: enum: - "'Single Quote'" - '"Double Quotes"' - øæåôöØÆÅÔÖ字符串 - 3.1 - '' type: string EnumWithNumbers: description: This is a simple enum with numbers enum: - 1 - 2 - 3 - 1.1 - 1.2 - 1.3 - 100 - 200 - 300 - -100 - -200 - -300 - -1.1 - -1.2 - -1.3 default: 200 EnumFromDescription: description: Success=1,Warning=2,Error=3 type: number EnumWithExtensions: description: This is a simple enum with numbers enum: - 200 - 400 - 500 x-enum-varnames: - CUSTOM_SUCCESS - CUSTOM_WARNING - CUSTOM_ERROR x-enum-descriptions: - Used when the status of something is successful - Used when the status of something has a warning - Used when the status of something has an error EnumWithXEnumNames: enum: - 0 - 1 - 2 x-enumNames: - zero - one - two ArrayWithNumbers: description: This is a simple array with numbers type: array items: type: integer ArrayWithBooleans: description: This is a simple array with booleans type: array items: type: boolean ArrayWithStrings: description: This is a simple array with strings type: array items: type: string default: - test ArrayWithReferences: description: This is a simple array with references type: array items: $ref: '#/components/schemas/ModelWithString' ArrayWithArray: description: This is a simple array containing an array type: array items: type: array items: $ref: '#/components/schemas/ModelWithString' ArrayWithProperties: description: This is a simple array with properties type: array items: type: object properties: 16x16: $ref: '#/components/schemas/camelCaseCommentWithBreaks' bar: type: string ArrayWithAnyOfProperties: description: This is a simple array with any of properties type: array items: anyOf: - type: object properties: foo: type: string default: test - type: object properties: bar: type: string AnyOfAnyAndNull: type: object properties: data: anyOf: - {} - type: 'null' AnyOfArrays: description: This is a simple array with any of properties type: object properties: results: items: anyOf: - type: object properties: foo: type: string - type: object properties: bar: type: string type: array DictionaryWithString: description: This is a string dictionary type: object additionalProperties: type: string DictionaryWithPropertiesAndAdditionalProperties: type: object properties: foo: type: number bar: type: boolean additionalProperties: type: string DictionaryWithReference: description: This is a string reference type: object additionalProperties: $ref: '#/components/schemas/ModelWithString' DictionaryWithArray: description: This is a complex dictionary type: object additionalProperties: type: array items: $ref: '#/components/schemas/ModelWithString' DictionaryWithDictionary: description: This is a string dictionary type: object additionalProperties: type: object additionalProperties: type: string DictionaryWithProperties: description: This is a complex dictionary type: object additionalProperties: type: object properties: foo: type: string bar: type: string ModelWithInteger: description: This is a model with one number property type: object properties: prop: description: This is a simple number property type: integer ModelWithBoolean: description: This is a model with one boolean property type: object properties: prop: description: This is a simple boolean property type: boolean ModelWithString: description: This is a model with one string property type: object properties: prop: description: This is a simple string property type: string ModelWithStringError: description: This is a model with one string property type: object properties: prop: description: This is a simple string property type: string Model-From.Zendesk: description: "`Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comment\ s-to-tickets)" type: string ModelWithNullableString: description: This is a model with one string property type: object required: - nullableRequiredProp1 - nullableRequiredProp2 properties: nullableProp1: description: This is a simple string property type: - string - 'null' nullableRequiredProp1: description: This is a simple string property type: - string - 'null' nullableProp2: description: This is a simple string property type: - string - 'null' nullableRequiredProp2: description: This is a simple string property type: - string - 'null' foo_bar-enum: description: This is a simple enum with strings enum: - Success - Warning - Error - ØÆÅ字符串 ModelWithEnum: description: This is a model with one enum type: object properties: foo_bar-enum: description: This is a simple enum with strings enum: - Success - Warning - Error - ØÆÅ字符串 statusCode: description: These are the HTTP error code enums enum: - '100' - 200 FOO - 300 FOO_BAR - 400 foo-bar - 500 foo.bar - 600 foo&bar bool: description: Simple boolean enum type: boolean enum: - true ModelWithEnumWithHyphen: description: This is a model with one enum with escaped name type: object properties: foo-bar-baz-qux: type: string enum: - '3.0' title: Foo-Bar-Baz-Qux default: '3.0' ModelWithEnumFromDescription: description: This is a model with one enum type: object properties: test: type: integer description: Success=1,Warning=2,Error=3 ModelWithNestedEnums: description: This is a model with nested enums type: object properties: dictionaryWithEnum: type: object additionalProperties: enum: - Success - Warning - Error dictionaryWithEnumFromDescription: type: object additionalProperties: type: integer description: Success=1,Warning=2,Error=3 arrayWithEnum: type: array items: enum: - Success - Warning - Error arrayWithDescription: type: array items: type: integer description: Success=1,Warning=2,Error=3 foo_bar-enum: description: This is a simple enum with strings enum: - Success - Warning - Error - ØÆÅ字符串 ModelWithReference: description: This is a model with one property containing a reference type: object properties: prop: $ref: '#/components/schemas/ModelWithProperties' ModelWithArrayReadOnlyAndWriteOnly: description: This is a model with one property containing an array type: object properties: prop: type: array items: $ref: '#/components/schemas/ModelWithReadOnlyAndWriteOnly' propWithFile: type: array items: format: binary type: string propWithNumber: type: array items: type: number ModelWithArray: description: This is a model with one property containing an array type: object properties: prop: type: array items: $ref: '#/components/schemas/ModelWithString' propWithFile: type: array items: format: binary type: string propWithNumber: type: array items: type: number ModelWithDictionary: description: This is a model with one property containing a dictionary type: object properties: prop: type: object additionalProperties: type: string DeprecatedModel: deprecated: true description: This is a deprecated model with a deprecated property type: object properties: prop: deprecated: true description: This is a deprecated property type: string ModelWithCircularReference: description: This is a model with one property containing a circular reference type: object properties: prop: $ref: '#/components/schemas/ModelWithCircularReference' CompositionWithOneOf: description: This is a model with one property with a 'one of' relationship type: object properties: propA: type: object oneOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithOneOfAnonymous: description: This is a model with one property with a 'one of' relationship where the options are not $ref type: object properties: propA: type: object oneOf: - description: Anonymous object type type: object properties: propA: type: string - description: Anonymous string type type: string - description: Anonymous integer type type: integer ModelCircle: description: Circle type: object required: - kind properties: kind: type: string radius: type: number ModelSquare: description: Square type: object required: - kind properties: kind: type: string sideLength: type: number CompositionWithOneOfDiscriminator: description: This is a model with one property with a 'one of' relationship where the options are not $ref type: object oneOf: - $ref: '#/components/schemas/ModelCircle' - $ref: '#/components/schemas/ModelSquare' discriminator: propertyName: kind mapping: circle: '#/components/schemas/ModelCircle' square: '#/components/schemas/ModelSquare' CompositionWithAnyOf: description: This is a model with one property with a 'any of' relationship type: object properties: propA: type: object anyOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithAnyOfAnonymous: description: This is a model with one property with a 'any of' relationship where the options are not $ref type: object properties: propA: type: object anyOf: - description: Anonymous object type type: object properties: propA: type: string - description: Anonymous string type type: string - description: Anonymous integer type type: integer CompositionWithNestedAnyAndTypeNull: description: This is a model with nested 'any of' property with a type null type: object properties: propA: type: object anyOf: - items: anyOf: - $ref: '#/components/schemas/ModelWithDictionary' - type: 'null' type: array - items: anyOf: - $ref: '#/components/schemas/ModelWithArray' - type: 'null' type: array 3e-num_1Период: enum: - Bird - Dog type: string ConstValue: type: string const: ConstValue CompositionWithNestedAnyOfAndNull: description: This is a model with one property with a 'any of' relationship where the options are not $ref type: object properties: propA: anyOf: - items: anyOf: - $ref: '#/components/schemas/3e-num_1Период' - $ref: '#/components/schemas/ConstValue' type: array - type: 'null' title: Scopes CompositionWithOneOfAndNullable: description: This is a model with one property with a 'one of' relationship type: object properties: propA: type: - object - 'null' oneOf: - type: object properties: boolean: type: boolean - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithOneOfAndSimpleDictionary: description: This is a model that contains a simple dictionary within composition type: object properties: propA: oneOf: - type: boolean - type: object additionalProperties: type: number CompositionWithOneOfAndSimpleArrayDictionary: description: This is a model that contains a dictionary of simple arrays within composition type: object properties: propA: oneOf: - type: boolean - type: object additionalProperties: type: array items: type: boolean CompositionWithOneOfAndComplexArrayDictionary: description: This is a model that contains a dictionary of complex arrays (composited) within composition type: object properties: propA: oneOf: - type: boolean - type: object additionalProperties: type: array items: oneOf: - type: number - type: string CompositionWithAllOfAndNullable: description: This is a model with one property with a 'all of' relationship type: object properties: propA: type: - object - 'null' allOf: - type: object properties: boolean: type: boolean - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionWithAnyOfAndNullable: description: This is a model with one property with a 'any of' relationship type: object properties: propA: type: - object - 'null' anyOf: - type: object properties: boolean: type: boolean - $ref: '#/components/schemas/ModelWithEnum' - $ref: '#/components/schemas/ModelWithArray' - $ref: '#/components/schemas/ModelWithDictionary' CompositionBaseModel: description: This is a base model with two simple optional properties type: object properties: firstName: type: string lastname: type: string CompositionExtendedModel: description: This is a model that extends the base model type: object allOf: - $ref: '#/components/schemas/CompositionBaseModel' properties: age: type: number required: - firstName - lastname - age ModelWithProperties: description: This is a model with one nested property type: object required: - required - requiredAndReadOnly - requiredAndNullable properties: required: type: string requiredAndReadOnly: type: string readOnly: true requiredAndNullable: type: - string - 'null' string: type: string number: type: number boolean: type: boolean reference: $ref: '#/components/schemas/ModelWithString' property with space: type: string default: type: string try: type: string '@namespace.string': type: string readOnly: true '@namespace.integer': type: integer readOnly: true ModelWithNestedProperties: description: This is a model with one nested property type: object required: - first properties: first: type: - object - 'null' required: - second readOnly: true properties: second: type: - object - 'null' required: - third readOnly: true properties: third: type: - string - 'null' required: true readOnly: true ModelWithDuplicateProperties: description: This is a model with duplicated properties type: object properties: prop: $ref: '#/components/schemas/ModelWithString' ModelWithOrderedProperties: description: This is a model with ordered properties type: object properties: zebra: type: string apple: type: string hawaii: type: string ModelWithDuplicateImports: description: This is a model with duplicated imports type: object properties: propA: $ref: '#/components/schemas/ModelWithString' propB: $ref: '#/components/schemas/ModelWithString' propC: $ref: '#/components/schemas/ModelWithString' ModelThatExtends: description: This is a model that extends another model type: object allOf: - $ref: '#/components/schemas/ModelWithString' - type: object properties: propExtendsA: type: string propExtendsB: $ref: '#/components/schemas/ModelWithString' ModelThatExtendsExtends: description: This is a model that extends another model type: object allOf: - $ref: '#/components/schemas/ModelWithString' - $ref: '#/components/schemas/ModelThatExtends' - type: object properties: propExtendsC: type: string propExtendsD: $ref: '#/components/schemas/ModelWithString' ModelWithPattern: description: This is a model that contains a some patterns type: object required: - key - name properties: key: maxLength: 64 pattern: ^[a-zA-Z0-9_]*$ type: string name: maxLength: 255 type: string enabled: type: boolean readOnly: true modified: type: string format: date-time readOnly: true id: type: string pattern: ^\d{2}-\d{3}-\d{4}$ text: type: string pattern: ^\w+$ patternWithSingleQuotes: type: string pattern: ^[a-zA-Z0-9']*$ patternWithNewline: type: string pattern: aaa\nbbb patternWithBacktick: type: string pattern: aaa`bbb patternWithUnicode: type: string pattern: ^\p{L}+$ File: required: - mime type: object properties: id: title: Id type: string readOnly: true minLength: 1 updated_at: title: Updated at type: string format: date-time readOnly: true created_at: title: Created at type: string format: date-time readOnly: true mime: title: Mime type: string maxLength: 24 minLength: 1 file: title: File type: string readOnly: true format: uri default: type: object properties: name: type: string Pageable: type: object properties: page: minimum: 0 type: integer format: int32 default: 0 size: minimum: 1 type: integer format: int32 sort: type: array items: type: string FreeFormObjectWithoutAdditionalProperties: description: This is a free-form object without additionalProperties. type: object FreeFormObjectWithAdditionalPropertiesEqTrue: description: 'This is a free-form object with additionalProperties: true.' type: object additionalProperties: true FreeFormObjectWithAdditionalPropertiesEqEmptyObject: description: 'This is a free-form object with additionalProperties: {}.' type: object additionalProperties: {} ModelWithConst: type: object properties: String: const: String number: const: 0 'null': const: null withType: type: string const: Some string ModelWithAdditionalPropertiesEqTrue: description: 'This is a model with one property and additionalProperties: true' type: object properties: prop: description: This is a simple string property type: string additionalProperties: true NestedAnyOfArraysNullable: properties: nullableArray: anyOf: - items: anyOf: - type: string - type: boolean type: array - type: 'null' type: object CompositionWithOneOfAndProperties: type: object oneOf: - type: object required: - foo properties: foo: $ref: '#/components/parameters/SimpleParameter' additionalProperties: false - type: object required: - bar properties: bar: $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' additionalProperties: false required: - baz - qux properties: baz: type: - integer - 'null' format: uint16 minimum: 0 qux: type: integer format: uint8 minimum: 0 NullableObject: type: - object - 'null' description: An object that can be null properties: foo: type: string default: null CharactersInDescription: type: string description: Some % character ModelWithNullableObject: type: object properties: data: $ref: '#/components/schemas/NullableObject' ModelWithAdditionalPropertiesRef: type: object description: An object with additional properties that can be null (anyOf ref + null) additionalProperties: anyOf: - $ref: '#/components/schemas/NullableObject' - type: 'null' ModelWithOneOfEnum: oneOf: - type: object required: - foo properties: foo: type: string enum: - Bar - type: object required: - foo properties: foo: type: string enum: - Baz - type: object required: - foo properties: foo: type: string enum: - Qux - type: object required: - content - foo properties: content: type: string format: date-time foo: type: string enum: - Quux - type: object required: - content - foo properties: content: type: array prefixItems: - type: string format: date-time - type: string maxItems: 2 minItems: 2 foo: type: string enum: - Corge ModelWithNestedArrayEnumsDataFoo: enum: - foo - bar type: string ModelWithNestedArrayEnumsDataBar: enum: - baz - qux type: string ModelWithNestedArrayEnumsData: type: object properties: foo: type: array items: $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' bar: type: array items: $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataBar' ModelWithNestedArrayEnums: type: object properties: array_strings: type: array items: type: string data: allOf: - $ref: '#/components/schemas/ModelWithNestedArrayEnumsData' ModelWithNestedCompositionEnums: type: object properties: foo: allOf: - $ref: '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' ModelWithReadOnlyAndWriteOnly: type: object required: - foo - bar - baz properties: foo: type: string bar: readOnly: true type: string baz: type: string writeOnly: true ModelWithConstantSizeArray: type: array items: type: number minItems: 2 maxItems: 2 ModelWithAnyOfConstantSizeArray: type: array items: oneOf: - type: number - type: string minItems: 3 maxItems: 3 ModelWithPrefixItemsConstantSizeArray: type: array prefixItems: - $ref: '#/components/schemas/ModelWithInteger' - oneOf: - type: number - type: string - type: string ModelWithAnyOfConstantSizeArrayNullable: type: - array items: oneOf: - type: - number - 'null' - type: string minItems: 3 maxItems: 3 ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions: type: array items: oneOf: - type: number - $ref: '#/components/schemas/import' minItems: 2 maxItems: 2 ModelWithAnyOfConstantSizeArrayAndIntersect: type: array items: allOf: - type: number - type: string minItems: 2 maxItems: 2 ModelWithNumericEnumUnion: type: object properties: value: type: number description: Период enum: - -10 - -1 - 0 - 1 - 3 - 6 - 12 ModelWithBackticksInDescription: description: Some description with `back ticks` type: object properties: template: type: string description: >- The template `that` should be used for parsing and importing the contents of the CSV file.

    There is one placeholder currently supported:

    • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

    Example of a correct JSON template:

    
                [
                  {
                    "resourceType": "Asset",
                    "identifier": {
                      "name": "${1}",
                      "domain": {
                        "name": "${2}",
                        "community": {
                          "name": "Some Community"
                        }
                      }
                    },
                    "attributes" : {
                      "00000000-0000-0000-0000-000000003115" : [ {
                        "value" : "${3}"
                      } ],
                      "00000000-0000-0000-0000-000000000222" : [ {
                        "value" : "${4}"
                      } ]
                    }
                  }
                ]
    
                
    ModelWithOneOfAndProperties: type: object oneOf: - $ref: '#/components/parameters/SimpleParameter' - $ref: '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' required: - baz - qux properties: baz: type: - integer - 'null' format: uint16 minimum: 0 qux: type: integer format: uint8 minimum: 0 ParameterSimpleParameterUnused: description: Model used to test deduplication strategy (unused) type: string PostServiceWithEmptyTagResponse: description: Model used to test deduplication strategy type: string PostServiceWithEmptyTagResponse2: description: Model used to test deduplication strategy type: string DeleteFooData: description: Model used to test deduplication strategy type: string DeleteFooData2: description: Model used to test deduplication strategy type: string import: description: Model with restricted keyword name type: string SchemaWithFormRestrictedKeys: type: object properties: description: type: string x-enum-descriptions: type: string x-enum-varnames: type: string x-enumNames: type: string title: type: string object: type: object properties: description: type: string x-enum-descriptions: type: string x-enum-varnames: type: string x-enumNames: type: string title: type: string array: type: array items: type: object properties: description: type: string x-enum-descriptions: type: string x-enum-varnames: type: string x-enumNames: type: string title: type: string io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions: description: This schema was giving PascalCase transformations a hard time properties: preconditions: allOf: - $ref: '#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions' description: Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. type: object io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions: description: This schema was giving PascalCase transformations a hard time properties: resourceVersion: description: Specifies the target ResourceVersion type: string uid: description: Specifies the target UID. type: string type: object AdditionalPropertiesUnknownIssue: type: object properties: {} additionalProperties: anyOf: - type: string - type: number AdditionalPropertiesUnknownIssue2: type: object additionalProperties: anyOf: - type: string - type: number AdditionalPropertiesUnknownIssue3: type: object allOf: - type: string - type: object required: - entries properties: entries: type: object additionalProperties: $ref: '#/components/schemas/AdditionalPropertiesUnknownIssue' AdditionalPropertiesIntegerIssue: type: object required: - value properties: value: type: integer additionalProperties: type: integer OneOfAllOfIssue: oneOf: - allOf: - oneOf: - $ref: '#/components/schemas/ConstValue' - $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' - $ref: '#/components/schemas/3e-num_1Период' - $ref: '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' Generic.Schema.Duplicate.Issue`1[System.Boolean]: type: object properties: item: type: boolean error: type: - string - 'null' hasError: type: boolean readOnly: true data: type: object properties: {} additionalProperties: false additionalProperties: false Generic.Schema.Duplicate.Issue`1[System.String]: type: object properties: item: type: - string - 'null' error: type: - string - 'null' hasError: type: boolean readOnly: true additionalProperties: false ================================================ FILE: specs/3.1.x/headers.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 headers example version: 1 paths: /foo: get: parameters: - in: header name: Content-Type required: true schema: type: string requestBody: required: true content: application/json: schema: type: string responses: '200': description: OK content: application/json: schema: type: string patch: parameters: - in: header name: Content-Type required: false schema: type: string requestBody: required: false content: application/json: schema: type: string responses: '200': description: OK content: application/json: schema: type: string post: parameters: - in: header name: content-type required: false schema: type: string requestBody: required: true content: application/json: schema: type: string responses: '200': description: OK content: application/json: schema: type: string put: requestBody: required: true content: application/json: schema: type: string responses: '200': description: OK content: application/json: schema: type: string ================================================ FILE: specs/3.1.x/integer-formats.yaml ================================================ openapi: '3.1.0' info: title: Integer Formats Test version: '1.0.0' components: schemas: IntegerFormats: type: object properties: numberNoFormat: type: number numberInt8: type: number format: int8 numberInt16: type: number format: int16 numberInt32: type: number format: int32 numberInt64: type: number format: int64 numberUint8: type: number format: uint8 numberUint16: type: number format: uint16 numberUint32: type: number format: uint32 numberUint64: type: number format: uint64 integerNoFormat: type: integer integerInt8: type: integer format: int8 integerInt16: type: integer format: int16 integerInt32: type: integer format: int32 integerInt64: type: integer format: int64 integerUint8: type: integer format: uint8 integerUint16: type: integer format: uint16 integerUint32: type: integer format: uint32 integerUint64: type: integer format: uint64 stringInt64: type: string format: int64 stringUint64: type: string format: uint64 ================================================ FILE: specs/3.1.x/internal-name-conflict.json ================================================ { "openapi": "3.1.1", "info": { "title": "OpenAPI 3.1.1 internal name conflict example", "version": "1" }, "paths": { "/foo": { "get": { "operationId": "create__", "responses": { "200": { "description": "OK" } } }, "patch": { "operationId": "create_", "responses": { "200": { "description": "OK" } } }, "post": { "operationId": "create", "responses": { "200": { "description": "OK" } } } } } } ================================================ FILE: specs/3.1.x/invalid/operationId-unique.yaml ================================================ openapi: 3.1.1 info: title: Invalid OpenAPI 3.1.1 operationId unique example version: 1 paths: /foo: get: operationId: foo responses: '200': content: '*/*': schema: type: string description: OK post: operationId: foo responses: '200': content: '*/*': schema: type: string description: OK ================================================ FILE: specs/3.1.x/invalid/servers-array.yaml ================================================ openapi: 3.1.1 info: title: Invalid OpenAPI 3.1.1 servers array example version: 1 servers: foo: bar ================================================ FILE: specs/3.1.x/invalid/servers-entry.yaml ================================================ openapi: 3.1.1 info: title: Invalid OpenAPI 3.1.1 servers entry example version: 1 servers: - foo ================================================ FILE: specs/3.1.x/invalid/servers-required.yaml ================================================ openapi: 3.1.1 info: title: Invalid OpenAPI 3.1.1 servers required example version: 1 servers: - description: missing url ================================================ FILE: specs/3.1.x/min-max-constraints.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 min max constraints example version: '1' components: schemas: NumberWithMinimum: type: number minimum: 10 NumberWithMaximum: type: number maximum: 100 NumberWithMinMax: type: number minimum: 0 maximum: 100 IntegerWithMinimum: type: integer minimum: 5 IntegerWithMaximum: type: integer maximum: 999 IntegerWithMinMax: type: integer minimum: 1 maximum: 999 NumberWithExclusiveMin: type: number exclusiveMinimum: 0 NumberWithExclusiveMax: type: number exclusiveMaximum: 100 NumberWithExclusiveMinMax: type: number exclusiveMinimum: 0 exclusiveMaximum: 1 IntegerWithExclusiveMin: type: integer exclusiveMinimum: 10 IntegerWithExclusiveMax: type: integer exclusiveMaximum: 50 IntegerWithExclusiveMinMax: type: integer exclusiveMinimum: 5 exclusiveMaximum: 15 NumberWithExclusiveMinInclusiveMax: type: number exclusiveMinimum: 10 maximum: 90 NumberWithInclusiveMinExclusiveMax: type: number minimum: 20 exclusiveMaximum: 80 IntegerWithExclusiveMinInclusiveMax: type: integer exclusiveMinimum: 5 maximum: 50 IntegerWithInclusiveMinExclusiveMax: type: integer minimum: 10 exclusiveMaximum: 100 Int64WithMinimum: type: integer format: int64 minimum: -5000000000000 Int64WithMaximum: type: integer format: int64 maximum: 5000000000000 Int64WithMinMax: type: integer format: int64 minimum: -4000000000000 maximum: 4000000000000 Int64WithExclusiveMin: type: integer format: int64 exclusiveMinimum: -3000000000000 Int64WithExclusiveMax: type: integer format: int64 exclusiveMaximum: 3000000000000 Int64WithExclusiveMinMax: type: integer format: int64 exclusiveMinimum: -2000000000000 exclusiveMaximum: 2000000000000 Int64WithExclusiveMinInclusiveMax: type: integer format: int64 exclusiveMinimum: -6000000000000 maximum: 6000000000000 Int64WithInclusiveMinExclusiveMax: type: integer format: int64 minimum: -7000000000000 exclusiveMaximum: 7000000000000 UInt64WithMinimum: type: integer format: uint64 minimum: 5000000000000 UInt64WithMaximum: type: integer format: uint64 maximum: 15000000000000 UInt64WithMinMax: type: integer format: uint64 minimum: 1000000000000 maximum: 10000000000000 UInt64WithExclusiveMin: type: integer format: uint64 exclusiveMinimum: 8000000000000 UInt64WithExclusiveMax: type: integer format: uint64 exclusiveMaximum: 12000000000000 UInt64WithExclusiveMinMax: type: integer format: uint64 exclusiveMinimum: 2000000000000 exclusiveMaximum: 8000000000000 UInt64WithExclusiveMinInclusiveMax: type: integer format: uint64 exclusiveMinimum: 3000000000000 maximum: 13000000000000 UInt64WithInclusiveMinExclusiveMax: type: integer format: uint64 minimum: 4000000000000 exclusiveMaximum: 14000000000000 PrecedenceTest: type: number minimum: 10 maximum: 90 exclusiveMinimum: 5 exclusiveMaximum: 95 ================================================ FILE: specs/3.1.x/negative-property-names.json ================================================ { "openapi": "3.1.1", "info": { "title": "OpenAPI 3.1.1 negative property names example", "version": "1" }, "components": { "schemas": { "ReactionRollup": { "title": "Reaction Rollup", "type": "object", "properties": { "url": { "format": "uri", "type": "string" }, "total_count": { "type": "integer" }, "+1": { "type": "integer" }, "-1": { "type": "integer" }, "laugh": { "type": "integer" }, "confused": { "type": "integer" }, "heart": { "type": "integer" }, "hooray": { "type": "integer" }, "eyes": { "type": "integer" }, "rocket": { "type": "integer" } }, "required": [ "url", "total_count", "+1", "-1", "laugh", "confused", "heart", "hooray", "eyes", "rocket" ] } } } } ================================================ FILE: specs/3.1.x/object-properties-all-of.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.0.0" }, "components": { "schemas": { "Foo": { "properties": { "foo": { "type": "string" }, "bar": { "type": "string" }, "baz": { "type": "string" } }, "required": ["foo"], "allOf": [ { "properties": { "bar": { "type": "string" } }, "required": ["bar"] }, { "properties": { "baz": { "type": "string" } }, "required": ["baz"] } ] } } } } ================================================ FILE: specs/3.1.x/object-properties-any-of.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.0.0" }, "components": { "schemas": { "Foo": { "properties": { "foo": { "type": "string" }, "bar": { "type": "string" }, "baz": { "type": "string" } }, "required": ["foo"], "anyOf": [ { "properties": { "bar": { "type": "string" } }, "required": ["bar"] }, { "properties": { "baz": { "type": "string" } }, "required": ["baz"] } ] } } } } ================================================ FILE: specs/3.1.x/object-properties-one-of.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.0.0" }, "components": { "schemas": { "Foo": { "properties": { "foo": { "type": "string" }, "bar": { "type": "string" }, "baz": { "type": "string" } }, "required": ["foo"], "oneOf": [ { "properties": { "bar": { "type": "string" } }, "required": ["bar"] }, { "properties": { "baz": { "type": "string" } }, "required": ["baz"] } ] } } } } ================================================ FILE: specs/3.1.x/object-property-names.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 object property names example version: 1 components: schemas: Foo: enum: - foo - bar type: string Bar: additionalProperties: type: string propertyNames: $ref: '#/components/schemas/Foo' type: object Baz: additionalProperties: type: integer propertyNames: $ref: '#/components/schemas/Foo' type: object ================================================ FILE: specs/3.1.x/openai.yaml ================================================ openapi: 3.1.0 info: title: OpenAI API description: The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. version: 2.3.0 termsOfService: https://openai.com/policies/terms-of-use contact: name: OpenAI Support url: https://help.openai.com/ license: name: MIT url: https://github.com/openai/openai-openapi/blob/master/LICENSE servers: - url: https://api.openai.com/v1 security: - ApiKeyAuth: [] tags: - name: Assistants description: Build Assistants that can call models and use tools. - name: Audio description: Turn audio into text or text into audio. - name: Chat description: Given a list of messages comprising a conversation, the model will return a response. - name: Completions description: >- Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position. - name: Embeddings description: >- Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. - name: Evals description: Manage and run evals in the OpenAI platform. - name: Fine-tuning description: Manage fine-tuning jobs to tailor a model to your specific training data. - name: Graders description: Manage and run graders in the OpenAI platform. - name: Batch description: Create large batches of API requests to run asynchronously. - name: Files description: Files are used to upload documents that can be used with features like Assistants and Fine-tuning. - name: Uploads description: Use Uploads to upload large files in multiple parts. - name: Images description: Given a prompt and/or an input image, the model will generate a new image. - name: Models description: List and describe the various models available in the API. - name: Moderations description: Given text and/or image inputs, classifies if those inputs are potentially harmful. - name: Audit Logs description: List user actions and configuration changes within this organization. paths: /assistants: get: operationId: listAssistants tags: - Assistants summary: List assistants parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListAssistantsResponse' x-oaiMeta: name: List assistants group: assistants beta: true returns: A list of [assistant](https://platform.openai.com/docs/api-reference/assistants/object) objects. examples: response: | { "object": "list", "data": [ { "id": "asst_abc123", "object": "assistant", "created_at": 1698982736, "name": "Coding Tutor", "description": null, "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" }, { "id": "asst_abc456", "object": "assistant", "created_at": 1698982718, "name": "My Assistant", "description": null, "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" }, { "id": "asst_abc789", "object": "assistant", "created_at": 1698982643, "name": null, "description": null, "model": "gpt-4o", "instructions": null, "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } ], "first_id": "asst_abc123", "last_id": "asst_abc789", "has_more": false } request: curl: | curl "https://api.openai.com/v1/assistants?order=desc&limit=20" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.beta.assistants.list() page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const assistant of client.beta.assistants.list()) { console.log(assistant.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Beta.Assistants.List(context.TODO(), openai.BetaAssistantListParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.assistants.AssistantListPage; import com.openai.models.beta.assistants.AssistantListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); AssistantListPage page = client.beta().assistants().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.beta.assistants.list puts(page) description: Returns a list of assistants. post: operationId: createAssistant tags: - Assistants summary: Create assistant requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateAssistantRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/AssistantObject' x-oaiMeta: name: Create assistant group: assistants beta: true returns: An [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object. examples: - title: Code Interpreter request: curl: | curl "https://api.openai.com/v1/assistants" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", "name": "Math Tutor", "tools": [{"type": "code_interpreter"}], "model": "gpt-4o" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) assistant = client.beta.assistants.create( model="gpt-4o", ) print(assistant.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const assistant = await client.beta.assistants.create({ model: 'gpt-4o' }); console.log(assistant.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{ Model: shared.ChatModelGPT5, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", assistant.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.ChatModel; import com.openai.models.beta.assistants.Assistant; import com.openai.models.beta.assistants.AssistantCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); AssistantCreateParams params = AssistantCreateParams.builder() .model(ChatModel.GPT_5) .build(); Assistant assistant = client.beta().assistants().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") assistant = openai.beta.assistants.create(model: :"gpt-5") puts(assistant) response: | { "id": "asst_abc123", "object": "assistant", "created_at": 1698984975, "name": "Math Tutor", "description": null, "model": "gpt-4o", "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", "tools": [ { "type": "code_interpreter" } ], "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } - title: Files request: curl: | curl https://api.openai.com/v1/assistants \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [{"type": "file_search"}], "tool_resources": {"file_search": {"vector_store_ids": ["vs_123"]}}, "model": "gpt-4o" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) assistant = client.beta.assistants.create( model="gpt-4o", ) print(assistant.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const assistant = await client.beta.assistants.create({ model: 'gpt-4o' }); console.log(assistant.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{ Model: shared.ChatModelGPT5, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", assistant.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.ChatModel; import com.openai.models.beta.assistants.Assistant; import com.openai.models.beta.assistants.AssistantCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); AssistantCreateParams params = AssistantCreateParams.builder() .model(ChatModel.GPT_5) .build(); Assistant assistant = client.beta().assistants().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") assistant = openai.beta.assistants.create(model: :"gpt-5") puts(assistant) response: | { "id": "asst_abc123", "object": "assistant", "created_at": 1699009403, "name": "HR Helper", "description": null, "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [ { "type": "file_search" } ], "tool_resources": { "file_search": { "vector_store_ids": ["vs_123"] } }, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } description: Create an assistant with a model and instructions. /assistants/{assistant_id}: get: operationId: getAssistant tags: - Assistants summary: Retrieve assistant parameters: - in: path name: assistant_id required: true schema: type: string description: The ID of the assistant to retrieve. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/AssistantObject' x-oaiMeta: name: Retrieve assistant group: assistants beta: true returns: >- The [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object matching the specified ID. examples: response: | { "id": "asst_abc123", "object": "assistant", "created_at": 1699009709, "name": "HR Helper", "description": null, "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [ { "type": "file_search" } ], "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } request: curl: | curl https://api.openai.com/v1/assistants/asst_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) assistant = client.beta.assistants.retrieve( "assistant_id", ) print(assistant.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const assistant = await client.beta.assistants.retrieve('assistant_id'); console.log(assistant.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) assistant, err := client.Beta.Assistants.Get(context.TODO(), "assistant_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", assistant.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.assistants.Assistant; import com.openai.models.beta.assistants.AssistantRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Assistant assistant = client.beta().assistants().retrieve("assistant_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") assistant = openai.beta.assistants.retrieve("assistant_id") puts(assistant) description: Retrieves an assistant. post: operationId: modifyAssistant tags: - Assistants summary: Modify assistant parameters: - in: path name: assistant_id required: true schema: type: string description: The ID of the assistant to modify. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ModifyAssistantRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/AssistantObject' x-oaiMeta: name: Modify assistant group: assistants beta: true returns: The modified [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object. examples: response: | { "id": "asst_123", "object": "assistant", "created_at": 1699009709, "name": "HR Helper", "description": null, "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", "tools": [ { "type": "file_search" } ], "tool_resources": { "file_search": { "vector_store_ids": [] } }, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } request: curl: | curl https://api.openai.com/v1/assistants/asst_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", "tools": [{"type": "file_search"}], "model": "gpt-4o" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) assistant = client.beta.assistants.update( assistant_id="assistant_id", ) print(assistant.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const assistant = await client.beta.assistants.update('assistant_id'); console.log(assistant.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) assistant, err := client.Beta.Assistants.Update( context.TODO(), "assistant_id", openai.BetaAssistantUpdateParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", assistant.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.assistants.Assistant; import com.openai.models.beta.assistants.AssistantUpdateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Assistant assistant = client.beta().assistants().update("assistant_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") assistant = openai.beta.assistants.update("assistant_id") puts(assistant) description: Modifies an assistant. delete: operationId: deleteAssistant tags: - Assistants summary: Delete assistant parameters: - in: path name: assistant_id required: true schema: type: string description: The ID of the assistant to delete. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteAssistantResponse' x-oaiMeta: name: Delete assistant group: assistants beta: true returns: Deletion status examples: response: | { "id": "asst_abc123", "object": "assistant.deleted", "deleted": true } request: curl: | curl https://api.openai.com/v1/assistants/asst_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -X DELETE python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) assistant_deleted = client.beta.assistants.delete( "assistant_id", ) print(assistant_deleted.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const assistantDeleted = await client.beta.assistants.delete('assistant_id'); console.log(assistantDeleted.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) assistantDeleted, err := client.Beta.Assistants.Delete(context.TODO(), "assistant_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", assistantDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.assistants.AssistantDeleteParams; import com.openai.models.beta.assistants.AssistantDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); AssistantDeleted assistantDeleted = client.beta().assistants().delete("assistant_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") assistant_deleted = openai.beta.assistants.delete("assistant_id") puts(assistant_deleted) description: Delete an assistant. /audio/speech: post: operationId: createSpeech tags: - Audio summary: Create speech requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateSpeechRequest' responses: '200': description: OK headers: Transfer-Encoding: schema: type: string description: chunked content: application/octet-stream: schema: type: string format: binary text/event-stream: schema: $ref: '#/components/schemas/CreateSpeechResponseStreamEvent' x-oaiMeta: name: Create speech group: audio returns: >- The audio file content or a [stream of audio events](https://platform.openai.com/docs/api-reference/audio/speech-audio-delta-event). examples: - title: Default request: curl: | curl https://api.openai.com/v1/audio/speech \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini-tts", "input": "The quick brown fox jumped over the lazy dog.", "voice": "alloy" }' \ --output speech.mp3 python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) speech = client.audio.speech.create( input="input", model="string", voice="ash", ) print(speech) content = speech.read() print(content) javascript: | import fs from "fs"; import path from "path"; import OpenAI from "openai"; const openai = new OpenAI(); const speechFile = path.resolve("./speech.mp3"); async function main() { const mp3 = await openai.audio.speech.create({ model: "gpt-4o-mini-tts", voice: "alloy", input: "Today is a wonderful day to build something people love!", }); console.log(speechFile); const buffer = Buffer.from(await mp3.arrayBuffer()); await fs.promises.writeFile(speechFile, buffer); } main(); csharp: | using System; using System.IO; using OpenAI.Audio; AudioClient client = new( model: "gpt-4o-mini-tts", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); BinaryData speech = client.GenerateSpeech( text: "The quick brown fox jumped over the lazy dog.", voice: GeneratedSpeechVoice.Alloy ); using FileStream stream = File.OpenWrite("speech.mp3"); speech.ToStream().CopyTo(stream); node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: 'ash' }); console.log(speech); const content = await speech.blob(); console.log(content); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{ Input: "input", Model: openai.SpeechModelTTS1, Voice: openai.AudioSpeechNewParamsVoiceAlloy, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", speech) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.http.HttpResponse; import com.openai.models.audio.speech.SpeechCreateParams; import com.openai.models.audio.speech.SpeechModel; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); SpeechCreateParams params = SpeechCreateParams.builder() .input("input") .model(SpeechModel.TTS_1) .voice(SpeechCreateParams.Voice.ALLOY) .build(); HttpResponse speech = client.audio().speech().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") speech = openai.audio.speech.create(input: "input", model: :"tts-1", voice: :alloy) puts(speech) - title: SSE Stream Format request: curl: | curl https://api.openai.com/v1/audio/speech \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini-tts", "input": "The quick brown fox jumped over the lazy dog.", "voice": "alloy", "stream_format": "sse" }' node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: 'ash' }); console.log(speech); const content = await speech.blob(); console.log(content); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) speech = client.audio.speech.create( input="input", model="string", voice="ash", ) print(speech) content = speech.read() print(content) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{ Input: "input", Model: openai.SpeechModelTTS1, Voice: openai.AudioSpeechNewParamsVoiceAlloy, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", speech) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.http.HttpResponse; import com.openai.models.audio.speech.SpeechCreateParams; import com.openai.models.audio.speech.SpeechModel; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); SpeechCreateParams params = SpeechCreateParams.builder() .input("input") .model(SpeechModel.TTS_1) .voice(SpeechCreateParams.Voice.ALLOY) .build(); HttpResponse speech = client.audio().speech().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") speech = openai.audio.speech.create(input: "input", model: :"tts-1", voice: :alloy) puts(speech) description: Generates audio from the input text. /audio/transcriptions: post: operationId: createTranscription tags: - Audio summary: Create transcription requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/CreateTranscriptionRequest' responses: '200': description: OK content: application/json: schema: anyOf: - $ref: '#/components/schemas/CreateTranscriptionResponseJson' - $ref: '#/components/schemas/CreateTranscriptionResponseVerboseJson' x-stainless-skip: - go text/event-stream: schema: $ref: '#/components/schemas/CreateTranscriptionResponseStreamEvent' x-oaiMeta: name: Create transcription group: audio returns: >- The [transcription object](https://platform.openai.com/docs/api-reference/audio/json-object), a [verbose transcription object](https://platform.openai.com/docs/api-reference/audio/verbose-json-object) or a [stream of transcript events](https://platform.openai.com/docs/api-reference/audio/transcript-text-delta-event). examples: - title: Default request: curl: | curl https://api.openai.com/v1/audio/transcriptions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/audio.mp3" \ -F model="gpt-4o-transcribe" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) transcription = client.audio.transcriptions.create( file=b"raw file contents", model="gpt-4o-transcribe", ) print(transcription) javascript: | import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "gpt-4o-transcribe", }); console.log(transcription.text); } main(); csharp: | using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "gpt-4o-transcribe", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscription transcription = client.TranscribeAudio(audioFilePath); Console.WriteLine($"{transcription.Text}"); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('speech.mp3'), model: 'gpt-4o-transcribe', }); console.log(transcription); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), Model: openai.AudioModelWhisper1, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", transcription) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.audio.AudioModel; import com.openai.models.audio.transcriptions.TranscriptionCreateParams; import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); TranscriptionCreateParams params = TranscriptionCreateParams.builder() .file(ByteArrayInputStream("some content".getBytes())) .model(AudioModel.WHISPER_1) .build(); TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1") puts(transcription) response: | { "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.", "usage": { "type": "tokens", "input_tokens": 14, "input_token_details": { "text_tokens": 0, "audio_tokens": 14 }, "output_tokens": 45, "total_tokens": 59 } } - title: Streaming request: curl: | curl https://api.openai.com/v1/audio/transcriptions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/audio.mp3" \ -F model="gpt-4o-mini-transcribe" \ -F stream=true python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) transcription = client.audio.transcriptions.create( file=b"raw file contents", model="gpt-4o-transcribe", ) print(transcription) javascript: | import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); const stream = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "gpt-4o-mini-transcribe", stream: true, }); for await (const event of stream) { console.log(event); } node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('speech.mp3'), model: 'gpt-4o-transcribe', }); console.log(transcription); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), Model: openai.AudioModelWhisper1, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", transcription) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.audio.AudioModel; import com.openai.models.audio.transcriptions.TranscriptionCreateParams; import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); TranscriptionCreateParams params = TranscriptionCreateParams.builder() .file(ByteArrayInputStream("some content".getBytes())) .model(AudioModel.WHISPER_1) .build(); TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1") puts(transcription) response: > data: {"type":"transcript.text.delta","delta":"I","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]}]} data: {"type":"transcript.text.delta","delta":" see","logprobs":[{"token":" see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]}]} data: {"type":"transcript.text.delta","delta":" skies","logprobs":[{"token":" skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]}]} data: {"type":"transcript.text.delta","delta":" of","logprobs":[{"token":" of","logprob":-3.1281633e-7,"bytes":[32,111,102]}]} data: {"type":"transcript.text.delta","delta":" blue","logprobs":[{"token":" blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]}]} data: {"type":"transcript.text.delta","delta":" and","logprobs":[{"token":" and","logprob":-0.0005108566,"bytes":[32,97,110,100]}]} data: {"type":"transcript.text.delta","delta":" clouds","logprobs":[{"token":" clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]}]} data: {"type":"transcript.text.delta","delta":" of","logprobs":[{"token":" of","logprob":-1.9361265e-7,"bytes":[32,111,102]}]} data: {"type":"transcript.text.delta","delta":" white","logprobs":[{"token":" white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]}]} data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0014890312,"bytes":[44]}]} data: {"type":"transcript.text.delta","delta":" the","logprobs":[{"token":" the","logprob":-0.0110956915,"bytes":[32,116,104,101]}]} data: {"type":"transcript.text.delta","delta":" bright","logprobs":[{"token":" bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]}]} data: {"type":"transcript.text.delta","delta":" blessed","logprobs":[{"token":" blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]}]} data: {"type":"transcript.text.delta","delta":" days","logprobs":[{"token":" days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]}]} data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.00001700133,"bytes":[44]}]} data: {"type":"transcript.text.delta","delta":" the","logprobs":[{"token":" the","logprob":-0.0000118755715,"bytes":[32,116,104,101]}]} data: {"type":"transcript.text.delta","delta":" dark","logprobs":[{"token":" dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]}]} data: {"type":"transcript.text.delta","delta":" sacred","logprobs":[{"token":" sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]}]} data: {"type":"transcript.text.delta","delta":" nights","logprobs":[{"token":" nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]}]} data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0036910512,"bytes":[44]}]} data: {"type":"transcript.text.delta","delta":" and","logprobs":[{"token":" and","logprob":-0.0031903093,"bytes":[32,97,110,100]}]} data: {"type":"transcript.text.delta","delta":" I","logprobs":[{"token":" I","logprob":-1.504853e-6,"bytes":[32,73]}]} data: {"type":"transcript.text.delta","delta":" think","logprobs":[{"token":" think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]}]} data: {"type":"transcript.text.delta","delta":" to","logprobs":[{"token":" to","logprob":-1.9361265e-7,"bytes":[32,116,111]}]} data: {"type":"transcript.text.delta","delta":" myself","logprobs":[{"token":" myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]}]} data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.29254505,"bytes":[44]}]} data: {"type":"transcript.text.delta","delta":" what","logprobs":[{"token":" what","logprob":-0.016815351,"bytes":[32,119,104,97,116]}]} data: {"type":"transcript.text.delta","delta":" a","logprobs":[{"token":" a","logprob":-3.1281633e-7,"bytes":[32,97]}]} data: {"type":"transcript.text.delta","delta":" wonderful","logprobs":[{"token":" wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]}]} data: {"type":"transcript.text.delta","delta":" world","logprobs":[{"token":" world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]}]} data: {"type":"transcript.text.delta","delta":".","logprobs":[{"token":".","logprob":-0.014231676,"bytes":[46]}]} data: {"type":"transcript.text.done","text":"I see skies of blue and clouds of white, the bright blessed days, the dark sacred nights, and I think to myself, what a wonderful world.","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]},{"token":" see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]},{"token":" skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]},{"token":" of","logprob":-3.1281633e-7,"bytes":[32,111,102]},{"token":" blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]},{"token":" and","logprob":-0.0005108566,"bytes":[32,97,110,100]},{"token":" clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]},{"token":" of","logprob":-1.9361265e-7,"bytes":[32,111,102]},{"token":" white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]},{"token":",","logprob":-0.0014890312,"bytes":[44]},{"token":" the","logprob":-0.0110956915,"bytes":[32,116,104,101]},{"token":" bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]},{"token":" blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]},{"token":" days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]},{"token":",","logprob":-0.00001700133,"bytes":[44]},{"token":" the","logprob":-0.0000118755715,"bytes":[32,116,104,101]},{"token":" dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]},{"token":" sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]},{"token":" nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]},{"token":",","logprob":-0.0036910512,"bytes":[44]},{"token":" and","logprob":-0.0031903093,"bytes":[32,97,110,100]},{"token":" I","logprob":-1.504853e-6,"bytes":[32,73]},{"token":" think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]},{"token":" to","logprob":-1.9361265e-7,"bytes":[32,116,111]},{"token":" myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]},{"token":",","logprob":-0.29254505,"bytes":[44]},{"token":" what","logprob":-0.016815351,"bytes":[32,119,104,97,116]},{"token":" a","logprob":-3.1281633e-7,"bytes":[32,97]},{"token":" wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]},{"token":" world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]},{"token":".","logprob":-0.014231676,"bytes":[46]}],"usage":{"input_tokens":14,"input_token_details":{"text_tokens":0,"audio_tokens":14},"output_tokens":45,"total_tokens":59}} - title: Logprobs request: curl: | curl https://api.openai.com/v1/audio/transcriptions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/audio.mp3" \ -F "include[]=logprobs" \ -F model="gpt-4o-transcribe" \ -F response_format="json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) transcription = client.audio.transcriptions.create( file=b"raw file contents", model="gpt-4o-transcribe", ) print(transcription) javascript: | import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "gpt-4o-transcribe", response_format: "json", include: ["logprobs"] }); console.log(transcription); } main(); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('speech.mp3'), model: 'gpt-4o-transcribe', }); console.log(transcription); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), Model: openai.AudioModelWhisper1, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", transcription) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.audio.AudioModel; import com.openai.models.audio.transcriptions.TranscriptionCreateParams; import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); TranscriptionCreateParams params = TranscriptionCreateParams.builder() .file(ByteArrayInputStream("some content".getBytes())) .model(AudioModel.WHISPER_1) .build(); TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1") puts(transcription) response: | { "text": "Hey, my knee is hurting and I want to see the doctor tomorrow ideally.", "logprobs": [ { "token": "Hey", "logprob": -1.0415299, "bytes": [72, 101, 121] }, { "token": ",", "logprob": -9.805982e-5, "bytes": [44] }, { "token": " my", "logprob": -0.00229799, "bytes": [32, 109, 121] }, { "token": " knee", "logprob": -4.7159858e-5, "bytes": [32, 107, 110, 101, 101] }, { "token": " is", "logprob": -0.043909557, "bytes": [32, 105, 115] }, { "token": " hurting", "logprob": -1.1041146e-5, "bytes": [32, 104, 117, 114, 116, 105, 110, 103] }, { "token": " and", "logprob": -0.011076359, "bytes": [32, 97, 110, 100] }, { "token": " I", "logprob": -5.3193703e-6, "bytes": [32, 73] }, { "token": " want", "logprob": -0.0017156356, "bytes": [32, 119, 97, 110, 116] }, { "token": " to", "logprob": -7.89631e-7, "bytes": [32, 116, 111] }, { "token": " see", "logprob": -5.5122365e-7, "bytes": [32, 115, 101, 101] }, { "token": " the", "logprob": -0.0040786397, "bytes": [32, 116, 104, 101] }, { "token": " doctor", "logprob": -2.3392786e-6, "bytes": [32, 100, 111, 99, 116, 111, 114] }, { "token": " tomorrow", "logprob": -7.89631e-7, "bytes": [32, 116, 111, 109, 111, 114, 114, 111, 119] }, { "token": " ideally", "logprob": -0.5800861, "bytes": [32, 105, 100, 101, 97, 108, 108, 121] }, { "token": ".", "logprob": -0.00011093382, "bytes": [46] } ], "usage": { "type": "tokens", "input_tokens": 14, "input_token_details": { "text_tokens": 0, "audio_tokens": 14 }, "output_tokens": 45, "total_tokens": 59 } } - title: Word timestamps request: curl: | curl https://api.openai.com/v1/audio/transcriptions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/audio.mp3" \ -F "timestamp_granularities[]=word" \ -F model="whisper-1" \ -F response_format="verbose_json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) transcription = client.audio.transcriptions.create( file=b"raw file contents", model="gpt-4o-transcribe", ) print(transcription) javascript: | import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "whisper-1", response_format: "verbose_json", timestamp_granularities: ["word"] }); console.log(transcription.text); } main(); csharp: | using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "whisper-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscriptionOptions options = new() { ResponseFormat = AudioTranscriptionFormat.Verbose, TimestampGranularities = AudioTimestampGranularities.Word, }; AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options); Console.WriteLine($"{transcription.Text}"); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('speech.mp3'), model: 'gpt-4o-transcribe', }); console.log(transcription); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), Model: openai.AudioModelWhisper1, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", transcription) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.audio.AudioModel; import com.openai.models.audio.transcriptions.TranscriptionCreateParams; import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); TranscriptionCreateParams params = TranscriptionCreateParams.builder() .file(ByteArrayInputStream("some content".getBytes())) .model(AudioModel.WHISPER_1) .build(); TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1") puts(transcription) response: | { "task": "transcribe", "language": "english", "duration": 8.470000267028809, "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", "words": [ { "word": "The", "start": 0.0, "end": 0.23999999463558197 }, ... { "word": "volleyball", "start": 7.400000095367432, "end": 7.900000095367432 } ], "usage": { "type": "duration", "seconds": 9 } } - title: Segment timestamps request: curl: | curl https://api.openai.com/v1/audio/transcriptions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/audio.mp3" \ -F "timestamp_granularities[]=segment" \ -F model="whisper-1" \ -F response_format="verbose_json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) transcription = client.audio.transcriptions.create( file=b"raw file contents", model="gpt-4o-transcribe", ) print(transcription) javascript: | import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "whisper-1", response_format: "verbose_json", timestamp_granularities: ["segment"] }); console.log(transcription.text); } main(); csharp: | using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "whisper-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscriptionOptions options = new() { ResponseFormat = AudioTranscriptionFormat.Verbose, TimestampGranularities = AudioTimestampGranularities.Segment, }; AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options); Console.WriteLine($"{transcription.Text}"); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('speech.mp3'), model: 'gpt-4o-transcribe', }); console.log(transcription); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), Model: openai.AudioModelWhisper1, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", transcription) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.audio.AudioModel; import com.openai.models.audio.transcriptions.TranscriptionCreateParams; import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); TranscriptionCreateParams params = TranscriptionCreateParams.builder() .file(ByteArrayInputStream("some content".getBytes())) .model(AudioModel.WHISPER_1) .build(); TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1") puts(transcription) response: | { "task": "transcribe", "language": "english", "duration": 8.470000267028809, "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", "segments": [ { "id": 0, "seek": 0, "start": 0.0, "end": 3.319999933242798, "text": " The beach was a popular spot on a hot summer day.", "tokens": [ 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530 ], "temperature": 0.0, "avg_logprob": -0.2860786020755768, "compression_ratio": 1.2363636493682861, "no_speech_prob": 0.00985979475080967 }, ... ], "usage": { "type": "duration", "seconds": 9 } } description: Transcribes audio into the input language. /audio/translations: post: operationId: createTranslation tags: - Audio summary: Create translation requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/CreateTranslationRequest' responses: '200': description: OK content: application/json: schema: anyOf: - $ref: '#/components/schemas/CreateTranslationResponseJson' - $ref: '#/components/schemas/CreateTranslationResponseVerboseJson' x-stainless-skip: - go x-oaiMeta: name: Create translation group: audio returns: The translated text. examples: response: | { "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?" } request: curl: | curl https://api.openai.com/v1/audio/translations \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/german.m4a" \ -F model="whisper-1" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) translation = client.audio.translations.create( file=b"raw file contents", model="whisper-1", ) print(translation) javascript: | import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const translation = await openai.audio.translations.create({ file: fs.createReadStream("speech.mp3"), model: "whisper-1", }); console.log(translation.text); } main(); csharp: | using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "whisper-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscription transcription = client.TranscribeAudio(audioFilePath); Console.WriteLine($"{transcription.Text}"); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const translation = await client.audio.translations.create({ file: fs.createReadStream('speech.mp3'), model: 'whisper-1', }); console.log(translation); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) translation, err := client.Audio.Translations.New(context.TODO(), openai.AudioTranslationNewParams{ File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), Model: openai.AudioModelWhisper1, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", translation) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.audio.AudioModel; import com.openai.models.audio.translations.TranslationCreateParams; import com.openai.models.audio.translations.TranslationCreateResponse; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); TranslationCreateParams params = TranslationCreateParams.builder() .file(ByteArrayInputStream("some content".getBytes())) .model(AudioModel.WHISPER_1) .build(); TranslationCreateResponse translation = client.audio().translations().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") translation = openai.audio.translations.create(file: Pathname(__FILE__), model: :"whisper-1") puts(translation) description: Translates audio into English. /batches: post: summary: Create batch operationId: createBatch tags: - Batch requestBody: required: true content: application/json: schema: type: object required: - input_file_id - endpoint - completion_window properties: input_file_id: type: string description: > The ID of an uploaded file that contains requests for the new batch. See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size. endpoint: type: string enum: - /v1/responses - /v1/chat/completions - /v1/embeddings - /v1/completions description: >- The endpoint to be used for all requests in the batch. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch. completion_window: type: string enum: - 24h description: >- The time frame within which the batch should be processed. Currently only `24h` is supported. metadata: $ref: '#/components/schemas/Metadata' output_expires_after: $ref: '#/components/schemas/BatchFileExpirationAfter' responses: '200': description: Batch created successfully. content: application/json: schema: $ref: '#/components/schemas/Batch' x-oaiMeta: name: Create batch group: batch returns: The created [Batch](https://platform.openai.com/docs/api-reference/batch/object) object. examples: response: | { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "validating", "output_file_id": null, "error_file_id": null, "created_at": 1711471533, "in_progress_at": null, "expires_at": null, "finalizing_at": null, "completed_at": null, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 0, "completed": 0, "failed": 0 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly eval job", } } request: curl: | curl https://api.openai.com/v1/batches \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input_file_id": "file-abc123", "endpoint": "/v1/chat/completions", "completion_window": "24h" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) batch = client.batches.create( completion_window="24h", endpoint="/v1/responses", input_file_id="input_file_id", ) print(batch.id) node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const batch = await openai.batches.create({ input_file_id: "file-abc123", endpoint: "/v1/chat/completions", completion_window: "24h" }); console.log(batch); } main(); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const batch = await client.batches.create({ completion_window: '24h', endpoint: '/v1/responses', input_file_id: 'input_file_id', }); console.log(batch.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) batch, err := client.Batches.New(context.TODO(), openai.BatchNewParams{ CompletionWindow: openai.BatchNewParamsCompletionWindow24h, Endpoint: openai.BatchNewParamsEndpointV1Responses, InputFileID: "input_file_id", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", batch.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.batches.Batch; import com.openai.models.batches.BatchCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); BatchCreateParams params = BatchCreateParams.builder() .completionWindow(BatchCreateParams.CompletionWindow._24H) .endpoint(BatchCreateParams.Endpoint.V1_RESPONSES) .inputFileId("input_file_id") .build(); Batch batch = client.batches().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") batch = openai.batches.create( completion_window: :"24h", endpoint: :"/v1/responses", input_file_id: "input_file_id" ) puts(batch) description: Creates and executes a batch from an uploaded file of requests get: operationId: listBatches tags: - Batch summary: List batch parameters: - in: query name: after required: false schema: type: string description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 responses: '200': description: Batch listed successfully. content: application/json: schema: $ref: '#/components/schemas/ListBatchesResponse' x-oaiMeta: name: List batch group: batch returns: A list of paginated [Batch](https://platform.openai.com/docs/api-reference/batch/object) objects. examples: response: | { "object": "list", "data": [ { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "completed", "output_file_id": "file-cvaTdG", "error_file_id": "file-HOWS94", "created_at": 1711471533, "in_progress_at": 1711471538, "expires_at": 1711557933, "finalizing_at": 1711493133, "completed_at": 1711493163, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 100, "completed": 95, "failed": 5 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly job", } }, { ... }, ], "first_id": "batch_abc123", "last_id": "batch_abc456", "has_more": true } request: curl: | curl https://api.openai.com/v1/batches?limit=2 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.batches.list() page = page.data[0] print(page.id) node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const list = await openai.batches.list(); for await (const batch of list) { console.log(batch); } } main(); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const batch of client.batches.list()) { console.log(batch.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Batches.List(context.TODO(), openai.BatchListParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.batches.BatchListPage; import com.openai.models.batches.BatchListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); BatchListPage page = client.batches().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.batches.list puts(page) description: List your organization's batches. /batches/{batch_id}: get: operationId: retrieveBatch tags: - Batch summary: Retrieve batch parameters: - in: path name: batch_id required: true schema: type: string description: The ID of the batch to retrieve. responses: '200': description: Batch retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/Batch' x-oaiMeta: name: Retrieve batch group: batch returns: >- The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the specified ID. examples: response: | { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "completed", "output_file_id": "file-cvaTdG", "error_file_id": "file-HOWS94", "created_at": 1711471533, "in_progress_at": 1711471538, "expires_at": 1711557933, "finalizing_at": 1711493133, "completed_at": 1711493163, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 100, "completed": 95, "failed": 5 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly eval job", } } request: curl: | curl https://api.openai.com/v1/batches/batch_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) batch = client.batches.retrieve( "batch_id", ) print(batch.id) node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const batch = await openai.batches.retrieve("batch_abc123"); console.log(batch); } main(); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const batch = await client.batches.retrieve('batch_id'); console.log(batch.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) batch, err := client.Batches.Get(context.TODO(), "batch_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", batch.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.batches.Batch; import com.openai.models.batches.BatchRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Batch batch = client.batches().retrieve("batch_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") batch = openai.batches.retrieve("batch_id") puts(batch) description: Retrieves a batch. /batches/{batch_id}/cancel: post: operationId: cancelBatch tags: - Batch summary: Cancel batch parameters: - in: path name: batch_id required: true schema: type: string description: The ID of the batch to cancel. responses: '200': description: Batch is cancelling. Returns the cancelling batch's details. content: application/json: schema: $ref: '#/components/schemas/Batch' x-oaiMeta: name: Cancel batch group: batch returns: >- The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the specified ID. examples: response: | { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "cancelling", "output_file_id": null, "error_file_id": null, "created_at": 1711471533, "in_progress_at": 1711471538, "expires_at": 1711557933, "finalizing_at": null, "completed_at": null, "failed_at": null, "expired_at": null, "cancelling_at": 1711475133, "cancelled_at": null, "request_counts": { "total": 100, "completed": 23, "failed": 1 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly eval job", } } request: curl: | curl https://api.openai.com/v1/batches/batch_abc123/cancel \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -X POST python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) batch = client.batches.cancel( "batch_id", ) print(batch.id) node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const batch = await openai.batches.cancel("batch_abc123"); console.log(batch); } main(); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const batch = await client.batches.cancel('batch_id'); console.log(batch.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) batch, err := client.Batches.Cancel(context.TODO(), "batch_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", batch.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.batches.Batch; import com.openai.models.batches.BatchCancelParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Batch batch = client.batches().cancel("batch_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") batch = openai.batches.cancel("batch_id") puts(batch) description: >- Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file. /chat/completions: get: operationId: listChatCompletions tags: - Chat summary: List Chat Completions parameters: - name: model in: query description: The model used to generate the Chat Completions. required: false schema: type: string - name: metadata in: query description: | A list of metadata keys to filter the Chat Completions by. Example: `metadata[key1]=value1&metadata[key2]=value2` required: false schema: $ref: '#/components/schemas/Metadata' - name: after in: query description: Identifier for the last chat completion from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of Chat Completions to retrieve. required: false schema: type: integer default: 20 - name: order in: query description: >- Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. required: false schema: type: string enum: - asc - desc default: asc responses: '200': description: A list of Chat Completions content: application/json: schema: $ref: '#/components/schemas/ChatCompletionList' x-oaiMeta: name: List Chat Completions group: chat returns: >- A list of [Chat Completions](https://platform.openai.com/docs/api-reference/chat/list-object) matching the specified filters. path: list examples: response: | { "object": "list", "data": [ { "object": "chat.completion", "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "model": "gpt-4.1-2025-04-14", "created": 1738960610, "request_id": "req_ded8ab984ec4bf840f37566c1011c417", "tool_choice": null, "usage": { "total_tokens": 31, "completion_tokens": 18, "prompt_tokens": 13 }, "seed": 4944116822809979520, "top_p": 1.0, "temperature": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, "system_fingerprint": "fp_50cad350e4", "input_user": null, "service_tier": "default", "tools": null, "metadata": {}, "choices": [ { "index": 0, "message": { "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", "role": "assistant", "tool_calls": null, "function_call": null }, "finish_reason": "stop", "logprobs": null } ], "response_format": null } ], "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "has_more": false } request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.chat.completions.list() page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const chatCompletion of client.chat.completions.list()) { console.log(chatCompletion.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Chat.Completions.List(context.TODO(), openai.ChatCompletionListParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.chat.completions.ChatCompletionListPage; import com.openai.models.chat.completions.ChatCompletionListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionListPage page = client.chat().completions().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.chat.completions.list puts(page) description: | List stored Chat Completions. Only Chat Completions that have been stored with the `store` parameter set to `true` will be returned. post: operationId: createChatCompletion tags: - Chat summary: Create chat completion requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateChatCompletionRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/CreateChatCompletionResponse' text/event-stream: schema: $ref: '#/components/schemas/CreateChatCompletionStreamResponse' x-oaiMeta: name: Create chat completion group: chat returns: > Returns a [chat completion](https://platform.openai.com/docs/api-reference/chat/object) object, or a streamed sequence of [chat completion chunk](https://platform.openai.com/docs/api-reference/chat/streaming) objects if the request is streamed. path: create examples: - title: Default request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_chat_model_id", "messages": [ { "role": "developer", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello!" } ] }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion = client.chat.completions.create( messages=[{ "content": "string", "role": "developer", }], model="gpt-4o", ) print(chat_completion) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletion = await client.chat.completions.create({ messages: [{ content: 'string', role: 'developer' }], model: 'gpt-4o', }); console.log(chatCompletion); csharp: | using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List messages = [ new SystemChatMessage("You are a helpful assistant."), new UserChatMessage("Hello!") ]; ChatCompletion completion = client.CompleteChat(messages); Console.WriteLine(completion.Content[0].Text); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ OfString: openai.String("string"), }, }, }}, Model: shared.ChatModelGPT5, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletion) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.ChatModel; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() .addDeveloperMessage("string") .model(ChatModel.GPT_5) .build(); ChatCompletion chatCompletion = client.chat().completions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5") puts(chat_completion) response: | { "id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT", "object": "chat.completion", "created": 1741569952, "model": "gpt-4.1-2025-04-14", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I assist you today?", "refusal": null, "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 19, "completion_tokens": 10, "total_tokens": 29, "prompt_tokens_details": { "cached_tokens": 0, "audio_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "service_tier": "default" } - title: Image input request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } } ] } ], "max_tokens": 300 }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion = client.chat.completions.create( messages=[{ "content": "string", "role": "developer", }], model="gpt-4o", ) print(chat_completion) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletion = await client.chat.completions.create({ messages: [{ content: 'string', role: 'developer' }], model: 'gpt-4o', }); console.log(chatCompletion); csharp: | using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List messages = [ new UserChatMessage( [ ChatMessageContentPart.CreateTextPart("What's in this image?"), ChatMessageContentPart.CreateImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")) ]) ]; ChatCompletion completion = client.CompleteChat(messages); Console.WriteLine(completion.Content[0].Text); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ OfString: openai.String("string"), }, }, }}, Model: shared.ChatModelGPT5, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletion) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.ChatModel; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() .addDeveloperMessage("string") .model(ChatModel.GPT_5) .build(); ChatCompletion chatCompletion = client.chat().completions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5") puts(chat_completion) response: | { "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", "object": "chat.completion", "created": 1741570283, "model": "gpt-4.1-2025-04-14", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.", "refusal": null, "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 1117, "completion_tokens": 46, "total_tokens": 1163, "prompt_tokens_details": { "cached_tokens": 0, "audio_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "service_tier": "default" } - title: Streaming request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_chat_model_id", "messages": [ { "role": "developer", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello!" } ], "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion = client.chat.completions.create( messages=[{ "content": "string", "role": "developer", }], model="gpt-4o", ) print(chat_completion) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletion = await client.chat.completions.create({ messages: [{ content: 'string', role: 'developer' }], model: 'gpt-4o', }); console.log(chatCompletion); csharp: > using System; using System.ClientModel; using System.Collections.Generic; using System.Threading.Tasks; using OpenAI.Chat; ChatClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List messages = [ new SystemChatMessage("You are a helpful assistant."), new UserChatMessage("Hello!") ]; AsyncCollectionResult completionUpdates = client.CompleteChatStreamingAsync(messages); await foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates) { if (completionUpdate.ContentUpdate.Count > 0) { Console.Write(completionUpdate.ContentUpdate[0].Text); } } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ OfString: openai.String("string"), }, }, }}, Model: shared.ChatModelGPT5, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletion) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.ChatModel; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() .addDeveloperMessage("string") .model(ChatModel.GPT_5) .build(); ChatCompletion chatCompletion = client.chat().completions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5") puts(chat_completion) response: > {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} .... {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - title: Functions request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "messages": [ { "role": "user", "content": "What is the weather like in Boston today?" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], "tool_choice": "auto" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion = client.chat.completions.create( messages=[{ "content": "string", "role": "developer", }], model="gpt-4o", ) print(chat_completion) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletion = await client.chat.completions.create({ messages: [{ content: 'string', role: 'developer' }], model: 'gpt-4o', }); console.log(chatCompletion); csharp: | using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool( functionName: "get_current_weather", functionDescription: "Get the current weather in a given location", functionParameters: BinaryData.FromString(""" { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit" ] } }, "required": [ "location" ] } """) ); List messages = [ new UserChatMessage("What's the weather like in Boston today?"), ]; ChatCompletionOptions options = new() { Tools = { getCurrentWeatherTool }, ToolChoice = ChatToolChoice.CreateAutoChoice(), }; ChatCompletion completion = client.CompleteChat(messages, options); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ OfString: openai.String("string"), }, }, }}, Model: shared.ChatModelGPT5, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletion) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.ChatModel; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() .addDeveloperMessage("string") .model(ChatModel.GPT_5) .build(); ChatCompletion chatCompletion = client.chat().completions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5") puts(chat_completion) response: | { "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1699896916, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_current_weather", "arguments": "{\n\"location\": \"Boston, MA\"\n}" } } ] }, "logprobs": null, "finish_reason": "tool_calls" } ], "usage": { "prompt_tokens": 82, "completion_tokens": 17, "total_tokens": 99, "completion_tokens_details": { "reasoning_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } } } - title: Logprobs request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_chat_model_id", "messages": [ { "role": "user", "content": "Hello!" } ], "logprobs": true, "top_logprobs": 2 }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion = client.chat.completions.create( messages=[{ "content": "string", "role": "developer", }], model="gpt-4o", ) print(chat_completion) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletion = await client.chat.completions.create({ messages: [{ content: 'string', role: 'developer' }], model: 'gpt-4o', }); console.log(chatCompletion); csharp: | using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List messages = [ new UserChatMessage("Hello!") ]; ChatCompletionOptions options = new() { IncludeLogProbabilities = true, TopLogProbabilityCount = 2 }; ChatCompletion completion = client.CompleteChat(messages, options); Console.WriteLine(completion.Content[0].Text); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ OfString: openai.String("string"), }, }, }}, Model: shared.ChatModelGPT5, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletion) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.ChatModel; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() .addDeveloperMessage("string") .model(ChatModel.GPT_5) .build(); ChatCompletion chatCompletion = client.chat().completions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5") puts(chat_completion) response: | { "id": "chatcmpl-123", "object": "chat.completion", "created": 1702685778, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I assist you today?" }, "logprobs": { "content": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111], "top_logprobs": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111] }, { "token": "Hi", "logprob": -1.3190403, "bytes": [72, 105] } ] }, { "token": "!", "logprob": -0.02380986, "bytes": [ 33 ], "top_logprobs": [ { "token": "!", "logprob": -0.02380986, "bytes": [33] }, { "token": " there", "logprob": -3.787621, "bytes": [32, 116, 104, 101, 114, 101] } ] }, { "token": " How", "logprob": -0.000054669687, "bytes": [32, 72, 111, 119], "top_logprobs": [ { "token": " How", "logprob": -0.000054669687, "bytes": [32, 72, 111, 119] }, { "token": "<|end|>", "logprob": -10.953937, "bytes": null } ] }, { "token": " can", "logprob": -0.015801601, "bytes": [32, 99, 97, 110], "top_logprobs": [ { "token": " can", "logprob": -0.015801601, "bytes": [32, 99, 97, 110] }, { "token": " may", "logprob": -4.161023, "bytes": [32, 109, 97, 121] } ] }, { "token": " I", "logprob": -3.7697225e-6, "bytes": [ 32, 73 ], "top_logprobs": [ { "token": " I", "logprob": -3.7697225e-6, "bytes": [32, 73] }, { "token": " assist", "logprob": -13.596657, "bytes": [32, 97, 115, 115, 105, 115, 116] } ] }, { "token": " assist", "logprob": -0.04571125, "bytes": [32, 97, 115, 115, 105, 115, 116], "top_logprobs": [ { "token": " assist", "logprob": -0.04571125, "bytes": [32, 97, 115, 115, 105, 115, 116] }, { "token": " help", "logprob": -3.1089056, "bytes": [32, 104, 101, 108, 112] } ] }, { "token": " you", "logprob": -5.4385737e-6, "bytes": [32, 121, 111, 117], "top_logprobs": [ { "token": " you", "logprob": -5.4385737e-6, "bytes": [32, 121, 111, 117] }, { "token": " today", "logprob": -12.807695, "bytes": [32, 116, 111, 100, 97, 121] } ] }, { "token": " today", "logprob": -0.0040071653, "bytes": [32, 116, 111, 100, 97, 121], "top_logprobs": [ { "token": " today", "logprob": -0.0040071653, "bytes": [32, 116, 111, 100, 97, 121] }, { "token": "?", "logprob": -5.5247097, "bytes": [63] } ] }, { "token": "?", "logprob": -0.0008108172, "bytes": [63], "top_logprobs": [ { "token": "?", "logprob": -0.0008108172, "bytes": [63] }, { "token": "?\n", "logprob": -7.184561, "bytes": [63, 10] } ] } ] }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 9, "completion_tokens": 9, "total_tokens": 18, "completion_tokens_details": { "reasoning_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "system_fingerprint": null } description: > **Starting a new project?** We recommend trying [Responses](https://platform.openai.com/docs/api-reference/responses) to take advantage of the latest OpenAI platform features. Compare [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). --- Creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. Parameter support can differ depending on the model used to generate the response, particularly for newer reasoning models. Parameters that are only supported for reasoning models are noted below. For the current state of unsupported parameters in reasoning models, [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). /chat/completions/{completion_id}: get: operationId: getChatCompletion tags: - Chat summary: Get chat completion parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to retrieve. responses: '200': description: A chat completion content: application/json: schema: $ref: '#/components/schemas/CreateChatCompletionResponse' x-oaiMeta: name: Get chat completion group: chat returns: >- The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the specified ID. examples: response: | { "object": "chat.completion", "id": "chatcmpl-abc123", "model": "gpt-4o-2024-08-06", "created": 1738960610, "request_id": "req_ded8ab984ec4bf840f37566c1011c417", "tool_choice": null, "usage": { "total_tokens": 31, "completion_tokens": 18, "prompt_tokens": 13 }, "seed": 4944116822809979520, "top_p": 1.0, "temperature": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, "system_fingerprint": "fp_50cad350e4", "input_user": null, "service_tier": "default", "tools": null, "metadata": {}, "choices": [ { "index": 0, "message": { "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", "role": "assistant", "tool_calls": null, "function_call": null }, "finish_reason": "stop", "logprobs": null } ], "response_format": null } request: curl: | curl https://api.openai.com/v1/chat/completions/chatcmpl-abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion = client.chat.completions.retrieve( "completion_id", ) print(chat_completion.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletion = await client.chat.completions.retrieve('completion_id'); console.log(chatCompletion.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletion, err := client.Chat.Completions.Get(context.TODO(), "completion_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletion.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletion chatCompletion = client.chat().completions().retrieve("completion_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion = openai.chat.completions.retrieve("completion_id") puts(chat_completion) description: | Get a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. post: operationId: updateChatCompletion tags: - Chat summary: Update chat completion parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to update. requestBody: required: true content: application/json: schema: type: object required: - metadata properties: metadata: $ref: '#/components/schemas/Metadata' responses: '200': description: A chat completion content: application/json: schema: $ref: '#/components/schemas/CreateChatCompletionResponse' x-oaiMeta: name: Update chat completion group: chat returns: >- The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the specified ID. examples: response: | { "object": "chat.completion", "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "model": "gpt-4o-2024-08-06", "created": 1738960610, "request_id": "req_ded8ab984ec4bf840f37566c1011c417", "tool_choice": null, "usage": { "total_tokens": 31, "completion_tokens": 18, "prompt_tokens": 13 }, "seed": 4944116822809979520, "top_p": 1.0, "temperature": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, "system_fingerprint": "fp_50cad350e4", "input_user": null, "service_tier": "default", "tools": null, "metadata": { "foo": "bar" }, "choices": [ { "index": 0, "message": { "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", "role": "assistant", "tool_calls": null, "function_call": null }, "finish_reason": "stop", "logprobs": null } ], "response_format": null } request: curl: | curl -X POST https://api.openai.com/v1/chat/completions/chat_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"metadata": {"foo": "bar"}}' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion = client.chat.completions.update( completion_id="completion_id", metadata={ "foo": "string" }, ) print(chat_completion.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletion = await client.chat.completions.update('completion_id', { metadata: { foo: 'string' } }); console.log(chatCompletion.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/shared" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletion, err := client.Chat.Completions.Update( context.TODO(), "completion_id", openai.ChatCompletionUpdateParams{ Metadata: shared.Metadata{ "foo": "string", }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletion.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.JsonValue; import com.openai.models.chat.completions.ChatCompletion; import com.openai.models.chat.completions.ChatCompletionUpdateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionUpdateParams params = ChatCompletionUpdateParams.builder() .completionId("completion_id") .metadata(ChatCompletionUpdateParams.Metadata.builder() .putAdditionalProperty("foo", JsonValue.from("string")) .build()) .build(); ChatCompletion chatCompletion = client.chat().completions().update(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion = openai.chat.completions.update("completion_id", metadata: {foo: "string"}) puts(chat_completion) description: | Modify a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` can be modified. Currently, the only supported modification is to update the `metadata` field. delete: operationId: deleteChatCompletion tags: - Chat summary: Delete chat completion parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to delete. responses: '200': description: The chat completion was deleted successfully. content: application/json: schema: $ref: '#/components/schemas/ChatCompletionDeleted' x-oaiMeta: name: Delete chat completion group: chat returns: A deletion confirmation object. examples: response: | { "object": "chat.completion.deleted", "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/chat/completions/chat_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) chat_completion_deleted = client.chat.completions.delete( "completion_id", ) print(chat_completion_deleted.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const chatCompletionDeleted = await client.chat.completions.delete('completion_id'); console.log(chatCompletionDeleted.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) chatCompletionDeleted, err := client.Chat.Completions.Delete(context.TODO(), "completion_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", chatCompletionDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.chat.completions.ChatCompletionDeleteParams; import com.openai.models.chat.completions.ChatCompletionDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ChatCompletionDeleted chatCompletionDeleted = client.chat().completions().delete("completion_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") chat_completion_deleted = openai.chat.completions.delete("completion_id") puts(chat_completion_deleted) description: | Delete a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` can be deleted. /chat/completions/{completion_id}/messages: get: operationId: getChatCompletionMessages tags: - Chat summary: Get chat messages parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to retrieve messages from. - name: after in: query description: Identifier for the last message from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of messages to retrieve. required: false schema: type: integer default: 20 - name: order in: query description: >- Sort order for messages by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. required: false schema: type: string enum: - asc - desc default: asc responses: '200': description: A list of messages content: application/json: schema: $ref: '#/components/schemas/ChatCompletionMessageList' x-oaiMeta: name: Get chat messages group: chat returns: >- A list of [messages](https://platform.openai.com/docs/api-reference/chat/message-list) for the specified chat completion. examples: response: | { "object": "list", "data": [ { "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "role": "user", "content": "write a haiku about ai", "name": null, "content_parts": null } ], "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "has_more": false } request: curl: | curl https://api.openai.com/v1/chat/completions/chat_abc123/messages \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.chat.completions.messages.list( completion_id="completion_id", ) page = page.data[0] print(page) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const chatCompletionStoreMessage of client.chat.completions.messages.list('completion_id')) { console.log(chatCompletionStoreMessage); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Chat.Completions.Messages.List( context.TODO(), "completion_id", openai.ChatCompletionMessageListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.chat.completions.messages.MessageListPage; import com.openai.models.chat.completions.messages.MessageListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); MessageListPage page = client.chat().completions().messages().list("completion_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.chat.completions.messages.list("completion_id") puts(page) description: | Get the messages in a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. /completions: post: operationId: createCompletion tags: - Completions summary: Create completion requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateCompletionRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/CreateCompletionResponse' x-oaiMeta: name: Create completion group: completions returns: > Returns a [completion](https://platform.openai.com/docs/api-reference/completions/object) object, or a sequence of completion objects if the request is streamed. legacy: true examples: - title: No streaming request: curl: | curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_completion_model_id", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0 }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) completion = client.completions.create( model="string", prompt="This is a test.", ) print(completion) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const completion = await client.completions.create({ model: 'string', prompt: 'This is a test.' }); console.log(completion); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{ Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct, Prompt: openai.CompletionNewParamsPromptUnion{ OfString: openai.String("This is a test."), }, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", completion) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.completions.Completion; import com.openai.models.completions.CompletionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); CompletionCreateParams params = CompletionCreateParams.builder() .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT) .prompt("This is a test.") .build(); Completion completion = client.completions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") completion = openai.completions.create(model: :"gpt-3.5-turbo-instruct", prompt: "This is a test.") puts(completion) response: | { "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", "object": "text_completion", "created": 1589478378, "model": "VAR_completion_model_id", "system_fingerprint": "fp_44709d6fcb", "choices": [ { "text": "\n\nThis is indeed a test", "index": 0, "logprobs": null, "finish_reason": "length" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12 } } - title: Streaming request: curl: | curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_completion_model_id", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0, "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) completion = client.completions.create( model="string", prompt="This is a test.", ) print(completion) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const completion = await client.completions.create({ model: 'string', prompt: 'This is a test.' }); console.log(completion); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{ Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct, Prompt: openai.CompletionNewParamsPromptUnion{ OfString: openai.String("This is a test."), }, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", completion) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.completions.Completion; import com.openai.models.completions.CompletionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); CompletionCreateParams params = CompletionCreateParams.builder() .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT) .prompt("This is a test.") .build(); Completion completion = client.completions().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") completion = openai.completions.create(model: :"gpt-3.5-turbo-instruct", prompt: "This is a test.") puts(completion) response: | { "id": "cmpl-7iA7iJjj8V2zOkCGvWF2hAkDWBQZe", "object": "text_completion", "created": 1690759702, "choices": [ { "text": "This", "index": 0, "logprobs": null, "finish_reason": null } ], "model": "gpt-3.5-turbo-instruct" "system_fingerprint": "fp_44709d6fcb", } description: Creates a completion for the provided prompt and parameters. /containers: get: summary: List containers description: List Containers operationId: ListContainers parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ContainerListResource' x-oaiMeta: name: List containers group: containers returns: a list of [container](https://platform.openai.com/docs/api-reference/containers/object) objects. path: get examples: response: | { "object": "list", "data": [ { "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", "object": "container", "created_at": 1747844794, "status": "running", "expires_after": { "anchor": "last_active_at", "minutes": 20 }, "last_active_at": 1747844794, "name": "My Container" } ], "first_id": "container_123", "last_id": "container_123", "has_more": false } request: curl: | curl https://api.openai.com/v1/containers \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const containerListResponse of client.containers.list()) { console.log(containerListResponse.id); } python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.containers.list() page = page.data[0] print(page.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Containers.List(context.TODO(), openai.ContainerListParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.ContainerListPage; import com.openai.models.containers.ContainerListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ContainerListPage page = client.containers().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.containers.list puts(page) post: summary: Create container description: Create Container operationId: CreateContainer parameters: [] requestBody: content: application/json: schema: $ref: '#/components/schemas/CreateContainerBody' responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ContainerResource' x-oaiMeta: name: Create container group: containers returns: The created [container](https://platform.openai.com/docs/api-reference/containers/object) object. path: post examples: response: | { "id": "cntr_682e30645a488191b6363a0cbefc0f0a025ec61b66250591", "object": "container", "created_at": 1747857508, "status": "running", "expires_after": { "anchor": "last_active_at", "minutes": 20 }, "last_active_at": 1747857508, "name": "My Container" } request: curl: | curl https://api.openai.com/v1/containers \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "My Container" }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const container = await client.containers.create({ name: 'name' }); console.log(container.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) container = client.containers.create( name="name", ) print(container.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) container, err := client.Containers.New(context.TODO(), openai.ContainerNewParams{ Name: "name", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", container.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.ContainerCreateParams; import com.openai.models.containers.ContainerCreateResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ContainerCreateParams params = ContainerCreateParams.builder() .name("name") .build(); ContainerCreateResponse container = client.containers().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") container = openai.containers.create(name: "name") puts(container) /containers/{container_id}: get: summary: Retrieve container description: Retrieve Container operationId: RetrieveContainer parameters: - name: container_id in: path required: true schema: type: string responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ContainerResource' x-oaiMeta: name: Retrieve container group: containers returns: The [container](https://platform.openai.com/docs/api-reference/containers/object) object. path: get examples: response: | { "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", "object": "container", "created_at": 1747844794, "status": "running", "expires_after": { "anchor": "last_active_at", "minutes": 20 }, "last_active_at": 1747844794, "name": "My Container" } request: curl: > curl https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const container = await client.containers.retrieve('container_id'); console.log(container.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) container = client.containers.retrieve( "container_id", ) print(container.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) container, err := client.Containers.Get(context.TODO(), "container_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", container.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.ContainerRetrieveParams; import com.openai.models.containers.ContainerRetrieveResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ContainerRetrieveResponse container = client.containers().retrieve("container_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") container = openai.containers.retrieve("container_id") puts(container) delete: operationId: DeleteContainer summary: Delete a container description: Delete Container parameters: - name: container_id in: path description: The ID of the container to delete. required: true schema: type: string responses: '200': description: OK x-oaiMeta: name: Delete a container group: containers returns: Deletion Status path: delete examples: response: | { "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", "object": "container.deleted", "deleted": true } request: curl: > curl -X DELETE https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); await client.containers.delete('container_id'); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) client.containers.delete( "container_id", ) go: | package main import ( "context" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) err := client.Containers.Delete(context.TODO(), "container_id") if err != nil { panic(err.Error()) } } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.ContainerDeleteParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); client.containers().delete("container_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") result = openai.containers.delete("container_id") puts(result) /containers/{container_id}/files: post: summary: Create container file description: > Create a Container File You can send either a multipart/form-data request with the raw file content, or a JSON request with a file ID. operationId: CreateContainerFile parameters: - name: container_id in: path required: true schema: type: string requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/CreateContainerFileBody' responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ContainerFileResource' x-oaiMeta: name: Create container file group: containers returns: >- The created [container file](https://platform.openai.com/docs/api-reference/container-files/object) object. path: post examples: response: | { "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", "object": "container.file", "created_at": 1747848842, "bytes": 880, "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", "source": "user" } request: curl: > curl https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -F file="@example.txt" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const file = await client.containers.files.create('container_id'); console.log(file.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) file = client.containers.files.create( container_id="container_id", ) print(file.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) file, err := client.Containers.Files.New( context.TODO(), "container_id", openai.ContainerFileNewParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", file.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.files.FileCreateParams; import com.openai.models.containers.files.FileCreateResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileCreateResponse file = client.containers().files().create("container_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") file = openai.containers.files.create("container_id") puts(file) get: summary: List container files description: List Container files operationId: ListContainerFiles parameters: - name: container_id in: path required: true schema: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ContainerFileListResource' x-oaiMeta: name: List container files group: containers returns: >- a list of [container file](https://platform.openai.com/docs/api-reference/container-files/object) objects. path: get examples: response: | { "object": "list", "data": [ { "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", "object": "container.file", "created_at": 1747848842, "bytes": 880, "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", "source": "user" } ], "first_id": "cfile_682e0e8a43c88191a7978f477a09bdf5", "has_more": false, "last_id": "cfile_682e0e8a43c88191a7978f477a09bdf5" } request: curl: > curl https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const fileListResponse of client.containers.files.list('container_id')) { console.log(fileListResponse.id); } python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.containers.files.list( container_id="container_id", ) page = page.data[0] print(page.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Containers.Files.List( context.TODO(), "container_id", openai.ContainerFileListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.files.FileListPage; import com.openai.models.containers.files.FileListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileListPage page = client.containers().files().list("container_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.containers.files.list("container_id") puts(page) /containers/{container_id}/files/{file_id}: get: summary: Retrieve container file description: Retrieve Container File operationId: RetrieveContainerFile parameters: - name: container_id in: path required: true schema: type: string - name: file_id in: path required: true schema: type: string responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ContainerFileResource' x-oaiMeta: name: Retrieve container file group: containers returns: The [container file](https://platform.openai.com/docs/api-reference/container-files/object) object. path: get examples: response: | { "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", "object": "container.file", "created_at": 1747848842, "bytes": 880, "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", "source": "user" } request: curl: | curl https://api.openai.com/v1/containers/container_123/files/file_456 \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const file = await client.containers.files.retrieve('file_id', { container_id: 'container_id' }); console.log(file.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) file = client.containers.files.retrieve( file_id="file_id", container_id="container_id", ) print(file.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) file, err := client.Containers.Files.Get( context.TODO(), "container_id", "file_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", file.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.files.FileRetrieveParams; import com.openai.models.containers.files.FileRetrieveResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileRetrieveParams params = FileRetrieveParams.builder() .containerId("container_id") .fileId("file_id") .build(); FileRetrieveResponse file = client.containers().files().retrieve(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") file = openai.containers.files.retrieve("file_id", container_id: "container_id") puts(file) delete: operationId: DeleteContainerFile summary: Delete a container file description: Delete Container File parameters: - name: container_id in: path required: true schema: type: string - name: file_id in: path required: true schema: type: string responses: '200': description: OK x-oaiMeta: name: Delete a container file group: containers returns: Deletion Status path: delete examples: response: | { "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", "object": "container.file.deleted", "deleted": true } request: curl: > curl -X DELETE https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863/files/cfile_682e0e8a43c88191a7978f477a09bdf5 \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); await client.containers.files.delete('file_id', { container_id: 'container_id' }); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) client.containers.files.delete( file_id="file_id", container_id="container_id", ) go: | package main import ( "context" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) err := client.Containers.Files.Delete( context.TODO(), "container_id", "file_id", ) if err != nil { panic(err.Error()) } } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.containers.files.FileDeleteParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileDeleteParams params = FileDeleteParams.builder() .containerId("container_id") .fileId("file_id") .build(); client.containers().files().delete(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") result = openai.containers.files.delete("file_id", container_id: "container_id") puts(result) /containers/{container_id}/files/{file_id}/content: get: summary: Retrieve container file content description: Retrieve Container File Content operationId: RetrieveContainerFileContent parameters: - name: container_id in: path required: true schema: type: string - name: file_id in: path required: true schema: type: string responses: '200': description: Success x-oaiMeta: name: Retrieve container file content group: containers returns: The contents of the container file. path: get examples: response: | request: curl: | curl https://api.openai.com/v1/containers/container_123/files/cfile_456/content \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const content = await client.containers.files.content.retrieve('file_id', { container_id: 'container_id' }); console.log(content); const data = await content.blob(); console.log(data); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) content = client.containers.files.content.retrieve( file_id="file_id", container_id="container_id", ) print(content) data = content.read() print(data) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) content, err := client.Containers.Files.Content.Get( context.TODO(), "container_id", "file_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", content) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.http.HttpResponse; import com.openai.models.containers.files.content.ContentRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ContentRetrieveParams params = ContentRetrieveParams.builder() .containerId("container_id") .fileId("file_id") .build(); HttpResponse content = client.containers().files().content().retrieve(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") content = openai.containers.files.content.retrieve("file_id", container_id: "container_id") puts(content) /embeddings: post: operationId: createEmbedding tags: - Embeddings summary: Create embeddings requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateEmbeddingRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/CreateEmbeddingResponse' x-oaiMeta: name: Create embeddings group: embeddings returns: A list of [embedding](https://platform.openai.com/docs/api-reference/embeddings/object) objects. examples: response: | { "object": "list", "data": [ { "object": "embedding", "embedding": [ 0.0023064255, -0.009327292, .... (1536 floats total for ada-002) -0.0028842222, ], "index": 0 } ], "model": "text-embedding-ada-002", "usage": { "prompt_tokens": 8, "total_tokens": 8 } } request: curl: | curl https://api.openai.com/v1/embeddings \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input": "The food was delicious and the waiter...", "model": "text-embedding-ada-002", "encoding_format": "float" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) create_embedding_response = client.embeddings.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-3-small", ) print(create_embedding_response.data) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const createEmbeddingResponse = await client.embeddings.create({ input: 'The quick brown fox jumped over the lazy dog', model: 'text-embedding-3-small', }); console.log(createEmbeddingResponse.data); csharp: > using System; using OpenAI.Embeddings; EmbeddingClient client = new( model: "text-embedding-3-small", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); OpenAIEmbedding embedding = client.GenerateEmbedding(input: "The quick brown fox jumped over the lazy dog"); ReadOnlyMemory vector = embedding.ToFloats(); for (int i = 0; i < vector.Length; i++) { Console.WriteLine($" [{i,4}] = {vector.Span[i]}"); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) createEmbeddingResponse, err := client.Embeddings.New(context.TODO(), openai.EmbeddingNewParams{ Input: openai.EmbeddingNewParamsInputUnion{ OfString: openai.String("The quick brown fox jumped over the lazy dog"), }, Model: openai.EmbeddingModelTextEmbeddingAda002, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", createEmbeddingResponse.Data) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.embeddings.CreateEmbeddingResponse; import com.openai.models.embeddings.EmbeddingCreateParams; import com.openai.models.embeddings.EmbeddingModel; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); EmbeddingCreateParams params = EmbeddingCreateParams.builder() .input("The quick brown fox jumped over the lazy dog") .model(EmbeddingModel.TEXT_EMBEDDING_ADA_002) .build(); CreateEmbeddingResponse createEmbeddingResponse = client.embeddings().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") create_embedding_response = openai.embeddings.create( input: "The quick brown fox jumped over the lazy dog", model: :"text-embedding-ada-002" ) puts(create_embedding_response) description: Creates an embedding vector representing the input text. /evals: get: operationId: listEvals tags: - Evals summary: List evals parameters: - name: after in: query description: Identifier for the last eval from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of evals to retrieve. required: false schema: type: integer default: 20 - name: order in: query description: Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for descending order. required: false schema: type: string enum: - asc - desc default: asc - name: order_by in: query description: | Evals can be ordered by creation time or last updated time. Use `created_at` for creation time or `updated_at` for last updated time. required: false schema: type: string enum: - created_at - updated_at default: created_at responses: '200': description: A list of evals content: application/json: schema: $ref: '#/components/schemas/EvalList' x-oaiMeta: name: List evals group: evals returns: >- A list of [evals](https://platform.openai.com/docs/api-reference/evals/object) matching the specified filters. path: list examples: response: | { "object": "list", "data": [ { "id": "eval_67abd54d9b0081909a86353f6fb9317a", "object": "eval", "data_source_config": { "type": "stored_completions", "metadata": { "usecase": "push_notifications_summarizer" }, "schema": { "type": "object", "properties": { "item": { "type": "object" }, "sample": { "type": "object" } }, "required": [ "item", "sample" ] } }, "testing_criteria": [ { "name": "Push Notification Summary Grader", "id": "Push Notification Summary Grader-9b876f24-4762-4be9-aff4-db7a9b31c673", "type": "label_model", "model": "o3-mini", "input": [ { "type": "message", "role": "developer", "content": { "type": "input_text", "text": "\nLabel the following push notification summary as either correct or incorrect.\nThe push notification and the summary will be provided below.\nA good push notificiation summary is concise and snappy.\nIf it is good, then label it as correct, if not, then incorrect.\n" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "\nPush notifications: {{item.input}}\nSummary: {{sample.output_text}}\n" } } ], "passing_labels": [ "correct" ], "labels": [ "correct", "incorrect" ], "sampling_params": null } ], "name": "Push Notification Summary Grader", "created_at": 1739314509, "metadata": { "description": "A stored completions eval for push notification summaries" } } ], "first_id": "eval_67abd54d9b0081909a86353f6fb9317a", "last_id": "eval_67aa884cf6688190b58f657d4441c8b7", "has_more": true } request: curl: | curl https://api.openai.com/v1/evals?limit=1 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.evals.list() page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const evalListResponse of client.evals.list()) { console.log(evalListResponse.id); } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.EvalListPage; import com.openai.models.evals.EvalListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); EvalListPage page = client.evals().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.evals.list puts(page) description: | List evaluations for a project. post: operationId: createEval tags: - Evals summary: Create eval requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateEvalRequest' responses: '201': description: OK content: application/json: schema: $ref: '#/components/schemas/Eval' x-oaiMeta: name: Create eval group: evals returns: The created [Eval](https://platform.openai.com/docs/api-reference/evals/object) object. path: post examples: response: | { "object": "eval", "id": "eval_67b7fa9a81a88190ab4aa417e397ea21", "data_source_config": { "type": "stored_completions", "metadata": { "usecase": "chatbot" }, "schema": { "type": "object", "properties": { "item": { "type": "object" }, "sample": { "type": "object" } }, "required": [ "item", "sample" ] }, "testing_criteria": [ { "name": "Example label grader", "type": "label_model", "model": "o3-mini", "input": [ { "type": "message", "role": "developer", "content": { "type": "input_text", "text": "Classify the sentiment of the following statement as one of positive, neutral, or negative" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "Statement: {{item.input}}" } } ], "passing_labels": [ "positive" ], "labels": [ "positive", "neutral", "negative" ] } ], "name": "Sentiment", "created_at": 1740110490, "metadata": { "description": "An eval for sentiment analysis" } } request: curl: | curl https://api.openai.com/v1/evals \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Sentiment", "data_source_config": { "type": "stored_completions", "metadata": { "usecase": "chatbot" } }, "testing_criteria": [ { "type": "label_model", "model": "o3-mini", "input": [ { "role": "developer", "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'" }, { "role": "user", "content": "Statement: {{item.input}}" } ], "passing_labels": [ "positive" ], "labels": [ "positive", "neutral", "negative" ], "name": "Example label grader" } ] }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) eval = client.evals.create( data_source_config={ "item_schema": { "foo": "bar" }, "type": "custom", }, testing_criteria=[{ "input": [{ "content": "content", "role": "role", }], "labels": ["string"], "model": "model", "name": "name", "passing_labels": ["string"], "type": "label_model", }], ) print(eval.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const _eval = await client.evals.create({ data_source_config: { item_schema: { foo: 'bar' }, type: 'custom' }, testing_criteria: [ { input: [{ content: 'content', role: 'role' }], labels: ['string'], model: 'model', name: 'name', passing_labels: ['string'], type: 'label_model', }, ], }); console.log(_eval.id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.JsonValue; import com.openai.models.evals.EvalCreateParams; import com.openai.models.evals.EvalCreateResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); EvalCreateParams params = EvalCreateParams.builder() .customDataSourceConfig(EvalCreateParams.DataSourceConfig.Custom.ItemSchema.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) .build()) .addTestingCriterion(EvalCreateParams.TestingCriterion.LabelModel.builder() .addInput(EvalCreateParams.TestingCriterion.LabelModel.Input.SimpleInputMessage.builder() .content("content") .role("role") .build()) .addLabel("string") .model("model") .name("name") .addPassingLabel("string") .build()) .build(); EvalCreateResponse eval = client.evals().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") eval_ = openai.evals.create( data_source_config: {item_schema: {foo: "bar"}, type: :custom}, testing_criteria: [ { input: [{content: "content", role: "role"}], labels: ["string"], model: "model", name: "name", passing_labels: ["string"], type: :label_model } ] ) puts(eval_) description: > Create the structure of an evaluation that can be used to test a model's performance. An evaluation is a set of testing criteria and the config for a data source, which dictates the schema of the data used in the evaluation. After creating an evaluation, you can run it on different models and model parameters. We support several types of graders and datasources. For more information, see the [Evals guide](https://platform.openai.com/docs/guides/evals). /evals/{eval_id}: get: operationId: getEval tags: - Evals summary: Get an eval parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to retrieve. responses: '200': description: The evaluation content: application/json: schema: $ref: '#/components/schemas/Eval' x-oaiMeta: name: Get an eval group: evals returns: >- The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the specified ID. path: get examples: response: | { "object": "eval", "id": "eval_67abd54d9b0081909a86353f6fb9317a", "data_source_config": { "type": "custom", "schema": { "type": "object", "properties": { "item": { "type": "object", "properties": { "input": { "type": "string" }, "ground_truth": { "type": "string" } }, "required": [ "input", "ground_truth" ] } }, "required": [ "item" ] } }, "testing_criteria": [ { "name": "String check", "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", "type": "string_check", "input": "{{item.input}}", "reference": "{{item.ground_truth}}", "operation": "eq" } ], "name": "External Data Eval", "created_at": 1739314509, "metadata": {}, } request: curl: | curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) eval = client.evals.retrieve( "eval_id", ) print(eval.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const _eval = await client.evals.retrieve('eval_id'); console.log(_eval.id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.EvalRetrieveParams; import com.openai.models.evals.EvalRetrieveResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); EvalRetrieveResponse eval = client.evals().retrieve("eval_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") eval_ = openai.evals.retrieve("eval_id") puts(eval_) description: | Get an evaluation by ID. post: operationId: updateEval tags: - Evals summary: Update an eval parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to update. requestBody: description: Request to update an evaluation required: true content: application/json: schema: type: object properties: name: type: string description: Rename the evaluation. metadata: $ref: '#/components/schemas/Metadata' responses: '200': description: The updated evaluation content: application/json: schema: $ref: '#/components/schemas/Eval' x-oaiMeta: name: Update an eval group: evals returns: >- The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the updated version. path: update examples: response: | { "object": "eval", "id": "eval_67abd54d9b0081909a86353f6fb9317a", "data_source_config": { "type": "custom", "schema": { "type": "object", "properties": { "item": { "type": "object", "properties": { "input": { "type": "string" }, "ground_truth": { "type": "string" } }, "required": [ "input", "ground_truth" ] } }, "required": [ "item" ] } }, "testing_criteria": [ { "name": "String check", "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", "type": "string_check", "input": "{{item.input}}", "reference": "{{item.ground_truth}}", "operation": "eq" } ], "name": "Updated Eval", "created_at": 1739314509, "metadata": {"description": "Updated description"}, } request: curl: | curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "Updated Eval", "metadata": {"description": "Updated description"}}' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) eval = client.evals.update( eval_id="eval_id", ) print(eval.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const _eval = await client.evals.update('eval_id'); console.log(_eval.id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.EvalUpdateParams; import com.openai.models.evals.EvalUpdateResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); EvalUpdateResponse eval = client.evals().update("eval_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") eval_ = openai.evals.update("eval_id") puts(eval_) description: | Update certain properties of an evaluation. delete: operationId: deleteEval tags: - Evals summary: Delete an eval parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to delete. responses: '200': description: Successfully deleted the evaluation. content: application/json: schema: type: object properties: object: type: string example: eval.deleted deleted: type: boolean example: true eval_id: type: string example: eval_abc123 required: - object - deleted - eval_id '404': description: Evaluation not found. content: application/json: schema: $ref: '#/components/schemas/Error' x-oaiMeta: name: Delete an eval group: evals returns: A deletion confirmation object. examples: response: | { "object": "eval.deleted", "deleted": true, "eval_id": "eval_abc123" } request: curl: | curl https://api.openai.com/v1/evals/eval_abc123 \ -X DELETE \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) eval = client.evals.delete( "eval_id", ) print(eval.eval_id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const _eval = await client.evals.delete('eval_id'); console.log(_eval.eval_id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.EvalDeleteParams; import com.openai.models.evals.EvalDeleteResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); EvalDeleteResponse eval = client.evals().delete("eval_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") eval_ = openai.evals.delete("eval_id") puts(eval_) description: | Delete an evaluation. /evals/{eval_id}/runs: get: operationId: getEvalRuns tags: - Evals summary: Get eval runs parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to retrieve runs for. - name: after in: query description: Identifier for the last run from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of runs to retrieve. required: false schema: type: integer default: 20 - name: order in: query description: >- Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. required: false schema: type: string enum: - asc - desc default: asc - name: status in: query description: Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` | `canceled`. required: false schema: type: string enum: - queued - in_progress - completed - canceled - failed responses: '200': description: A list of runs for the evaluation content: application/json: schema: $ref: '#/components/schemas/EvalRunList' x-oaiMeta: name: Get eval runs group: evals returns: >- A list of [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) objects matching the specified ID. path: get-runs examples: response: | { "object": "list", "data": [ { "object": "eval.run", "id": "evalrun_67e0c7d31560819090d60c0780591042", "eval_id": "eval_67e0c726d560819083f19a957c4c640b", "report_url": "https://platform.openai.com/evaluations/eval_67e0c726d560819083f19a957c4c640b", "status": "completed", "model": "o3-mini", "name": "bulk_with_negative_examples_o3-mini", "created_at": 1742784467, "result_counts": { "total": 1, "errored": 0, "failed": 0, "passed": 1 }, "per_model_usage": [ { "model_name": "o3-mini", "invocation_count": 1, "prompt_tokens": 563, "completion_tokens": 874, "total_tokens": 1437, "cached_tokens": 0 } ], "per_testing_criteria_results": [ { "testing_criteria": "Push Notification Summary Grader-1808cd0b-eeec-4e0b-a519-337e79f4f5d1", "passed": 1, "failed": 0 } ], "data_source": { "type": "completions", "source": { "type": "file_content", "content": [ { "item": { "notifications": "\n- New message from Sarah: \"Can you call me later?\"\n- Your package has been delivered!\n- Flash sale: 20% off electronics for the next 2 hours!\n" } } ] }, "input_messages": { "type": "template", "template": [ { "type": "message", "role": "developer", "content": { "type": "input_text", "text": "\n\n\n\nYou are a helpful assistant that takes in an array of push notifications and returns a collapsed summary of them.\nThe push notification will be provided as follows:\n\n...notificationlist...\n\n\nYou should return just the summary and nothing else.\n\n\nYou should return a summary that is concise and snappy.\n\n\nHere is an example of a good summary:\n\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n\n\nTraffic alert, package expected by 5pm, suggestion for new friend (Emily).\n\n\n\nHere is an example of a bad summary:\n\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n\n\nTraffic alert reported on main street. You have a package that will arrive by 5pm, Emily is a new friend suggested for you.\n\n" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "{{item.notifications}}" } } ] }, "model": "o3-mini", "sampling_params": null }, "error": null, "metadata": {} } ], "first_id": "evalrun_67e0c7d31560819090d60c0780591042", "last_id": "evalrun_67e0c7d31560819090d60c0780591042", "has_more": true } request: curl: | curl https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.evals.runs.list( eval_id="eval_id", ) page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const runListResponse of client.evals.runs.list('eval_id')) { console.log(runListResponse.id); } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.runs.RunListPage; import com.openai.models.evals.runs.RunListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunListPage page = client.evals().runs().list("eval_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.evals.runs.list("eval_id") puts(page) description: | Get a list of runs for an evaluation. post: operationId: createEvalRun tags: - Evals summary: Create eval run parameters: - in: path name: eval_id required: true schema: type: string description: The ID of the evaluation to create a run for. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateEvalRunRequest' responses: '201': description: Successfully created a run for the evaluation content: application/json: schema: $ref: '#/components/schemas/EvalRun' '400': description: Bad request (for example, missing eval object) content: application/json: schema: $ref: '#/components/schemas/Error' x-oaiMeta: name: Create eval run group: evals returns: >- The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the specified ID. examples: response: | { "object": "eval.run", "id": "evalrun_67e57965b480819094274e3a32235e4c", "eval_id": "eval_67e579652b548190aaa83ada4b125f47", "report_url": "https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47&run_id=evalrun_67e57965b480819094274e3a32235e4c", "status": "queued", "model": "gpt-4o-mini", "name": "gpt-4o-mini", "created_at": 1743092069, "result_counts": { "total": 0, "errored": 0, "failed": 0, "passed": 0 }, "per_model_usage": null, "per_testing_criteria_results": null, "data_source": { "type": "completions", "source": { "type": "file_content", "content": [ { "item": { "input": "Tech Company Launches Advanced Artificial Intelligence Platform", "ground_truth": "Technology" } } ] }, "input_messages": { "type": "template", "template": [ { "type": "message", "role": "developer", "content": { "type": "input_text", "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "{{item.input}}" } } ] }, "model": "gpt-4o-mini", "sampling_params": { "seed": 42, "temperature": 1.0, "top_p": 1.0, "max_completions_tokens": 2048 } }, "error": null, "metadata": {} } request: curl: | curl https://api.openai.com/v1/evals/eval_67e579652b548190aaa83ada4b125f47/runs \ -X POST \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"gpt-4o-mini","data_source":{"type":"completions","input_messages":{"type":"template","template":[{"role":"developer","content":"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n"} , {"role":"user","content":"{{item.input}}"}]} ,"sampling_params":{"temperature":1,"max_completions_tokens":2048,"top_p":1,"seed":42},"model":"gpt-4o-mini","source":{"type":"file_content","content":[{"item":{"input":"Tech Company Launches Advanced Artificial Intelligence Platform","ground_truth":"Technology"}}]}}' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.evals.runs.create( eval_id="eval_id", data_source={ "source": { "content": [{ "item": { "foo": "bar" } }], "type": "file_content", }, "type": "jsonl", }, ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.evals.runs.create('eval_id', { data_source: { source: { content: [{ item: { foo: 'bar' } }], type: 'file_content' }, type: 'jsonl' }, }); console.log(run.id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.JsonValue; import com.openai.models.evals.runs.CreateEvalJsonlRunDataSource; import com.openai.models.evals.runs.RunCreateParams; import com.openai.models.evals.runs.RunCreateResponse; import java.util.List; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunCreateParams params = RunCreateParams.builder() .evalId("eval_id") .dataSource(CreateEvalJsonlRunDataSource.builder() .fileContentSource(List.of(CreateEvalJsonlRunDataSource.Source.FileContent.Content.builder() .item(CreateEvalJsonlRunDataSource.Source.FileContent.Content.Item.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) .build()) .build())) .build()) .build(); RunCreateResponse run = client.evals().runs().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.evals.runs.create( "eval_id", data_source: {source: {content: [{item: {foo: "bar"}}], type: :file_content}, type: :jsonl} ) puts(run) description: > Kicks off a new run for a given evaluation, specifying the data source, and what model configuration to use to test. The datasource will be validated against the schema specified in the config of the evaluation. /evals/{eval_id}/runs/{run_id}: get: operationId: getEvalRun tags: - Evals summary: Get an eval run parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to retrieve runs for. - name: run_id in: path required: true schema: type: string description: The ID of the run to retrieve. responses: '200': description: The evaluation run content: application/json: schema: $ref: '#/components/schemas/EvalRun' x-oaiMeta: name: Get an eval run group: evals returns: >- The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the specified ID. path: get examples: response: | { "object": "eval.run", "id": "evalrun_67abd54d60ec8190832b46859da808f7", "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7", "status": "queued", "model": "gpt-4o-mini", "name": "gpt-4o-mini", "created_at": 1743092069, "result_counts": { "total": 0, "errored": 0, "failed": 0, "passed": 0 }, "per_model_usage": null, "per_testing_criteria_results": null, "data_source": { "type": "completions", "source": { "type": "file_content", "content": [ { "item": { "input": "Tech Company Launches Advanced Artificial Intelligence Platform", "ground_truth": "Technology" } }, { "item": { "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", "ground_truth": "Markets" } }, { "item": { "input": "International Summit Addresses Climate Change Strategies", "ground_truth": "World" } }, { "item": { "input": "Major Retailer Reports Record-Breaking Holiday Sales", "ground_truth": "Business" } }, { "item": { "input": "National Team Qualifies for World Championship Finals", "ground_truth": "Sports" } }, { "item": { "input": "Stock Markets Rally After Positive Economic Data Released", "ground_truth": "Markets" } }, { "item": { "input": "Global Manufacturer Announces Merger with Competitor", "ground_truth": "Business" } }, { "item": { "input": "Breakthrough in Renewable Energy Technology Unveiled", "ground_truth": "Technology" } }, { "item": { "input": "World Leaders Sign Historic Climate Agreement", "ground_truth": "World" } }, { "item": { "input": "Professional Athlete Sets New Record in Championship Event", "ground_truth": "Sports" } }, { "item": { "input": "Financial Institutions Adapt to New Regulatory Requirements", "ground_truth": "Business" } }, { "item": { "input": "Tech Conference Showcases Advances in Artificial Intelligence", "ground_truth": "Technology" } }, { "item": { "input": "Global Markets Respond to Oil Price Fluctuations", "ground_truth": "Markets" } }, { "item": { "input": "International Cooperation Strengthened Through New Treaty", "ground_truth": "World" } }, { "item": { "input": "Sports League Announces Revised Schedule for Upcoming Season", "ground_truth": "Sports" } } ] }, "input_messages": { "type": "template", "template": [ { "type": "message", "role": "developer", "content": { "type": "input_text", "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "{{item.input}}" } } ] }, "model": "gpt-4o-mini", "sampling_params": { "seed": 42, "temperature": 1.0, "top_p": 1.0, "max_completions_tokens": 2048 } }, "error": null, "metadata": {} } request: curl: > curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.evals.runs.retrieve( run_id="run_id", eval_id="eval_id", ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.evals.runs.retrieve('run_id', { eval_id: 'eval_id' }); console.log(run.id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.runs.RunRetrieveParams; import com.openai.models.evals.runs.RunRetrieveResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunRetrieveParams params = RunRetrieveParams.builder() .evalId("eval_id") .runId("run_id") .build(); RunRetrieveResponse run = client.evals().runs().retrieve(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.evals.runs.retrieve("run_id", eval_id: "eval_id") puts(run) description: | Get an evaluation run by ID. post: operationId: cancelEvalRun tags: - Evals summary: Cancel eval run parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation whose run you want to cancel. - name: run_id in: path required: true schema: type: string description: The ID of the run to cancel. responses: '200': description: The canceled eval run object content: application/json: schema: $ref: '#/components/schemas/EvalRun' x-oaiMeta: name: Cancel eval run group: evals returns: >- The updated [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object reflecting that the run is canceled. path: post examples: response: | { "object": "eval.run", "id": "evalrun_67abd54d60ec8190832b46859da808f7", "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7", "status": "canceled", "model": "gpt-4o-mini", "name": "gpt-4o-mini", "created_at": 1743092069, "result_counts": { "total": 0, "errored": 0, "failed": 0, "passed": 0 }, "per_model_usage": null, "per_testing_criteria_results": null, "data_source": { "type": "completions", "source": { "type": "file_content", "content": [ { "item": { "input": "Tech Company Launches Advanced Artificial Intelligence Platform", "ground_truth": "Technology" } }, { "item": { "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", "ground_truth": "Markets" } }, { "item": { "input": "International Summit Addresses Climate Change Strategies", "ground_truth": "World" } }, { "item": { "input": "Major Retailer Reports Record-Breaking Holiday Sales", "ground_truth": "Business" } }, { "item": { "input": "National Team Qualifies for World Championship Finals", "ground_truth": "Sports" } }, { "item": { "input": "Stock Markets Rally After Positive Economic Data Released", "ground_truth": "Markets" } }, { "item": { "input": "Global Manufacturer Announces Merger with Competitor", "ground_truth": "Business" } }, { "item": { "input": "Breakthrough in Renewable Energy Technology Unveiled", "ground_truth": "Technology" } }, { "item": { "input": "World Leaders Sign Historic Climate Agreement", "ground_truth": "World" } }, { "item": { "input": "Professional Athlete Sets New Record in Championship Event", "ground_truth": "Sports" } }, { "item": { "input": "Financial Institutions Adapt to New Regulatory Requirements", "ground_truth": "Business" } }, { "item": { "input": "Tech Conference Showcases Advances in Artificial Intelligence", "ground_truth": "Technology" } }, { "item": { "input": "Global Markets Respond to Oil Price Fluctuations", "ground_truth": "Markets" } }, { "item": { "input": "International Cooperation Strengthened Through New Treaty", "ground_truth": "World" } }, { "item": { "input": "Sports League Announces Revised Schedule for Upcoming Season", "ground_truth": "Sports" } } ] }, "input_messages": { "type": "template", "template": [ { "type": "message", "role": "developer", "content": { "type": "input_text", "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "{{item.input}}" } } ] }, "model": "gpt-4o-mini", "sampling_params": { "seed": 42, "temperature": 1.0, "top_p": 1.0, "max_completions_tokens": 2048 } }, "error": null, "metadata": {} } request: curl: > curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/cancel \ -X POST \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.evals.runs.cancel( run_id="run_id", eval_id="eval_id", ) print(response.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.evals.runs.cancel('run_id', { eval_id: 'eval_id' }); console.log(response.id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.runs.RunCancelParams; import com.openai.models.evals.runs.RunCancelResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunCancelParams params = RunCancelParams.builder() .evalId("eval_id") .runId("run_id") .build(); RunCancelResponse response = client.evals().runs().cancel(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.evals.runs.cancel("run_id", eval_id: "eval_id") puts(response) description: | Cancel an ongoing evaluation run. delete: operationId: deleteEvalRun tags: - Evals summary: Delete eval run parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to delete the run from. - name: run_id in: path required: true schema: type: string description: The ID of the run to delete. responses: '200': description: Successfully deleted the eval run content: application/json: schema: type: object properties: object: type: string example: eval.run.deleted deleted: type: boolean example: true run_id: type: string example: evalrun_677469f564d48190807532a852da3afb '404': description: Run not found content: application/json: schema: $ref: '#/components/schemas/Error' x-oaiMeta: name: Delete eval run group: evals returns: An object containing the status of the delete operation. path: delete examples: response: | { "object": "eval.run.deleted", "deleted": true, "run_id": "evalrun_abc456" } request: curl: | curl https://api.openai.com/v1/evals/eval_123abc/runs/evalrun_abc456 \ -X DELETE \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.evals.runs.delete( run_id="run_id", eval_id="eval_id", ) print(run.run_id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.evals.runs.delete('run_id', { eval_id: 'eval_id' }); console.log(run.run_id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.runs.RunDeleteParams; import com.openai.models.evals.runs.RunDeleteResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunDeleteParams params = RunDeleteParams.builder() .evalId("eval_id") .runId("run_id") .build(); RunDeleteResponse run = client.evals().runs().delete(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.evals.runs.delete("run_id", eval_id: "eval_id") puts(run) description: | Delete an eval run. /evals/{eval_id}/runs/{run_id}/output_items: get: operationId: getEvalRunOutputItems tags: - Evals summary: Get eval run output items parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to retrieve runs for. - name: run_id in: path required: true schema: type: string description: The ID of the run to retrieve output items for. - name: after in: query description: Identifier for the last output item from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of output items to retrieve. required: false schema: type: integer default: 20 - name: status in: query description: | Filter output items by status. Use `failed` to filter by failed output items or `pass` to filter by passed output items. required: false schema: type: string enum: - fail - pass - name: order in: query description: >- Sort order for output items by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. required: false schema: type: string enum: - asc - desc default: asc responses: '200': description: A list of output items for the evaluation run content: application/json: schema: $ref: '#/components/schemas/EvalRunOutputItemList' x-oaiMeta: name: Get eval run output items group: evals returns: >- A list of [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) objects matching the specified ID. path: get examples: response: | { "object": "list", "data": [ { "object": "eval.run.output_item", "id": "outputitem_67e5796c28e081909917bf79f6e6214d", "created_at": 1743092076, "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", "status": "pass", "datasource_item_id": 5, "datasource_item": { "input": "Stock Markets Rally After Positive Economic Data Released", "ground_truth": "Markets" }, "results": [ { "name": "String check-a2486074-d803-4445-b431-ad2262e85d47", "sample": null, "passed": true, "score": 1.0 } ], "sample": { "input": [ { "role": "developer", "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n", "tool_call_id": null, "tool_calls": null, "function_call": null }, { "role": "user", "content": "Stock Markets Rally After Positive Economic Data Released", "tool_call_id": null, "tool_calls": null, "function_call": null } ], "output": [ { "role": "assistant", "content": "Markets", "tool_call_id": null, "tool_calls": null, "function_call": null } ], "finish_reason": "stop", "model": "gpt-4o-mini-2024-07-18", "usage": { "total_tokens": 325, "completion_tokens": 2, "prompt_tokens": 323, "cached_tokens": 0 }, "error": null, "temperature": 1.0, "max_completion_tokens": 2048, "top_p": 1.0, "seed": 42 } } ], "first_id": "outputitem_67e5796c28e081909917bf79f6e6214d", "last_id": "outputitem_67e5796c28e081909917bf79f6e6214d", "has_more": true } request: curl: > curl https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs/erun_67abd54d60ec8190832b46859da808f7/output_items \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.evals.runs.output_items.list( run_id="run_id", eval_id="eval_id", ) page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const outputItemListResponse of client.evals.runs.outputItems.list('run_id', { eval_id: 'eval_id', })) { console.log(outputItemListResponse.id); } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.runs.outputitems.OutputItemListPage; import com.openai.models.evals.runs.outputitems.OutputItemListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); OutputItemListParams params = OutputItemListParams.builder() .evalId("eval_id") .runId("run_id") .build(); OutputItemListPage page = client.evals().runs().outputItems().list(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.evals.runs.output_items.list("run_id", eval_id: "eval_id") puts(page) description: | Get a list of output items for an evaluation run. /evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}: get: operationId: getEvalRunOutputItem tags: - Evals summary: Get an output item of an eval run parameters: - name: eval_id in: path required: true schema: type: string description: The ID of the evaluation to retrieve runs for. - name: run_id in: path required: true schema: type: string description: The ID of the run to retrieve. - name: output_item_id in: path required: true schema: type: string description: The ID of the output item to retrieve. responses: '200': description: The evaluation run output item content: application/json: schema: $ref: '#/components/schemas/EvalRunOutputItem' x-oaiMeta: name: Get an output item of an eval run group: evals returns: >- The [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) object matching the specified ID. path: get examples: response: | { "object": "eval.run.output_item", "id": "outputitem_67e5796c28e081909917bf79f6e6214d", "created_at": 1743092076, "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", "status": "pass", "datasource_item_id": 5, "datasource_item": { "input": "Stock Markets Rally After Positive Economic Data Released", "ground_truth": "Markets" }, "results": [ { "name": "String check-a2486074-d803-4445-b431-ad2262e85d47", "sample": null, "passed": true, "score": 1.0 } ], "sample": { "input": [ { "role": "developer", "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n", "tool_call_id": null, "tool_calls": null, "function_call": null }, { "role": "user", "content": "Stock Markets Rally After Positive Economic Data Released", "tool_call_id": null, "tool_calls": null, "function_call": null } ], "output": [ { "role": "assistant", "content": "Markets", "tool_call_id": null, "tool_calls": null, "function_call": null } ], "finish_reason": "stop", "model": "gpt-4o-mini-2024-07-18", "usage": { "total_tokens": 325, "completion_tokens": 2, "prompt_tokens": 323, "cached_tokens": 0 }, "error": null, "temperature": 1.0, "max_completion_tokens": 2048, "top_p": 1.0, "seed": 42 } } request: curl: > curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/output_items/outputitem_67abd55eb6548190bb580745d5644a33 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) output_item = client.evals.runs.output_items.retrieve( output_item_id="output_item_id", eval_id="eval_id", run_id="run_id", ) print(output_item.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const outputItem = await client.evals.runs.outputItems.retrieve('output_item_id', { eval_id: 'eval_id', run_id: 'run_id', }); console.log(outputItem.id); java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.evals.runs.outputitems.OutputItemRetrieveParams; import com.openai.models.evals.runs.outputitems.OutputItemRetrieveResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); OutputItemRetrieveParams params = OutputItemRetrieveParams.builder() .evalId("eval_id") .runId("run_id") .outputItemId("output_item_id") .build(); OutputItemRetrieveResponse outputItem = client.evals().runs().outputItems().retrieve(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") output_item = openai.evals.runs.output_items.retrieve("output_item_id", eval_id: "eval_id", run_id: "run_id") puts(output_item) description: | Get an evaluation run output item by ID. /files: get: operationId: listFiles tags: - Files summary: List files parameters: - in: query name: purpose required: false schema: type: string description: Only return files with the given purpose. - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 10,000, and the default is 10,000. required: false schema: type: integer default: 10000 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListFilesResponse' x-oaiMeta: name: List files group: files returns: A list of [File](https://platform.openai.com/docs/api-reference/files/object) objects. examples: response: | { "object": "list", "data": [ { "id": "file-abc123", "object": "file", "bytes": 175, "created_at": 1613677385, "expires_at": 1677614202, "filename": "salesOverview.pdf", "purpose": "assistants", }, { "id": "file-abc456", "object": "file", "bytes": 140, "created_at": 1613779121, "expires_at": 1677614202, "filename": "puppy.jsonl", "purpose": "fine-tune", } ], "first_id": "file-abc123", "last_id": "file-abc456", "has_more": false } request: curl: | curl https://api.openai.com/v1/files \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.files.list() page = page.data[0] print(page) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const fileObject of client.files.list()) { console.log(fileObject); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Files.List(context.TODO(), openai.FileListParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.files.FileListPage; import com.openai.models.files.FileListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileListPage page = client.files().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.files.list puts(page) description: Returns a list of files. post: operationId: createFile tags: - Files summary: Upload file requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/CreateFileRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/OpenAIFile' x-oaiMeta: name: Upload file group: files returns: The uploaded [File](https://platform.openai.com/docs/api-reference/files/object) object. examples: response: | { "id": "file-abc123", "object": "file", "bytes": 120000, "created_at": 1677610602, "expires_at": 1677614202, "filename": "mydata.jsonl", "purpose": "fine-tune", } request: curl: | curl https://api.openai.com/v1/files \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -F purpose="fine-tune" \ -F file="@mydata.jsonl" -F expires_after[anchor]="created_at" -F expires_after[seconds]=3600 python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) file_object = client.files.create( file=b"raw file contents", purpose="assistants", ) print(file_object.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fileObject = await client.files.create({ file: fs.createReadStream('fine-tune.jsonl'), purpose: 'assistants', }); console.log(fileObject.id); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fileObject, err := client.Files.New(context.TODO(), openai.FileNewParams{ File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), Purpose: openai.FilePurposeAssistants, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fileObject.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.files.FileCreateParams; import com.openai.models.files.FileObject; import com.openai.models.files.FilePurpose; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileCreateParams params = FileCreateParams.builder() .file(ByteArrayInputStream("some content".getBytes())) .purpose(FilePurpose.ASSISTANTS) .build(); FileObject fileObject = client.files().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") file_object = openai.files.create(file: Pathname(__FILE__), purpose: :assistants) puts(file_object) description: > Upload a file that can be used across various endpoints. Individual files can be up to 512 MB, and the size of all files uploaded by one organization can be up to 1 TB. The Assistants API supports files up to 2 million tokens and of specific file types. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models. The Batch API only supports `.jsonl` files up to 200 MB in size. The input also has a specific required [format](https://platform.openai.com/docs/api-reference/batch/request-input). Please [contact us](https://help.openai.com/) if you need to increase these storage limits. /files/{file_id}: delete: operationId: deleteFile tags: - Files summary: Delete file parameters: - in: path name: file_id required: true schema: type: string description: The ID of the file to use for this request. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteFileResponse' x-oaiMeta: name: Delete file group: files returns: Deletion status. examples: response: | { "id": "file-abc123", "object": "file", "deleted": true } request: curl: | curl https://api.openai.com/v1/files/file-abc123 \ -X DELETE \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) file_deleted = client.files.delete( "file_id", ) print(file_deleted.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fileDeleted = await client.files.delete('file_id'); console.log(fileDeleted.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fileDeleted, err := client.Files.Delete(context.TODO(), "file_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fileDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.files.FileDeleteParams; import com.openai.models.files.FileDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileDeleted fileDeleted = client.files().delete("file_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") file_deleted = openai.files.delete("file_id") puts(file_deleted) description: Delete a file. get: operationId: retrieveFile tags: - Files summary: Retrieve file parameters: - in: path name: file_id required: true schema: type: string description: The ID of the file to use for this request. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/OpenAIFile' x-oaiMeta: name: Retrieve file group: files returns: >- The [File](https://platform.openai.com/docs/api-reference/files/object) object matching the specified ID. examples: response: | { "id": "file-abc123", "object": "file", "bytes": 120000, "created_at": 1677610602, "expires_at": 1677614202, "filename": "mydata.jsonl", "purpose": "fine-tune", } request: curl: | curl https://api.openai.com/v1/files/file-abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) file_object = client.files.retrieve( "file_id", ) print(file_object.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fileObject = await client.files.retrieve('file_id'); console.log(fileObject.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fileObject, err := client.Files.Get(context.TODO(), "file_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fileObject.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.files.FileObject; import com.openai.models.files.FileRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileObject fileObject = client.files().retrieve("file_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") file_object = openai.files.retrieve("file_id") puts(file_object) description: Returns information about a specific file. /files/{file_id}/content: get: operationId: downloadFile tags: - Files summary: Retrieve file content parameters: - in: path name: file_id required: true schema: type: string description: The ID of the file to use for this request. responses: '200': description: OK content: application/json: schema: type: string x-oaiMeta: name: Retrieve file content group: files returns: The file content. examples: response: '' request: curl: | curl https://api.openai.com/v1/files/file-abc123/content \ -H "Authorization: Bearer $OPENAI_API_KEY" > file.jsonl python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.files.content( "file_id", ) print(response) content = response.read() print(content) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.files.content('file_id'); console.log(response); const content = await response.blob(); console.log(content); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Files.Content(context.TODO(), "file_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.http.HttpResponse; import com.openai.models.files.FileContentParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); HttpResponse response = client.files().content("file_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.files.content("file_id") puts(response) description: Returns the contents of the specified file. /fine_tuning/alpha/graders/run: post: operationId: runGrader tags: - Fine-tuning summary: Run grader requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/RunGraderRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunGraderResponse' x-oaiMeta: name: Run grader beta: true group: graders returns: The results from the grader run. examples: response: | { "reward": 1.0, "metadata": { "name": "Example score model grader", "type": "score_model", "errors": { "formula_parse_error": false, "sample_parse_error": false, "truncated_observation_error": false, "unresponsive_reward_error": false, "invalid_variable_error": false, "other_error": false, "python_grader_server_error": false, "python_grader_server_error_type": null, "python_grader_runtime_error": false, "python_grader_runtime_error_details": null, "model_grader_server_error": false, "model_grader_refusal_error": false, "model_grader_parse_error": false, "model_grader_server_error_details": null }, "execution_time": 4.365238428115845, "scores": {}, "token_usage": { "prompt_tokens": 190, "total_tokens": 324, "completion_tokens": 134, "cached_tokens": 0 }, "sampled_model_name": "gpt-4o-2024-08-06" }, "sub_rewards": {}, "model_grader_token_usage_per_model": { "gpt-4o-2024-08-06": { "prompt_tokens": 190, "total_tokens": 324, "completion_tokens": 134, "cached_tokens": 0 } } } request: curl: | curl -X POST https://api.openai.com/v1/fine_tuning/alpha/graders/run \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "grader": { "type": "score_model", "name": "Example score model grader", "input": [ { "role": "user", "content": "Score how close the reference answer is to the model answer. Score 1.0 if they are the same and 0.0 if they are different. Return just a floating point score\n\nReference answer: {{item.reference_answer}}\n\nModel answer: {{sample.output_text}}" } ], "model": "gpt-4o-2024-08-06", "sampling_params": { "temperature": 1, "top_p": 1, "seed": 42 } }, "item": { "reference_answer": "fuzzy wuzzy was a bear" }, "model_sample": "fuzzy wuzzy was a bear" }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.fineTuning.alpha.graders.run({ grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' }, model_sample: 'model_sample', }); console.log(response.metadata); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.fine_tuning.alpha.graders.run( grader={ "input": "input", "name": "name", "operation": "eq", "reference": "reference", "type": "string_check", }, model_sample="model_sample", ) print(response.metadata) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.FineTuning.Alpha.Graders.Run(context.TODO(), openai.FineTuningAlphaGraderRunParams{ Grader: openai.FineTuningAlphaGraderRunParamsGraderUnion{ OfStringCheck: &openai.StringCheckGraderParam{ Input: "input", Name: "name", Operation: openai.StringCheckGraderOperationEq, Reference: "reference", }, }, ModelSample: "model_sample", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Metadata) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.alpha.graders.GraderRunParams; import com.openai.models.finetuning.alpha.graders.GraderRunResponse; import com.openai.models.graders.gradermodels.StringCheckGrader; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); GraderRunParams params = GraderRunParams.builder() .grader(StringCheckGrader.builder() .input("input") .name("name") .operation(StringCheckGrader.Operation.EQ) .reference("reference") .build()) .modelSample("model_sample") .build(); GraderRunResponse response = client.fineTuning().alpha().graders().run(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.fine_tuning.alpha.graders.run( grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check}, model_sample: "model_sample" ) puts(response) description: | Run a grader. /fine_tuning/alpha/graders/validate: post: operationId: validateGrader tags: - Fine-tuning summary: Validate grader requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ValidateGraderRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ValidateGraderResponse' x-oaiMeta: name: Validate grader beta: true group: graders returns: The validated grader object. examples: response: | { "grader": { "type": "string_check", "name": "Example string check grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "operation": "eq" } } request: curl: | curl https://api.openai.com/v1/fine_tuning/alpha/graders/validate \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "grader": { "type": "string_check", "name": "Example string check grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "operation": "eq" } }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.fineTuning.alpha.graders.validate({ grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' }, }); console.log(response.grader); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.fine_tuning.alpha.graders.validate( grader={ "input": "input", "name": "name", "operation": "eq", "reference": "reference", "type": "string_check", }, ) print(response.grader) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.FineTuning.Alpha.Graders.Validate(context.TODO(), openai.FineTuningAlphaGraderValidateParams{ Grader: openai.FineTuningAlphaGraderValidateParamsGraderUnion{ OfStringCheckGrader: &openai.StringCheckGraderParam{ Input: "input", Name: "name", Operation: openai.StringCheckGraderOperationEq, Reference: "reference", }, }, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Grader) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.alpha.graders.GraderValidateParams; import com.openai.models.finetuning.alpha.graders.GraderValidateResponse; import com.openai.models.graders.gradermodels.StringCheckGrader; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); GraderValidateParams params = GraderValidateParams.builder() .grader(StringCheckGrader.builder() .input("input") .name("name") .operation(StringCheckGrader.Operation.EQ) .reference("reference") .build()) .build(); GraderValidateResponse response = client.fineTuning().alpha().graders().validate(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.fine_tuning.alpha.graders.validate( grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check} ) puts(response) description: | Validate a grader. /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions: get: operationId: listFineTuningCheckpointPermissions tags: - Fine-tuning summary: List checkpoint permissions parameters: - in: path name: fine_tuned_model_checkpoint required: true schema: type: string example: ft-AF1WoRqd3aJAHsqc9NY7iL8F description: | The ID of the fine-tuned model checkpoint to get permissions for. - name: project_id in: query description: The ID of the project to get permissions for. required: false schema: type: string - name: after in: query description: Identifier for the last permission ID from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of permissions to retrieve. required: false schema: type: integer default: 10 - name: order in: query description: The order in which to retrieve permissions. required: false schema: type: string enum: - ascending - descending default: descending responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListFineTuningCheckpointPermissionResponse' x-oaiMeta: name: List checkpoint permissions group: fine-tuning returns: >- A list of fine-tuned model checkpoint [permission objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a fine-tuned model checkpoint. examples: response: | { "object": "list", "data": [ { "object": "checkpoint.permission", "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", "created_at": 1721764867, "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" }, { "object": "checkpoint.permission", "id": "cp_enQCFmOTGj3syEpYVhBRLTSy", "created_at": 1721764800, "project_id": "proj_iqGMw1llN8IrBb6SvvY5A1oF" }, ], "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", "last_id": "cp_enQCFmOTGj3syEpYVhBRLTSy", "has_more": false } request: curl: > curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const permission = await client.fineTuning.checkpoints.permissions.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); console.log(permission.first_id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) permission = client.fine_tuning.checkpoints.permissions.retrieve( fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) print(permission.first_id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) permission, err := client.FineTuning.Checkpoints.Permissions.Get( context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F", openai.FineTuningCheckpointPermissionGetParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", permission.FirstID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveParams; import com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); PermissionRetrieveResponse permission = client.fineTuning().checkpoints().permissions().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") permission = openai.fine_tuning.checkpoints.permissions.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F") puts(permission) description: | **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). Organization owners can use this endpoint to view all permissions for a fine-tuned model checkpoint. post: operationId: createFineTuningCheckpointPermission tags: - Fine-tuning summary: Create checkpoint permissions parameters: - in: path name: fine_tuned_model_checkpoint required: true schema: type: string example: ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd description: | The ID of the fine-tuned model checkpoint to create a permission for. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateFineTuningCheckpointPermissionRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListFineTuningCheckpointPermissionResponse' x-oaiMeta: name: Create checkpoint permissions group: fine-tuning returns: >- A list of fine-tuned model checkpoint [permission objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a fine-tuned model checkpoint. examples: response: | { "object": "list", "data": [ { "object": "checkpoint.permission", "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", "created_at": 1721764867, "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" } ], "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", "last_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", "has_more": false } request: curl: > curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions \ -H "Authorization: Bearer $OPENAI_API_KEY" -d '{"project_ids": ["proj_abGMw1llN8IrBb6SvvY5A1iH"]}' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', { project_ids: ['string'] }, )) { console.log(permissionCreateResponse.id); } python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.fine_tuning.checkpoints.permissions.create( fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", project_ids=["string"], ) page = page.data[0] print(page.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.FineTuning.Checkpoints.Permissions.New( context.TODO(), "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", openai.FineTuningCheckpointPermissionNewParams{ ProjectIDs: []string{"string"}, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.checkpoints.permissions.PermissionCreatePage; import com.openai.models.finetuning.checkpoints.permissions.PermissionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); PermissionCreateParams params = PermissionCreateParams.builder() .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd") .addProjectId("string") .build(); PermissionCreatePage page = client.fineTuning().checkpoints().permissions().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.fine_tuning.checkpoints.permissions.create( "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", project_ids: ["string"] ) puts(page) description: | **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). This enables organization owners to share fine-tuned models with other projects in their organization. /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}: delete: operationId: deleteFineTuningCheckpointPermission tags: - Fine-tuning summary: Delete checkpoint permission parameters: - in: path name: fine_tuned_model_checkpoint required: true schema: type: string example: ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd description: | The ID of the fine-tuned model checkpoint to delete a permission for. - in: path name: permission_id required: true schema: type: string example: cp_zc4Q7MP6XxulcVzj4MZdwsAB description: | The ID of the fine-tuned model checkpoint permission to delete. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteFineTuningCheckpointPermissionResponse' x-oaiMeta: name: Delete checkpoint permission group: fine-tuning returns: >- The deletion status of the fine-tuned model checkpoint [permission object](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object). examples: response: | { "object": "checkpoint.permission", "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", "deleted": true } request: curl: > curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions/cp_zc4Q7MP6XxulcVzj4MZdwsAB \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const permission = await client.fineTuning.checkpoints.permissions.delete('cp_zc4Q7MP6XxulcVzj4MZdwsAB', { fine_tuned_model_checkpoint: 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', }); console.log(permission.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) permission = client.fine_tuning.checkpoints.permissions.delete( permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) print(permission.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) permission, err := client.FineTuning.Checkpoints.Permissions.Delete( context.TODO(), "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", "cp_zc4Q7MP6XxulcVzj4MZdwsAB", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", permission.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteParams; import com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); PermissionDeleteParams params = PermissionDeleteParams.builder() .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd") .permissionId("cp_zc4Q7MP6XxulcVzj4MZdwsAB") .build(); PermissionDeleteResponse permission = client.fineTuning().checkpoints().permissions().delete(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") permission = openai.fine_tuning.checkpoints.permissions.delete( "cp_zc4Q7MP6XxulcVzj4MZdwsAB", fine_tuned_model_checkpoint: "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd" ) puts(permission) description: | **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). Organization owners can use this endpoint to delete a permission for a fine-tuned model checkpoint. /fine_tuning/jobs: post: operationId: createFineTuningJob tags: - Fine-tuning summary: Create fine-tuning job requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateFineTuningJobRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/FineTuningJob' x-oaiMeta: name: Create fine-tuning job group: fine-tuning returns: A [fine-tuning.job](https://platform.openai.com/docs/api-reference/fine-tuning/object) object. examples: - title: Default request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo", "model": "gpt-4o-mini" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.create( model="gpt-4o-mini", training_file="file-abc123", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.create({ model: 'gpt-4o-mini', training_file: 'file-abc123', }); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ Model: openai.FineTuningJobNewParamsModelBabbage002, TrainingFile: "file-abc123", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobCreateParams params = JobCreateParams.builder() .model(JobCreateParams.Model.BABBAGE_002) .trainingFile("file-abc123") .build(); FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123") puts(fine_tuning_job) response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini-2024-07-18", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "queued", "validation_file": null, "training_file": "file-abc123", "method": { "type": "supervised", "supervised": { "hyperparameters": { "batch_size": "auto", "learning_rate_multiplier": "auto", "n_epochs": "auto", } } }, "metadata": null } - title: Epochs request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-abc123", "model": "gpt-4o-mini", "method": { "type": "supervised", "supervised": { "hyperparameters": { "n_epochs": 2 } } } }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.create( model="gpt-4o-mini", training_file="file-abc123", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.create({ model: 'gpt-4o-mini', training_file: 'file-abc123', }); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ Model: openai.FineTuningJobNewParamsModelBabbage002, TrainingFile: "file-abc123", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobCreateParams params = JobCreateParams.builder() .model(JobCreateParams.Model.BABBAGE_002) .trainingFile("file-abc123") .build(); FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123") puts(fine_tuning_job) response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "queued", "validation_file": null, "training_file": "file-abc123", "hyperparameters": { "batch_size": "auto", "learning_rate_multiplier": "auto", "n_epochs": 2 }, "method": { "type": "supervised", "supervised": { "hyperparameters": { "batch_size": "auto", "learning_rate_multiplier": "auto", "n_epochs": 2 } } }, "metadata": null, "error": { "code": null, "message": null, "param": null }, "finished_at": null, "seed": 683058546, "trained_tokens": null, "estimated_finish": null, "integrations": [], "user_provided_suffix": null, "usage_metrics": null, "shared_with_openai": false } - title: DPO request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-abc123", "validation_file": "file-abc123", "model": "gpt-4o-mini", "method": { "type": "dpo", "dpo": { "hyperparameters": { "beta": 0.1 } } } }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.create({ model: 'gpt-4o-mini', training_file: 'file-abc123', }); console.log(fineTuningJob.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.create( model="gpt-4o-mini", training_file="file-abc123", ) print(fine_tuning_job.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ Model: openai.FineTuningJobNewParamsModelBabbage002, TrainingFile: "file-abc123", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobCreateParams params = JobCreateParams.builder() .model(JobCreateParams.Model.BABBAGE_002) .trainingFile("file-abc123") .build(); FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123") puts(fine_tuning_job) python: | from openai import OpenAI from openai.types.fine_tuning import DpoMethod, DpoHyperparameters client = OpenAI() client.fine_tuning.jobs.create( training_file="file-abc", validation_file="file-123", model="gpt-4o-mini", method={ "type": "dpo", "dpo": DpoMethod( hyperparameters=DpoHyperparameters(beta=0.1) ) } ) response: | { "object": "fine_tuning.job", "id": "ftjob-abc", "model": "gpt-4o-mini", "created_at": 1746130590, "fine_tuned_model": null, "organization_id": "org-abc", "result_files": [], "status": "queued", "validation_file": "file-123", "training_file": "file-abc", "method": { "type": "dpo", "dpo": { "hyperparameters": { "beta": 0.1, "batch_size": "auto", "learning_rate_multiplier": "auto", "n_epochs": "auto" } } }, "metadata": null, "error": { "code": null, "message": null, "param": null }, "finished_at": null, "hyperparameters": null, "seed": 1036326793, "estimated_finish": null, "integrations": [], "user_provided_suffix": null, "usage_metrics": null, "shared_with_openai": false } - title: Reinforcement request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-abc", "validation_file": "file-123", "model": "o4-mini", "method": { "type": "reinforcement", "reinforcement": { "grader": { "type": "string_check", "name": "Example string check grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "operation": "eq" }, "hyperparameters": { "reasoning_effort": "medium" } } } }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.create( model="gpt-4o-mini", training_file="file-abc123", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.create({ model: 'gpt-4o-mini', training_file: 'file-abc123', }); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ Model: openai.FineTuningJobNewParamsModelBabbage002, TrainingFile: "file-abc123", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobCreateParams params = JobCreateParams.builder() .model(JobCreateParams.Model.BABBAGE_002) .trainingFile("file-abc123") .build(); FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123") puts(fine_tuning_job) response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "o4-mini", "created_at": 1721764800, "finished_at": null, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "validating_files", "validation_file": "file-123", "training_file": "file-abc", "trained_tokens": null, "error": {}, "user_provided_suffix": null, "seed": 950189191, "estimated_finish": null, "integrations": [], "method": { "type": "reinforcement", "reinforcement": { "hyperparameters": { "batch_size": "auto", "learning_rate_multiplier": "auto", "n_epochs": "auto", "eval_interval": "auto", "eval_samples": "auto", "compute_multiplier": "auto", "reasoning_effort": "medium" }, "grader": { "type": "string_check", "name": "Example string check grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "operation": "eq" }, "response_format": null } }, "metadata": null, "usage_metrics": null, "shared_with_openai": false } - title: Validation file request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-abc123", "validation_file": "file-abc123", "model": "gpt-4o-mini" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.create( model="gpt-4o-mini", training_file="file-abc123", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.create({ model: 'gpt-4o-mini', training_file: 'file-abc123', }); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ Model: openai.FineTuningJobNewParamsModelBabbage002, TrainingFile: "file-abc123", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobCreateParams params = JobCreateParams.builder() .model(JobCreateParams.Model.BABBAGE_002) .trainingFile("file-abc123") .build(); FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123") puts(fine_tuning_job) response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini-2024-07-18", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "queued", "validation_file": "file-abc123", "training_file": "file-abc123", "method": { "type": "supervised", "supervised": { "hyperparameters": { "batch_size": "auto", "learning_rate_multiplier": "auto", "n_epochs": "auto", } } }, "metadata": null } - title: W&B Integration request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-abc123", "validation_file": "file-abc123", "model": "gpt-4o-mini", "integrations": [ { "type": "wandb", "wandb": { "project": "my-wandb-project", "name": "ft-run-display-name" "tags": [ "first-experiment", "v2" ] } } ] }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.create({ model: 'gpt-4o-mini', training_file: 'file-abc123', }); console.log(fineTuningJob.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.create( model="gpt-4o-mini", training_file="file-abc123", ) print(fine_tuning_job.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ Model: openai.FineTuningJobNewParamsModelBabbage002, TrainingFile: "file-abc123", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobCreateParams params = JobCreateParams.builder() .model(JobCreateParams.Model.BABBAGE_002) .trainingFile("file-abc123") .build(); FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123") puts(fine_tuning_job) response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini-2024-07-18", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "queued", "validation_file": "file-abc123", "training_file": "file-abc123", "integrations": [ { "type": "wandb", "wandb": { "project": "my-wandb-project", "entity": None, "run_id": "ftjob-abc123" } } ], "method": { "type": "supervised", "supervised": { "hyperparameters": { "batch_size": "auto", "learning_rate_multiplier": "auto", "n_epochs": "auto", } } }, "metadata": null } description: > Creates a fine-tuning job which begins the process of creating a new model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) get: operationId: listPaginatedFineTuningJobs tags: - Fine-tuning summary: List fine-tuning jobs parameters: - name: after in: query description: Identifier for the last job from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of fine-tuning jobs to retrieve. required: false schema: type: integer default: 20 - in: query name: metadata required: false schema: type: object nullable: true additionalProperties: type: string style: deepObject explode: true description: > Optional metadata filter. To filter, use the syntax `metadata[k]=v`. Alternatively, set `metadata=null` to indicate no metadata. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListPaginatedFineTuningJobsResponse' x-oaiMeta: name: List fine-tuning jobs group: fine-tuning returns: >- A list of paginated [fine-tuning job](https://platform.openai.com/docs/api-reference/fine-tuning/object) objects. examples: response: | { "object": "list", "data": [ { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini-2024-07-18", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "queued", "validation_file": null, "training_file": "file-abc123", "metadata": { "key": "value" } }, { ... }, { ... } ], "has_more": true } request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs?limit=2&metadata[key]=value \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.fine_tuning.jobs.list() page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const fineTuningJob of client.fineTuning.jobs.list()) { console.log(fineTuningJob.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.FineTuning.Jobs.List(context.TODO(), openai.FineTuningJobListParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.JobListPage; import com.openai.models.finetuning.jobs.JobListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobListPage page = client.fineTuning().jobs().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.fine_tuning.jobs.list puts(page) description: | List your organization's fine-tuning jobs /fine_tuning/jobs/{fine_tuning_job_id}: get: operationId: retrieveFineTuningJob tags: - Fine-tuning summary: Retrieve fine-tuning job parameters: - in: path name: fine_tuning_job_id required: true schema: type: string example: ft-AF1WoRqd3aJAHsqc9NY7iL8F description: | The ID of the fine-tuning job. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/FineTuningJob' x-oaiMeta: name: Retrieve fine-tuning job group: fine-tuning returns: >- The [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object with the given ID. examples: response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "davinci-002", "created_at": 1692661014, "finished_at": 1692661190, "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy", "organization_id": "org-123", "result_files": [ "file-abc123" ], "status": "succeeded", "validation_file": null, "training_file": "file-abc123", "hyperparameters": { "n_epochs": 4, "batch_size": 1, "learning_rate_multiplier": 1.0 }, "trained_tokens": 5768, "integrations": [], "seed": 0, "estimated_finish": 0, "method": { "type": "supervised", "supervised": { "hyperparameters": { "n_epochs": 4, "batch_size": 1, "learning_rate_multiplier": 1.0 } } } } request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs/ft-AF1WoRqd3aJAHsqc9NY7iL8F \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.retrieve( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.Get(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FineTuningJob fineTuningJob = client.fineTuning().jobs().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F") puts(fine_tuning_job) description: | Get info about a fine-tuning job. [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) /fine_tuning/jobs/{fine_tuning_job_id}/cancel: post: operationId: cancelFineTuningJob tags: - Fine-tuning summary: Cancel fine-tuning parameters: - in: path name: fine_tuning_job_id required: true schema: type: string example: ft-AF1WoRqd3aJAHsqc9NY7iL8F description: | The ID of the fine-tuning job to cancel. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/FineTuningJob' x-oaiMeta: name: Cancel fine-tuning group: fine-tuning returns: >- The cancelled [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object. examples: response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini-2024-07-18", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "cancelled", "validation_file": "file-abc123", "training_file": "file-abc123" } request: curl: | curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/cancel \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.cancel( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.Cancel(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobCancelParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FineTuningJob fineTuningJob = client.fineTuning().jobs().cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F") puts(fine_tuning_job) description: | Immediately cancel a fine-tune job. /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints: get: operationId: listFineTuningJobCheckpoints tags: - Fine-tuning summary: List fine-tuning checkpoints parameters: - in: path name: fine_tuning_job_id required: true schema: type: string example: ft-AF1WoRqd3aJAHsqc9NY7iL8F description: | The ID of the fine-tuning job to get checkpoints for. - name: after in: query description: Identifier for the last checkpoint ID from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of checkpoints to retrieve. required: false schema: type: integer default: 10 responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListFineTuningJobCheckpointsResponse' x-oaiMeta: name: List fine-tuning checkpoints group: fine-tuning returns: >- A list of fine-tuning [checkpoint objects](https://platform.openai.com/docs/api-reference/fine-tuning/checkpoint-object) for a fine-tuning job. examples: response: | { "object": "list", "data": [ { "object": "fine_tuning.job.checkpoint", "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", "created_at": 1721764867, "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:96olL566:ckpt-step-2000", "metrics": { "full_valid_loss": 0.134, "full_valid_mean_token_accuracy": 0.874 }, "fine_tuning_job_id": "ftjob-abc123", "step_number": 2000 }, { "object": "fine_tuning.job.checkpoint", "id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", "created_at": 1721764800, "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000", "metrics": { "full_valid_loss": 0.167, "full_valid_mean_token_accuracy": 0.781 }, "fine_tuning_job_id": "ftjob-abc123", "step_number": 1000 } ], "first_id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", "last_id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", "has_more": true } request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/checkpoints \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', )) { console.log(fineTuningJobCheckpoint.id); } python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.fine_tuning.jobs.checkpoints.list( fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) page = page.data[0] print(page.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.FineTuning.Jobs.Checkpoints.List( context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F", openai.FineTuningJobCheckpointListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.checkpoints.CheckpointListPage; import com.openai.models.finetuning.jobs.checkpoints.CheckpointListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); CheckpointListPage page = client.fineTuning().jobs().checkpoints().list("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.fine_tuning.jobs.checkpoints.list("ft-AF1WoRqd3aJAHsqc9NY7iL8F") puts(page) description: | List checkpoints for a fine-tuning job. /fine_tuning/jobs/{fine_tuning_job_id}/events: get: operationId: listFineTuningEvents tags: - Fine-tuning summary: List fine-tuning events parameters: - in: path name: fine_tuning_job_id required: true schema: type: string example: ft-AF1WoRqd3aJAHsqc9NY7iL8F description: | The ID of the fine-tuning job to get events for. - name: after in: query description: Identifier for the last event from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of events to retrieve. required: false schema: type: integer default: 20 responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListFineTuningJobEventsResponse' x-oaiMeta: name: List fine-tuning events group: fine-tuning returns: A list of fine-tuning event objects. examples: response: | { "object": "list", "data": [ { "object": "fine_tuning.job.event", "id": "ft-event-ddTJfwuMVpfLXseO0Am0Gqjm", "created_at": 1721764800, "level": "info", "message": "Fine tuning job successfully completed", "data": null, "type": "message" }, { "object": "fine_tuning.job.event", "id": "ft-event-tyiGuB72evQncpH87xe505Sv", "created_at": 1721764800, "level": "info", "message": "New fine-tuned model created: ft:gpt-4o-mini:openai::7p4lURel", "data": null, "type": "message" } ], "has_more": true } request: curl: | curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/events \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.fine_tuning.jobs.list_events( fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) page = page.data[0] print(page.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F')) { console.log(fineTuningJobEvent.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.FineTuning.Jobs.ListEvents( context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F", openai.FineTuningJobListEventsParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.JobListEventsPage; import com.openai.models.finetuning.jobs.JobListEventsParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); JobListEventsPage page = client.fineTuning().jobs().listEvents("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.fine_tuning.jobs.list_events("ft-AF1WoRqd3aJAHsqc9NY7iL8F") puts(page) description: | Get status updates for a fine-tuning job. /fine_tuning/jobs/{fine_tuning_job_id}/pause: post: operationId: pauseFineTuningJob tags: - Fine-tuning summary: Pause fine-tuning parameters: - in: path name: fine_tuning_job_id required: true schema: type: string example: ft-AF1WoRqd3aJAHsqc9NY7iL8F description: | The ID of the fine-tuning job to pause. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/FineTuningJob' x-oaiMeta: name: Pause fine-tuning group: fine-tuning returns: The paused [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object. examples: response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini-2024-07-18", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "paused", "validation_file": "file-abc123", "training_file": "file-abc123" } request: curl: | curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/pause \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.pause( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.pause('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.Pause(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobPauseParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FineTuningJob fineTuningJob = client.fineTuning().jobs().pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F") puts(fine_tuning_job) description: | Pause a fine-tune job. /fine_tuning/jobs/{fine_tuning_job_id}/resume: post: operationId: resumeFineTuningJob tags: - Fine-tuning summary: Resume fine-tuning parameters: - in: path name: fine_tuning_job_id required: true schema: type: string example: ft-AF1WoRqd3aJAHsqc9NY7iL8F description: | The ID of the fine-tuning job to resume. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/FineTuningJob' x-oaiMeta: name: Resume fine-tuning group: fine-tuning returns: The resumed [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object. examples: response: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "gpt-4o-mini-2024-07-18", "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], "status": "queued", "validation_file": "file-abc123", "training_file": "file-abc123" } request: curl: | curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/resume \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) fine_tuning_job = client.fine_tuning.jobs.resume( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) print(fine_tuning_job.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const fineTuningJob = await client.fineTuning.jobs.resume('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); console.log(fineTuningJob.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) fineTuningJob, err := client.FineTuning.Jobs.Resume(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", fineTuningJob.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.finetuning.jobs.FineTuningJob; import com.openai.models.finetuning.jobs.JobResumeParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FineTuningJob fineTuningJob = client.fineTuning().jobs().resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") fine_tuning_job = openai.fine_tuning.jobs.resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F") puts(fine_tuning_job) description: | Resume a fine-tune job. /images/edits: post: operationId: createImageEdit tags: - Images summary: Create image edit requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/CreateImageEditRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ImagesResponse' text/event-stream: schema: $ref: '#/components/schemas/ImageEditStreamEvent' x-oaiMeta: name: Create image edit group: images returns: Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object. examples: - title: Edit image request: curl: | curl -s -D >(grep -i x-request-id >&2) \ -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \ -X POST "https://api.openai.com/v1/images/edits" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -F "model=gpt-image-1" \ -F "image[]=@body-lotion.png" \ -F "image[]=@bath-bomb.png" \ -F "image[]=@incense-kit.png" \ -F "image[]=@soap.png" \ -F 'prompt=Create a lovely gift basket with these four items in it' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) images_response = client.images.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", ) print(images_response) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const imagesResponse = await client.images.edit({ image: fs.createReadStream('path/to/file'), prompt: 'A cute baby sea otter wearing a beret', }); console.log(imagesResponse); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{ Image: openai.ImageEditParamsImageUnion{ OfFile: io.Reader(bytes.NewBuffer([]byte("some file contents"))), }, Prompt: "A cute baby sea otter wearing a beret", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", imagesResponse) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.images.ImageEditParams; import com.openai.models.images.ImagesResponse; import java.io.ByteArrayInputStream; import java.io.InputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ImageEditParams params = ImageEditParams.builder() .image(ByteArrayInputStream("some content".getBytes())) .prompt("A cute baby sea otter wearing a beret") .build(); ImagesResponse imagesResponse = client.images().edit(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") images_response = openai.images.edit(image: Pathname(__FILE__), prompt: "A cute baby sea otter wearing a beret") puts(images_response) - title: Streaming request: curl: | curl -s -N -X POST "https://api.openai.com/v1/images/edits" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -F "model=gpt-image-1" \ -F "image[]=@body-lotion.png" \ -F "image[]=@bath-bomb.png" \ -F "image[]=@incense-kit.png" \ -F "image[]=@soap.png" \ -F 'prompt=Create a lovely gift basket with these four items in it' \ -F "stream=true" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) images_response = client.images.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", ) print(images_response) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const imagesResponse = await client.images.edit({ image: fs.createReadStream('path/to/file'), prompt: 'A cute baby sea otter wearing a beret', }); console.log(imagesResponse); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{ Image: openai.ImageEditParamsImageUnion{ OfFile: io.Reader(bytes.NewBuffer([]byte("some file contents"))), }, Prompt: "A cute baby sea otter wearing a beret", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", imagesResponse) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.images.ImageEditParams; import com.openai.models.images.ImagesResponse; import java.io.ByteArrayInputStream; import java.io.InputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ImageEditParams params = ImageEditParams.builder() .image(ByteArrayInputStream("some content".getBytes())) .prompt("A cute baby sea otter wearing a beret") .build(); ImagesResponse imagesResponse = client.images().edit(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") images_response = openai.images.edit(image: Pathname(__FILE__), prompt: "A cute baby sea otter wearing a beret") puts(images_response) response: > event: image_edit.partial_image data: {"type":"image_edit.partial_image","b64_json":"...","partial_image_index":0} event: image_edit.completed data: {"type":"image_edit.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}} description: >- Creates an edited or extended image given one or more source images and a prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. /images/generations: post: operationId: createImage tags: - Images summary: Create image requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateImageRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ImagesResponse' text/event-stream: schema: $ref: '#/components/schemas/ImageGenStreamEvent' x-oaiMeta: name: Create image group: images returns: Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object. examples: - title: Generate image request: curl: | curl https://api.openai.com/v1/images/generations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-image-1", "prompt": "A cute baby sea otter", "n": 1, "size": "1024x1024" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) images_response = client.images.generate( prompt="A cute baby sea otter", ) print(images_response) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' }); console.log(imagesResponse); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{ Prompt: "A cute baby sea otter", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", imagesResponse) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.images.ImageGenerateParams; import com.openai.models.images.ImagesResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ImageGenerateParams params = ImageGenerateParams.builder() .prompt("A cute baby sea otter") .build(); ImagesResponse imagesResponse = client.images().generate(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") images_response = openai.images.generate(prompt: "A cute baby sea otter") puts(images_response) response: | { "created": 1713833628, "data": [ { "b64_json": "..." } ], "usage": { "total_tokens": 100, "input_tokens": 50, "output_tokens": 50, "input_tokens_details": { "text_tokens": 10, "image_tokens": 40 } } } - title: Streaming request: curl: | curl https://api.openai.com/v1/images/generations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-image-1", "prompt": "A cute baby sea otter", "n": 1, "size": "1024x1024", "stream": true }' \ --no-buffer python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) images_response = client.images.generate( prompt="A cute baby sea otter", ) print(images_response) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' }); console.log(imagesResponse); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{ Prompt: "A cute baby sea otter", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", imagesResponse) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.images.ImageGenerateParams; import com.openai.models.images.ImagesResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ImageGenerateParams params = ImageGenerateParams.builder() .prompt("A cute baby sea otter") .build(); ImagesResponse imagesResponse = client.images().generate(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") images_response = openai.images.generate(prompt: "A cute baby sea otter") puts(images_response) response: > event: image_generation.partial_image data: {"type":"image_generation.partial_image","b64_json":"...","partial_image_index":0} event: image_generation.completed data: {"type":"image_generation.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}} description: | Creates an image given a prompt. [Learn more](https://platform.openai.com/docs/guides/images). /images/variations: post: operationId: createImageVariation tags: - Images summary: Create image variation requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/CreateImageVariationRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ImagesResponse' x-oaiMeta: name: Create image variation group: images returns: Returns a list of [image](https://platform.openai.com/docs/api-reference/images/object) objects. examples: response: | { "created": 1589478378, "data": [ { "url": "https://..." }, { "url": "https://..." } ] } request: curl: | curl https://api.openai.com/v1/images/variations \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -F image="@otter.png" \ -F n=2 \ -F size="1024x1024" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) images_response = client.images.create_variation( image=b"raw file contents", ) print(images_response.created) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const imagesResponse = await client.images.createVariation({ image: fs.createReadStream('otter.png') }); console.log(imagesResponse.created); csharp: | using System; using OpenAI.Images; ImageClient client = new( model: "dall-e-2", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); GeneratedImage image = client.GenerateImageVariation(imageFilePath: "otter.png"); Console.WriteLine(image.ImageUri); go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) imagesResponse, err := client.Images.NewVariation(context.TODO(), openai.ImageNewVariationParams{ Image: io.Reader(bytes.NewBuffer([]byte("some file contents"))), }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", imagesResponse.Created) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.images.ImageCreateVariationParams; import com.openai.models.images.ImagesResponse; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ImageCreateVariationParams params = ImageCreateVariationParams.builder() .image(ByteArrayInputStream("some content".getBytes())) .build(); ImagesResponse imagesResponse = client.images().createVariation(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") images_response = openai.images.create_variation(image: Pathname(__FILE__)) puts(images_response) description: Creates a variation of a given image. This endpoint only supports `dall-e-2`. /models: get: operationId: listModels tags: - Models summary: List models responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListModelsResponse' x-oaiMeta: name: List models group: models returns: A list of [model](https://platform.openai.com/docs/api-reference/models/object) objects. examples: response: | { "object": "list", "data": [ { "id": "model-id-0", "object": "model", "created": 1686935002, "owned_by": "organization-owner" }, { "id": "model-id-1", "object": "model", "created": 1686935002, "owned_by": "organization-owner", }, { "id": "model-id-2", "object": "model", "created": 1686935002, "owned_by": "openai" }, ], "object": "list" } request: curl: | curl https://api.openai.com/v1/models \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.models.list() page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const model of client.models.list()) { console.log(model.id); } csharp: | using System; using OpenAI.Models; OpenAIModelClient client = new( apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); foreach (var model in client.GetModels().Value) { Console.WriteLine(model.Id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Models.List(context.TODO()) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.models.ModelListPage; import com.openai.models.models.ModelListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ModelListPage page = client.models().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.models.list puts(page) description: >- Lists the currently available models, and provides basic information about each one such as the owner and availability. /models/{model}: get: operationId: retrieveModel tags: - Models summary: Retrieve model parameters: - in: path name: model required: true schema: type: string example: gpt-4o-mini description: The ID of the model to use for this request responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Model' x-oaiMeta: name: Retrieve model group: models returns: >- The [model](https://platform.openai.com/docs/api-reference/models/object) object matching the specified ID. examples: response: | { "id": "VAR_chat_model_id", "object": "model", "created": 1686935002, "owned_by": "openai" } request: curl: | curl https://api.openai.com/v1/models/VAR_chat_model_id \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) model = client.models.retrieve( "gpt-4o-mini", ) print(model.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const model = await client.models.retrieve('gpt-4o-mini'); console.log(model.id); csharp: | using System; using System.ClientModel; using OpenAI.Models; OpenAIModelClient client = new( apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); ClientResult model = client.GetModel("babbage-002"); Console.WriteLine(model.Value.Id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) model, err := client.Models.Get(context.TODO(), "gpt-4o-mini") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", model.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.models.Model; import com.openai.models.models.ModelRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Model model = client.models().retrieve("gpt-4o-mini"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") model = openai.models.retrieve("gpt-4o-mini") puts(model) description: >- Retrieves a model instance, providing basic information about the model such as the owner and permissioning. delete: operationId: deleteModel tags: - Models summary: Delete a fine-tuned model parameters: - in: path name: model required: true schema: type: string example: ft:gpt-4o-mini:acemeco:suffix:abc123 description: The model to delete responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteModelResponse' x-oaiMeta: name: Delete a fine-tuned model group: models returns: Deletion status. examples: response: | { "id": "ft:gpt-4o-mini:acemeco:suffix:abc123", "object": "model", "deleted": true } request: curl: | curl https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 \ -X DELETE \ -H "Authorization: Bearer $OPENAI_API_KEY" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) model_deleted = client.models.delete( "ft:gpt-4o-mini:acemeco:suffix:abc123", ) print(model_deleted.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const modelDeleted = await client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123'); console.log(modelDeleted.id); csharp: | using System; using System.ClientModel; using OpenAI.Models; OpenAIModelClient client = new( apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); ClientResult success = client.DeleteModel("ft:gpt-4o-mini:acemeco:suffix:abc123"); Console.WriteLine(success); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) modelDeleted, err := client.Models.Delete(context.TODO(), "ft:gpt-4o-mini:acemeco:suffix:abc123") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", modelDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.models.ModelDeleteParams; import com.openai.models.models.ModelDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ModelDeleted modelDeleted = client.models().delete("ft:gpt-4o-mini:acemeco:suffix:abc123"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") model_deleted = openai.models.delete("ft:gpt-4o-mini:acemeco:suffix:abc123") puts(model_deleted) description: Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. /moderations: post: operationId: createModeration tags: - Moderations summary: Create moderation requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateModerationRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/CreateModerationResponse' x-oaiMeta: name: Create moderation group: moderations returns: A [moderation](https://platform.openai.com/docs/api-reference/moderations/object) object. examples: - title: Single string request: curl: | curl https://api.openai.com/v1/moderations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "input": "I want to kill them." }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) moderation = client.moderations.create( input="I want to kill them.", ) print(moderation.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const moderation = await client.moderations.create({ input: 'I want to kill them.' }); console.log(moderation.id); csharp: | using System; using System.ClientModel; using OpenAI.Moderations; ModerationClient client = new( model: "omni-moderation-latest", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); ClientResult moderation = client.ClassifyText("I want to kill them."); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{ Input: openai.ModerationNewParamsInputUnion{ OfString: openai.String("I want to kill them."), }, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", moderation.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.moderations.ModerationCreateParams; import com.openai.models.moderations.ModerationCreateResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ModerationCreateParams params = ModerationCreateParams.builder() .input("I want to kill them.") .build(); ModerationCreateResponse moderation = client.moderations().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") moderation = openai.moderations.create(input: "I want to kill them.") puts(moderation) response: | { "id": "modr-AB8CjOTu2jiq12hp1AQPfeqFWaORR", "model": "text-moderation-007", "results": [ { "flagged": true, "categories": { "sexual": false, "hate": false, "harassment": true, "self-harm": false, "sexual/minors": false, "hate/threatening": false, "violence/graphic": false, "self-harm/intent": false, "self-harm/instructions": false, "harassment/threatening": true, "violence": true }, "category_scores": { "sexual": 0.000011726012417057063, "hate": 0.22706663608551025, "harassment": 0.5215635299682617, "self-harm": 2.227119921371923e-6, "sexual/minors": 7.107352217872176e-8, "hate/threatening": 0.023547329008579254, "violence/graphic": 0.00003391829886822961, "self-harm/intent": 1.646940972932498e-6, "self-harm/instructions": 1.1198755256458526e-9, "harassment/threatening": 0.5694745779037476, "violence": 0.9971134662628174 } } ] } - title: Image and text request: curl: | curl https://api.openai.com/v1/moderations \ -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "omni-moderation-latest", "input": [ { "type": "text", "text": "...text to classify goes here..." }, { "type": "image_url", "image_url": { "url": "https://example.com/image.png" } } ] }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) moderation = client.moderations.create( input="I want to kill them.", ) print(moderation.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const moderation = await client.moderations.create({ input: 'I want to kill them.' }); console.log(moderation.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{ Input: openai.ModerationNewParamsInputUnion{ OfString: openai.String("I want to kill them."), }, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", moderation.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.moderations.ModerationCreateParams; import com.openai.models.moderations.ModerationCreateResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ModerationCreateParams params = ModerationCreateParams.builder() .input("I want to kill them.") .build(); ModerationCreateResponse moderation = client.moderations().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") moderation = openai.moderations.create(input: "I want to kill them.") puts(moderation) response: | { "id": "modr-0d9740456c391e43c445bf0f010940c7", "model": "omni-moderation-latest", "results": [ { "flagged": true, "categories": { "harassment": true, "harassment/threatening": true, "sexual": false, "hate": false, "hate/threatening": false, "illicit": false, "illicit/violent": false, "self-harm/intent": false, "self-harm/instructions": false, "self-harm": false, "sexual/minors": false, "violence": true, "violence/graphic": true }, "category_scores": { "harassment": 0.8189693396524255, "harassment/threatening": 0.804985420696006, "sexual": 1.573112165348997e-6, "hate": 0.007562942636942845, "hate/threatening": 0.004208854591835476, "illicit": 0.030535955153511665, "illicit/violent": 0.008925306722380033, "self-harm/intent": 0.00023023930975076432, "self-harm/instructions": 0.0002293869201073356, "self-harm": 0.012598046106750154, "sexual/minors": 2.212566909570261e-8, "violence": 0.9999992735124786, "violence/graphic": 0.843064871157054 }, "category_applied_input_types": { "harassment": [ "text" ], "harassment/threatening": [ "text" ], "sexual": [ "text", "image" ], "hate": [ "text" ], "hate/threatening": [ "text" ], "illicit": [ "text" ], "illicit/violent": [ "text" ], "self-harm/intent": [ "text", "image" ], "self-harm/instructions": [ "text", "image" ], "self-harm": [ "text", "image" ], "sexual/minors": [ "text" ], "violence": [ "text", "image" ], "violence/graphic": [ "text", "image" ] } } ] } description: | Classifies if text and/or image inputs are potentially harmful. Learn more in the [moderation guide](https://platform.openai.com/docs/guides/moderation). /organization/admin_api_keys: get: summary: List all organization and project API keys. operationId: admin-api-keys-list description: List organization API keys parameters: - in: query name: after required: false schema: type: string nullable: true description: Return keys with IDs that come after this ID in the pagination order. - in: query name: order required: false schema: type: string enum: - asc - desc default: asc description: Order results by creation time, ascending or descending. - in: query name: limit required: false schema: type: integer default: 20 description: Maximum number of keys to return. responses: '200': description: A list of organization API keys. content: application/json: schema: $ref: '#/components/schemas/ApiKeyList' x-oaiMeta: name: List all organization and project API keys. group: administration returns: A list of admin and project API key objects. examples: response: | { "object": "list", "data": [ { "object": "organization.admin_api_key", "id": "key_abc", "name": "Main Admin Key", "redacted_value": "sk-admin...def", "created_at": 1711471533, "last_used_at": 1711471534, "owner": { "type": "service_account", "object": "organization.service_account", "id": "sa_456", "name": "My Service Account", "created_at": 1711471533, "role": "member" } } ], "first_id": "key_abc", "last_id": "key_abc", "has_more": false } request: curl: | curl https://api.openai.com/v1/organization/admin_api_keys?after=key_abc&limit=20 \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" post: summary: Create admin API key operationId: admin-api-keys-create description: Create an organization admin API key requestBody: required: true content: application/json: schema: type: object required: - name properties: name: type: string example: New Admin Key responses: '200': description: The newly created admin API key. content: application/json: schema: $ref: '#/components/schemas/AdminApiKey' x-oaiMeta: name: Create admin API key group: administration returns: >- The created [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) object. examples: response: | { "object": "organization.admin_api_key", "id": "key_xyz", "name": "New Admin Key", "redacted_value": "sk-admin...xyz", "created_at": 1711471533, "last_used_at": 1711471534, "owner": { "type": "user", "object": "organization.user", "id": "user_123", "name": "John Doe", "created_at": 1711471533, "role": "owner" }, "value": "sk-admin-1234abcd" } request: curl: | curl -X POST https://api.openai.com/v1/organization/admin_api_keys \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "New Admin Key" }' /organization/admin_api_keys/{key_id}: get: summary: Retrieve admin API key operationId: admin-api-keys-get description: Retrieve a single organization API key parameters: - in: path name: key_id required: true schema: type: string description: The ID of the API key. responses: '200': description: Details of the requested API key. content: application/json: schema: $ref: '#/components/schemas/AdminApiKey' x-oaiMeta: name: Retrieve admin API key group: administration returns: >- The requested [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) object. examples: response: | { "object": "organization.admin_api_key", "id": "key_abc", "name": "Main Admin Key", "redacted_value": "sk-admin...xyz", "created_at": 1711471533, "last_used_at": 1711471534, "owner": { "type": "user", "object": "organization.user", "id": "user_123", "name": "John Doe", "created_at": 1711471533, "role": "owner" } } request: curl: | curl https://api.openai.com/v1/organization/admin_api_keys/key_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" delete: summary: Delete admin API key operationId: admin-api-keys-delete description: Delete an organization admin API key parameters: - in: path name: key_id required: true schema: type: string description: The ID of the API key to be deleted. responses: '200': description: Confirmation that the API key was deleted. content: application/json: schema: type: object properties: id: type: string example: key_abc object: type: string example: organization.admin_api_key.deleted deleted: type: boolean example: true x-oaiMeta: name: Delete admin API key group: administration returns: A confirmation object indicating the key was deleted. examples: response: | { "id": "key_abc", "object": "organization.admin_api_key.deleted", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/organization/admin_api_keys/key_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" /organization/audit_logs: get: summary: List audit logs operationId: list-audit-logs tags: - Audit Logs parameters: - name: effective_at in: query description: Return only events whose `effective_at` (Unix seconds) is in this range. required: false schema: type: object properties: gt: type: integer description: Return only events whose `effective_at` (Unix seconds) is greater than this value. gte: type: integer description: >- Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value. lt: type: integer description: Return only events whose `effective_at` (Unix seconds) is less than this value. lte: type: integer description: Return only events whose `effective_at` (Unix seconds) is less than or equal to this value. - name: project_ids[] in: query description: Return only events for these projects. required: false schema: type: array items: type: string - name: event_types[] in: query description: >- Return only events with a `type` in one of these values. For example, `project.created`. For all options, see the documentation for the [audit log object](https://platform.openai.com/docs/api-reference/audit-logs/object). required: false schema: type: array items: $ref: '#/components/schemas/AuditLogEventType' - name: actor_ids[] in: query description: >- Return only events performed by these actors. Can be a user ID, a service account ID, or an api key tracking ID. required: false schema: type: array items: type: string - name: actor_emails[] in: query description: Return only events performed by users with these emails. required: false schema: type: array items: type: string - name: resource_ids[] in: query description: Return only events performed on these targets. For example, a project ID updated. required: false schema: type: array items: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string responses: '200': description: Audit logs listed successfully. content: application/json: schema: $ref: '#/components/schemas/ListAuditLogsResponse' x-oaiMeta: name: List audit logs group: audit-logs returns: >- A list of paginated [Audit Log](https://platform.openai.com/docs/api-reference/audit-logs/object) objects. examples: response: | { "object": "list", "data": [ { "id": "audit_log-xxx_yyyymmdd", "type": "project.archived", "effective_at": 1722461446, "actor": { "type": "api_key", "api_key": { "type": "user", "user": { "id": "user-xxx", "email": "user@example.com" } } }, "project.archived": { "id": "proj_abc" }, }, { "id": "audit_log-yyy__20240101", "type": "api_key.updated", "effective_at": 1720804190, "actor": { "type": "session", "session": { "user": { "id": "user-xxx", "email": "user@example.com" }, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", "ja3": "a497151ce4338a12c4418c44d375173e", "ja4": "q13d0313h3_55b375c5d22e_c7319ce65786", "ip_address_details": { "country": "US", "city": "San Francisco", "region": "California", "region_code": "CA", "asn": "1234", "latitude": "37.77490", "longitude": "-122.41940" } } }, "api_key.updated": { "id": "key_xxxx", "data": { "scopes": ["resource_2.operation_2"] } }, } ], "first_id": "audit_log-xxx__20240101", "last_id": "audit_log_yyy__20240101", "has_more": true } request: curl: | curl https://api.openai.com/v1/organization/audit_logs \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: List user actions and configuration changes within this organization. /organization/certificates: get: summary: List organization certificates operationId: listOrganizationCertificates tags: - Certificates parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc responses: '200': description: Certificates listed successfully. content: application/json: schema: $ref: '#/components/schemas/ListCertificatesResponse' x-oaiMeta: name: List organization certificates group: administration returns: A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects. examples: request: curl: | curl https://api.openai.com/v1/organization/certificates \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" response: | { "object": "list", "data": [ { "object": "organization.certificate", "id": "cert_abc", "name": "My Example Certificate", "active": true, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, ], "first_id": "cert_abc", "last_id": "cert_abc", "has_more": false } description: List uploaded certificates for this organization. post: summary: Upload certificate operationId: uploadCertificate tags: - Certificates requestBody: description: The certificate upload payload. required: true content: application/json: schema: $ref: '#/components/schemas/UploadCertificateRequest' responses: '200': description: Certificate uploaded successfully. content: application/json: schema: $ref: '#/components/schemas/Certificate' x-oaiMeta: name: Upload certificate group: administration returns: A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object. examples: request: curl: | curl -X POST https://api.openai.com/v1/organization/certificates \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "My Example Certificate", "certificate": "-----BEGIN CERTIFICATE-----\\nMIIDeT...\\n-----END CERTIFICATE-----" }' response: | { "object": "certificate", "id": "cert_abc", "name": "My Example Certificate", "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } } description: | Upload a certificate to the organization. This does **not** automatically activate the certificate. Organizations can upload up to 50 certificates. /organization/certificates/activate: post: summary: Activate certificates for organization operationId: activateOrganizationCertificates tags: - Certificates requestBody: description: The certificate activation payload. required: true content: application/json: schema: $ref: '#/components/schemas/ToggleCertificatesRequest' responses: '200': description: Certificates activated successfully. content: application/json: schema: $ref: '#/components/schemas/ListCertificatesResponse' x-oaiMeta: name: Activate certificates for organization group: administration returns: >- A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were activated. examples: request: curl: | curl https://api.openai.com/v1/organization/certificates/activate \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": ["cert_abc", "cert_def"] }' response: | { "object": "organization.certificate.activation", "data": [ { "object": "organization.certificate", "id": "cert_abc", "name": "My Example Certificate", "active": true, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, { "object": "organization.certificate", "id": "cert_def", "name": "My Example Certificate 2", "active": true, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, ], } description: | Activate certificates at the organization level. You can atomically and idempotently activate up to 10 certificates at a time. /organization/certificates/deactivate: post: summary: Deactivate certificates for organization operationId: deactivateOrganizationCertificates tags: - Certificates requestBody: description: The certificate deactivation payload. required: true content: application/json: schema: $ref: '#/components/schemas/ToggleCertificatesRequest' responses: '200': description: Certificates deactivated successfully. content: application/json: schema: $ref: '#/components/schemas/ListCertificatesResponse' x-oaiMeta: name: Deactivate certificates for organization group: administration returns: >- A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were deactivated. examples: request: curl: | curl https://api.openai.com/v1/organization/certificates/deactivate \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": ["cert_abc", "cert_def"] }' response: | { "object": "organization.certificate.deactivation", "data": [ { "object": "organization.certificate", "id": "cert_abc", "name": "My Example Certificate", "active": false, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, { "object": "organization.certificate", "id": "cert_def", "name": "My Example Certificate 2", "active": false, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, ], } description: | Deactivate certificates at the organization level. You can atomically and idempotently deactivate up to 10 certificates at a time. /organization/certificates/{certificate_id}: get: summary: Get certificate operationId: getCertificate tags: - Certificates parameters: - name: certificate_id in: path description: Unique ID of the certificate to retrieve. required: true schema: type: string - name: include in: query description: >- A list of additional fields to include in the response. Currently the only supported value is `content` to fetch the PEM content of the certificate. required: false schema: type: array items: type: string enum: - content responses: '200': description: Certificate retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/Certificate' x-oaiMeta: name: Get certificate group: administration returns: A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object. examples: request: curl: | curl "https://api.openai.com/v1/organization/certificates/cert_abc?include[]=content" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" response: | { "object": "certificate", "id": "cert_abc", "name": "My Example Certificate", "created_at": 1234567, "certificate_details": { "valid_at": 1234567, "expires_at": 12345678, "content": "-----BEGIN CERTIFICATE-----MIIDeT...-----END CERTIFICATE-----" } } description: | Get a certificate that has been uploaded to the organization. You can get a certificate regardless of whether it is active or not. post: summary: Modify certificate operationId: modifyCertificate tags: - Certificates requestBody: description: The certificate modification payload. required: true content: application/json: schema: $ref: '#/components/schemas/ModifyCertificateRequest' responses: '200': description: Certificate modified successfully. content: application/json: schema: $ref: '#/components/schemas/Certificate' x-oaiMeta: name: Modify certificate group: administration returns: >- The updated [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object. examples: request: curl: | curl -X POST https://api.openai.com/v1/organization/certificates/cert_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Renamed Certificate" }' response: | { "object": "certificate", "id": "cert_abc", "name": "Renamed Certificate", "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } } description: | Modify a certificate. Note that only the name can be modified. delete: summary: Delete certificate operationId: deleteCertificate tags: - Certificates responses: '200': description: Certificate deleted successfully. content: application/json: schema: $ref: '#/components/schemas/DeleteCertificateResponse' x-oaiMeta: name: Delete certificate group: administration returns: A confirmation object indicating the certificate was deleted. examples: request: curl: | curl -X DELETE https://api.openai.com/v1/organization/certificates/cert_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" response: | { "object": "certificate.deleted", "id": "cert_abc" } description: | Delete a certificate from the organization. The certificate must be inactive for the organization and all projects. /organization/costs: get: summary: Costs operationId: usage-costs tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: Width of each time bucket in response. Currently only `1d` is supported, default to `1d`. required: false schema: type: string enum: - 1d default: 1d - name: project_ids in: query description: Return only costs for these projects. required: false schema: type: array items: type: string - name: group_by in: query description: >- Group the costs by the specified fields. Support fields include `project_id`, `line_item` and any combination of them. required: false schema: type: array items: type: string enum: - project_id - line_item - name: limit in: query description: > A limit on the number of buckets to be returned. Limit can range between 1 and 180, and the default is 7. required: false schema: type: integer default: 7 - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Costs data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Costs group: usage-costs returns: >- A list of paginated, time bucketed [Costs](https://platform.openai.com/docs/api-reference/usage/costs_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.costs.result", "amount": { "value": 0.06, "currency": "usd" }, "line_item": null, "project_id": null } ] } ], "has_more": false, "next_page": null } request: curl: | curl "https://api.openai.com/v1/organization/costs?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get costs details for the organization. /organization/invites: get: summary: List invites operationId: list-invites tags: - Invites parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string responses: '200': description: Invites listed successfully. content: application/json: schema: $ref: '#/components/schemas/InviteListResponse' x-oaiMeta: name: List invites group: administration returns: A list of [Invite](https://platform.openai.com/docs/api-reference/invite/object) objects. examples: response: | { "object": "list", "data": [ { "object": "organization.invite", "id": "invite-abc", "email": "user@example.com", "role": "owner", "status": "accepted", "invited_at": 1711471533, "expires_at": 1711471533, "accepted_at": 1711471533 } ], "first_id": "invite-abc", "last_id": "invite-abc", "has_more": false } request: curl: | curl https://api.openai.com/v1/organization/invites?after=invite-abc&limit=20 \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Returns a list of invites in the organization. post: summary: Create invite operationId: inviteUser tags: - Invites requestBody: description: The invite request payload. required: true content: application/json: schema: $ref: '#/components/schemas/InviteRequest' responses: '200': description: User invited successfully. content: application/json: schema: $ref: '#/components/schemas/Invite' x-oaiMeta: name: Create invite group: administration returns: The created [Invite](https://platform.openai.com/docs/api-reference/invite/object) object. examples: response: | { "object": "organization.invite", "id": "invite-def", "email": "anotheruser@example.com", "role": "reader", "status": "pending", "invited_at": 1711471533, "expires_at": 1711471533, "accepted_at": null, "projects": [ { "id": "project-xyz", "role": "member" }, { "id": "project-abc", "role": "owner" } ] } request: curl: | curl -X POST https://api.openai.com/v1/organization/invites \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "email": "anotheruser@example.com", "role": "reader", "projects": [ { "id": "project-xyz", "role": "member" }, { "id": "project-abc", "role": "owner" } ] }' description: >- Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization. /organization/invites/{invite_id}: get: summary: Retrieve invite operationId: retrieve-invite tags: - Invites parameters: - in: path name: invite_id required: true schema: type: string description: The ID of the invite to retrieve. responses: '200': description: Invite retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/Invite' x-oaiMeta: name: Retrieve invite group: administration returns: >- The [Invite](https://platform.openai.com/docs/api-reference/invite/object) object matching the specified ID. examples: response: | { "object": "organization.invite", "id": "invite-abc", "email": "user@example.com", "role": "owner", "status": "accepted", "invited_at": 1711471533, "expires_at": 1711471533, "accepted_at": 1711471533 } request: curl: | curl https://api.openai.com/v1/organization/invites/invite-abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Retrieves an invite. delete: summary: Delete invite operationId: delete-invite tags: - Invites parameters: - in: path name: invite_id required: true schema: type: string description: The ID of the invite to delete. responses: '200': description: Invite deleted successfully. content: application/json: schema: $ref: '#/components/schemas/InviteDeleteResponse' x-oaiMeta: name: Delete invite group: administration returns: Confirmation that the invite has been deleted examples: response: | { "object": "organization.invite.deleted", "id": "invite-abc", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/organization/invites/invite-abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Delete an invite. If the invite has already been accepted, it cannot be deleted. /organization/projects: get: summary: List projects operationId: list-projects tags: - Projects parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string - name: include_archived in: query schema: type: boolean default: false description: >- If `true` returns all projects including those that have been `archived`. Archived projects are not included by default. responses: '200': description: Projects listed successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectListResponse' x-oaiMeta: name: List projects group: administration returns: A list of [Project](https://platform.openai.com/docs/api-reference/projects/object) objects. examples: response: | { "object": "list", "data": [ { "id": "proj_abc", "object": "organization.project", "name": "Project example", "created_at": 1711471533, "archived_at": null, "status": "active" } ], "first_id": "proj-abc", "last_id": "proj-xyz", "has_more": false } request: curl: > curl https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Returns a list of projects. post: summary: Create project operationId: create-project tags: - Projects requestBody: description: The project create request payload. required: true content: application/json: schema: $ref: '#/components/schemas/ProjectCreateRequest' responses: '200': description: Project created successfully. content: application/json: schema: $ref: '#/components/schemas/Project' x-oaiMeta: name: Create project group: administration returns: The created [Project](https://platform.openai.com/docs/api-reference/projects/object) object. examples: response: | { "id": "proj_abc", "object": "organization.project", "name": "Project ABC", "created_at": 1711471533, "archived_at": null, "status": "active" } request: curl: | curl -X POST https://api.openai.com/v1/organization/projects \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Project ABC" }' description: Create a new project in the organization. Projects can be created and archived, but cannot be deleted. /organization/projects/{project_id}: get: summary: Retrieve project operationId: retrieve-project tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string responses: '200': description: Project retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/Project' x-oaiMeta: name: Retrieve project group: administration description: Retrieve a project. returns: >- The [Project](https://platform.openai.com/docs/api-reference/projects/object) object matching the specified ID. examples: response: | { "id": "proj_abc", "object": "organization.project", "name": "Project example", "created_at": 1711471533, "archived_at": null, "status": "active" } request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Retrieves a project. post: summary: Modify project operationId: modify-project tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string requestBody: description: The project update request payload. required: true content: application/json: schema: $ref: '#/components/schemas/ProjectUpdateRequest' responses: '200': description: Project updated successfully. content: application/json: schema: $ref: '#/components/schemas/Project' '400': description: Error response when updating the default project. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: Modify project group: administration returns: The updated [Project](https://platform.openai.com/docs/api-reference/projects/object) object. examples: response: '' request: curl: | curl -X POST https://api.openai.com/v1/organization/projects/proj_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Project DEF" }' description: Modifies a project in the organization. /organization/projects/{project_id}/api_keys: get: summary: List project API keys operationId: list-project-api-keys tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string responses: '200': description: Project API keys listed successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectApiKeyListResponse' x-oaiMeta: name: List project API keys group: administration returns: >- A list of [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) objects. examples: response: | { "object": "list", "data": [ { "object": "organization.project.api_key", "redacted_value": "sk-abc...def", "name": "My API Key", "created_at": 1711471533, "last_used_at": 1711471534, "id": "key_abc", "owner": { "type": "user", "user": { "object": "organization.project.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } } } ], "first_id": "key_abc", "last_id": "key_xyz", "has_more": false } request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys?after=key_abc&limit=20 \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Returns a list of API keys in the project. /organization/projects/{project_id}/api_keys/{key_id}: get: summary: Retrieve project API key operationId: retrieve-project-api-key tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: key_id in: path description: The ID of the API key. required: true schema: type: string responses: '200': description: Project API key retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectApiKey' x-oaiMeta: name: Retrieve project API key group: administration returns: >- The [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) object matching the specified ID. examples: response: | { "object": "organization.project.api_key", "redacted_value": "sk-abc...def", "name": "My API Key", "created_at": 1711471533, "last_used_at": 1711471534, "id": "key_abc", "owner": { "type": "user", "user": { "object": "organization.project.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } } } request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Retrieves an API key in the project. delete: summary: Delete project API key operationId: delete-project-api-key tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: key_id in: path description: The ID of the API key. required: true schema: type: string responses: '200': description: Project API key deleted successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectApiKeyDeleteResponse' '400': description: Error response for various conditions. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: Delete project API key group: administration returns: Confirmation of the key's deletion or an error if the key belonged to a service account examples: response: | { "object": "organization.project.api_key.deleted", "id": "key_abc", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Deletes an API key from the project. /organization/projects/{project_id}/archive: post: summary: Archive project operationId: archive-project tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string responses: '200': description: Project archived successfully. content: application/json: schema: $ref: '#/components/schemas/Project' x-oaiMeta: name: Archive project group: administration returns: The archived [Project](https://platform.openai.com/docs/api-reference/projects/object) object. examples: response: | { "id": "proj_abc", "object": "organization.project", "name": "Project DEF", "created_at": 1711471533, "archived_at": 1711471533, "status": "archived" } request: curl: | curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/archive \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Archives a project in the organization. Archived projects cannot be used or updated. /organization/projects/{project_id}/certificates: get: summary: List project certificates operationId: listProjectCertificates tags: - Certificates parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc responses: '200': description: Certificates listed successfully. content: application/json: schema: $ref: '#/components/schemas/ListCertificatesResponse' x-oaiMeta: name: List project certificates group: administration returns: A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects. examples: request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/certificates \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" response: | { "object": "list", "data": [ { "object": "organization.project.certificate", "id": "cert_abc", "name": "My Example Certificate", "active": true, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, ], "first_id": "cert_abc", "last_id": "cert_abc", "has_more": false } description: List certificates for this project. /organization/projects/{project_id}/certificates/activate: post: summary: Activate certificates for project operationId: activateProjectCertificates tags: - Certificates parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string requestBody: description: The certificate activation payload. required: true content: application/json: schema: $ref: '#/components/schemas/ToggleCertificatesRequest' responses: '200': description: Certificates activated successfully. content: application/json: schema: $ref: '#/components/schemas/ListCertificatesResponse' x-oaiMeta: name: Activate certificates for project group: administration returns: >- A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were activated. examples: request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/activate \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": ["cert_abc", "cert_def"] }' response: | { "object": "organization.project.certificate.activation", "data": [ { "object": "organization.project.certificate", "id": "cert_abc", "name": "My Example Certificate", "active": true, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, { "object": "organization.project.certificate", "id": "cert_def", "name": "My Example Certificate 2", "active": true, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, ], } description: | Activate certificates at the project level. You can atomically and idempotently activate up to 10 certificates at a time. /organization/projects/{project_id}/certificates/deactivate: post: summary: Deactivate certificates for project operationId: deactivateProjectCertificates tags: - Certificates parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string requestBody: description: The certificate deactivation payload. required: true content: application/json: schema: $ref: '#/components/schemas/ToggleCertificatesRequest' responses: '200': description: Certificates deactivated successfully. content: application/json: schema: $ref: '#/components/schemas/ListCertificatesResponse' x-oaiMeta: name: Deactivate certificates for project group: administration returns: >- A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were deactivated. examples: request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/deactivate \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": ["cert_abc", "cert_def"] }' response: | { "object": "organization.project.certificate.deactivation", "data": [ { "object": "organization.project.certificate", "id": "cert_abc", "name": "My Example Certificate", "active": false, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, { "object": "organization.project.certificate", "id": "cert_def", "name": "My Example Certificate 2", "active": false, "created_at": 1234567, "certificate_details": { "valid_at": 12345667, "expires_at": 12345678 } }, ], } description: | Deactivate certificates at the project level. You can atomically and idempotently deactivate up to 10 certificates at a time. /organization/projects/{project_id}/rate_limits: get: summary: List project rate limits operationId: list-project-rate-limits tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: limit in: query description: | A limit on the number of objects to be returned. The default is 100. required: false schema: type: integer default: 100 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, beginning with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. required: false schema: type: string responses: '200': description: Project rate limits listed successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectRateLimitListResponse' x-oaiMeta: name: List project rate limits group: administration returns: >- A list of [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) objects. examples: response: | { "object": "list", "data": [ { "object": "project.rate_limit", "id": "rl-ada", "model": "ada", "max_requests_per_1_minute": 600, "max_tokens_per_1_minute": 150000, "max_images_per_1_minute": 10 } ], "first_id": "rl-ada", "last_id": "rl-ada", "has_more": false } request: curl: > curl https://api.openai.com/v1/organization/projects/proj_abc/rate_limits?after=rl_xxx&limit=20 \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" error_response: | { "code": 404, "message": "The project {project_id} was not found" } description: Returns the rate limits per model for a project. /organization/projects/{project_id}/rate_limits/{rate_limit_id}: post: summary: Modify project rate limit operationId: update-project-rate-limits tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: rate_limit_id in: path description: The ID of the rate limit. required: true schema: type: string requestBody: description: The project rate limit update request payload. required: true content: application/json: schema: $ref: '#/components/schemas/ProjectRateLimitUpdateRequest' responses: '200': description: Project rate limit updated successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectRateLimit' '400': description: Error response for various conditions. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: Modify project rate limit group: administration returns: >- The updated [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) object. examples: response: | { "object": "project.rate_limit", "id": "rl-ada", "model": "ada", "max_requests_per_1_minute": 600, "max_tokens_per_1_minute": 150000, "max_images_per_1_minute": 10 } request: curl: | curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/rate_limits/rl_xxx \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "max_requests_per_1_minute": 500 }' error_response: | { "code": 404, "message": "The project {project_id} was not found" } description: Updates a project rate limit. /organization/projects/{project_id}/service_accounts: get: summary: List project service accounts operationId: list-project-service-accounts tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string responses: '200': description: Project service accounts listed successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectServiceAccountListResponse' '400': description: Error response when project is archived. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: List project service accounts group: administration returns: >- A list of [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) objects. examples: response: | { "object": "list", "data": [ { "object": "organization.project.service_account", "id": "svc_acct_abc", "name": "Service Account", "role": "owner", "created_at": 1711471533 } ], "first_id": "svc_acct_abc", "last_id": "svc_acct_xyz", "has_more": false } request: curl: > curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts?after=custom_id&limit=20 \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Returns a list of service accounts in the project. post: summary: Create project service account operationId: create-project-service-account tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string requestBody: description: The project service account create request payload. required: true content: application/json: schema: $ref: '#/components/schemas/ProjectServiceAccountCreateRequest' responses: '200': description: Project service account created successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectServiceAccountCreateResponse' '400': description: Error response when project is archived. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: Create project service account group: administration returns: >- The created [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) object. examples: response: | { "object": "organization.project.service_account", "id": "svc_acct_abc", "name": "Production App", "role": "member", "created_at": 1711471533, "api_key": { "object": "organization.project.service_account.api_key", "value": "sk-abcdefghijklmnop123", "name": "Secret Key", "created_at": 1711471533, "id": "key_abc" } } request: curl: | curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/service_accounts \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Production App" }' description: >- Creates a new service account in the project. This also returns an unredacted API key for the service account. /organization/projects/{project_id}/service_accounts/{service_account_id}: get: summary: Retrieve project service account operationId: retrieve-project-service-account tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: service_account_id in: path description: The ID of the service account. required: true schema: type: string responses: '200': description: Project service account retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectServiceAccount' x-oaiMeta: name: Retrieve project service account group: administration returns: >- The [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) object matching the specified ID. examples: response: | { "object": "organization.project.service_account", "id": "svc_acct_abc", "name": "Service Account", "role": "owner", "created_at": 1711471533 } request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Retrieves a service account in the project. delete: summary: Delete project service account operationId: delete-project-service-account tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: service_account_id in: path description: The ID of the service account. required: true schema: type: string responses: '200': description: Project service account deleted successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectServiceAccountDeleteResponse' x-oaiMeta: name: Delete project service account group: administration returns: >- Confirmation of service account being deleted, or an error in case of an archived project, which has no service accounts examples: response: | { "object": "organization.project.service_account.deleted", "id": "svc_acct_abc", "deleted": true } request: curl: > curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Deletes a service account from the project. /organization/projects/{project_id}/users: get: summary: List project users operationId: list-project-users tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string responses: '200': description: Project users listed successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectUserListResponse' '400': description: Error response when project is archived. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: List project users group: administration returns: >- A list of [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) objects. examples: response: | { "object": "list", "data": [ { "object": "organization.project.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } ], "first_id": "user-abc", "last_id": "user-xyz", "has_more": false } request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/users?after=user_abc&limit=20 \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Returns a list of users in the project. post: summary: Create project user operationId: create-project-user parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string tags: - Projects requestBody: description: The project user create request payload. required: true content: application/json: schema: $ref: '#/components/schemas/ProjectUserCreateRequest' responses: '200': description: User added to project successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectUser' '400': description: Error response for various conditions. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: Create project user group: administration returns: >- The created [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object. examples: response: | { "object": "organization.project.user", "id": "user_abc", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } request: curl: | curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "user_abc", "role": "member" }' description: >- Adds a user to the project. Users must already be members of the organization to be added to a project. /organization/projects/{project_id}/users/{user_id}: get: summary: Retrieve project user operationId: retrieve-project-user tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: user_id in: path description: The ID of the user. required: true schema: type: string responses: '200': description: Project user retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectUser' x-oaiMeta: name: Retrieve project user group: administration returns: >- The [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object matching the specified ID. examples: response: | { "object": "organization.project.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } request: curl: | curl https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Retrieves a user in the project. post: summary: Modify project user operationId: modify-project-user tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: user_id in: path description: The ID of the user. required: true schema: type: string requestBody: description: The project user update request payload. required: true content: application/json: schema: $ref: '#/components/schemas/ProjectUserUpdateRequest' responses: '200': description: Project user's role updated successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectUser' '400': description: Error response for various conditions. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: Modify project user group: administration returns: >- The updated [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object. examples: response: | { "object": "organization.project.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } request: curl: | curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "role": "owner" }' description: Modifies a user's role in the project. delete: summary: Delete project user operationId: delete-project-user tags: - Projects parameters: - name: project_id in: path description: The ID of the project. required: true schema: type: string - name: user_id in: path description: The ID of the user. required: true schema: type: string responses: '200': description: Project user deleted successfully. content: application/json: schema: $ref: '#/components/schemas/ProjectUserDeleteResponse' '400': description: Error response for various conditions. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: name: Delete project user group: administration returns: >- Confirmation that project has been deleted or an error in case of an archived project, which has no users examples: response: | { "object": "organization.project.user.deleted", "id": "user_abc", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Deletes a user from the project. /organization/usage/audio_speeches: get: summary: Audio speeches operationId: usage-audio-speeches tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: user_ids in: query description: Return only usage for these users. required: false schema: type: array items: type: string - name: api_key_ids in: query description: Return only usage for these API keys. required: false schema: type: array items: type: string - name: models in: query description: Return only usage for these models. required: false schema: type: array items: type: string - name: group_by in: query description: >- Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. required: false schema: type: array items: type: string enum: - project_id - user_id - api_key_id - model - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Audio speeches group: usage-audio-speeches returns: >- A list of paginated, time bucketed [Audio speeches usage](https://platform.openai.com/docs/api-reference/usage/audio_speeches_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.audio_speeches.result", "characters": 45, "num_model_requests": 1, "project_id": null, "user_id": null, "api_key_id": null, "model": null } ] } ], "has_more": false, "next_page": null } request: curl: > curl "https://api.openai.com/v1/organization/usage/audio_speeches?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get audio speeches usage details for the organization. /organization/usage/audio_transcriptions: get: summary: Audio transcriptions operationId: usage-audio-transcriptions tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: user_ids in: query description: Return only usage for these users. required: false schema: type: array items: type: string - name: api_key_ids in: query description: Return only usage for these API keys. required: false schema: type: array items: type: string - name: models in: query description: Return only usage for these models. required: false schema: type: array items: type: string - name: group_by in: query description: >- Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. required: false schema: type: array items: type: string enum: - project_id - user_id - api_key_id - model - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Audio transcriptions group: usage-audio-transcriptions returns: >- A list of paginated, time bucketed [Audio transcriptions usage](https://platform.openai.com/docs/api-reference/usage/audio_transcriptions_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.audio_transcriptions.result", "seconds": 20, "num_model_requests": 1, "project_id": null, "user_id": null, "api_key_id": null, "model": null } ] } ], "has_more": false, "next_page": null } request: curl: > curl "https://api.openai.com/v1/organization/usage/audio_transcriptions?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get audio transcriptions usage details for the organization. /organization/usage/code_interpreter_sessions: get: summary: Code interpreter sessions operationId: usage-code-interpreter-sessions tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: group_by in: query description: Group the usage data by the specified fields. Support fields include `project_id`. required: false schema: type: array items: type: string enum: - project_id - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Code interpreter sessions group: usage-code-interpreter-sessions returns: >- A list of paginated, time bucketed [Code interpreter sessions usage](https://platform.openai.com/docs/api-reference/usage/code_interpreter_sessions_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.code_interpreter_sessions.result", "num_sessions": 1, "project_id": null } ] } ], "has_more": false, "next_page": null } request: curl: > curl "https://api.openai.com/v1/organization/usage/code_interpreter_sessions?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get code interpreter sessions usage details for the organization. /organization/usage/completions: get: summary: Completions operationId: usage-completions tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: user_ids in: query description: Return only usage for these users. required: false schema: type: array items: type: string - name: api_key_ids in: query description: Return only usage for these API keys. required: false schema: type: array items: type: string - name: models in: query description: Return only usage for these models. required: false schema: type: array items: type: string - name: batch in: query description: > If `true`, return batch jobs only. If `false`, return non-batch jobs only. By default, return both. required: false schema: type: boolean - name: group_by in: query description: >- Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch` or any combination of them. required: false schema: type: array items: type: string enum: - project_id - user_id - api_key_id - model - batch - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Completions group: usage-completions returns: >- A list of paginated, time bucketed [Completions usage](https://platform.openai.com/docs/api-reference/usage/completions_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.completions.result", "input_tokens": 1000, "output_tokens": 500, "input_cached_tokens": 800, "input_audio_tokens": 0, "output_audio_tokens": 0, "num_model_requests": 5, "project_id": null, "user_id": null, "api_key_id": null, "model": null, "batch": null } ] } ], "has_more": true, "next_page": "page_AAAAAGdGxdEiJdKOAAAAAGcqsYA=" } request: curl: | curl "https://api.openai.com/v1/organization/usage/completions?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get completions usage details for the organization. /organization/usage/embeddings: get: summary: Embeddings operationId: usage-embeddings tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: user_ids in: query description: Return only usage for these users. required: false schema: type: array items: type: string - name: api_key_ids in: query description: Return only usage for these API keys. required: false schema: type: array items: type: string - name: models in: query description: Return only usage for these models. required: false schema: type: array items: type: string - name: group_by in: query description: >- Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. required: false schema: type: array items: type: string enum: - project_id - user_id - api_key_id - model - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Embeddings group: usage-embeddings returns: >- A list of paginated, time bucketed [Embeddings usage](https://platform.openai.com/docs/api-reference/usage/embeddings_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.embeddings.result", "input_tokens": 16, "num_model_requests": 2, "project_id": null, "user_id": null, "api_key_id": null, "model": null } ] } ], "has_more": false, "next_page": null } request: curl: | curl "https://api.openai.com/v1/organization/usage/embeddings?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get embeddings usage details for the organization. /organization/usage/images: get: summary: Images operationId: usage-images tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: sources in: query description: >- Return only usages for these sources. Possible values are `image.generation`, `image.edit`, `image.variation` or any combination of them. required: false schema: type: array items: type: string enum: - image.generation - image.edit - image.variation - name: sizes in: query description: >- Return only usages for these image sizes. Possible values are `256x256`, `512x512`, `1024x1024`, `1792x1792`, `1024x1792` or any combination of them. required: false schema: type: array items: type: string enum: - 256x256 - 512x512 - 1024x1024 - 1792x1792 - 1024x1792 - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: user_ids in: query description: Return only usage for these users. required: false schema: type: array items: type: string - name: api_key_ids in: query description: Return only usage for these API keys. required: false schema: type: array items: type: string - name: models in: query description: Return only usage for these models. required: false schema: type: array items: type: string - name: group_by in: query description: >- Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `size`, `source` or any combination of them. required: false schema: type: array items: type: string enum: - project_id - user_id - api_key_id - model - size - source - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Images group: usage-images returns: >- A list of paginated, time bucketed [Images usage](https://platform.openai.com/docs/api-reference/usage/images_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.images.result", "images": 2, "num_model_requests": 2, "size": null, "source": null, "project_id": null, "user_id": null, "api_key_id": null, "model": null } ] } ], "has_more": false, "next_page": null } request: curl: | curl "https://api.openai.com/v1/organization/usage/images?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get images usage details for the organization. /organization/usage/moderations: get: summary: Moderations operationId: usage-moderations tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: user_ids in: query description: Return only usage for these users. required: false schema: type: array items: type: string - name: api_key_ids in: query description: Return only usage for these API keys. required: false schema: type: array items: type: string - name: models in: query description: Return only usage for these models. required: false schema: type: array items: type: string - name: group_by in: query description: >- Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them. required: false schema: type: array items: type: string enum: - project_id - user_id - api_key_id - model - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Moderations group: usage-moderations returns: >- A list of paginated, time bucketed [Moderations usage](https://platform.openai.com/docs/api-reference/usage/moderations_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.moderations.result", "input_tokens": 16, "num_model_requests": 2, "project_id": null, "user_id": null, "api_key_id": null, "model": null } ] } ], "has_more": false, "next_page": null } request: curl: | curl "https://api.openai.com/v1/organization/usage/moderations?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get moderations usage details for the organization. /organization/usage/vector_stores: get: summary: Vector stores operationId: usage-vector-stores tags: - Usage parameters: - name: start_time in: query description: Start time (Unix seconds) of the query time range, inclusive. required: true schema: type: integer - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer - name: bucket_width in: query description: >- Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`. required: false schema: type: string enum: - 1m - 1h - 1d default: 1d - name: project_ids in: query description: Return only usage for these projects. required: false schema: type: array items: type: string - name: group_by in: query description: Group the usage data by the specified fields. Support fields include `project_id`. required: false schema: type: array items: type: string enum: - project_id - name: limit in: query description: | Specifies the number of buckets to return. - `bucket_width=1d`: default: 7, max: 31 - `bucket_width=1h`: default: 24, max: 168 - `bucket_width=1m`: default: 60, max: 1440 required: false schema: type: integer - name: page in: query description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. schema: type: string responses: '200': description: Usage data retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/UsageResponse' x-oaiMeta: name: Vector stores group: usage-vector-stores returns: >- A list of paginated, time bucketed [Vector stores usage](https://platform.openai.com/docs/api-reference/usage/vector_stores_object) objects. examples: response: | { "object": "page", "data": [ { "object": "bucket", "start_time": 1730419200, "end_time": 1730505600, "results": [ { "object": "organization.usage.vector_stores.result", "usage_bytes": 1024, "project_id": null } ] } ], "has_more": false, "next_page": null } request: curl: > curl "https://api.openai.com/v1/organization/usage/vector_stores?start_time=1730419200&limit=1" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Get vector stores usage details for the organization. /organization/users: get: summary: List users operationId: list-users tags: - Users parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. required: false schema: type: string - name: emails in: query description: Filter by the email address of users. required: false schema: type: array items: type: string responses: '200': description: Users listed successfully. content: application/json: schema: $ref: '#/components/schemas/UserListResponse' x-oaiMeta: name: List users group: administration returns: A list of [User](https://platform.openai.com/docs/api-reference/users/object) objects. examples: response: | { "object": "list", "data": [ { "object": "organization.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } ], "first_id": "user-abc", "last_id": "user-xyz", "has_more": false } request: curl: | curl https://api.openai.com/v1/organization/users?after=user_abc&limit=20 \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Lists all of the users in the organization. /organization/users/{user_id}: get: summary: Retrieve user operationId: retrieve-user tags: - Users parameters: - name: user_id in: path description: The ID of the user. required: true schema: type: string responses: '200': description: User retrieved successfully. content: application/json: schema: $ref: '#/components/schemas/User' x-oaiMeta: name: Retrieve user group: administration returns: >- The [User](https://platform.openai.com/docs/api-reference/users/object) object matching the specified ID. examples: response: | { "object": "organization.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } request: curl: | curl https://api.openai.com/v1/organization/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Retrieves a user by their identifier. post: summary: Modify user operationId: modify-user tags: - Users parameters: - name: user_id in: path description: The ID of the user. required: true schema: type: string requestBody: description: The new user role to modify. This must be one of `owner` or `member`. required: true content: application/json: schema: $ref: '#/components/schemas/UserRoleUpdateRequest' responses: '200': description: User role updated successfully. content: application/json: schema: $ref: '#/components/schemas/User' x-oaiMeta: name: Modify user group: administration returns: The updated [User](https://platform.openai.com/docs/api-reference/users/object) object. examples: response: | { "object": "organization.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } request: curl: | curl -X POST https://api.openai.com/v1/organization/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "role": "owner" }' description: Modifies a user's role in the organization. delete: summary: Delete user operationId: delete-user tags: - Users parameters: - name: user_id in: path description: The ID of the user. required: true schema: type: string responses: '200': description: User deleted successfully. content: application/json: schema: $ref: '#/components/schemas/UserDeleteResponse' x-oaiMeta: name: Delete user group: administration returns: Confirmation of the deleted user examples: response: | { "object": "organization.user.deleted", "id": "user_abc", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/organization/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" description: Deletes a user from the organization. /realtime/sessions: post: summary: Create session operationId: create-realtime-session tags: - Realtime requestBody: description: Create an ephemeral API key with the given session configuration. required: true content: application/json: schema: $ref: '#/components/schemas/RealtimeSessionCreateRequest' responses: '200': description: Session created successfully. content: application/json: schema: $ref: '#/components/schemas/RealtimeSessionCreateResponse' x-oaiMeta: name: Create session group: realtime returns: The created Realtime session object, plus an ephemeral key examples: response: | { "id": "sess_001", "object": "realtime.session", "model": "gpt-4o-realtime-preview", "modalities": ["audio", "text"], "instructions": "You are a friendly assistant.", "voice": "alloy", "input_audio_format": "pcm16", "output_audio_format": "pcm16", "input_audio_transcription": { "model": "whisper-1" }, "turn_detection": null, "tools": [], "tool_choice": "none", "temperature": 0.7, "max_response_output_tokens": 200, "speed": 1.1, "tracing": "auto", "client_secret": { "value": "ek_abc123", "expires_at": 1234567890 } } request: curl: | curl -X POST https://api.openai.com/v1/realtime/sessions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-realtime-preview", "modalities": ["audio", "text"], "instructions": "You are a friendly assistant." }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const session = await client.beta.realtime.sessions.create(); console.log(session.client_secret); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) session = client.beta.realtime.sessions.create() print(session.client_secret) java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.realtime.sessions.SessionCreateParams; import com.openai.models.beta.realtime.sessions.SessionCreateResponse; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); SessionCreateResponse session = client.beta().realtime().sessions().create(); } } description: | Create an ephemeral API token for use in client-side applications with the Realtime API. Can be configured with the same session parameters as the `session.update` client event. It responds with a session object, plus a `client_secret` key which contains a usable ephemeral API token that can be used to authenticate browser clients for the Realtime API. /realtime/transcription_sessions: post: summary: Create transcription session operationId: create-realtime-transcription-session tags: - Realtime requestBody: description: Create an ephemeral API key with the given session configuration. required: true content: application/json: schema: $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' responses: '200': description: Session created successfully. content: application/json: schema: $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' x-oaiMeta: name: Create transcription session group: realtime returns: >- The created [Realtime transcription session object](https://platform.openai.com/docs/api-reference/realtime-sessions/transcription_session_object), plus an ephemeral key examples: response: | { "id": "sess_BBwZc7cFV3XizEyKGDCGL", "object": "realtime.transcription_session", "modalities": ["audio", "text"], "turn_detection": { "type": "server_vad", "threshold": 0.5, "prefix_padding_ms": 300, "silence_duration_ms": 200 }, "input_audio_format": "pcm16", "input_audio_transcription": { "model": "gpt-4o-transcribe", "language": null, "prompt": "" }, "client_secret": null } request: curl: | curl -X POST https://api.openai.com/v1/realtime/transcription_sessions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const transcriptionSession = await client.beta.realtime.transcriptionSessions.create(); console.log(transcriptionSession.client_secret); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) transcription_session = client.beta.realtime.transcription_sessions.create() print(transcription_session.client_secret) java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.realtime.transcriptionsessions.TranscriptionSession; import com.openai.models.beta.realtime.transcriptionsessions.TranscriptionSessionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); TranscriptionSession transcriptionSession = client.beta().realtime().transcriptionSessions().create(); } } description: | Create an ephemeral API token for use in client-side applications with the Realtime API specifically for realtime transcriptions. Can be configured with the same session parameters as the `transcription_session.update` client event. It responds with a session object, plus a `client_secret` key which contains a usable ephemeral API token that can be used to authenticate browser clients for the Realtime API. /responses: post: operationId: createResponse tags: - Responses summary: Create a model response requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateResponse' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Response' text/event-stream: schema: $ref: '#/components/schemas/ResponseStreamEvent' x-oaiMeta: name: Create a model response group: responses returns: | Returns a [Response](https://platform.openai.com/docs/api-reference/responses/object) object. path: create examples: - title: Text input request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "input": "Tell me a three sentence bedtime story about a unicorn." }' javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const response = await openai.responses.create({ model: "gpt-4.1", input: "Tell me a three sentence bedtime story about a unicorn." }); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) csharp: > using System; using OpenAI.Responses; OpenAIResponseClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); OpenAIResponse response = client.CreateResponse("Tell me a three sentence bedtime story about a unicorn."); Console.WriteLine(response.GetOutputText()); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: | { "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b", "object": "response", "created_at": 1741476542, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4.1-2025-04-14", "output": [ { "type": "message", "id": "msg_67ccd2bf17f0819081ff3bb2cf6508e60bb6a6b452d3795b", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "In a peaceful grove beneath a silver moon, a unicorn named Lumina discovered a hidden pool that reflected the stars. As she dipped her horn into the water, the pool began to shimmer, revealing a pathway to a magical realm of endless night skies. Filled with wonder, Lumina whispered a wish for all who dream to find their own hidden magic, and as she glanced back, her hoofprints sparkled like stardust.", "annotations": [] } ] } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 36, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 87, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 123 }, "user": null, "metadata": {} } - title: Image input request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "input": [ { "role": "user", "content": [ {"type": "input_text", "text": "what is in this image?"}, { "type": "input_image", "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } ] } ] }' javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const response = await openai.responses.create({ model: "gpt-4.1", input: [ { role: "user", content: [ { type: "input_text", text: "what is in this image?" }, { type: "input_image", image_url: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", }, ], }, ], }); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) csharp: | using System; using System.Collections.Generic; using OpenAI.Responses; OpenAIResponseClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List inputItems = [ ResponseItem.CreateUserMessageItem( [ ResponseContentPart.CreateInputTextPart("What is in this image?"), ResponseContentPart.CreateInputImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")) ] ) ]; OpenAIResponse response = client.CreateResponse(inputItems); Console.WriteLine(response.GetOutputText()); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: | { "id": "resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41", "object": "response", "created_at": 1741476777, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4.1-2025-04-14", "output": [ { "type": "message", "id": "msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "The image depicts a scenic landscape with a wooden boardwalk or pathway leading through lush, green grass under a blue sky with some clouds. The setting suggests a peaceful natural area, possibly a park or nature reserve. There are trees and shrubs in the background.", "annotations": [] } ] } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 328, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 52, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 380 }, "user": null, "metadata": {} } - title: File input request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "input": [ { "role": "user", "content": [ {"type": "input_text", "text": "what is in this file?"}, { "type": "input_file", "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf" } ] } ] }' javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const response = await openai.responses.create({ model: "gpt-4.1", input: [ { role: "user", content: [ { type: "input_text", text: "what is in this file?" }, { type: "input_file", file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf", }, ], }, ], }); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: | { "id": "resp_686eef60237881a2bd1180bb8b13de430e34c516d176ff86", "object": "response", "created_at": 1752100704, "status": "completed", "background": false, "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "max_tool_calls": null, "model": "gpt-4.1-2025-04-14", "output": [ { "id": "msg_686eef60d3e081a29283bdcbc4322fd90e34c516d176ff86", "type": "message", "status": "completed", "content": [ { "type": "output_text", "annotations": [], "logprobs": [], "text": "The file seems to contain excerpts from a letter to the shareholders of Berkshire Hathaway Inc., likely written by Warren Buffett. It covers several topics:\n\n1. **Communication Philosophy**: Buffett emphasizes the importance of transparency and candidness in reporting mistakes and successes to shareholders.\n\n2. **Mistakes and Learnings**: The letter acknowledges past mistakes in business assessments and management hires, highlighting the importance of correcting errors promptly.\n\n3. **CEO Succession**: Mention of Greg Abel stepping in as the new CEO and continuing the tradition of honest communication.\n\n4. **Pete Liegl Story**: A detailed account of acquiring Forest River and the relationship with its founder, highlighting trust and effective business decisions.\n\n5. **2024 Performance**: Overview of business performance, particularly in insurance and investment activities, with a focus on GEICO's improvement.\n\n6. **Tax Contributions**: Discussion of significant tax payments to the U.S. Treasury, credited to shareholders' reinvestments.\n\n7. **Investment Strategy**: A breakdown of Berkshire\u2019s investments in both controlled subsidiaries and marketable equities, along with a focus on long-term holding strategies.\n\n8. **American Capitalism**: Reflections on America\u2019s economic development and Berkshire\u2019s role within it.\n\n9. **Property-Casualty Insurance**: Insights into the P/C insurance business model and its challenges and benefits.\n\n10. **Japanese Investments**: Information about Berkshire\u2019s investments in Japanese companies and future plans.\n\n11. **Annual Meeting**: Details about the upcoming annual gathering in Omaha, including schedule changes and new book releases.\n\n12. **Personal Anecdotes**: Light-hearted stories about family and interactions, conveying Buffett's personable approach.\n\n13. **Financial Performance Data**: Tables comparing Berkshire\u2019s annual performance to the S&P 500, showing impressive long-term gains.\n\nOverall, the letter reinforces Berkshire Hathaway's commitment to transparency, investment in both its businesses and the wider economy, and emphasizes strong leadership and prudent financial management." } ], "role": "assistant" } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "service_tier": "default", "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_logprobs": 0, "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 8438, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 398, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 8836 }, "user": null, "metadata": {} } - title: Web search request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "tools": [{ "type": "web_search_preview" }], "input": "What was a positive news story from today?" }' javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const response = await openai.responses.create({ model: "gpt-4.1", tools: [{ type: "web_search_preview" }], input: "What was a positive news story from today?", }); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) csharp: | using System; using OpenAI.Responses; OpenAIResponseClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); string userInputText = "What was a positive news story from today?"; ResponseCreationOptions options = new() { Tools = { ResponseTool.CreateWebSearchTool() }, }; OpenAIResponse response = client.CreateResponse(userInputText, options); Console.WriteLine(response.GetOutputText()); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: | { "id": "resp_67ccf18ef5fc8190b16dbee19bc54e5f087bb177ab789d5c", "object": "response", "created_at": 1741484430, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4.1-2025-04-14", "output": [ { "type": "web_search_call", "id": "ws_67ccf18f64008190a39b619f4c8455ef087bb177ab789d5c", "status": "completed" }, { "type": "message", "id": "msg_67ccf190ca3881909d433c50b1f6357e087bb177ab789d5c", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "As of today, March 9, 2025, one notable positive news story...", "annotations": [ { "type": "url_citation", "start_index": 442, "end_index": 557, "url": "https://.../?utm_source=chatgpt.com", "title": "..." }, { "type": "url_citation", "start_index": 962, "end_index": 1077, "url": "https://.../?utm_source=chatgpt.com", "title": "..." }, { "type": "url_citation", "start_index": 1336, "end_index": 1451, "url": "https://.../?utm_source=chatgpt.com", "title": "..." } ] } ] } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [ { "type": "web_search_preview", "domains": [], "search_context_size": "medium", "user_location": { "type": "approximate", "city": null, "country": "US", "region": null, "timezone": null } } ], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 328, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 356, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 684 }, "user": null, "metadata": {} } - title: File search request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "tools": [{ "type": "file_search", "vector_store_ids": ["vs_1234567890"], "max_num_results": 20 }], "input": "What are the attributes of an ancient brown dragon?" }' javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const response = await openai.responses.create({ model: "gpt-4.1", tools: [{ type: "file_search", vector_store_ids: ["vs_1234567890"], max_num_results: 20 }], input: "What are the attributes of an ancient brown dragon?", }); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) csharp: | using System; using OpenAI.Responses; OpenAIResponseClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); string userInputText = "What are the attributes of an ancient brown dragon?"; ResponseCreationOptions options = new() { Tools = { ResponseTool.CreateFileSearchTool( vectorStoreIds: ["vs_1234567890"], maxResultCount: 20 ) }, }; OpenAIResponse response = client.CreateResponse(userInputText, options); Console.WriteLine(response.GetOutputText()); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: | { "id": "resp_67ccf4c55fc48190b71bd0463ad3306d09504fb6872380d7", "object": "response", "created_at": 1741485253, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4.1-2025-04-14", "output": [ { "type": "file_search_call", "id": "fs_67ccf4c63cd08190887ef6464ba5681609504fb6872380d7", "status": "completed", "queries": [ "attributes of an ancient brown dragon" ], "results": null }, { "type": "message", "id": "msg_67ccf4c93e5c81909d595b369351a9d309504fb6872380d7", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "The attributes of an ancient brown dragon include...", "annotations": [ { "type": "file_citation", "index": 320, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" }, { "type": "file_citation", "index": 576, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" }, { "type": "file_citation", "index": 815, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" }, { "type": "file_citation", "index": 815, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" }, { "type": "file_citation", "index": 1030, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" }, { "type": "file_citation", "index": 1030, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" }, { "type": "file_citation", "index": 1156, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" }, { "type": "file_citation", "index": 1225, "file_id": "file-4wDz5b167pAf72nx1h9eiN", "filename": "dragons.pdf" } ] } ] } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [ { "type": "file_search", "filters": null, "max_num_results": 20, "ranking_options": { "ranker": "auto", "score_threshold": 0.0 }, "vector_store_ids": [ "vs_1234567890" ] } ], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 18307, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 348, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 18655 }, "user": null, "metadata": {} } - title: Streaming request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "instructions": "You are a helpful assistant.", "input": "Hello!", "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const response = await openai.responses.create({ model: "gpt-4.1", instructions: "You are a helpful assistant.", input: "Hello!", stream: true, }); for await (const event of response) { console.log(event); } csharp: > using System; using System.ClientModel; using System.Threading.Tasks; using OpenAI.Responses; OpenAIResponseClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); string userInputText = "Hello!"; ResponseCreationOptions options = new() { Instructions = "You are a helpful assistant.", }; AsyncCollectionResult responseUpdates = client.CreateResponseStreamingAsync(userInputText, options); await foreach (StreamingResponseUpdate responseUpdate in responseUpdates) { if (responseUpdate is StreamingResponseOutputTextDeltaUpdate outputTextDeltaUpdate) { Console.Write(outputTextDeltaUpdate.Delta); } } node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: > event: response.created data: {"type":"response.created","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}} event: response.in_progress data: {"type":"response.in_progress","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}} event: response.output_item.added data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"in_progress","role":"assistant","content":[]}} event: response.content_part.added data: {"type":"response.content_part.added","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}} event: response.output_text.delta data: {"type":"response.output_text.delta","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"delta":"Hi"} ... event: response.output_text.done data: {"type":"response.output_text.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"text":"Hi there! How can I assist you today?"} event: response.content_part.done data: {"type":"response.content_part.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"Hi there! How can I assist you today?","annotations":[]}} event: response.output_item.done data: {"type":"response.output_item.done","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi there! How can I assist you today?","annotations":[]}]}} event: response.completed data: {"type":"response.completed","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"completed","error":null,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi there! How can I assist you today?","annotations":[]}]}],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":{"input_tokens":37,"output_tokens":11,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":48},"user":null,"metadata":{}}} - title: Functions request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-4.1", "input": "What is the weather like in Boston today?", "tools": [ { "type": "function", "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location", "unit"] } } ], "tool_choice": "auto" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const tools = [ { type: "function", name: "get_current_weather", description: "Get the current weather in a given location", parameters: { type: "object", properties: { location: { type: "string", description: "The city and state, e.g. San Francisco, CA", }, unit: { type: "string", enum: ["celsius", "fahrenheit"] }, }, required: ["location", "unit"], }, }, ]; const response = await openai.responses.create({ model: "gpt-4.1", tools: tools, input: "What is the weather like in Boston today?", tool_choice: "auto", }); console.log(response); csharp: | using System; using OpenAI.Responses; OpenAIResponseClient client = new( model: "gpt-4.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); ResponseTool getCurrentWeatherFunctionTool = ResponseTool.CreateFunctionTool( functionName: "get_current_weather", functionDescription: "Get the current weather in a given location", functionParameters: BinaryData.FromString(""" { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["location", "unit"] } """ ) ); string userInputText = "What is the weather like in Boston today?"; ResponseCreationOptions options = new() { Tools = { getCurrentWeatherFunctionTool }, ToolChoice = ResponseToolChoice.CreateAutoChoice(), }; OpenAIResponse response = client.CreateResponse(userInputText, options); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: | { "id": "resp_67ca09c5efe0819096d0511c92b8c890096610f474011cc0", "object": "response", "created_at": 1741294021, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4.1-2025-04-14", "output": [ { "type": "function_call", "id": "fc_67ca09c6bedc8190a7abfec07b1a1332096610f474011cc0", "call_id": "call_unLAR8MvFNptuiZK6K6HCy5k", "name": "get_current_weather", "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}", "status": "completed" } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [ { "type": "function", "description": "Get the current weather in a given location", "name": "get_current_weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit" ] } }, "required": [ "location", "unit" ] }, "strict": true } ], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 291, "output_tokens": 23, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 314 }, "user": null, "metadata": {} } - title: Reasoning request: curl: | curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "o3-mini", "input": "How much wood would a woodchuck chuck?", "reasoning": { "effort": "high" } }' javascript: | import OpenAI from "openai"; const openai = new OpenAI(); const response = await openai.responses.create({ model: "o3-mini", input: "How much wood would a woodchuck chuck?", reasoning: { effort: "high" } }); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.create() print(response.id) csharp: | using System; using OpenAI.Responses; OpenAIResponseClient client = new( model: "o3-mini", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); string userInputText = "How much wood would a woodchuck chuck?"; ResponseCreationOptions options = new() { ReasoningOptions = new() { ReasoningEffortLevel = ResponseReasoningEffortLevel.High, }, }; OpenAIResponse response = client.CreateResponse(userInputText, options); Console.WriteLine(response.GetOutputText()); node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.create(); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.create puts(response) response: | { "id": "resp_67ccd7eca01881908ff0b5146584e408072912b2993db808", "object": "response", "created_at": 1741477868, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "o1-2024-12-17", "output": [ { "type": "message", "id": "msg_67ccd7f7b5848190a6f3e95d809f6b44072912b2993db808", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "The classic tongue twister...", "annotations": [] } ] } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": "high", "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 81, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 1035, "output_tokens_details": { "reasoning_tokens": 832 }, "total_tokens": 1116 }, "user": null, "metadata": {} } description: > Creates a model response. Provide [text](https://platform.openai.com/docs/guides/text) or [image](https://platform.openai.com/docs/guides/images) inputs to generate [text](https://platform.openai.com/docs/guides/text) or [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have the model call your own [custom code](https://platform.openai.com/docs/guides/function-calling) or use built-in [tools](https://platform.openai.com/docs/guides/tools) like [web search](https://platform.openai.com/docs/guides/tools-web-search) or [file search](https://platform.openai.com/docs/guides/tools-file-search) to use your own data as input for the model's response. /responses/{response_id}: get: operationId: getResponse tags: - Responses summary: Get a model response parameters: - in: path name: response_id required: true schema: type: string example: resp_677efb5139a88190b512bc3fef8e535d description: The ID of the response to retrieve. - in: query name: include schema: type: array items: $ref: '#/components/schemas/Includable' description: | Additional fields to include in the response. See the `include` parameter for Response creation above for more information. - in: query name: stream schema: type: boolean description: > If set to true, the model response data will be streamed to the client as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). See the [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) for more information. - in: query name: starting_after schema: type: integer description: | The sequence number of the event after which to start streaming. - in: query name: include_obfuscation schema: type: boolean description: | When true, stream obfuscation will be enabled. Stream obfuscation adds random characters to an `obfuscation` field on streaming delta events to normalize payload sizes as a mitigation to certain side-channel attacks. These obfuscation fields are included by default, but add a small amount of overhead to the data stream. You can set `include_obfuscation` to false to optimize for bandwidth if you trust the network links between your application and the OpenAI API. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Response' x-oaiMeta: name: Get a model response group: responses returns: | The [Response](https://platform.openai.com/docs/api-reference/responses/object) object matching the specified ID. examples: response: | { "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44", "object": "response", "created_at": 1741386163, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4o-2024-08-06", "output": [ { "type": "message", "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "Silent circuits hum, \nThoughts emerge in data streams— \nDigital dawn breaks.", "annotations": [] } ] } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 32, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 18, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 50 }, "user": null, "metadata": {} } request: curl: | curl https://api.openai.com/v1/responses/resp_123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" javascript: | import OpenAI from "openai"; const client = new OpenAI(); const response = await client.responses.retrieve("resp_123"); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.retrieve( response_id="resp_677efb5139a88190b512bc3fef8e535d", ) print(response.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.retrieve('resp_677efb5139a88190b512bc3fef8e535d'); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.Get( context.TODO(), "resp_677efb5139a88190b512bc3fef8e535d", responses.ResponseGetParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().retrieve("resp_677efb5139a88190b512bc3fef8e535d"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.retrieve("resp_677efb5139a88190b512bc3fef8e535d") puts(response) description: | Retrieves a model response with the given ID. delete: operationId: deleteResponse tags: - Responses summary: Delete a model response parameters: - in: path name: response_id required: true schema: type: string example: resp_677efb5139a88190b512bc3fef8e535d description: The ID of the response to delete. responses: '200': description: OK '404': description: Not Found content: application/json: schema: $ref: '#/components/schemas/Error' x-oaiMeta: name: Delete a model response group: responses returns: | A success message. examples: response: | { "id": "resp_6786a1bec27481909a17d673315b29f6", "object": "response", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/responses/resp_123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" javascript: | import OpenAI from "openai"; const client = new OpenAI(); const response = await client.responses.delete("resp_123"); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) client.responses.delete( "resp_677efb5139a88190b512bc3fef8e535d", ) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); await client.responses.delete('resp_677efb5139a88190b512bc3fef8e535d'); go: | package main import ( "context" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) err := client.Responses.Delete(context.TODO(), "resp_677efb5139a88190b512bc3fef8e535d") if err != nil { panic(err.Error()) } } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.ResponseDeleteParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); client.responses().delete("resp_677efb5139a88190b512bc3fef8e535d"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") result = openai.responses.delete("resp_677efb5139a88190b512bc3fef8e535d") puts(result) description: | Deletes a model response with the given ID. /responses/{response_id}/cancel: post: operationId: cancelResponse tags: - Responses summary: Cancel a response parameters: - in: path name: response_id required: true schema: type: string example: resp_677efb5139a88190b512bc3fef8e535d description: The ID of the response to cancel. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Response' '404': description: Not Found content: application/json: schema: $ref: '#/components/schemas/Error' x-oaiMeta: name: Cancel a response group: responses returns: | A [Response](https://platform.openai.com/docs/api-reference/responses/object) object. examples: response: | { "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44", "object": "response", "created_at": 1741386163, "status": "completed", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4o-2024-08-06", "output": [ { "type": "message", "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "Silent circuits hum, \nThoughts emerge in data streams— \nDigital dawn breaks.", "annotations": [] } ] } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1.0, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1.0, "truncation": "disabled", "usage": { "input_tokens": 32, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 18, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 50 }, "user": null, "metadata": {} } request: curl: | curl -X POST https://api.openai.com/v1/responses/resp_123/cancel \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" javascript: | import OpenAI from "openai"; const client = new OpenAI(); const response = await client.responses.cancel("resp_123"); console.log(response); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) response = client.responses.cancel( "resp_677efb5139a88190b512bc3fef8e535d", ) print(response.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const response = await client.responses.cancel('resp_677efb5139a88190b512bc3fef8e535d'); console.log(response.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Responses.Cancel(context.TODO(), "resp_677efb5139a88190b512bc3fef8e535d") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCancelParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Response response = client.responses().cancel("resp_677efb5139a88190b512bc3fef8e535d"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") response = openai.responses.cancel("resp_677efb5139a88190b512bc3fef8e535d") puts(response) description: | Cancels a model response with the given ID. Only responses created with the `background` parameter set to `true` can be cancelled. [Learn more](https://platform.openai.com/docs/guides/background). /responses/{response_id}/input_items: get: operationId: listInputItems tags: - Responses summary: List input items parameters: - in: path name: response_id required: true schema: type: string description: The ID of the response to retrieve input items for. - name: limit in: query description: | A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - in: query name: order schema: type: string enum: - asc - desc description: | The order to return the input items in. Default is `desc`. - `asc`: Return the input items in ascending order. - `desc`: Return the input items in descending order. - in: query name: after schema: type: string description: | An item ID to list items after, used in pagination. - in: query name: before schema: type: string description: | An item ID to list items before, used in pagination. - in: query name: include schema: type: array items: $ref: '#/components/schemas/Includable' description: | Additional fields to include in the response. See the `include` parameter for Response creation above for more information. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ResponseItemList' x-oaiMeta: name: List input items group: responses returns: A list of input item objects. examples: response: | { "object": "list", "data": [ { "id": "msg_abc123", "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "Tell me a three sentence bedtime story about a unicorn." } ] } ], "first_id": "msg_abc123", "last_id": "msg_abc123", "has_more": false } request: curl: | curl https://api.openai.com/v1/responses/resp_abc123/input_items \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" javascript: | import OpenAI from "openai"; const client = new OpenAI(); const response = await client.responses.inputItems.list("resp_123"); console.log(response.data); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.responses.input_items.list( response_id="response_id", ) page = page.data[0] print(page) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const responseItem of client.responses.inputItems.list('response_id')) { console.log(responseItem); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/openai/openai-go/responses" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Responses.InputItems.List( context.TODO(), "response_id", responses.InputItemListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.inputitems.InputItemListPage; import com.openai.models.responses.inputitems.InputItemListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); InputItemListPage page = client.responses().inputItems().list("response_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.responses.input_items.list("response_id") puts(page) description: Returns a list of input items for a given response. /threads: post: operationId: createThread tags: - Assistants summary: Create thread requestBody: content: application/json: schema: $ref: '#/components/schemas/CreateThreadRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ThreadObject' x-oaiMeta: name: Create thread group: threads beta: true returns: A [thread](https://platform.openai.com/docs/api-reference/threads) object. examples: - title: Empty request: curl: | curl https://api.openai.com/v1/threads \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) thread = client.beta.threads.create() print(thread.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const thread = await client.beta.threads.create(); console.log(thread.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", thread.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.Thread; import com.openai.models.beta.threads.ThreadCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Thread thread = client.beta().threads().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") thread = openai.beta.threads.create puts(thread) response: | { "id": "thread_abc123", "object": "thread", "created_at": 1699012949, "metadata": {}, "tool_resources": {} } - title: Messages request: curl: | curl https://api.openai.com/v1/threads \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "messages": [{ "role": "user", "content": "Hello, what is AI?" }, { "role": "user", "content": "How does AI work? Explain it in simple terms." }] }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) thread = client.beta.threads.create() print(thread.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const thread = await client.beta.threads.create(); console.log(thread.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", thread.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.Thread; import com.openai.models.beta.threads.ThreadCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Thread thread = client.beta().threads().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") thread = openai.beta.threads.create puts(thread) response: | { "id": "thread_abc123", "object": "thread", "created_at": 1699014083, "metadata": {}, "tool_resources": {} } description: Create a thread. /threads/runs: post: operationId: createThreadAndRun tags: - Assistants summary: Create thread and run requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateThreadAndRunRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunObject' x-oaiMeta: name: Create thread and run group: threads beta: true returns: A [run](https://platform.openai.com/docs/api-reference/runs/object) object. examples: - title: Default request: curl: | curl https://api.openai.com/v1/threads/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "assistant_id": "asst_abc123", "thread": { "messages": [ {"role": "user", "content": "Explain deep learning to a 5 year old."} ] } }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.create_and_run( assistant_id="assistant_id", ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{ AssistantID: "assistant_id", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.ThreadCreateAndRunParams; import com.openai.models.beta.threads.runs.Run; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() .assistantId("assistant_id") .build(); Run run = client.beta().threads().createAndRun(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.create_and_run(assistant_id: "assistant_id") puts(run) response: | { "id": "run_abc123", "object": "thread.run", "created_at": 1699076792, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "queued", "started_at": null, "expires_at": 1699077392, "cancelled_at": null, "failed_at": null, "completed_at": null, "required_action": null, "last_error": null, "model": "gpt-4o", "instructions": "You are a helpful assistant.", "tools": [], "tool_resources": {}, "metadata": {}, "temperature": 1.0, "top_p": 1.0, "max_completion_tokens": null, "max_prompt_tokens": null, "truncation_strategy": { "type": "auto", "last_messages": null }, "incomplete_details": null, "usage": null, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } - title: Streaming request: curl: | curl https://api.openai.com/v1/threads/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "assistant_id": "asst_123", "thread": { "messages": [ {"role": "user", "content": "Hello"} ] }, "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.create_and_run( assistant_id="assistant_id", ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{ AssistantID: "assistant_id", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.ThreadCreateAndRunParams; import com.openai.models.beta.threads.runs.Run; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() .assistantId("assistant_id") .build(); Run run = client.beta().threads().createAndRun(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.create_and_run(assistant_id: "assistant_id") puts(run) response: > event: thread.created data: {"id":"thread_123","object":"thread","created_at":1710348075,"metadata":{}} event: thread.run.created data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: thread.run.queued data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: thread.run.in_progress data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} event: thread.run.step.in_progress data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} event: thread.message.created data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], "metadata":{}} event: thread.message.in_progress data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], "metadata":{}} event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} ... event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}} event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} event: thread.message.completed data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}], "metadata":{}} event: thread.run.step.completed data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} event: thread.run.completed {"id":"run_123","object":"thread.run","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1713226836,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1713226837,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: done data: [DONE] - title: Streaming with Functions request: curl: | curl https://api.openai.com/v1/threads/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "assistant_id": "asst_abc123", "thread": { "messages": [ {"role": "user", "content": "What is the weather like in San Francisco?"} ] }, "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.create_and_run( assistant_id="assistant_id", ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{ AssistantID: "assistant_id", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.ThreadCreateAndRunParams; import com.openai.models.beta.threads.runs.Run; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() .assistantId("assistant_id") .build(); Run run = client.beta().threads().createAndRun(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.create_and_run(assistant_id: "assistant_id") puts(run) response: > event: thread.created data: {"id":"thread_123","object":"thread","created_at":1710351818,"metadata":{}} event: thread.run.created data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.queued data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} event: thread.run.step.in_progress data: {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} event: thread.run.step.delta data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"","output":null}}]}}} event: thread.run.step.delta data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"{\""}}]}}} event: thread.run.step.delta data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"location"}}]}}} ... event: thread.run.step.delta data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"ahrenheit"}}]}}} event: thread.run.step.delta data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"\"}"}}]}}} event: thread.run.requires_action data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"requires_action","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":{"type":"submit_tool_outputs","submit_tool_outputs":{"tool_calls":[{"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}"}}]}},"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] description: Create a thread and run it in one request. /threads/{thread_id}: get: operationId: getThread tags: - Assistants summary: Retrieve thread parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to retrieve. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ThreadObject' x-oaiMeta: name: Retrieve thread group: threads beta: true returns: >- The [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching the specified ID. examples: response: | { "id": "thread_abc123", "object": "thread", "created_at": 1699014083, "metadata": {}, "tool_resources": { "code_interpreter": { "file_ids": [] } } } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) thread = client.beta.threads.retrieve( "thread_id", ) print(thread.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const thread = await client.beta.threads.retrieve('thread_id'); console.log(thread.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) thread, err := client.Beta.Threads.Get(context.TODO(), "thread_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", thread.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.Thread; import com.openai.models.beta.threads.ThreadRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Thread thread = client.beta().threads().retrieve("thread_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") thread = openai.beta.threads.retrieve("thread_id") puts(thread) description: Retrieves a thread. post: operationId: modifyThread tags: - Assistants summary: Modify thread parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to modify. Only the `metadata` can be modified. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ModifyThreadRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ThreadObject' x-oaiMeta: name: Modify thread group: threads beta: true returns: >- The modified [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching the specified ID. examples: response: | { "id": "thread_abc123", "object": "thread", "created_at": 1699014083, "metadata": { "modified": "true", "user": "abc123" }, "tool_resources": {} } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "metadata": { "modified": "true", "user": "abc123" } }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) thread = client.beta.threads.update( thread_id="thread_id", ) print(thread.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const thread = await client.beta.threads.update('thread_id'); console.log(thread.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) thread, err := client.Beta.Threads.Update( context.TODO(), "thread_id", openai.BetaThreadUpdateParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", thread.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.Thread; import com.openai.models.beta.threads.ThreadUpdateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Thread thread = client.beta().threads().update("thread_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") thread = openai.beta.threads.update("thread_id") puts(thread) description: Modifies a thread. delete: operationId: deleteThread tags: - Assistants summary: Delete thread parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to delete. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteThreadResponse' x-oaiMeta: name: Delete thread group: threads beta: true returns: Deletion status examples: response: | { "id": "thread_abc123", "object": "thread.deleted", "deleted": true } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -X DELETE python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) thread_deleted = client.beta.threads.delete( "thread_id", ) print(thread_deleted.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const threadDeleted = await client.beta.threads.delete('thread_id'); console.log(threadDeleted.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) threadDeleted, err := client.Beta.Threads.Delete(context.TODO(), "thread_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", threadDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.ThreadDeleteParams; import com.openai.models.beta.threads.ThreadDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); ThreadDeleted threadDeleted = client.beta().threads().delete("thread_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") thread_deleted = openai.beta.threads.delete("thread_id") puts(thread_deleted) description: Delete a thread. /threads/{thread_id}/messages: get: operationId: listMessages tags: - Assistants summary: List messages parameters: - in: path name: thread_id required: true schema: type: string description: >- The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) the messages belong to. - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string - name: run_id in: query description: | Filter messages by the run ID that generated them. schema: type: string responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListMessagesResponse' x-oaiMeta: name: List messages group: threads beta: true returns: A list of [message](https://platform.openai.com/docs/api-reference/messages) objects. examples: response: | { "object": "list", "data": [ { "id": "msg_abc123", "object": "thread.message", "created_at": 1699016383, "assistant_id": null, "thread_id": "thread_abc123", "run_id": null, "role": "user", "content": [ { "type": "text", "text": { "value": "How does AI work? Explain it in simple terms.", "annotations": [] } } ], "attachments": [], "metadata": {} }, { "id": "msg_abc456", "object": "thread.message", "created_at": 1699016383, "assistant_id": null, "thread_id": "thread_abc123", "run_id": null, "role": "user", "content": [ { "type": "text", "text": { "value": "Hello, what is AI?", "annotations": [] } } ], "attachments": [], "metadata": {} } ], "first_id": "msg_abc123", "last_id": "msg_abc456", "has_more": false } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/messages \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.beta.threads.messages.list( thread_id="thread_id", ) page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const message of client.beta.threads.messages.list('thread_id')) { console.log(message.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Beta.Threads.Messages.List( context.TODO(), "thread_id", openai.BetaThreadMessageListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.messages.MessageListPage; import com.openai.models.beta.threads.messages.MessageListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); MessageListPage page = client.beta().threads().messages().list("thread_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.beta.threads.messages.list("thread_id") puts(page) description: Returns a list of messages for a given thread. post: operationId: createMessage tags: - Assistants summary: Create message parameters: - in: path name: thread_id required: true schema: type: string description: >- The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to create a message for. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateMessageRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/MessageObject' x-oaiMeta: name: Create message group: threads beta: true returns: A [message](https://platform.openai.com/docs/api-reference/messages/object) object. examples: response: | { "id": "msg_abc123", "object": "thread.message", "created_at": 1713226573, "assistant_id": null, "thread_id": "thread_abc123", "run_id": null, "role": "user", "content": [ { "type": "text", "text": { "value": "How does AI work? Explain it in simple terms.", "annotations": [] } } ], "attachments": [], "metadata": {} } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/messages \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "role": "user", "content": "How does AI work? Explain it in simple terms." }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) message = client.beta.threads.messages.create( thread_id="thread_id", content="string", role="user", ) print(message.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const message = await client.beta.threads.messages.create('thread_id', { content: 'string', role: 'user' }); console.log(message.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) message, err := client.Beta.Threads.Messages.New( context.TODO(), "thread_id", openai.BetaThreadMessageNewParams{ Content: openai.BetaThreadMessageNewParamsContentUnion{ OfString: openai.String("string"), }, Role: openai.BetaThreadMessageNewParamsRoleUser, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", message.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.messages.Message; import com.openai.models.beta.threads.messages.MessageCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); MessageCreateParams params = MessageCreateParams.builder() .threadId("thread_id") .content("string") .role(MessageCreateParams.Role.USER) .build(); Message message = client.beta().threads().messages().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") message = openai.beta.threads.messages.create("thread_id", content: "string", role: :user) puts(message) description: Create a message. /threads/{thread_id}/messages/{message_id}: get: operationId: getMessage tags: - Assistants summary: Retrieve message parameters: - in: path name: thread_id required: true schema: type: string description: >- The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this message belongs. - in: path name: message_id required: true schema: type: string description: The ID of the message to retrieve. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/MessageObject' x-oaiMeta: name: Retrieve message group: threads beta: true returns: >- The [message](https://platform.openai.com/docs/api-reference/messages/object) object matching the specified ID. examples: response: | { "id": "msg_abc123", "object": "thread.message", "created_at": 1699017614, "assistant_id": null, "thread_id": "thread_abc123", "run_id": null, "role": "user", "content": [ { "type": "text", "text": { "value": "How does AI work? Explain it in simple terms.", "annotations": [] } } ], "attachments": [], "metadata": {} } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) message = client.beta.threads.messages.retrieve( message_id="message_id", thread_id="thread_id", ) print(message.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const message = await client.beta.threads.messages.retrieve('message_id', { thread_id: 'thread_id' }); console.log(message.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) message, err := client.Beta.Threads.Messages.Get( context.TODO(), "thread_id", "message_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", message.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.messages.Message; import com.openai.models.beta.threads.messages.MessageRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); MessageRetrieveParams params = MessageRetrieveParams.builder() .threadId("thread_id") .messageId("message_id") .build(); Message message = client.beta().threads().messages().retrieve(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") message = openai.beta.threads.messages.retrieve("message_id", thread_id: "thread_id") puts(message) description: Retrieve a message. post: operationId: modifyMessage tags: - Assistants summary: Modify message parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to which this message belongs. - in: path name: message_id required: true schema: type: string description: The ID of the message to modify. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ModifyMessageRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/MessageObject' x-oaiMeta: name: Modify message group: threads beta: true returns: The modified [message](https://platform.openai.com/docs/api-reference/messages/object) object. examples: response: | { "id": "msg_abc123", "object": "thread.message", "created_at": 1699017614, "assistant_id": null, "thread_id": "thread_abc123", "run_id": null, "role": "user", "content": [ { "type": "text", "text": { "value": "How does AI work? Explain it in simple terms.", "annotations": [] } } ], "file_ids": [], "metadata": { "modified": "true", "user": "abc123" } } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "metadata": { "modified": "true", "user": "abc123" } }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) message = client.beta.threads.messages.update( message_id="message_id", thread_id="thread_id", ) print(message.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const message = await client.beta.threads.messages.update('message_id', { thread_id: 'thread_id' }); console.log(message.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) message, err := client.Beta.Threads.Messages.Update( context.TODO(), "thread_id", "message_id", openai.BetaThreadMessageUpdateParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", message.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.messages.Message; import com.openai.models.beta.threads.messages.MessageUpdateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); MessageUpdateParams params = MessageUpdateParams.builder() .threadId("thread_id") .messageId("message_id") .build(); Message message = client.beta().threads().messages().update(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") message = openai.beta.threads.messages.update("message_id", thread_id: "thread_id") puts(message) description: Modifies a message. delete: operationId: deleteMessage tags: - Assistants summary: Delete message parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to which this message belongs. - in: path name: message_id required: true schema: type: string description: The ID of the message to delete. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteMessageResponse' x-oaiMeta: name: Delete message group: threads beta: true returns: Deletion status examples: response: | { "id": "msg_abc123", "object": "thread.message.deleted", "deleted": true } request: curl: | curl -X DELETE https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) message_deleted = client.beta.threads.messages.delete( message_id="message_id", thread_id="thread_id", ) print(message_deleted.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const messageDeleted = await client.beta.threads.messages.delete('message_id', { thread_id: 'thread_id' }); console.log(messageDeleted.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) messageDeleted, err := client.Beta.Threads.Messages.Delete( context.TODO(), "thread_id", "message_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", messageDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.messages.MessageDeleteParams; import com.openai.models.beta.threads.messages.MessageDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); MessageDeleteParams params = MessageDeleteParams.builder() .threadId("thread_id") .messageId("message_id") .build(); MessageDeleted messageDeleted = client.beta().threads().messages().delete(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") message_deleted = openai.beta.threads.messages.delete("message_id", thread_id: "thread_id") puts(message_deleted) description: Deletes a message. /threads/{thread_id}/runs: get: operationId: listRuns tags: - Assistants summary: List runs parameters: - name: thread_id in: path required: true schema: type: string description: The ID of the thread the run belongs to. - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListRunsResponse' x-oaiMeta: name: List runs group: threads beta: true returns: A list of [run](https://platform.openai.com/docs/api-reference/runs/object) objects. examples: response: | { "object": "list", "data": [ { "id": "run_abc123", "object": "thread.run", "created_at": 1699075072, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "completed", "started_at": 1699075072, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699075073, "last_error": null, "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ { "type": "code_interpreter" } ], "tool_resources": { "code_interpreter": { "file_ids": [ "file-abc123", "file-abc456" ] } }, "metadata": {}, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 }, "temperature": 1.0, "top_p": 1.0, "max_prompt_tokens": 1000, "max_completion_tokens": 1000, "truncation_strategy": { "type": "auto", "last_messages": null }, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true }, { "id": "run_abc456", "object": "thread.run", "created_at": 1699063290, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "completed", "started_at": 1699063290, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699063291, "last_error": null, "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ { "type": "code_interpreter" } ], "tool_resources": { "code_interpreter": { "file_ids": [ "file-abc123", "file-abc456" ] } }, "metadata": {}, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 }, "temperature": 1.0, "top_p": 1.0, "max_prompt_tokens": 1000, "max_completion_tokens": 1000, "truncation_strategy": { "type": "auto", "last_messages": null }, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } ], "first_id": "run_abc123", "last_id": "run_abc456", "has_more": false } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.beta.threads.runs.list( thread_id="thread_id", ) page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const run of client.beta.threads.runs.list('thread_id')) { console.log(run.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Beta.Threads.Runs.List( context.TODO(), "thread_id", openai.BetaThreadRunListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.RunListPage; import com.openai.models.beta.threads.runs.RunListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunListPage page = client.beta().threads().runs().list("thread_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.beta.threads.runs.list("thread_id") puts(page) description: Returns a list of runs belonging to a thread. post: operationId: createRun tags: - Assistants summary: Create run parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to run. - name: include[] in: query description: > A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. schema: type: array items: type: string enum: - step_details.tool_calls[*].file_search.results[*].content requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateRunRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunObject' x-oaiMeta: name: Create run group: threads beta: true returns: A [run](https://platform.openai.com/docs/api-reference/runs/object) object. examples: - title: Default request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "assistant_id": "asst_abc123" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.create( thread_id="thread_id", assistant_id="assistant_id", ) print(run.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.New( context.TODO(), "thread_id", openai.BetaThreadRunNewParams{ AssistantID: "assistant_id", }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunCreateParams params = RunCreateParams.builder() .threadId("thread_id") .assistantId("assistant_id") .build(); Run run = client.beta().threads().runs().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id") puts(run) response: | { "id": "run_abc123", "object": "thread.run", "created_at": 1699063290, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "queued", "started_at": 1699063290, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699063291, "last_error": null, "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ { "type": "code_interpreter" } ], "metadata": {}, "usage": null, "temperature": 1.0, "top_p": 1.0, "max_prompt_tokens": 1000, "max_completion_tokens": 1000, "truncation_strategy": { "type": "auto", "last_messages": null }, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } - title: Streaming request: curl: | curl https://api.openai.com/v1/threads/thread_123/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "assistant_id": "asst_123", "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.create( thread_id="thread_id", assistant_id="assistant_id", ) print(run.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.New( context.TODO(), "thread_id", openai.BetaThreadRunNewParams{ AssistantID: "assistant_id", }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunCreateParams params = RunCreateParams.builder() .threadId("thread_id") .assistantId("assistant_id") .build(); Run run = client.beta().threads().runs().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id") puts(run) response: > event: thread.run.created data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.queued data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710330641,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} event: thread.run.step.in_progress data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} event: thread.message.created data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} event: thread.message.in_progress data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} ... event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}} event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} event: thread.message.completed data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710330642,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}],"metadata":{}} event: thread.run.step.completed data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710330642,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} event: thread.run.completed data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710330641,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710330642,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] - title: Streaming with Functions request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "assistant_id": "asst_abc123", "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.create( thread_id="thread_id", assistant_id="assistant_id", ) print(run.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.New( context.TODO(), "thread_id", openai.BetaThreadRunNewParams{ AssistantID: "assistant_id", }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunCreateParams params = RunCreateParams.builder() .threadId("thread_id") .assistantId("assistant_id") .build(); Run run = client.beta().threads().runs().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id") puts(run) response: > event: thread.run.created data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.queued data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710348075,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} event: thread.run.step.in_progress data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} event: thread.message.created data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} event: thread.message.in_progress data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} ... event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}} event: thread.message.delta data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} event: thread.message.completed data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}],"metadata":{}} event: thread.run.step.completed data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} event: thread.run.completed data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710348075,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710348077,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] description: Create a run. /threads/{thread_id}/runs/{run_id}: get: operationId: getRun tags: - Assistants summary: Retrieve run parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. - in: path name: run_id required: true schema: type: string description: The ID of the run to retrieve. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunObject' x-oaiMeta: name: Retrieve run group: threads beta: true returns: >- The [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID. examples: response: | { "id": "run_abc123", "object": "thread.run", "created_at": 1699075072, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "completed", "started_at": 1699075072, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699075073, "last_error": null, "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ { "type": "code_interpreter" } ], "metadata": {}, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 }, "temperature": 1.0, "top_p": 1.0, "max_prompt_tokens": 1000, "max_completion_tokens": 1000, "truncation_strategy": { "type": "auto", "last_messages": null }, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.retrieve( run_id="run_id", thread_id="thread_id", ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.retrieve('run_id', { thread_id: 'thread_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.Get( context.TODO(), "thread_id", "run_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunRetrieveParams params = RunRetrieveParams.builder() .threadId("thread_id") .runId("run_id") .build(); Run run = client.beta().threads().runs().retrieve(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.retrieve("run_id", thread_id: "thread_id") puts(run) description: Retrieves a run. post: operationId: modifyRun tags: - Assistants summary: Modify run parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. - in: path name: run_id required: true schema: type: string description: The ID of the run to modify. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ModifyRunRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunObject' x-oaiMeta: name: Modify run group: threads beta: true returns: >- The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID. examples: response: | { "id": "run_abc123", "object": "thread.run", "created_at": 1699075072, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "completed", "started_at": 1699075072, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699075073, "last_error": null, "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ { "type": "code_interpreter" } ], "tool_resources": { "code_interpreter": { "file_ids": [ "file-abc123", "file-abc456" ] } }, "metadata": { "user_id": "user_abc123" }, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 }, "temperature": 1.0, "top_p": 1.0, "max_prompt_tokens": 1000, "max_completion_tokens": 1000, "truncation_strategy": { "type": "auto", "last_messages": null }, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "metadata": { "user_id": "user_abc123" } }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.update( run_id="run_id", thread_id="thread_id", ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.update('run_id', { thread_id: 'thread_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.Update( context.TODO(), "thread_id", "run_id", openai.BetaThreadRunUpdateParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunUpdateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunUpdateParams params = RunUpdateParams.builder() .threadId("thread_id") .runId("run_id") .build(); Run run = client.beta().threads().runs().update(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.update("run_id", thread_id: "thread_id") puts(run) description: Modifies a run. /threads/{thread_id}/runs/{run_id}/cancel: post: operationId: cancelRun tags: - Assistants summary: Cancel a run parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to which this run belongs. - in: path name: run_id required: true schema: type: string description: The ID of the run to cancel. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunObject' x-oaiMeta: name: Cancel a run group: threads beta: true returns: >- The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID. examples: response: | { "id": "run_abc123", "object": "thread.run", "created_at": 1699076126, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "cancelling", "started_at": 1699076126, "expires_at": 1699076726, "cancelled_at": null, "failed_at": null, "completed_at": null, "last_error": null, "model": "gpt-4o", "instructions": "You summarize books.", "tools": [ { "type": "file_search" } ], "tool_resources": { "file_search": { "vector_store_ids": ["vs_123"] } }, "metadata": {}, "usage": null, "temperature": 1.0, "top_p": 1.0, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/cancel \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -X POST python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.cancel( run_id="run_id", thread_id="thread_id", ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.cancel('run_id', { thread_id: 'thread_id' }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.Cancel( context.TODO(), "thread_id", "run_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunCancelParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunCancelParams params = RunCancelParams.builder() .threadId("thread_id") .runId("run_id") .build(); Run run = client.beta().threads().runs().cancel(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.cancel("run_id", thread_id: "thread_id") puts(run) description: Cancels a run that is `in_progress`. /threads/{thread_id}/runs/{run_id}/steps: get: operationId: listRunSteps tags: - Assistants summary: List run steps parameters: - name: thread_id in: path required: true schema: type: string description: The ID of the thread the run and run steps belong to. - name: run_id in: path required: true schema: type: string description: The ID of the run the run steps belong to. - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string - name: include[] in: query description: > A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. schema: type: array items: type: string enum: - step_details.tool_calls[*].file_search.results[*].content responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListRunStepsResponse' x-oaiMeta: name: List run steps group: threads beta: true returns: A list of [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) objects. examples: response: | { "object": "list", "data": [ { "id": "step_abc123", "object": "thread.run.step", "created_at": 1699063291, "run_id": "run_abc123", "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "type": "message_creation", "status": "completed", "cancelled_at": null, "completed_at": 1699063291, "expired_at": null, "failed_at": null, "last_error": null, "step_details": { "type": "message_creation", "message_creation": { "message_id": "msg_abc123" } }, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 } } ], "first_id": "step_abc123", "last_id": "step_abc456", "has_more": false } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.beta.threads.runs.steps.list( run_id="run_id", thread_id="thread_id", ) page = page.data[0] print(page.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const runStep of client.beta.threads.runs.steps.list('run_id', { thread_id: 'thread_id' })) { console.log(runStep.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.Beta.Threads.Runs.Steps.List( context.TODO(), "thread_id", "run_id", openai.BetaThreadRunStepListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.steps.StepListPage; import com.openai.models.beta.threads.runs.steps.StepListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); StepListParams params = StepListParams.builder() .threadId("thread_id") .runId("run_id") .build(); StepListPage page = client.beta().threads().runs().steps().list(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.beta.threads.runs.steps.list("run_id", thread_id: "thread_id") puts(page) description: Returns a list of run steps belonging to a run. /threads/{thread_id}/runs/{run_id}/steps/{step_id}: get: operationId: getRunStep tags: - Assistants summary: Retrieve run step parameters: - in: path name: thread_id required: true schema: type: string description: The ID of the thread to which the run and run step belongs. - in: path name: run_id required: true schema: type: string description: The ID of the run to which the run step belongs. - in: path name: step_id required: true schema: type: string description: The ID of the run step to retrieve. - name: include[] in: query description: > A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. schema: type: array items: type: string enum: - step_details.tool_calls[*].file_search.results[*].content responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunStepObject' x-oaiMeta: name: Retrieve run step group: threads beta: true returns: >- The [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) object matching the specified ID. examples: response: | { "id": "step_abc123", "object": "thread.run.step", "created_at": 1699063291, "run_id": "run_abc123", "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "type": "message_creation", "status": "completed", "cancelled_at": null, "completed_at": 1699063291, "expired_at": null, "failed_at": null, "last_error": null, "step_details": { "type": "message_creation", "message_creation": { "message_id": "msg_abc123" } }, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 } } request: curl: | curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run_step = client.beta.threads.runs.steps.retrieve( step_id="step_id", thread_id="thread_id", run_id="run_id", ) print(run_step.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const runStep = await client.beta.threads.runs.steps.retrieve('step_id', { thread_id: 'thread_id', run_id: 'run_id', }); console.log(runStep.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) runStep, err := client.Beta.Threads.Runs.Steps.Get( context.TODO(), "thread_id", "run_id", "step_id", openai.BetaThreadRunStepGetParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", runStep.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.steps.RunStep; import com.openai.models.beta.threads.runs.steps.StepRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); StepRetrieveParams params = StepRetrieveParams.builder() .threadId("thread_id") .runId("run_id") .stepId("step_id") .build(); RunStep runStep = client.beta().threads().runs().steps().retrieve(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run_step = openai.beta.threads.runs.steps.retrieve("step_id", thread_id: "thread_id", run_id: "run_id") puts(run_step) description: Retrieves a run step. /threads/{thread_id}/runs/{run_id}/submit_tool_outputs: post: operationId: submitToolOuputsToRun tags: - Assistants summary: Submit tool outputs to run parameters: - in: path name: thread_id required: true schema: type: string description: >- The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this run belongs. - in: path name: run_id required: true schema: type: string description: The ID of the run that requires the tool output submission. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/SubmitToolOutputsRunRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/RunObject' x-oaiMeta: name: Submit tool outputs to run group: threads beta: true returns: >- The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID. examples: - title: Default request: curl: | curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "tool_outputs": [ { "tool_call_id": "call_001", "output": "70 degrees and sunny." } ] }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.submit_tool_outputs( run_id="run_id", thread_id="thread_id", tool_outputs=[{}], ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.submitToolOutputs('run_id', { thread_id: 'thread_id', tool_outputs: [{}], }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.SubmitToolOutputs( context.TODO(), "thread_id", "run_id", openai.BetaThreadRunSubmitToolOutputsParams{ ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{ }}, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder() .threadId("thread_id") .runId("run_id") .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build()) .build(); Run run = client.beta().threads().runs().submitToolOutputs(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.submit_tool_outputs("run_id", thread_id: "thread_id", tool_outputs: [{}]) puts(run) response: | { "id": "run_123", "object": "thread.run", "created_at": 1699075592, "assistant_id": "asst_123", "thread_id": "thread_123", "status": "queued", "started_at": 1699075592, "expires_at": 1699076192, "cancelled_at": null, "failed_at": null, "completed_at": null, "last_error": null, "model": "gpt-4o", "instructions": null, "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], "metadata": {}, "usage": null, "temperature": 1.0, "top_p": 1.0, "max_prompt_tokens": 1000, "max_completion_tokens": 1000, "truncation_strategy": { "type": "auto", "last_messages": null }, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } - title: Streaming request: curl: | curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "tool_outputs": [ { "tool_call_id": "call_001", "output": "70 degrees and sunny." } ], "stream": true }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) run = client.beta.threads.runs.submit_tool_outputs( run_id="run_id", thread_id="thread_id", tool_outputs=[{}], ) print(run.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const run = await client.beta.threads.runs.submitToolOutputs('run_id', { thread_id: 'thread_id', tool_outputs: [{}], }); console.log(run.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) run, err := client.Beta.Threads.Runs.SubmitToolOutputs( context.TODO(), "thread_id", "run_id", openai.BetaThreadRunSubmitToolOutputsParams{ ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{ }}, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", run.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.threads.runs.Run; import com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder() .threadId("thread_id") .runId("run_id") .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build()) .build(); Run run = client.beta().threads().runs().submitToolOutputs(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") run = openai.beta.threads.runs.submit_tool_outputs("run_id", thread_id: "thread_id", tool_outputs: [{}]) puts(run) response: > event: thread.run.step.completed data: {"id":"step_001","object":"thread.run.step","created_at":1710352449,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"completed","cancelled_at":null,"completed_at":1710352475,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[{"id":"call_iWr0kQ2EaYMaxNdl0v3KYkx7","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}","output":"70 degrees and sunny."}}]},"usage":{"prompt_tokens":291,"completion_tokens":24,"total_tokens":315}} event: thread.run.queued data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":1710352448,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710352475,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} event: thread.run.step.in_progress data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} event: thread.message.created data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} event: thread.message.in_progress data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} event: thread.message.delta data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"The","annotations":[]}}]}} event: thread.message.delta data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" current"}}]}} event: thread.message.delta data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" weather"}}]}} ... event: thread.message.delta data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" sunny"}}]}} event: thread.message.delta data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"."}}]}} event: thread.message.completed data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710352477,"role":"assistant","content":[{"type":"text","text":{"value":"The current weather in San Francisco, CA is 70 degrees Fahrenheit and sunny.","annotations":[]}}],"metadata":{}} event: thread.run.step.completed data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710352477,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":{"prompt_tokens":329,"completion_tokens":18,"total_tokens":347}} event: thread.run.completed data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710352475,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710352477,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] description: > When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request. /uploads: post: operationId: createUpload tags: - Uploads summary: Create upload requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateUploadRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Upload' x-oaiMeta: name: Create upload group: uploads returns: >- The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `pending`. examples: response: | { "id": "upload_abc123", "object": "upload", "bytes": 2147483648, "created_at": 1719184911, "filename": "training_examples.jsonl", "purpose": "fine-tune", "status": "pending", "expires_at": 1719127296 } request: curl: | curl https://api.openai.com/v1/uploads \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "purpose": "fine-tune", "filename": "training_examples.jsonl", "bytes": 2147483648, "mime_type": "text/jsonl", "expires_after": { "anchor": "created_at", "seconds": 3600 } }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const upload = await client.uploads.create({ bytes: 0, filename: 'filename', mime_type: 'mime_type', purpose: 'assistants', }); console.log(upload.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) upload = client.uploads.create( bytes=0, filename="filename", mime_type="mime_type", purpose="assistants", ) print(upload.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) upload, err := client.Uploads.New(context.TODO(), openai.UploadNewParams{ Bytes: 0, Filename: "filename", MimeType: "mime_type", Purpose: openai.FilePurposeAssistants, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", upload.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.files.FilePurpose; import com.openai.models.uploads.Upload; import com.openai.models.uploads.UploadCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); UploadCreateParams params = UploadCreateParams.builder() .bytes(0L) .filename("filename") .mimeType("mime_type") .purpose(FilePurpose.ASSISTANTS) .build(); Upload upload = client.uploads().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") upload = openai.uploads.create(bytes: 0, filename: "filename", mime_type: "mime_type", purpose: :assistants) puts(upload) description: > Creates an intermediate [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object that you can add [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. Once you complete the Upload, we will create a [File](https://platform.openai.com/docs/api-reference/files/object) object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. For certain `purpose` values, the correct `mime_type` must be specified. Please refer to documentation for the [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). For guidance on the proper filename extensions for each purpose, please follow the documentation on [creating a File](https://platform.openai.com/docs/api-reference/files/create). /uploads/{upload_id}/cancel: post: operationId: cancelUpload tags: - Uploads summary: Cancel upload parameters: - in: path name: upload_id required: true schema: type: string example: upload_abc123 description: | The ID of the Upload. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Upload' x-oaiMeta: name: Cancel upload group: uploads returns: >- The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `cancelled`. examples: response: | { "id": "upload_abc123", "object": "upload", "bytes": 2147483648, "created_at": 1719184911, "filename": "training_examples.jsonl", "purpose": "fine-tune", "status": "cancelled", "expires_at": 1719127296 } request: curl: | curl https://api.openai.com/v1/uploads/upload_abc123/cancel node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const upload = await client.uploads.cancel('upload_abc123'); console.log(upload.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) upload = client.uploads.cancel( "upload_abc123", ) print(upload.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) upload, err := client.Uploads.Cancel(context.TODO(), "upload_abc123") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", upload.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.uploads.Upload; import com.openai.models.uploads.UploadCancelParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Upload upload = client.uploads().cancel("upload_abc123"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") upload = openai.uploads.cancel("upload_abc123") puts(upload) description: | Cancels the Upload. No Parts may be added after an Upload is cancelled. /uploads/{upload_id}/complete: post: operationId: completeUpload tags: - Uploads summary: Complete upload parameters: - in: path name: upload_id required: true schema: type: string example: upload_abc123 description: | The ID of the Upload. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CompleteUploadRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/Upload' x-oaiMeta: name: Complete upload group: uploads returns: >- The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `completed` with an additional `file` property containing the created usable File object. examples: response: | { "id": "upload_abc123", "object": "upload", "bytes": 2147483648, "created_at": 1719184911, "filename": "training_examples.jsonl", "purpose": "fine-tune", "status": "completed", "expires_at": 1719127296, "file": { "id": "file-xyz321", "object": "file", "bytes": 2147483648, "created_at": 1719186911, "expires_at": 1719127296, "filename": "training_examples.jsonl", "purpose": "fine-tune", } } request: curl: | curl https://api.openai.com/v1/uploads/upload_abc123/complete -d '{ "part_ids": ["part_def456", "part_ghi789"] }' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const upload = await client.uploads.complete('upload_abc123', { part_ids: ['string'] }); console.log(upload.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) upload = client.uploads.complete( upload_id="upload_abc123", part_ids=["string"], ) print(upload.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) upload, err := client.Uploads.Complete( context.TODO(), "upload_abc123", openai.UploadCompleteParams{ PartIDs: []string{"string"}, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", upload.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.uploads.Upload; import com.openai.models.uploads.UploadCompleteParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); UploadCompleteParams params = UploadCompleteParams.builder() .uploadId("upload_abc123") .addPartId("string") .build(); Upload upload = client.uploads().complete(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") upload = openai.uploads.complete("upload_abc123", part_ids: ["string"]) puts(upload) description: > Completes the [Upload](https://platform.openai.com/docs/api-reference/uploads/object). Within the returned Upload object, there is a nested [File](https://platform.openai.com/docs/api-reference/files/object) object that is ready to use in the rest of the platform. You can specify the order of the Parts by passing in an ordered list of the Part IDs. The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. /uploads/{upload_id}/parts: post: operationId: addUploadPart tags: - Uploads summary: Add upload part parameters: - in: path name: upload_id required: true schema: type: string example: upload_abc123 description: | The ID of the Upload. requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/AddUploadPartRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/UploadPart' x-oaiMeta: name: Add upload part group: uploads returns: The upload [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) object. examples: response: | { "id": "part_def456", "object": "upload.part", "created_at": 1719185911, "upload_id": "upload_abc123" } request: curl: | curl https://api.openai.com/v1/uploads/upload_abc123/parts -F data="aHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MS91cGxvYWRz..." node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const uploadPart = await client.uploads.parts.create('upload_abc123', { data: fs.createReadStream('path/to/file'), }); console.log(uploadPart.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) upload_part = client.uploads.parts.create( upload_id="upload_abc123", data=b"raw file contents", ) print(upload_part.id) go: | package main import ( "bytes" "context" "fmt" "io" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) uploadPart, err := client.Uploads.Parts.New( context.TODO(), "upload_abc123", openai.UploadPartNewParams{ Data: io.Reader(bytes.NewBuffer([]byte("some file contents"))), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", uploadPart.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.uploads.parts.PartCreateParams; import com.openai.models.uploads.parts.UploadPart; import java.io.ByteArrayInputStream; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); PartCreateParams params = PartCreateParams.builder() .uploadId("upload_abc123") .data(ByteArrayInputStream("some content".getBytes())) .build(); UploadPart uploadPart = client.uploads().parts().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") upload_part = openai.uploads.parts.create("upload_abc123", data: Pathname(__FILE__)) puts(upload_part) description: > Adds a [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). /vector_stores: get: operationId: listVectorStores tags: - Vector stores summary: List vector stores parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListVectorStoresResponse' x-oaiMeta: name: List vector stores group: vector_stores returns: >- A list of [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) objects. examples: response: | { "object": "list", "data": [ { "id": "vs_abc123", "object": "vector_store", "created_at": 1699061776, "name": "Support FAQ", "bytes": 139920, "file_counts": { "in_progress": 0, "completed": 3, "failed": 0, "cancelled": 0, "total": 3 } }, { "id": "vs_abc456", "object": "vector_store", "created_at": 1699061776, "name": "Support FAQ v2", "bytes": 139920, "file_counts": { "in_progress": 0, "completed": 3, "failed": 0, "cancelled": 0, "total": 3 } } ], "first_id": "vs_abc123", "last_id": "vs_abc456", "has_more": false } request: curl: | curl https://api.openai.com/v1/vector_stores \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.vector_stores.list() page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const vectorStore of client.vectorStores.list()) { console.log(vectorStore.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.VectorStores.List(context.TODO(), openai.VectorStoreListParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.VectorStoreListPage; import com.openai.models.vectorstores.VectorStoreListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); VectorStoreListPage page = client.vectorStores().list(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.vector_stores.list puts(page) description: Returns a list of vector stores. post: operationId: createVectorStore tags: - Vector stores summary: Create vector store requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateVectorStoreRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreObject' x-oaiMeta: name: Create vector store group: vector_stores returns: A [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object. examples: response: | { "id": "vs_abc123", "object": "vector_store", "created_at": 1699061776, "name": "Support FAQ", "bytes": 139920, "file_counts": { "in_progress": 0, "completed": 3, "failed": 0, "cancelled": 0, "total": 3 } } request: curl: | curl https://api.openai.com/v1/vector_stores \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "name": "Support FAQ" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store = client.vector_stores.create() print(vector_store.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStore = await client.vectorStores.create(); console.log(vectorStore.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStore, err := client.VectorStores.New(context.TODO(), openai.VectorStoreNewParams{ }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStore.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.VectorStore; import com.openai.models.vectorstores.VectorStoreCreateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); VectorStore vectorStore = client.vectorStores().create(); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store = openai.vector_stores.create puts(vector_store) description: Create a vector store. /vector_stores/{vector_store_id}: get: operationId: getVectorStore tags: - Vector stores summary: Retrieve vector store parameters: - in: path name: vector_store_id required: true schema: type: string description: The ID of the vector store to retrieve. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreObject' x-oaiMeta: name: Retrieve vector store group: vector_stores returns: >- The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object matching the specified ID. examples: response: | { "id": "vs_abc123", "object": "vector_store", "created_at": 1699061776 } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store = client.vector_stores.retrieve( "vector_store_id", ) print(vector_store.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStore = await client.vectorStores.retrieve('vector_store_id'); console.log(vectorStore.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStore, err := client.VectorStores.Get(context.TODO(), "vector_store_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStore.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.VectorStore; import com.openai.models.vectorstores.VectorStoreRetrieveParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); VectorStore vectorStore = client.vectorStores().retrieve("vector_store_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store = openai.vector_stores.retrieve("vector_store_id") puts(vector_store) description: Retrieves a vector store. post: operationId: modifyVectorStore tags: - Vector stores summary: Modify vector store parameters: - in: path name: vector_store_id required: true schema: type: string description: The ID of the vector store to modify. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/UpdateVectorStoreRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreObject' x-oaiMeta: name: Modify vector store group: vector_stores returns: >- The modified [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object. examples: response: | { "id": "vs_abc123", "object": "vector_store", "created_at": 1699061776, "name": "Support FAQ", "bytes": 139920, "file_counts": { "in_progress": 0, "completed": 3, "failed": 0, "cancelled": 0, "total": 3 } } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" -d '{ "name": "Support FAQ" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store = client.vector_stores.update( vector_store_id="vector_store_id", ) print(vector_store.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStore = await client.vectorStores.update('vector_store_id'); console.log(vectorStore.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStore, err := client.VectorStores.Update( context.TODO(), "vector_store_id", openai.VectorStoreUpdateParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStore.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.VectorStore; import com.openai.models.vectorstores.VectorStoreUpdateParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); VectorStore vectorStore = client.vectorStores().update("vector_store_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store = openai.vector_stores.update("vector_store_id") puts(vector_store) description: Modifies a vector store. delete: operationId: deleteVectorStore tags: - Vector stores summary: Delete vector store parameters: - in: path name: vector_store_id required: true schema: type: string description: The ID of the vector store to delete. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteVectorStoreResponse' x-oaiMeta: name: Delete vector store group: vector_stores returns: Deletion status examples: response: | { id: "vs_abc123", object: "vector_store.deleted", deleted: true } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -X DELETE python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_deleted = client.vector_stores.delete( "vector_store_id", ) print(vector_store_deleted.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreDeleted = await client.vectorStores.delete('vector_store_id'); console.log(vectorStoreDeleted.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreDeleted, err := client.VectorStores.Delete(context.TODO(), "vector_store_id") if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.VectorStoreDeleteParams; import com.openai.models.vectorstores.VectorStoreDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); VectorStoreDeleted vectorStoreDeleted = client.vectorStores().delete("vector_store_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_deleted = openai.vector_stores.delete("vector_store_id") puts(vector_store_deleted) description: Delete a vector store. /vector_stores/{vector_store_id}/file_batches: post: operationId: createVectorStoreFileBatch tags: - Vector stores summary: Create vector store file batch parameters: - in: path name: vector_store_id required: true schema: type: string example: vs_abc123 description: | The ID of the vector store for which to create a File Batch. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateVectorStoreFileBatchRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreFileBatchObject' x-oaiMeta: name: Create vector store file batch group: vector_stores returns: >- A [vector store file batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) object. examples: response: | { "id": "vsfb_abc123", "object": "vector_store.file_batch", "created_at": 1699061776, "vector_store_id": "vs_abc123", "status": "in_progress", "file_counts": { "in_progress": 1, "completed": 1, "failed": 0, "cancelled": 0, "total": 0, } } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/file_batches \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "file_ids": ["file-abc123", "file-abc456"] }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_file_batch = client.vector_stores.file_batches.create( vector_store_id="vs_abc123", file_ids=["string"], ) print(vector_store_file_batch.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreFileBatch = await client.vectorStores.fileBatches.create('vs_abc123', { file_ids: ['string'], }); console.log(vectorStoreFileBatch.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreFileBatch, err := client.VectorStores.FileBatches.New( context.TODO(), "vs_abc123", openai.VectorStoreFileBatchNewParams{ FileIDs: []string{"string"}, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreFileBatch.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.filebatches.FileBatchCreateParams; import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileBatchCreateParams params = FileBatchCreateParams.builder() .vectorStoreId("vs_abc123") .addFileId("string") .build(); VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().create(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_file_batch = openai.vector_stores.file_batches.create("vs_abc123", file_ids: ["string"]) puts(vector_store_file_batch) description: Create a vector store file batch. /vector_stores/{vector_store_id}/file_batches/{batch_id}: get: operationId: getVectorStoreFileBatch tags: - Vector stores summary: Retrieve vector store file batch parameters: - in: path name: vector_store_id required: true schema: type: string example: vs_abc123 description: The ID of the vector store that the file batch belongs to. - in: path name: batch_id required: true schema: type: string example: vsfb_abc123 description: The ID of the file batch being retrieved. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreFileBatchObject' x-oaiMeta: name: Retrieve vector store file batch group: vector_stores returns: >- The [vector store file batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) object. examples: response: | { "id": "vsfb_abc123", "object": "vector_store.file_batch", "created_at": 1699061776, "vector_store_id": "vs_abc123", "status": "in_progress", "file_counts": { "in_progress": 1, "completed": 1, "failed": 0, "cancelled": 0, "total": 0, } } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_file_batch = client.vector_stores.file_batches.retrieve( batch_id="vsfb_abc123", vector_store_id="vs_abc123", ) print(vector_store_file_batch.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreFileBatch = await client.vectorStores.fileBatches.retrieve('vsfb_abc123', { vector_store_id: 'vs_abc123', }); console.log(vectorStoreFileBatch.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreFileBatch, err := client.VectorStores.FileBatches.Get( context.TODO(), "vs_abc123", "vsfb_abc123", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreFileBatch.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.filebatches.FileBatchRetrieveParams; import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileBatchRetrieveParams params = FileBatchRetrieveParams.builder() .vectorStoreId("vs_abc123") .batchId("vsfb_abc123") .build(); VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().retrieve(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_file_batch = openai.vector_stores.file_batches.retrieve("vsfb_abc123", vector_store_id: "vs_abc123") puts(vector_store_file_batch) description: Retrieves a vector store file batch. /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel: post: operationId: cancelVectorStoreFileBatch tags: - Vector stores summary: Cancel vector store file batch parameters: - in: path name: vector_store_id required: true schema: type: string description: The ID of the vector store that the file batch belongs to. - in: path name: batch_id required: true schema: type: string description: The ID of the file batch to cancel. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreFileBatchObject' x-oaiMeta: name: Cancel vector store file batch group: vector_stores returns: The modified vector store file batch object. examples: response: | { "id": "vsfb_abc123", "object": "vector_store.file_batch", "created_at": 1699061776, "vector_store_id": "vs_abc123", "status": "in_progress", "file_counts": { "in_progress": 12, "completed": 3, "failed": 0, "cancelled": 0, "total": 15, } } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/cancel \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -X POST python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_file_batch = client.vector_stores.file_batches.cancel( batch_id="batch_id", vector_store_id="vector_store_id", ) print(vector_store_file_batch.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreFileBatch = await client.vectorStores.fileBatches.cancel('batch_id', { vector_store_id: 'vector_store_id', }); console.log(vectorStoreFileBatch.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreFileBatch, err := client.VectorStores.FileBatches.Cancel( context.TODO(), "vector_store_id", "batch_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreFileBatch.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.filebatches.FileBatchCancelParams; import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileBatchCancelParams params = FileBatchCancelParams.builder() .vectorStoreId("vector_store_id") .batchId("batch_id") .build(); VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().cancel(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_file_batch = openai.vector_stores.file_batches.cancel("batch_id", vector_store_id: "vector_store_id") puts(vector_store_file_batch) description: >- Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. /vector_stores/{vector_store_id}/file_batches/{batch_id}/files: get: operationId: listFilesInVectorStoreBatch tags: - Vector stores summary: List vector store files in a batch parameters: - name: vector_store_id in: path description: The ID of the vector store that the files belong to. required: true schema: type: string - name: batch_id in: path description: The ID of the file batch that the files belong to. required: true schema: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string - name: filter in: query description: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. schema: type: string enum: - in_progress - completed - failed - cancelled responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListVectorStoreFilesResponse' x-oaiMeta: name: List vector store files in a batch group: vector_stores returns: >- A list of [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects. examples: response: | { "object": "list", "data": [ { "id": "file-abc123", "object": "vector_store.file", "created_at": 1699061776, "vector_store_id": "vs_abc123" }, { "id": "file-abc456", "object": "vector_store.file", "created_at": 1699061776, "vector_store_id": "vs_abc123" } ], "first_id": "file-abc123", "last_id": "file-abc456", "has_more": false } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/files \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.vector_stores.file_batches.list_files( batch_id="batch_id", vector_store_id="vector_store_id", ) page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const vectorStoreFile of client.vectorStores.fileBatches.listFiles('batch_id', { vector_store_id: 'vector_store_id', })) { console.log(vectorStoreFile.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.VectorStores.FileBatches.ListFiles( context.TODO(), "vector_store_id", "batch_id", openai.VectorStoreFileBatchListFilesParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.filebatches.FileBatchListFilesPage; import com.openai.models.vectorstores.filebatches.FileBatchListFilesParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileBatchListFilesParams params = FileBatchListFilesParams.builder() .vectorStoreId("vector_store_id") .batchId("batch_id") .build(); FileBatchListFilesPage page = client.vectorStores().fileBatches().listFiles(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.vector_stores.file_batches.list_files("batch_id", vector_store_id: "vector_store_id") puts(page) description: Returns a list of vector store files in a batch. /vector_stores/{vector_store_id}/files: get: operationId: listVectorStoreFiles tags: - Vector stores summary: List vector store files parameters: - name: vector_store_id in: path description: The ID of the vector store that the files belong to. required: true schema: type: string - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string - name: filter in: query description: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. schema: type: string enum: - in_progress - completed - failed - cancelled responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/ListVectorStoreFilesResponse' x-oaiMeta: name: List vector store files group: vector_stores returns: >- A list of [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects. examples: response: | { "object": "list", "data": [ { "id": "file-abc123", "object": "vector_store.file", "created_at": 1699061776, "vector_store_id": "vs_abc123" }, { "id": "file-abc456", "object": "vector_store.file", "created_at": 1699061776, "vector_store_id": "vs_abc123" } ], "first_id": "file-abc123", "last_id": "file-abc456", "has_more": false } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.vector_stores.files.list( vector_store_id="vector_store_id", ) page = page.data[0] print(page.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const vectorStoreFile of client.vectorStores.files.list('vector_store_id')) { console.log(vectorStoreFile.id); } go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.VectorStores.Files.List( context.TODO(), "vector_store_id", openai.VectorStoreFileListParams{ }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.files.FileListPage; import com.openai.models.vectorstores.files.FileListParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileListPage page = client.vectorStores().files().list("vector_store_id"); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.vector_stores.files.list("vector_store_id") puts(page) description: Returns a list of vector store files. post: operationId: createVectorStoreFile tags: - Vector stores summary: Create vector store file parameters: - in: path name: vector_store_id required: true schema: type: string example: vs_abc123 description: | The ID of the vector store for which to create a File. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateVectorStoreFileRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreFileObject' x-oaiMeta: name: Create vector store file group: vector_stores returns: >- A [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object. examples: response: | { "id": "file-abc123", "object": "vector_store.file", "created_at": 1699061776, "usage_bytes": 1234, "vector_store_id": "vs_abcd", "status": "completed", "last_error": null } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "file_id": "file-abc123" }' python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_file = client.vector_stores.files.create( vector_store_id="vs_abc123", file_id="file_id", ) print(vector_store_file.id) node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreFile = await client.vectorStores.files.create('vs_abc123', { file_id: 'file_id' }); console.log(vectorStoreFile.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreFile, err := client.VectorStores.Files.New( context.TODO(), "vs_abc123", openai.VectorStoreFileNewParams{ FileID: "file_id", }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreFile.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.files.FileCreateParams; import com.openai.models.vectorstores.files.VectorStoreFile; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileCreateParams params = FileCreateParams.builder() .vectorStoreId("vs_abc123") .fileId("file_id") .build(); VectorStoreFile vectorStoreFile = client.vectorStores().files().create(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_file = openai.vector_stores.files.create("vs_abc123", file_id: "file_id") puts(vector_store_file) description: >- Create a vector store file by attaching a [File](https://platform.openai.com/docs/api-reference/files) to a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). /vector_stores/{vector_store_id}/files/{file_id}: get: operationId: getVectorStoreFile tags: - Vector stores summary: Retrieve vector store file parameters: - in: path name: vector_store_id required: true schema: type: string example: vs_abc123 description: The ID of the vector store that the file belongs to. - in: path name: file_id required: true schema: type: string example: file-abc123 description: The ID of the file being retrieved. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreFileObject' x-oaiMeta: name: Retrieve vector store file group: vector_stores returns: >- The [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object. examples: response: | { "id": "file-abc123", "object": "vector_store.file", "created_at": 1699061776, "vector_store_id": "vs_abcd", "status": "completed", "last_error": null } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_file = client.vector_stores.files.retrieve( file_id="file-abc123", vector_store_id="vs_abc123", ) print(vector_store_file.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreFile = await client.vectorStores.files.retrieve('file-abc123', { vector_store_id: 'vs_abc123', }); console.log(vectorStoreFile.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreFile, err := client.VectorStores.Files.Get( context.TODO(), "vs_abc123", "file-abc123", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreFile.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.files.FileRetrieveParams; import com.openai.models.vectorstores.files.VectorStoreFile; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileRetrieveParams params = FileRetrieveParams.builder() .vectorStoreId("vs_abc123") .fileId("file-abc123") .build(); VectorStoreFile vectorStoreFile = client.vectorStores().files().retrieve(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_file = openai.vector_stores.files.retrieve("file-abc123", vector_store_id: "vs_abc123") puts(vector_store_file) description: Retrieves a vector store file. delete: operationId: deleteVectorStoreFile tags: - Vector stores summary: Delete vector store file parameters: - in: path name: vector_store_id required: true schema: type: string description: The ID of the vector store that the file belongs to. - in: path name: file_id required: true schema: type: string description: The ID of the file to delete. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DeleteVectorStoreFileResponse' x-oaiMeta: name: Delete vector store file group: vector_stores returns: Deletion status examples: response: | { id: "file-abc123", object: "vector_store.file.deleted", deleted: true } request: curl: | curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -H "OpenAI-Beta: assistants=v2" \ -X DELETE python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_file_deleted = client.vector_stores.files.delete( file_id="file_id", vector_store_id="vector_store_id", ) print(vector_store_file_deleted.id) node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreFileDeleted = await client.vectorStores.files.delete('file_id', { vector_store_id: 'vector_store_id', }); console.log(vectorStoreFileDeleted.id); go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreFileDeleted, err := client.VectorStores.Files.Delete( context.TODO(), "vector_store_id", "file_id", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreFileDeleted.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.files.FileDeleteParams; import com.openai.models.vectorstores.files.VectorStoreFileDeleted; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileDeleteParams params = FileDeleteParams.builder() .vectorStoreId("vector_store_id") .fileId("file_id") .build(); VectorStoreFileDeleted vectorStoreFileDeleted = client.vectorStores().files().delete(params); } } ruby: >- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_file_deleted = openai.vector_stores.files.delete("file_id", vector_store_id: "vector_store_id") puts(vector_store_file_deleted) description: >- Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](https://platform.openai.com/docs/api-reference/files/delete) endpoint. post: operationId: updateVectorStoreFileAttributes tags: - Vector stores summary: Update vector store file attributes parameters: - in: path name: vector_store_id required: true schema: type: string example: vs_abc123 description: The ID of the vector store the file belongs to. - in: path name: file_id required: true schema: type: string example: file-abc123 description: The ID of the file to update attributes. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/UpdateVectorStoreFileAttributesRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreFileObject' x-oaiMeta: name: Update vector store file attributes group: vector_stores returns: >- The updated [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object. examples: response: | { "id": "file-abc123", "object": "vector_store.file", "usage_bytes": 1234, "created_at": 1699061776, "vector_store_id": "vs_abcd", "status": "completed", "last_error": null, "chunking_strategy": {...}, "attributes": {"key1": "value1", "key2": 2} } request: curl: | curl https://api.openai.com/v1/vector_stores/{vector_store_id}/files/{file_id} \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"attributes": {"key1": "value1", "key2": 2}}' node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); const vectorStoreFile = await client.vectorStores.files.update('file-abc123', { vector_store_id: 'vs_abc123', attributes: { foo: 'string' }, }); console.log(vectorStoreFile.id); python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) vector_store_file = client.vector_stores.files.update( file_id="file-abc123", vector_store_id="vs_abc123", attributes={ "foo": "string" }, ) print(vector_store_file.id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) vectorStoreFile, err := client.VectorStores.Files.Update( context.TODO(), "vs_abc123", "file-abc123", openai.VectorStoreFileUpdateParams{ Attributes: map[string]openai.VectorStoreFileUpdateParamsAttributeUnion{ "foo": openai.VectorStoreFileUpdateParamsAttributeUnion{ OfString: openai.String("string"), }, }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", vectorStoreFile.ID) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.JsonValue; import com.openai.models.vectorstores.files.FileUpdateParams; import com.openai.models.vectorstores.files.VectorStoreFile; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileUpdateParams params = FileUpdateParams.builder() .vectorStoreId("vs_abc123") .fileId("file-abc123") .attributes(FileUpdateParams.Attributes.builder() .putAdditionalProperty("foo", JsonValue.from("string")) .build()) .build(); VectorStoreFile vectorStoreFile = client.vectorStores().files().update(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") vector_store_file = openai.vector_stores.files.update( "file-abc123", vector_store_id: "vs_abc123", attributes: {foo: "string"} ) puts(vector_store_file) description: Update attributes on a vector store file. /vector_stores/{vector_store_id}/files/{file_id}/content: get: operationId: retrieveVectorStoreFileContent tags: - Vector stores summary: Retrieve vector store file content parameters: - in: path name: vector_store_id required: true schema: type: string example: vs_abc123 description: The ID of the vector store. - in: path name: file_id required: true schema: type: string example: file-abc123 description: The ID of the file within the vector store. responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreFileContentResponse' x-oaiMeta: name: Retrieve vector store file content group: vector_stores returns: The parsed contents of the specified vector store file. examples: response: | { "file_id": "file-abc123", "filename": "example.txt", "attributes": {"key": "value"}, "content": [ {"type": "text", "text": "..."}, ... ] } request: curl: | curl \ https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123/content \ -H "Authorization: Bearer $OPENAI_API_KEY" node.js: |- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const fileContentResponse of client.vectorStores.files.content('file-abc123', { vector_store_id: 'vs_abc123', })) { console.log(fileContentResponse.text); } python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.vector_stores.files.content( file_id="file-abc123", vector_store_id="vs_abc123", ) page = page.data[0] print(page.text) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.VectorStores.Files.Content( context.TODO(), "vs_abc123", "file-abc123", ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.files.FileContentPage; import com.openai.models.vectorstores.files.FileContentParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); FileContentParams params = FileContentParams.builder() .vectorStoreId("vs_abc123") .fileId("file-abc123") .build(); FileContentPage page = client.vectorStores().files().content(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.vector_stores.files.content("file-abc123", vector_store_id: "vs_abc123") puts(page) description: Retrieve the parsed contents of a vector store file. /vector_stores/{vector_store_id}/search: post: operationId: searchVectorStore tags: - Vector stores summary: Search vector store parameters: - in: path name: vector_store_id required: true schema: type: string example: vs_abc123 description: The ID of the vector store to search. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/VectorStoreSearchRequest' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/VectorStoreSearchResultsPage' x-oaiMeta: name: Search vector store group: vector_stores returns: A page of search results from the vector store. examples: response: | { "object": "vector_store.search_results.page", "search_query": "What is the return policy?", "data": [ { "file_id": "file_123", "filename": "document.pdf", "score": 0.95, "attributes": { "author": "John Doe", "date": "2023-01-01" }, "content": [ { "type": "text", "text": "Relevant chunk" } ] }, { "file_id": "file_456", "filename": "notes.txt", "score": 0.89, "attributes": { "author": "Jane Smith", "date": "2023-01-02" }, "content": [ { "type": "text", "text": "Sample text content from the vector store." } ] } ], "has_more": false, "next_page": null } request: curl: | curl -X POST \ https://api.openai.com/v1/vector_stores/vs_abc123/search \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"query": "What is the return policy?", "filters": {...}}' node.js: >- import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'My API Key', }); // Automatically fetches more pages as needed. for await (const vectorStoreSearchResponse of client.vectorStores.search('vs_abc123', { query: 'string' })) { console.log(vectorStoreSearchResponse.file_id); } python: |- from openai import OpenAI client = OpenAI( api_key="My API Key", ) page = client.vector_stores.search( vector_store_id="vs_abc123", query="string", ) page = page.data[0] print(page.file_id) go: | package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("My API Key"), ) page, err := client.VectorStores.Search( context.TODO(), "vs_abc123", openai.VectorStoreSearchParams{ Query: openai.VectorStoreSearchParamsQueryUnion{ OfString: openai.String("string"), }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } java: |- package com.openai.example; import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.vectorstores.VectorStoreSearchPage; import com.openai.models.vectorstores.VectorStoreSearchParams; public final class Main { private Main() {} public static void main(String[] args) { OpenAIClient client = OpenAIOkHttpClient.fromEnv(); VectorStoreSearchParams params = VectorStoreSearchParams.builder() .vectorStoreId("vs_abc123") .query("string") .build(); VectorStoreSearchPage page = client.vectorStores().search(params); } } ruby: |- require "openai" openai = OpenAI::Client.new(api_key: "My API Key") page = openai.vector_stores.search("vs_abc123", query: "string") puts(page) description: Search a vector store for relevant chunks based on a query and file attributes filter. webhooks: batch_cancelled: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookBatchCancelled' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. batch_completed: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookBatchCompleted' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. batch_expired: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookBatchExpired' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. batch_failed: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookBatchFailed' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. eval_run_canceled: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookEvalRunCanceled' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. eval_run_failed: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookEvalRunFailed' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. eval_run_succeeded: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookEvalRunSucceeded' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. fine_tuning_job_cancelled: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookFineTuningJobCancelled' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. fine_tuning_job_failed: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookFineTuningJobFailed' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. fine_tuning_job_succeeded: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookFineTuningJobSucceeded' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. response_cancelled: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookResponseCancelled' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. response_completed: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookResponseCompleted' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. response_failed: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookResponseFailed' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. response_incomplete: post: requestBody: description: The event payload sent by the API. content: application/json: schema: $ref: '#/components/schemas/WebhookResponseIncomplete' responses: '200': description: | Return a 200 status code to acknowledge receipt of the event. Non-200 status codes will be retried. components: schemas: AddUploadPartRequest: type: object additionalProperties: false properties: data: description: | The chunk of bytes for this Part. type: string format: binary required: - data AdminApiKey: type: object description: Represents an individual Admin API key in an org. properties: object: type: string example: organization.admin_api_key description: The object type, which is always `organization.admin_api_key` x-stainless-const: true id: type: string example: key_abc description: The identifier, which can be referenced in API endpoints name: type: string example: Administration Key description: The name of the API key redacted_value: type: string example: sk-admin...def description: The redacted value of the API key value: type: string example: sk-admin-1234abcd description: The value of the API key. Only shown on create. created_at: type: integer format: int64 example: 1711471533 description: The Unix timestamp (in seconds) of when the API key was created last_used_at: type: integer format: int64 nullable: true example: 1711471534 description: The Unix timestamp (in seconds) of when the API key was last used owner: type: object properties: type: type: string example: user description: Always `user` object: type: string example: organization.user description: The object type, which is always organization.user id: type: string example: sa_456 description: The identifier, which can be referenced in API endpoints name: type: string example: My Service Account description: The name of the user created_at: type: integer format: int64 example: 1711471533 description: The Unix timestamp (in seconds) of when the user was created role: type: string example: owner description: Always `owner` required: - object - redacted_value - name - created_at - last_used_at - id - owner x-oaiMeta: name: The admin API key object example: | { "object": "organization.admin_api_key", "id": "key_abc", "name": "Main Admin Key", "redacted_value": "sk-admin...xyz", "created_at": 1711471533, "last_used_at": 1711471534, "owner": { "type": "user", "object": "organization.user", "id": "user_123", "name": "John Doe", "created_at": 1711471533, "role": "owner" } } ApiKeyList: type: object properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/AdminApiKey' has_more: type: boolean example: false first_id: type: string example: key_abc last_id: type: string example: key_xyz AssistantObject: type: object title: Assistant description: Represents an `assistant` that can call the model and use tools. properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: description: The object type, which is always `assistant`. type: string enum: - assistant x-stainless-const: true created_at: description: The Unix timestamp (in seconds) for when the assistant was created. type: integer name: description: | The name of the assistant. The maximum length is 256 characters. type: string maxLength: 256 nullable: true description: description: | The description of the assistant. The maximum length is 512 characters. type: string maxLength: 512 nullable: true model: description: > ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. type: string instructions: description: | The system instructions that the assistant uses. The maximum length is 256,000 characters. type: string maxLength: 256000 nullable: true tools: description: > A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. default: [] type: array maxItems: 128 items: $ref: '#/components/schemas/AssistantTool' tool_resources: type: object description: > A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. maxItems: 1 items: type: string nullable: true metadata: $ref: '#/components/schemas/Metadata' temperature: description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true required: - id - object - created_at - name - description - model - instructions - tools - metadata x-oaiMeta: name: The assistant object beta: true example: | { "id": "asst_abc123", "object": "assistant", "created_at": 1698984975, "name": "Math Tutor", "description": null, "model": "gpt-4o", "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", "tools": [ { "type": "code_interpreter" } ], "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } AssistantStreamEvent: description: > Represents an event emitted when streaming a Run. Each event in a server-sent events stream has an `event` and `data` property: ``` event: thread.created data: {"id": "thread_123", "object": "thread", ...} ``` We emit events whenever a new object is created, transitions to a new state, or is being streamed in parts (deltas). For example, we emit `thread.run.created` when a new run is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses to create a message during a run, we emit a `thread.message.created event`, a `thread.message.in_progress` event, many `thread.message.delta` events, and finally a `thread.message.completed` event. We may add additional events over time, so we recommend handling unknown events gracefully in your code. See the [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) to learn how to integrate the Assistants API with streaming. x-oaiMeta: name: Assistant stream events beta: true anyOf: - $ref: '#/components/schemas/ThreadStreamEvent' - $ref: '#/components/schemas/RunStreamEvent' - $ref: '#/components/schemas/RunStepStreamEvent' - $ref: '#/components/schemas/MessageStreamEvent' - $ref: '#/components/schemas/ErrorEvent' x-stainless-variantName: error_event discriminator: propertyName: event AssistantSupportedModels: type: string enum: - gpt-5 - gpt-5-mini - gpt-5-nano - gpt-5-2025-08-07 - gpt-5-mini-2025-08-07 - gpt-5-nano-2025-08-07 - gpt-4.1 - gpt-4.1-mini - gpt-4.1-nano - gpt-4.1-2025-04-14 - gpt-4.1-mini-2025-04-14 - gpt-4.1-nano-2025-04-14 - o3-mini - o3-mini-2025-01-31 - o1 - o1-2024-12-17 - gpt-4o - gpt-4o-2024-11-20 - gpt-4o-2024-08-06 - gpt-4o-2024-05-13 - gpt-4o-mini - gpt-4o-mini-2024-07-18 - gpt-4.5-preview - gpt-4.5-preview-2025-02-27 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview - gpt-4-turbo-preview - gpt-4-1106-preview - gpt-4-vision-preview - gpt-4 - gpt-4-0314 - gpt-4-0613 - gpt-4-32k - gpt-4-32k-0314 - gpt-4-32k-0613 - gpt-3.5-turbo - gpt-3.5-turbo-16k - gpt-3.5-turbo-0613 - gpt-3.5-turbo-1106 - gpt-3.5-turbo-0125 - gpt-3.5-turbo-16k-0613 AssistantToolsCode: type: object title: Code interpreter tool properties: type: type: string description: 'The type of tool being defined: `code_interpreter`' enum: - code_interpreter x-stainless-const: true required: - type AssistantToolsFileSearch: type: object title: FileSearch tool properties: type: type: string description: 'The type of tool being defined: `file_search`' enum: - file_search x-stainless-const: true file_search: type: object description: Overrides for the file search tool. properties: max_num_results: type: integer minimum: 1 maximum: 50 description: > The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive. Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. ranking_options: $ref: '#/components/schemas/FileSearchRankingOptions' required: - type AssistantToolsFileSearchTypeOnly: type: object title: FileSearch tool properties: type: type: string description: 'The type of tool being defined: `file_search`' enum: - file_search x-stainless-const: true required: - type AssistantToolsFunction: type: object title: Function tool properties: type: type: string description: 'The type of tool being defined: `function`' enum: - function x-stainless-const: true function: $ref: '#/components/schemas/FunctionObject' required: - type - function AssistantsApiResponseFormatOption: description: > Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. anyOf: - type: string description: | `auto` is the default value enum: - auto x-stainless-const: true - $ref: '#/components/schemas/ResponseFormatText' - $ref: '#/components/schemas/ResponseFormatJsonObject' - $ref: '#/components/schemas/ResponseFormatJsonSchema' AssistantsApiToolChoiceOption: description: > Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. anyOf: - type: string description: > `none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user. enum: - none - auto - required title: Auto - $ref: '#/components/schemas/AssistantsNamedToolChoice' AssistantsNamedToolChoice: type: object description: Specifies a tool the model should use. Use to force the model to call a specific tool. properties: type: type: string enum: - function - code_interpreter - file_search description: The type of the tool. If type is `function`, the function name must be set function: type: object properties: name: type: string description: The name of the function to call. required: - name required: - type AudioResponseFormat: description: > The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. type: string enum: - json - text - srt - verbose_json - vtt default: json AuditLog: type: object description: A log of a user action or configuration change within this organization. properties: id: type: string description: The ID of this log. type: $ref: '#/components/schemas/AuditLogEventType' effective_at: type: integer description: The Unix timestamp (in seconds) of the event. project: type: object description: >- The project that the action was scoped to. Absent for actions not scoped to projects. Note that any admin actions taken via Admin API keys are associated with the default project. properties: id: type: string description: The project ID. name: type: string description: The project title. actor: $ref: '#/components/schemas/AuditLogActor' api_key.created: type: object description: The details for events with this `type`. properties: id: type: string description: The tracking ID of the API key. data: type: object description: The payload used to create the API key. properties: scopes: type: array items: type: string description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` api_key.updated: type: object description: The details for events with this `type`. properties: id: type: string description: The tracking ID of the API key. changes_requested: type: object description: The payload used to update the API key. properties: scopes: type: array items: type: string description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` api_key.deleted: type: object description: The details for events with this `type`. properties: id: type: string description: The tracking ID of the API key. checkpoint_permission.created: type: object description: The project and fine-tuned model checkpoint that the checkpoint permission was created for. properties: id: type: string description: The ID of the checkpoint permission. data: type: object description: The payload used to create the checkpoint permission. properties: project_id: type: string description: The ID of the project that the checkpoint permission was created for. fine_tuned_model_checkpoint: type: string description: The ID of the fine-tuned model checkpoint. checkpoint_permission.deleted: type: object description: The details for events with this `type`. properties: id: type: string description: The ID of the checkpoint permission. invite.sent: type: object description: The details for events with this `type`. properties: id: type: string description: The ID of the invite. data: type: object description: The payload used to create the invite. properties: email: type: string description: The email invited to the organization. role: type: string description: The role the email was invited to be. Is either `owner` or `member`. invite.accepted: type: object description: The details for events with this `type`. properties: id: type: string description: The ID of the invite. invite.deleted: type: object description: The details for events with this `type`. properties: id: type: string description: The ID of the invite. login.failed: type: object description: The details for events with this `type`. properties: error_code: type: string description: The error code of the failure. error_message: type: string description: The error message of the failure. logout.failed: type: object description: The details for events with this `type`. properties: error_code: type: string description: The error code of the failure. error_message: type: string description: The error message of the failure. organization.updated: type: object description: The details for events with this `type`. properties: id: type: string description: The organization ID. changes_requested: type: object description: The payload used to update the organization settings. properties: title: type: string description: The organization title. description: type: string description: The organization description. name: type: string description: The organization name. threads_ui_visibility: type: string description: >- Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. usage_dashboard_visibility: type: string description: >- Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`. api_call_logging: type: string description: >- How your organization logs data from supported API calls. One of `disabled`, `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects` api_call_logging_project_ids: type: string description: The list of project ids if api_call_logging is set to `enabled_for_selected_projects` project.created: type: object description: The details for events with this `type`. properties: id: type: string description: The project ID. data: type: object description: The payload used to create the project. properties: name: type: string description: The project name. title: type: string description: The title of the project as seen on the dashboard. project.updated: type: object description: The details for events with this `type`. properties: id: type: string description: The project ID. changes_requested: type: object description: The payload used to update the project. properties: title: type: string description: The title of the project as seen on the dashboard. project.archived: type: object description: The details for events with this `type`. properties: id: type: string description: The project ID. rate_limit.updated: type: object description: The details for events with this `type`. properties: id: type: string description: The rate limit ID changes_requested: type: object description: The payload used to update the rate limits. properties: max_requests_per_1_minute: type: integer description: The maximum requests per minute. max_tokens_per_1_minute: type: integer description: The maximum tokens per minute. max_images_per_1_minute: type: integer description: The maximum images per minute. Only relevant for certain models. max_audio_megabytes_per_1_minute: type: integer description: The maximum audio megabytes per minute. Only relevant for certain models. max_requests_per_1_day: type: integer description: The maximum requests per day. Only relevant for certain models. batch_1_day_max_input_tokens: type: integer description: The maximum batch input tokens per day. Only relevant for certain models. rate_limit.deleted: type: object description: The details for events with this `type`. properties: id: type: string description: The rate limit ID service_account.created: type: object description: The details for events with this `type`. properties: id: type: string description: The service account ID. data: type: object description: The payload used to create the service account. properties: role: type: string description: The role of the service account. Is either `owner` or `member`. service_account.updated: type: object description: The details for events with this `type`. properties: id: type: string description: The service account ID. changes_requested: type: object description: The payload used to updated the service account. properties: role: type: string description: The role of the service account. Is either `owner` or `member`. service_account.deleted: type: object description: The details for events with this `type`. properties: id: type: string description: The service account ID. user.added: type: object description: The details for events with this `type`. properties: id: type: string description: The user ID. data: type: object description: The payload used to add the user to the project. properties: role: type: string description: The role of the user. Is either `owner` or `member`. user.updated: type: object description: The details for events with this `type`. properties: id: type: string description: The project ID. changes_requested: type: object description: The payload used to update the user. properties: role: type: string description: The role of the user. Is either `owner` or `member`. user.deleted: type: object description: The details for events with this `type`. properties: id: type: string description: The user ID. certificate.created: type: object description: The details for events with this `type`. properties: id: type: string description: The certificate ID. name: type: string description: The name of the certificate. certificate.updated: type: object description: The details for events with this `type`. properties: id: type: string description: The certificate ID. name: type: string description: The name of the certificate. certificate.deleted: type: object description: The details for events with this `type`. properties: id: type: string description: The certificate ID. name: type: string description: The name of the certificate. certificate: type: string description: The certificate content in PEM format. certificates.activated: type: object description: The details for events with this `type`. properties: certificates: type: array items: type: object properties: id: type: string description: The certificate ID. name: type: string description: The name of the certificate. certificates.deactivated: type: object description: The details for events with this `type`. properties: certificates: type: array items: type: object properties: id: type: string description: The certificate ID. name: type: string description: The name of the certificate. required: - id - type - effective_at - actor x-oaiMeta: name: The audit log object example: | { "id": "req_xxx_20240101", "type": "api_key.created", "effective_at": 1720804090, "actor": { "type": "session", "session": { "user": { "id": "user-xxx", "email": "user@example.com" }, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } }, "api_key.created": { "id": "key_xxxx", "data": { "scopes": ["resource.operation"] } } } AuditLogActor: type: object description: The actor who performed the audit logged action. properties: type: type: string description: The type of actor. Is either `session` or `api_key`. enum: - session - api_key session: $ref: '#/components/schemas/AuditLogActorSession' api_key: $ref: '#/components/schemas/AuditLogActorApiKey' AuditLogActorApiKey: type: object description: The API Key used to perform the audit logged action. properties: id: type: string description: The tracking id of the API key. type: type: string description: The type of API key. Can be either `user` or `service_account`. enum: - user - service_account user: $ref: '#/components/schemas/AuditLogActorUser' service_account: $ref: '#/components/schemas/AuditLogActorServiceAccount' AuditLogActorServiceAccount: type: object description: The service account that performed the audit logged action. properties: id: type: string description: The service account id. AuditLogActorSession: type: object description: The session in which the audit logged action was performed. properties: user: $ref: '#/components/schemas/AuditLogActorUser' ip_address: type: string description: The IP address from which the action was performed. AuditLogActorUser: type: object description: The user who performed the audit logged action. properties: id: type: string description: The user id. email: type: string description: The user email. AuditLogEventType: type: string description: The event type. enum: - api_key.created - api_key.updated - api_key.deleted - checkpoint_permission.created - checkpoint_permission.deleted - invite.sent - invite.accepted - invite.deleted - login.succeeded - login.failed - logout.succeeded - logout.failed - organization.updated - project.created - project.updated - project.archived - service_account.created - service_account.updated - service_account.deleted - rate_limit.updated - rate_limit.deleted - user.added - user.updated - user.deleted AutoChunkingStrategyRequestParam: type: object title: Auto Chunking Strategy description: >- The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. additionalProperties: false properties: type: type: string description: Always `auto`. enum: - auto x-stainless-const: true required: - type Batch: type: object properties: id: type: string object: type: string enum: - batch description: The object type, which is always `batch`. x-stainless-const: true endpoint: type: string description: The OpenAI API endpoint used by the batch. errors: type: object properties: object: type: string description: The object type, which is always `list`. data: type: array items: $ref: '#/components/schemas/BatchError' input_file_id: type: string description: The ID of the input file for the batch. completion_window: type: string description: The time frame within which the batch should be processed. status: type: string description: The current status of the batch. enum: - validating - failed - in_progress - finalizing - completed - expired - cancelling - cancelled output_file_id: type: string description: The ID of the file containing the outputs of successfully executed requests. error_file_id: type: string description: The ID of the file containing the outputs of requests with errors. created_at: type: integer description: The Unix timestamp (in seconds) for when the batch was created. in_progress_at: type: integer description: The Unix timestamp (in seconds) for when the batch started processing. expires_at: type: integer description: The Unix timestamp (in seconds) for when the batch will expire. finalizing_at: type: integer description: The Unix timestamp (in seconds) for when the batch started finalizing. completed_at: type: integer description: The Unix timestamp (in seconds) for when the batch was completed. failed_at: type: integer description: The Unix timestamp (in seconds) for when the batch failed. expired_at: type: integer description: The Unix timestamp (in seconds) for when the batch expired. cancelling_at: type: integer description: The Unix timestamp (in seconds) for when the batch started cancelling. cancelled_at: type: integer description: The Unix timestamp (in seconds) for when the batch was cancelled. request_counts: $ref: '#/components/schemas/BatchRequestCounts' metadata: $ref: '#/components/schemas/Metadata' required: - id - object - endpoint - input_file_id - completion_window - status - created_at x-oaiMeta: name: The batch object example: | { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "completed", "output_file_id": "file-cvaTdG", "error_file_id": "file-HOWS94", "created_at": 1711471533, "in_progress_at": 1711471538, "expires_at": 1711557933, "finalizing_at": 1711493133, "completed_at": 1711493163, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 100, "completed": 95, "failed": 5 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly eval job", } } BatchFileExpirationAfter: type: object title: File expiration policy description: The expiration policy for the output and/or error file that are generated for a batch. properties: anchor: description: >- Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created. type: string enum: - created_at x-stainless-const: true seconds: description: >- The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days). type: integer minimum: 3600 maximum: 2592000 required: - anchor - seconds BatchRequestInput: type: object description: The per-line object of the batch input file properties: custom_id: type: string description: >- A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch. method: type: string enum: - POST description: The HTTP method to be used for the request. Currently only `POST` is supported. x-stainless-const: true url: type: string description: >- The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. x-oaiMeta: name: The request input object example: > {"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is 2+2?"}]}} BatchRequestOutput: type: object description: The per-line object of the batch output and error files properties: id: type: string custom_id: type: string description: A developer-provided per-request id that will be used to match outputs to inputs. response: type: object nullable: true properties: status_code: type: integer description: The HTTP status code of the response request_id: type: string description: >- An unique identifier for the OpenAI API request. Please include this request ID when contacting support. body: type: object x-oaiTypeLabel: map description: The JSON body of the response error: type: object nullable: true description: >- For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure. properties: code: type: string description: A machine-readable error code. message: type: string description: A human-readable error message. x-oaiMeta: name: The request output object example: > {"id": "batch_req_wnaDys", "custom_id": "request-2", "response": {"status_code": 200, "request_id": "req_c187b3", "body": {"id": "chatcmpl-9758Iw", "object": "chat.completion", "created": 1711475054, "model": "gpt-4o-mini", "choices": [{"index": 0, "message": {"role": "assistant", "content": "2 + 2 equals 4."}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 24, "completion_tokens": 15, "total_tokens": 39}, "system_fingerprint": null}}, "error": null} Certificate: type: object description: Represents an individual `certificate` uploaded to the organization. properties: object: type: string enum: - certificate - organization.certificate - organization.project.certificate description: > The object type. - If creating, updating, or getting a specific certificate, the object type is `certificate`. - If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`. - If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`. x-stainless-const: true id: type: string description: The identifier, which can be referenced in API endpoints name: type: string description: The name of the certificate. created_at: type: integer description: The Unix timestamp (in seconds) of when the certificate was uploaded. certificate_details: type: object properties: valid_at: type: integer description: The Unix timestamp (in seconds) of when the certificate becomes valid. expires_at: type: integer description: The Unix timestamp (in seconds) of when the certificate expires. content: type: string description: The content of the certificate in PEM format. active: type: boolean description: >- Whether the certificate is currently active at the specified scope. Not returned when getting details for a specific certificate. required: - object - id - name - created_at - certificate_details x-oaiMeta: name: The certificate object example: | { "object": "certificate", "id": "cert_abc", "name": "My Certificate", "created_at": 1234567, "certificate_details": { "valid_at": 1234567, "expires_at": 12345678, "content": "-----BEGIN CERTIFICATE----- MIIGAjCCA...6znFlOW+ -----END CERTIFICATE-----" } } ChatCompletionAllowedTools: type: object title: Allowed tools description: | Constrains the tools available to the model to a pre-defined set. properties: mode: type: string enum: - auto - required description: | Constrains the tools available to the model to a pre-defined set. `auto` allows the model to pick from among the allowed tools and generate a message. `required` requires the model to call one or more of the allowed tools. tools: type: array description: | A list of tool definitions that the model should be allowed to call. For the Chat Completions API, the list of tool definitions might look like: ```json [ { "type": "function", "function": { "name": "get_weather" } }, { "type": "function", "function": { "name": "get_time" } } ] ``` items: type: object x-oaiExpandable: false description: | A tool definition that the model should be allowed to call. additionalProperties: true required: - mode - tools ChatCompletionAllowedToolsChoice: type: object title: Allowed tools description: | Constrains the tools available to the model to a pre-defined set. properties: type: type: string enum: - allowed_tools description: Allowed tool configuration type. Always `allowed_tools`. x-stainless-const: true allowed_tools: $ref: '#/components/schemas/ChatCompletionAllowedTools' required: - type - allowed_tools ChatCompletionDeleted: type: object properties: object: type: string description: The type of object being deleted. enum: - chat.completion.deleted x-stainless-const: true id: type: string description: The ID of the chat completion that was deleted. deleted: type: boolean description: Whether the chat completion was deleted. required: - object - id - deleted ChatCompletionFunctionCallOption: type: object description: | Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. properties: name: type: string description: The name of the function to call. required: - name x-stainless-variantName: function_call_option ChatCompletionFunctions: type: object deprecated: true properties: description: type: string description: >- A description of what the function does, used by the model to choose when and how to call the function. name: type: string description: >- The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. parameters: $ref: '#/components/schemas/FunctionParameters' required: - name ChatCompletionList: type: object title: ChatCompletionList description: | An object representing a list of Chat Completions. properties: object: type: string enum: - list default: list description: | The type of this object. It is always set to "list". x-stainless-const: true data: type: array description: | An array of chat completion objects. items: $ref: '#/components/schemas/CreateChatCompletionResponse' first_id: type: string description: The identifier of the first chat completion in the data array. last_id: type: string description: The identifier of the last chat completion in the data array. has_more: type: boolean description: Indicates whether there are more Chat Completions available. required: - object - data - first_id - last_id - has_more x-oaiMeta: name: The chat completion list object group: chat example: | { "object": "list", "data": [ { "object": "chat.completion", "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "model": "gpt-4o-2024-08-06", "created": 1738960610, "request_id": "req_ded8ab984ec4bf840f37566c1011c417", "tool_choice": null, "usage": { "total_tokens": 31, "completion_tokens": 18, "prompt_tokens": 13 }, "seed": 4944116822809979520, "top_p": 1.0, "temperature": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, "system_fingerprint": "fp_50cad350e4", "input_user": null, "service_tier": "default", "tools": null, "metadata": {}, "choices": [ { "index": 0, "message": { "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", "role": "assistant", "tool_calls": null, "function_call": null }, "finish_reason": "stop", "logprobs": null } ], "response_format": null } ], "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "has_more": false } ChatCompletionMessageCustomToolCall: type: object title: Custom tool call description: | A call to a custom tool created by the model. properties: id: type: string description: The ID of the tool call. type: type: string enum: - custom description: The type of the tool. Always `custom`. x-stainless-const: true custom: type: object description: The custom tool that the model called. properties: name: type: string description: The name of the custom tool to call. input: type: string description: The input for the custom tool call generated by the model. required: - name - input required: - id - type - custom ChatCompletionMessageList: type: object title: ChatCompletionMessageList description: | An object representing a list of chat completion messages. properties: object: type: string enum: - list default: list description: | The type of this object. It is always set to "list". x-stainless-const: true data: type: array description: | An array of chat completion message objects. items: allOf: - $ref: '#/components/schemas/ChatCompletionResponseMessage' - type: object required: - id properties: id: type: string description: The identifier of the chat message. content_parts: type: array nullable: true description: > If a content parts array was provided, this is an array of `text` and `image_url` parts. Otherwise, null. items: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartImage' first_id: type: string description: The identifier of the first chat message in the data array. last_id: type: string description: The identifier of the last chat message in the data array. has_more: type: boolean description: Indicates whether there are more chat messages available. required: - object - data - first_id - last_id - has_more x-oaiMeta: name: The chat completion message list object group: chat example: | { "object": "list", "data": [ { "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "role": "user", "content": "write a haiku about ai", "name": null, "content_parts": null } ], "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "has_more": false } ChatCompletionMessageToolCall: type: object title: Function tool call description: | A call to a function tool created by the model. properties: id: type: string description: The ID of the tool call. type: type: string enum: - function description: The type of the tool. Currently, only `function` is supported. x-stainless-const: true function: type: object description: The function that the model called. properties: name: type: string description: The name of the function to call. arguments: type: string description: >- The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. required: - name - arguments required: - id - type - function ChatCompletionMessageToolCallChunk: type: object properties: index: type: integer id: type: string description: The ID of the tool call. type: type: string enum: - function description: The type of the tool. Currently, only `function` is supported. x-stainless-const: true function: type: object properties: name: type: string description: The name of the function to call. arguments: type: string description: >- The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. required: - index ChatCompletionMessageToolCalls: type: array description: The tool calls generated by the model, such as function calls. items: anyOf: - $ref: '#/components/schemas/ChatCompletionMessageToolCall' - $ref: '#/components/schemas/ChatCompletionMessageCustomToolCall' x-stainless-naming: python: model_name: chat_completion_message_tool_call_union param_model_name: chat_completion_message_tool_call_union_param discriminator: propertyName: type x-stainless-go-variant-constructor: skip ChatCompletionModalities: type: array nullable: true description: > Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default: `["text"]` The `gpt-4o-audio-preview` model can also be used to [generate audio](https://platform.openai.com/docs/guides/audio). To request that this model generate both text and audio responses, you can use: `["text", "audio"]` items: type: string enum: - text - audio ChatCompletionNamedToolChoice: type: object title: Function tool choice description: Specifies a tool the model should use. Use to force the model to call a specific function. properties: type: type: string enum: - function description: For function calling, the type is always `function`. x-stainless-const: true function: type: object properties: name: type: string description: The name of the function to call. required: - name required: - type - function ChatCompletionNamedToolChoiceCustom: type: object title: Custom tool choice description: Specifies a tool the model should use. Use to force the model to call a specific custom tool. properties: type: type: string enum: - custom description: For custom tool calling, the type is always `custom`. x-stainless-const: true custom: type: object properties: name: type: string description: The name of the custom tool to call. required: - name required: - type - custom ChatCompletionRequestAssistantMessage: type: object title: Assistant message description: | Messages sent by the model in response to user messages. properties: content: nullable: true description: > The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. anyOf: - type: string description: The contents of the assistant message. title: Text content - type: array description: >- An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`. title: Array of content parts items: $ref: '#/components/schemas/ChatCompletionRequestAssistantMessageContentPart' minItems: 1 refusal: nullable: true type: string description: The refusal message by the assistant. role: type: string enum: - assistant description: The role of the messages author, in this case `assistant`. x-stainless-const: true name: type: string description: >- An optional name for the participant. Provides the model information to differentiate between participants of the same role. audio: type: object nullable: true description: | Data about a previous audio response from the model. [Learn more](https://platform.openai.com/docs/guides/audio). required: - id properties: id: type: string description: | Unique identifier for a previous audio response from the model. tool_calls: $ref: '#/components/schemas/ChatCompletionMessageToolCalls' function_call: type: object deprecated: true description: >- Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. nullable: true properties: arguments: type: string description: >- The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. name: type: string description: The name of the function to call. required: - arguments - name required: - role x-stainless-soft-required: - content ChatCompletionRequestAssistantMessageContentPart: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' discriminator: propertyName: type ChatCompletionRequestDeveloperMessage: type: object title: Developer message description: | Developer-provided instructions that the model should follow, regardless of messages sent by the user. With o1 models and newer, `developer` messages replace the previous `system` messages. properties: content: description: The contents of the developer message. anyOf: - type: string description: The contents of the developer message. title: Text content - type: array description: >- An array of content parts with a defined type. For developer messages, only type `text` is supported. title: Array of content parts items: $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' minItems: 1 role: type: string enum: - developer description: The role of the messages author, in this case `developer`. x-stainless-const: true name: type: string description: >- An optional name for the participant. Provides the model information to differentiate between participants of the same role. required: - content - role x-stainless-naming: go: variant_constructor: DeveloperMessage ChatCompletionRequestFunctionMessage: type: object title: Function message deprecated: true properties: role: type: string enum: - function description: The role of the messages author, in this case `function`. x-stainless-const: true content: nullable: true type: string description: The contents of the function message. name: type: string description: The name of the function to call. required: - role - content - name ChatCompletionRequestMessage: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestDeveloperMessage' - $ref: '#/components/schemas/ChatCompletionRequestSystemMessage' - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' discriminator: propertyName: role ChatCompletionRequestMessageContentPartAudio: type: object title: Audio content part description: | Learn about [audio inputs](https://platform.openai.com/docs/guides/audio). properties: type: type: string enum: - input_audio description: The type of the content part. Always `input_audio`. x-stainless-const: true input_audio: type: object properties: data: type: string description: Base64 encoded audio data. format: type: string enum: - wav - mp3 description: | The format of the encoded audio data. Currently supports "wav" and "mp3". required: - data - format required: - type - input_audio x-stainless-naming: go: variant_constructor: InputAudioContentPart ChatCompletionRequestMessageContentPartFile: type: object title: File content part description: | Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text generation. properties: type: type: string enum: - file description: The type of the content part. Always `file`. x-stainless-const: true file: type: object properties: filename: type: string description: | The name of the file, used when passing the file to the model as a string. file_data: type: string description: | The base64 encoded file data, used when passing the file to the model as a string. file_id: type: string description: | The ID of an uploaded file to use as input. x-stainless-naming: java: type_name: FileObject kotlin: type_name: FileObject required: - type - file x-stainless-naming: go: variant_constructor: FileContentPart ChatCompletionRequestMessageContentPartImage: type: object title: Image content part description: | Learn about [image inputs](https://platform.openai.com/docs/guides/vision). properties: type: type: string enum: - image_url description: The type of the content part. x-stainless-const: true image_url: type: object properties: url: type: string description: Either a URL of the image or the base64 encoded image data. format: uri detail: type: string description: >- Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). enum: - auto - low - high default: auto required: - url required: - type - image_url x-stainless-naming: go: variant_constructor: ImageContentPart ChatCompletionRequestMessageContentPartRefusal: type: object title: Refusal content part properties: type: type: string enum: - refusal description: The type of the content part. x-stainless-const: true refusal: type: string description: The refusal message generated by the model. required: - type - refusal ChatCompletionRequestMessageContentPartText: type: object title: Text content part description: | Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation). properties: type: type: string enum: - text description: The type of the content part. x-stainless-const: true text: type: string description: The text content. required: - type - text x-stainless-naming: go: variant_constructor: TextContentPart ChatCompletionRequestSystemMessage: type: object title: System message description: | Developer-provided instructions that the model should follow, regardless of messages sent by the user. With o1 models and newer, use `developer` messages for this purpose instead. properties: content: description: The contents of the system message. anyOf: - type: string description: The contents of the system message. title: Text content - type: array description: >- An array of content parts with a defined type. For system messages, only type `text` is supported. title: Array of content parts items: $ref: '#/components/schemas/ChatCompletionRequestSystemMessageContentPart' minItems: 1 role: type: string enum: - system description: The role of the messages author, in this case `system`. x-stainless-const: true name: type: string description: >- An optional name for the participant. Provides the model information to differentiate between participants of the same role. required: - content - role x-stainless-naming: go: variant_constructor: SystemMessage ChatCompletionRequestSystemMessageContentPart: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' ChatCompletionRequestToolMessage: type: object title: Tool message properties: role: type: string enum: - tool description: The role of the messages author, in this case `tool`. x-stainless-const: true content: description: The contents of the tool message. anyOf: - type: string description: The contents of the tool message. title: Text content - type: array description: >- An array of content parts with a defined type. For tool messages, only type `text` is supported. title: Array of content parts items: $ref: '#/components/schemas/ChatCompletionRequestToolMessageContentPart' minItems: 1 tool_call_id: type: string description: Tool call that this message is responding to. required: - role - content - tool_call_id x-stainless-naming: go: variant_constructor: ToolMessage ChatCompletionRequestToolMessageContentPart: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' ChatCompletionRequestUserMessage: type: object title: User message description: | Messages sent by an end user, containing prompts or additional context information. properties: content: description: | The contents of the user message. anyOf: - type: string description: The text contents of the message. title: Text content - type: array description: >- An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text, image, or audio inputs. title: Array of content parts items: $ref: '#/components/schemas/ChatCompletionRequestUserMessageContentPart' minItems: 1 role: type: string enum: - user description: The role of the messages author, in this case `user`. x-stainless-const: true name: type: string description: >- An optional name for the participant. Provides the model information to differentiate between participants of the same role. required: - content - role x-stainless-naming: go: variant_constructor: UserMessage ChatCompletionRequestUserMessageContentPart: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartImage' - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartAudio' - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartFile' discriminator: propertyName: type ChatCompletionResponseMessage: type: object description: A chat completion message generated by the model. properties: content: type: string description: The contents of the message. nullable: true refusal: type: string description: The refusal message generated by the model. nullable: true tool_calls: $ref: '#/components/schemas/ChatCompletionMessageToolCalls' annotations: type: array description: | Annotations for the message, when applicable, as when using the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). items: type: object description: | A URL citation when using web search. required: - type - url_citation properties: type: type: string description: The type of the URL citation. Always `url_citation`. enum: - url_citation x-stainless-const: true url_citation: type: object description: A URL citation when using web search. required: - end_index - start_index - url - title properties: end_index: type: integer description: The index of the last character of the URL citation in the message. start_index: type: integer description: The index of the first character of the URL citation in the message. url: type: string description: The URL of the web resource. title: type: string description: The title of the web resource. role: type: string enum: - assistant description: The role of the author of this message. x-stainless-const: true function_call: type: object deprecated: true description: >- Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. properties: arguments: type: string description: >- The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. name: type: string description: The name of the function to call. required: - name - arguments audio: type: object nullable: true description: > If the audio output modality is requested, this object contains data about the audio response from the model. [Learn more](https://platform.openai.com/docs/guides/audio). required: - id - expires_at - data - transcript properties: id: type: string description: Unique identifier for this audio response. expires_at: type: integer description: | The Unix timestamp (in seconds) for when this audio response will no longer be accessible on the server for use in multi-turn conversations. data: type: string description: | Base64 encoded audio bytes generated by the model, in the format specified in the request. transcript: type: string description: Transcript of the audio generated by the model. required: - role - content - refusal ChatCompletionRole: type: string description: The role of the author of a message enum: - developer - system - user - assistant - tool - function ChatCompletionStreamOptions: description: | Options for streaming response. Only set this when you set `stream: true`. type: object nullable: true default: null properties: include_usage: type: boolean description: | If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. **NOTE:** If the stream is interrupted, you may not receive the final usage chunk which contains the total token usage for the request. include_obfuscation: type: boolean description: | When true, stream obfuscation will be enabled. Stream obfuscation adds random characters to an `obfuscation` field on streaming delta events to normalize payload sizes as a mitigation to certain side-channel attacks. These obfuscation fields are included by default, but add a small amount of overhead to the data stream. You can set `include_obfuscation` to false to optimize for bandwidth if you trust the network links between your application and the OpenAI API. ChatCompletionStreamResponseDelta: type: object description: A chat completion delta generated by streamed model responses. properties: content: type: string description: The contents of the chunk message. nullable: true function_call: deprecated: true type: object description: >- Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. properties: arguments: type: string description: >- The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. name: type: string description: The name of the function to call. tool_calls: type: array items: $ref: '#/components/schemas/ChatCompletionMessageToolCallChunk' role: type: string enum: - developer - system - user - assistant - tool description: The role of the author of this message. refusal: type: string description: The refusal message generated by the model. nullable: true ChatCompletionTokenLogprob: type: object properties: token: description: The token. type: string logprob: description: >- The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. type: number bytes: description: >- A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. type: array items: type: integer nullable: true top_logprobs: description: >- List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. type: array items: type: object properties: token: description: The token. type: string logprob: description: >- The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. type: number bytes: description: >- A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. type: array items: type: integer nullable: true required: - token - logprob - bytes required: - token - logprob - bytes - top_logprobs ChatCompletionTool: type: object title: Function tool description: | A function tool that can be used to generate a response. properties: type: type: string enum: - function description: The type of the tool. Currently, only `function` is supported. x-stainless-const: true function: $ref: '#/components/schemas/FunctionObject' required: - type - function ChatCompletionToolChoiceOption: description: > Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. `none` is the default when no tools are present. `auto` is the default if tools are present. anyOf: - type: string title: Auto description: > `none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools. enum: - none - auto - required - $ref: '#/components/schemas/ChatCompletionAllowedToolsChoice' - $ref: '#/components/schemas/ChatCompletionNamedToolChoice' - $ref: '#/components/schemas/ChatCompletionNamedToolChoiceCustom' x-stainless-go-variant-constructor: naming: tool_choice_option_{variant} ChunkingStrategyRequestParam: type: object description: >- The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. anyOf: - $ref: '#/components/schemas/AutoChunkingStrategyRequestParam' - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' discriminator: propertyName: type Click: type: object title: Click description: | A click action. properties: type: type: string enum: - click default: click description: | Specifies the event type. For a click action, this property is always set to `click`. x-stainless-const: true button: type: string enum: - left - right - wheel - back - forward description: > Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`. x: type: integer description: | The x-coordinate where the click occurred. 'y': type: integer description: | The y-coordinate where the click occurred. required: - type - button - x - 'y' CodeInterpreterFileOutput: type: object title: Code interpreter file output description: | The output of a code interpreter tool call that is a file. properties: type: type: string enum: - files description: | The type of the code interpreter file output. Always `files`. x-stainless-const: true files: type: array items: type: object properties: mime_type: type: string description: | The MIME type of the file. file_id: type: string description: | The ID of the file. required: - mime_type - file_id required: - type - files CodeInterpreterOutputImage: type: object title: Code interpreter output image description: | The image output from the code interpreter. properties: type: type: string enum: - image default: image x-stainless-const: true description: The type of the output. Always 'image'. url: type: string description: The URL of the image output from the code interpreter. required: - type - url CodeInterpreterOutputLogs: type: object title: Code interpreter output logs description: | The logs output from the code interpreter. properties: type: type: string enum: - logs default: logs x-stainless-const: true description: The type of the output. Always 'logs'. logs: type: string description: The logs output from the code interpreter. required: - type - logs CodeInterpreterTextOutput: type: object title: Code interpreter text output description: | The output of a code interpreter tool call that is text. properties: type: type: string enum: - logs description: | The type of the code interpreter text output. Always `logs`. x-stainless-const: true logs: type: string description: | The logs of the code interpreter tool call. required: - type - logs CodeInterpreterTool: type: object title: Code interpreter description: | A tool that runs Python code to help generate a response to a prompt. properties: type: type: string enum: - code_interpreter description: | The type of the code interpreter tool. Always `code_interpreter`. x-stainless-const: true container: description: | The code interpreter container. Can be a container ID or an object that specifies uploaded file IDs to make available to your code. anyOf: - type: string description: The container ID. - $ref: '#/components/schemas/CodeInterpreterToolAuto' required: - type - container CodeInterpreterToolAuto: type: object title: CodeInterpreterContainerAuto description: | Configuration for a code interpreter container. Optionally specify the IDs of the files to run the code on. required: - type properties: type: type: string enum: - auto description: Always `auto`. x-stainless-const: true file_ids: type: array items: type: string description: | An optional list of uploaded files to make available to your code. CodeInterpreterToolCall: type: object title: Code interpreter tool call description: | A tool call to run code. properties: type: type: string enum: - code_interpreter_call default: code_interpreter_call x-stainless-const: true description: | The type of the code interpreter tool call. Always `code_interpreter_call`. id: type: string description: | The unique ID of the code interpreter tool call. status: type: string enum: - in_progress - completed - incomplete - interpreting - failed description: > The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`. container_id: type: string description: | The ID of the container used to run the code. code: type: string nullable: true description: | The code to run, or null if not available. outputs: type: array items: anyOf: - $ref: '#/components/schemas/CodeInterpreterOutputLogs' - $ref: '#/components/schemas/CodeInterpreterOutputImage' discriminator: propertyName: type discriminator: propertyName: type nullable: true description: | The outputs generated by the code interpreter, such as logs or images. Can be null if no outputs are available. required: - type - id - status - container_id - code - outputs ComparisonFilter: type: object additionalProperties: false title: Comparison Filter description: > A filter used to compare a specified attribute key to a given value using a defined comparison operation. properties: type: type: string default: eq enum: - eq - ne - gt - gte - lt - lte description: | Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. - `eq`: equals - `ne`: not equal - `gt`: greater than - `gte`: greater than or equal - `lt`: less than - `lte`: less than or equal key: type: string description: The key to compare against the value. value: description: The value to compare against the attribute key; supports string, number, or boolean types. anyOf: - type: string - type: number - type: boolean required: - type - key - value x-oaiMeta: name: ComparisonFilter CompleteUploadRequest: type: object additionalProperties: false properties: part_ids: type: array description: | The ordered list of Part IDs. items: type: string md5: description: > The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. type: string required: - part_ids CompletionUsage: type: object description: Usage statistics for the completion request. properties: completion_tokens: type: integer default: 0 description: Number of tokens in the generated completion. prompt_tokens: type: integer default: 0 description: Number of tokens in the prompt. total_tokens: type: integer default: 0 description: Total number of tokens used in the request (prompt + completion). completion_tokens_details: type: object description: Breakdown of tokens used in a completion. properties: accepted_prediction_tokens: type: integer default: 0 description: | When using Predicted Outputs, the number of tokens in the prediction that appeared in the completion. audio_tokens: type: integer default: 0 description: Audio input tokens generated by the model. reasoning_tokens: type: integer default: 0 description: Tokens generated by the model for reasoning. rejected_prediction_tokens: type: integer default: 0 description: | When using Predicted Outputs, the number of tokens in the prediction that did not appear in the completion. However, like reasoning tokens, these tokens are still counted in the total completion tokens for purposes of billing, output, and context window limits. prompt_tokens_details: type: object description: Breakdown of tokens used in the prompt. properties: audio_tokens: type: integer default: 0 description: Audio input tokens present in the prompt. cached_tokens: type: integer default: 0 description: Cached tokens present in the prompt. required: - prompt_tokens - completion_tokens - total_tokens CompoundFilter: $recursiveAnchor: true type: object additionalProperties: false title: Compound Filter description: Combine multiple filters using `and` or `or`. properties: type: type: string description: 'Type of operation: `and` or `or`.' enum: - and - or filters: type: array description: Array of filters to combine. Items can be `ComparisonFilter` or `CompoundFilter`. items: anyOf: - $ref: '#/components/schemas/ComparisonFilter' - $recursiveRef: '#' required: - type - filters x-oaiMeta: name: CompoundFilter ComputerAction: anyOf: - $ref: '#/components/schemas/Click' - $ref: '#/components/schemas/DoubleClick' - $ref: '#/components/schemas/Drag' - $ref: '#/components/schemas/KeyPress' - $ref: '#/components/schemas/Move' - $ref: '#/components/schemas/Screenshot' - $ref: '#/components/schemas/Scroll' - $ref: '#/components/schemas/Type' - $ref: '#/components/schemas/Wait' discriminator: propertyName: type ComputerScreenshotImage: type: object description: | A computer screenshot image used with the computer use tool. properties: type: type: string enum: - computer_screenshot default: computer_screenshot description: | Specifies the event type. For a computer screenshot, this property is always set to `computer_screenshot`. x-stainless-const: true image_url: type: string description: The URL of the screenshot image. file_id: type: string description: The identifier of an uploaded file that contains the screenshot. required: - type ComputerToolCall: type: object title: Computer tool call description: | A tool call to a computer use tool. See the [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information. properties: type: type: string description: The type of the computer call. Always `computer_call`. enum: - computer_call default: computer_call id: type: string description: The unique ID of the computer call. call_id: type: string description: | An identifier used when responding to the tool call with output. action: $ref: '#/components/schemas/ComputerAction' pending_safety_checks: type: array items: $ref: '#/components/schemas/ComputerToolCallSafetyCheck' description: | The pending safety checks for the computer call. status: type: string description: | The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. enum: - in_progress - completed - incomplete required: - type - id - action - call_id - pending_safety_checks - status ComputerToolCallOutput: type: object title: Computer tool call output description: | The output of a computer tool call. properties: type: type: string description: | The type of the computer tool call output. Always `computer_call_output`. enum: - computer_call_output default: computer_call_output x-stainless-const: true id: type: string description: | The ID of the computer tool call output. call_id: type: string description: | The ID of the computer tool call that produced the output. acknowledged_safety_checks: type: array description: | The safety checks reported by the API that have been acknowledged by the developer. items: $ref: '#/components/schemas/ComputerToolCallSafetyCheck' output: $ref: '#/components/schemas/ComputerScreenshotImage' status: type: string description: | The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. enum: - in_progress - completed - incomplete required: - type - call_id - output ComputerToolCallOutputResource: allOf: - $ref: '#/components/schemas/ComputerToolCallOutput' - type: object properties: id: type: string description: | The unique ID of the computer call tool output. required: - id ComputerToolCallSafetyCheck: type: object description: | A pending safety check for the computer call. properties: id: type: string description: The ID of the pending safety check. code: type: string description: The type of the pending safety check. message: type: string description: Details about the pending safety check. required: - id - code - message ContainerFileListResource: type: object properties: object: description: The type of object returned, must be 'list'. const: list data: type: array description: A list of container files. items: $ref: '#/components/schemas/ContainerFileResource' first_id: type: string description: The ID of the first file in the list. last_id: type: string description: The ID of the last file in the list. has_more: type: boolean description: Whether there are more files available. required: - object - data - first_id - last_id - has_more ContainerFileResource: type: object title: The container file object properties: id: type: string description: Unique identifier for the file. object: type: string description: The type of this object (`container.file`). const: container.file container_id: type: string description: The container this file belongs to. created_at: type: integer description: Unix timestamp (in seconds) when the file was created. bytes: type: integer description: Size of the file in bytes. path: type: string description: Path of the file in the container. source: type: string description: Source of the file (e.g., `user`, `assistant`). required: - id - object - created_at - bytes - container_id - path - source x-oaiMeta: name: The container file object example: | { "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", "object": "container.file", "created_at": 1747848842, "bytes": 880, "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", "source": "user" } ContainerListResource: type: object properties: object: description: The type of object returned, must be 'list'. const: list data: type: array description: A list of containers. items: $ref: '#/components/schemas/ContainerResource' first_id: type: string description: The ID of the first container in the list. last_id: type: string description: The ID of the last container in the list. has_more: type: boolean description: Whether there are more containers available. required: - object - data - first_id - last_id - has_more ContainerResource: type: object title: The container object properties: id: type: string description: Unique identifier for the container. object: type: string description: The type of this object. name: type: string description: Name of the container. created_at: type: integer description: Unix timestamp (in seconds) when the container was created. status: type: string description: Status of the container (e.g., active, deleted). expires_after: type: object description: | The container will expire after this time period. The anchor is the reference point for the expiration. The minutes is the number of minutes after the anchor before the container expires. properties: anchor: type: string description: The reference point for the expiration. enum: - last_active_at minutes: type: integer description: The number of minutes after the anchor before the container expires. required: - id - object - name - created_at - status - id - name - created_at - status x-oaiMeta: name: The container object example: | { "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", "object": "container", "created_at": 1747844794, "status": "running", "expires_after": { "anchor": "last_active_at", "minutes": 20 }, "last_active_at": 1747844794, "name": "My Container" } Content: description: | Multi-modal input and output contents. anyOf: - title: Input content types $ref: '#/components/schemas/InputContent' - title: Output content types $ref: '#/components/schemas/OutputContent' Coordinate: type: object title: Coordinate description: | An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`. properties: x: type: integer description: | The x-coordinate. 'y': type: integer description: | The y-coordinate. required: - x - 'y' CostsResult: type: object description: The aggregated costs details of the specific time bucket. properties: object: type: string enum: - organization.costs.result x-stainless-const: true amount: type: object description: The monetary value in its associated currency. properties: value: type: number description: The numeric value of the cost. currency: type: string description: Lowercase ISO-4217 currency e.g. "usd" line_item: type: string nullable: true description: When `group_by=line_item`, this field provides the line item of the grouped costs result. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped costs result. required: - object x-oaiMeta: name: Costs object example: | { "object": "organization.costs.result", "amount": { "value": 0.06, "currency": "usd" }, "line_item": "Image models", "project_id": "proj_abc" } CreateAssistantRequest: type: object additionalProperties: false properties: model: description: > ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. example: gpt-4o anyOf: - type: string - $ref: '#/components/schemas/AssistantSupportedModels' x-oaiTypeLabel: string name: description: | The name of the assistant. The maximum length is 256 characters. type: string nullable: true maxLength: 256 description: description: | The description of the assistant. The maximum length is 512 characters. type: string nullable: true maxLength: 512 instructions: description: | The system instructions that the assistant uses. The maximum length is 256,000 characters. type: string nullable: true maxLength: 256000 reasoning_effort: $ref: '#/components/schemas/ReasoningEffort' tools: description: > A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. default: [] type: array maxItems: 128 items: $ref: '#/components/schemas/AssistantTool' tool_resources: type: object description: > A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. maxItems: 1 items: type: string vector_stores: type: array description: > A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant. maxItems: 1 items: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. maxItems: 10000 items: type: string chunking_strategy: type: object description: >- The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. anyOf: - type: object title: Auto Chunking Strategy description: >- The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. additionalProperties: false properties: type: type: string description: Always `auto`. enum: - auto x-stainless-const: true required: - type - type: object title: Static Chunking Strategy additionalProperties: false properties: type: type: string description: Always `static`. enum: - static x-stainless-const: true static: type: object additionalProperties: false properties: max_chunk_size_tokens: type: integer minimum: 100 maximum: 4096 description: >- The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. chunk_overlap_tokens: type: integer description: > The number of tokens that overlap between chunks. The default value is `400`. Note that the overlap must not exceed half of `max_chunk_size_tokens`. required: - max_chunk_size_tokens - chunk_overlap_tokens required: - type - static x-stainless-naming: java: type_name: StaticObject kotlin: type_name: StaticObject discriminator: propertyName: type metadata: $ref: '#/components/schemas/Metadata' anyOf: - required: - vector_store_ids - required: - vector_stores nullable: true metadata: $ref: '#/components/schemas/Metadata' temperature: description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true required: - model CreateChatCompletionRequest: allOf: - $ref: '#/components/schemas/CreateModelResponseProperties' - type: object properties: messages: description: > A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message types (modalities) are supported, like [text](https://platform.openai.com/docs/guides/text-generation), [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). type: array minItems: 1 items: $ref: '#/components/schemas/ChatCompletionRequestMessage' model: description: > Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare available models. $ref: '#/components/schemas/ModelIdsShared' modalities: $ref: '#/components/schemas/ResponseModalities' verbosity: $ref: '#/components/schemas/Verbosity' reasoning_effort: $ref: '#/components/schemas/ReasoningEffort' max_completion_tokens: description: > An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). type: integer nullable: true frequency_penalty: type: number default: 0 minimum: -2 maximum: 2 nullable: true description: | Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. presence_penalty: type: number default: 0 minimum: -2 maximum: 2 nullable: true description: | Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. web_search_options: type: object title: Web search description: > This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). properties: user_location: type: object nullable: true required: - type - approximate description: | Approximate location parameters for the search. properties: type: type: string description: | The type of location approximation. Always `approximate`. enum: - approximate x-stainless-const: true approximate: $ref: '#/components/schemas/WebSearchLocation' search_context_size: $ref: '#/components/schemas/WebSearchContextSize' top_logprobs: description: | An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. type: integer minimum: 0 maximum: 20 nullable: true response_format: description: | An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables the older JSON mode, which ensures the message the model generates is valid JSON. Using `json_schema` is preferred for models that support it. anyOf: - $ref: '#/components/schemas/ResponseFormatText' - $ref: '#/components/schemas/ResponseFormatJsonSchema' - $ref: '#/components/schemas/ResponseFormatJsonObject' audio: type: object nullable: true description: | Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. [Learn more](https://platform.openai.com/docs/guides/audio). required: - voice - format properties: voice: $ref: '#/components/schemas/VoiceIdsShared' description: | The voice the model uses to respond. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. format: type: string enum: - wav - aac - mp3 - flac - opus - pcm16 description: | Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`. store: type: boolean default: false nullable: true description: | Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products. Supports text and image inputs. Note: image inputs over 8MB will be dropped. stream: description: > If set to true, the model response data will be streamed to the client as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). See the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) for more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) guide for more information on how to handle the streaming events. type: boolean nullable: true default: false stop: $ref: '#/components/schemas/StopConfiguration' logit_bias: type: object x-oaiTypeLabel: map default: null nullable: true additionalProperties: type: integer description: | Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. logprobs: description: | Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. type: boolean default: false nullable: true max_tokens: description: | The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. This value can be used to control [costs](https://openai.com/api/pricing/) for text generated via API. This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning). type: integer nullable: true deprecated: true 'n': type: integer minimum: 1 maximum: 128 default: 1 example: 1 nullable: true description: >- How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. prediction: nullable: true description: > Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs), which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content. anyOf: - $ref: '#/components/schemas/PredictionContent' discriminator: propertyName: type seed: type: integer minimum: -9223372036854776000 maximum: 9223372036854776000 nullable: true deprecated: true description: > This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. x-oaiMeta: beta: true stream_options: $ref: '#/components/schemas/ChatCompletionStreamOptions' tools: type: array description: | A list of tools the model may call. You can provide either [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or [function tools](https://platform.openai.com/docs/guides/function-calling). items: anyOf: - $ref: '#/components/schemas/ChatCompletionTool' - $ref: '#/components/schemas/CustomToolChatCompletions' x-stainless-naming: python: model_name: chat_completion_tool_union param_model_name: chat_completion_tool_union_param discriminator: propertyName: type x-stainless-go-variant-constructor: naming: chat_completion_{variant}_tool tool_choice: $ref: '#/components/schemas/ChatCompletionToolChoiceOption' parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' function_call: deprecated: true description: | Deprecated in favor of `tool_choice`. Controls which (if any) function is called by the model. `none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if functions are present. anyOf: - type: string description: > `none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. enum: - none - auto title: function call mode - $ref: '#/components/schemas/ChatCompletionFunctionCallOption' functions: deprecated: true description: | Deprecated in favor of `tools`. A list of functions the model may generate JSON inputs for. type: array minItems: 1 maxItems: 128 items: $ref: '#/components/schemas/ChatCompletionFunctions' required: - model - messages CreateChatCompletionResponse: type: object description: Represents a chat completion response returned by model, based on the provided input. properties: id: type: string description: A unique identifier for the chat completion. choices: type: array description: A list of chat completion choices. Can be more than one if `n` is greater than 1. items: type: object required: - finish_reason - index - message - logprobs properties: finish_reason: type: string description: > The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. enum: - stop - length - tool_calls - content_filter - function_call index: type: integer description: The index of the choice in the list of choices. message: $ref: '#/components/schemas/ChatCompletionResponseMessage' logprobs: description: Log probability information for the choice. type: object nullable: true properties: content: description: A list of message content tokens with log probability information. type: array items: $ref: '#/components/schemas/ChatCompletionTokenLogprob' nullable: true refusal: description: A list of message refusal tokens with log probability information. type: array items: $ref: '#/components/schemas/ChatCompletionTokenLogprob' nullable: true required: - content - refusal created: type: integer description: The Unix timestamp (in seconds) of when the chat completion was created. model: type: string description: The model used for the chat completion. service_tier: $ref: '#/components/schemas/ServiceTier' system_fingerprint: type: string deprecated: true description: > This fingerprint represents the backend configuration that the model runs with. Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. object: type: string description: The object type, which is always `chat.completion`. enum: - chat.completion x-stainless-const: true usage: $ref: '#/components/schemas/CompletionUsage' required: - choices - created - id - model - object x-oaiMeta: name: The chat completion object group: chat example: | { "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", "object": "chat.completion", "created": 1741570283, "model": "gpt-4o-2024-08-06", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.", "refusal": null, "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 1117, "completion_tokens": 46, "total_tokens": 1163, "prompt_tokens_details": { "cached_tokens": 0, "audio_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "service_tier": "default", "system_fingerprint": "fp_fc9f1d7035" } CreateChatCompletionStreamResponse: type: object description: | Represents a streamed chunk of a chat completion response returned by the model, based on the provided input. [Learn more](https://platform.openai.com/docs/guides/streaming-responses). properties: id: type: string description: A unique identifier for the chat completion. Each chunk has the same ID. choices: type: array description: > A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the last chunk if you set `stream_options: {"include_usage": true}`. items: type: object required: - delta - finish_reason - index properties: delta: $ref: '#/components/schemas/ChatCompletionStreamResponseDelta' logprobs: description: Log probability information for the choice. type: object nullable: true properties: content: description: A list of message content tokens with log probability information. type: array items: $ref: '#/components/schemas/ChatCompletionTokenLogprob' nullable: true refusal: description: A list of message refusal tokens with log probability information. type: array items: $ref: '#/components/schemas/ChatCompletionTokenLogprob' nullable: true required: - content - refusal finish_reason: type: string description: > The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. enum: - stop - length - tool_calls - content_filter - function_call nullable: true index: type: integer description: The index of the choice in the list of choices. created: type: integer description: >- The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp. model: type: string description: The model to generate the completion. service_tier: $ref: '#/components/schemas/ServiceTier' system_fingerprint: type: string deprecated: true description: > This fingerprint represents the backend configuration that the model runs with. Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. object: type: string description: The object type, which is always `chat.completion.chunk`. enum: - chat.completion.chunk x-stainless-const: true usage: $ref: '#/components/schemas/CompletionUsage' nullable: true description: | An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request. When present, it contains a null value **except for the last chunk** which contains the token usage statistics for the entire request. **NOTE:** If the stream is interrupted or cancelled, you may not receive the final usage chunk which contains the total token usage for the request. required: - choices - created - id - model - object x-oaiMeta: name: The chat completion chunk object group: chat example: > {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} .... {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} CreateCompletionRequest: type: object properties: model: description: > ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. anyOf: - type: string - type: string enum: - gpt-3.5-turbo-instruct - davinci-002 - babbage-002 title: Preset x-oaiTypeLabel: string prompt: description: > The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document. nullable: true anyOf: - type: string default: '' example: This is a test. - type: array items: type: string default: '' example: This is a test. title: Array of strings - type: array minItems: 1 items: type: integer title: Array of tokens - type: array minItems: 1 items: type: array minItems: 1 items: type: integer title: Array of token arrays best_of: type: integer default: 1 minimum: 0 maximum: 20 nullable: true description: > Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed. When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. echo: type: boolean default: false nullable: true description: | Echo back the prompt in addition to the completion frequency_penalty: type: number default: 0 minimum: -2 maximum: 2 nullable: true description: > Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) logit_bias: type: object x-oaiTypeLabel: map default: null nullable: true additionalProperties: type: integer description: > Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. logprobs: type: integer minimum: 0 maximum: 5 default: null nullable: true description: > Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. max_tokens: type: integer minimum: 0 default: 16 example: 16 nullable: true description: > The maximum number of [tokens](/tokenizer) that can be generated in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. 'n': type: integer minimum: 1 maximum: 128 default: 1 example: 1 nullable: true description: > How many completions to generate for each prompt. **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. presence_penalty: type: number default: 0 minimum: -2 maximum: 2 nullable: true description: > Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) seed: type: integer format: int64 nullable: true description: > If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. stop: $ref: '#/components/schemas/StopConfiguration' stream: description: > Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). type: boolean nullable: true default: false stream_options: $ref: '#/components/schemas/ChatCompletionStreamOptions' suffix: description: | The suffix that comes after a completion of inserted text. This parameter is only supported for `gpt-3.5-turbo-instruct`. default: null nullable: true type: string example: test. temperature: type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. user: type: string example: user-1234 description: > A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). required: - model - prompt CreateCompletionResponse: type: object description: > Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint). properties: id: type: string description: A unique identifier for the completion. choices: type: array description: The list of completion choices the model generated for the input prompt. items: type: object required: - finish_reason - index - logprobs - text properties: finish_reason: type: string description: > The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, or `content_filter` if content was omitted due to a flag from our content filters. enum: - stop - length - content_filter index: type: integer logprobs: type: object nullable: true properties: text_offset: type: array items: type: integer token_logprobs: type: array items: type: number tokens: type: array items: type: string top_logprobs: type: array items: type: object additionalProperties: type: number text: type: string created: type: integer description: The Unix timestamp (in seconds) of when the completion was created. model: type: string description: The model used for completion. system_fingerprint: type: string description: > This fingerprint represents the backend configuration that the model runs with. Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. object: type: string description: The object type, which is always "text_completion" enum: - text_completion x-stainless-const: true usage: $ref: '#/components/schemas/CompletionUsage' required: - id - object - created - model - choices x-oaiMeta: name: The completion object legacy: true example: | { "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", "object": "text_completion", "created": 1589478378, "model": "gpt-4-turbo", "choices": [ { "text": "\n\nThis is indeed a test", "index": 0, "logprobs": null, "finish_reason": "length" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12 } } CreateContainerBody: type: object properties: name: type: string description: Name of the container to create. file_ids: type: array description: IDs of files to copy to the container. items: type: string expires_after: type: object description: Container expiration time in seconds relative to the 'anchor' time. properties: anchor: type: string enum: - last_active_at description: Time anchor for the expiration time. Currently only 'last_active_at' is supported. minutes: type: integer required: - anchor - minutes required: - name CreateContainerFileBody: type: object properties: file_id: type: string description: Name of the file to create. file: description: | The File object (not file name) to be uploaded. type: string format: binary required: [] CreateEmbeddingRequest: type: object additionalProperties: false properties: input: description: > Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request. example: The quick brown fox jumped over the lazy dog anyOf: - type: string title: string description: The string that will be turned into an embedding. default: '' example: This is a test. - type: array title: Array of strings description: The array of strings that will be turned into an embedding. minItems: 1 maxItems: 2048 items: type: string default: '' example: "['This is a test.']" - type: array title: Array of tokens description: The array of integers that will be turned into an embedding. minItems: 1 maxItems: 2048 items: type: integer - type: array title: Array of token arrays description: The array of arrays containing integers that will be turned into an embedding. minItems: 1 maxItems: 2048 items: type: array minItems: 1 items: type: integer model: description: > ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. example: text-embedding-3-small anyOf: - type: string - type: string enum: - text-embedding-ada-002 - text-embedding-3-small - text-embedding-3-large x-stainless-nominal: false x-oaiTypeLabel: string encoding_format: description: >- The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/). example: float default: float type: string enum: - float - base64 dimensions: description: > The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. type: integer minimum: 1 user: type: string example: user-1234 description: > A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). required: - model - input CreateEmbeddingResponse: type: object properties: data: type: array description: The list of embeddings generated by the model. items: $ref: '#/components/schemas/Embedding' model: type: string description: The name of the model used to generate the embedding. object: type: string description: The object type, which is always "list". enum: - list x-stainless-const: true usage: type: object description: The usage information for the request. properties: prompt_tokens: type: integer description: The number of tokens used by the prompt. total_tokens: type: integer description: The total number of tokens used by the request. required: - prompt_tokens - total_tokens required: - object - model - data - usage CreateEvalCompletionsRunDataSource: type: object title: CompletionsRunDataSource description: | A CompletionsRunDataSource object describing a model sampling configuration. properties: type: type: string enum: - completions default: completions description: The type of run data source. Always `completions`. input_messages: description: >- Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace. anyOf: - type: object title: TemplateInputMessages properties: type: type: string enum: - template description: The type of input messages. Always `template`. template: type: array description: >- A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. items: anyOf: - $ref: '#/components/schemas/EasyInputMessage' - $ref: '#/components/schemas/EvalItem' discriminator: propertyName: type required: - type - template - type: object title: ItemReferenceInputMessages properties: type: type: string enum: - item_reference description: The type of input messages. Always `item_reference`. item_reference: type: string description: A reference to a variable in the `item` namespace. Ie, "item.input_trajectory" required: - type - item_reference discriminator: propertyName: type sampling_params: type: object properties: temperature: type: number description: A higher temperature increases randomness in the outputs. default: 1 max_completion_tokens: type: integer description: The maximum number of tokens in the generated output. top_p: type: number description: An alternative to temperature for nucleus sampling; 1.0 includes all tokens. default: 1 seed: type: integer description: A seed value to initialize the randomness, during sampling. default: 42 response_format: description: | An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables the older JSON mode, which ensures the message the model generates is valid JSON. Using `json_schema` is preferred for models that support it. anyOf: - $ref: '#/components/schemas/ResponseFormatText' - $ref: '#/components/schemas/ResponseFormatJsonSchema' - $ref: '#/components/schemas/ResponseFormatJsonObject' tools: type: array description: > A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. items: $ref: '#/components/schemas/ChatCompletionTool' model: type: string description: The name of the model to use for generating completions (e.g. "o3-mini"). source: description: Determines what populates the `item` namespace in this run's data source. anyOf: - $ref: '#/components/schemas/EvalJsonlFileContentSource' - $ref: '#/components/schemas/EvalJsonlFileIdSource' - $ref: '#/components/schemas/EvalStoredCompletionsSource' discriminator: propertyName: type required: - type - source x-oaiMeta: name: The completions data source object used to configure an individual run group: eval runs example: | { "name": "gpt-4o-mini-2024-07-18", "data_source": { "type": "completions", "input_messages": { "type": "item_reference", "item_reference": "item.input" }, "model": "gpt-4o-mini-2024-07-18", "source": { "type": "stored_completions", "model": "gpt-4o-mini-2024-07-18" } } } CreateEvalCustomDataSourceConfig: type: object title: CustomDataSourceConfig description: > A CustomDataSourceConfig object that defines the schema for the data source used for the evaluation runs. This schema is used to define the shape of the data that will be: - Used to define your testing criteria and - What data is required when creating a run properties: type: type: string enum: - custom default: custom description: The type of data source. Always `custom`. x-stainless-const: true item_schema: type: object description: The json schema for each row in the data source. additionalProperties: true include_sample_schema: type: boolean default: false description: >- Whether the eval should expect you to populate the sample namespace (ie, by generating responses off of your data source) required: - item_schema - type x-oaiMeta: name: The eval file data source config object group: evals example: | { "type": "custom", "item_schema": { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} }, "required": ["name", "age"] }, "include_sample_schema": true } CreateEvalItem: title: CreateEvalItem description: >- A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. type: object x-oaiMeta: name: The chat message object used to configure an individual run anyOf: - type: object title: SimpleInputMessage properties: role: type: string description: The role of the message (e.g. "system", "assistant", "user"). content: type: string description: The content of the message. required: - role - content - $ref: '#/components/schemas/EvalItem' CreateEvalJsonlRunDataSource: type: object title: JsonlRunDataSource description: | A JsonlRunDataSource object with that specifies a JSONL file that matches the eval properties: type: type: string enum: - jsonl default: jsonl description: The type of data source. Always `jsonl`. x-stainless-const: true source: description: Determines what populates the `item` namespace in the data source. anyOf: - $ref: '#/components/schemas/EvalJsonlFileContentSource' - $ref: '#/components/schemas/EvalJsonlFileIdSource' discriminator: propertyName: type required: - type - source x-oaiMeta: name: The file data source object for the eval run configuration group: evals example: | { "type": "jsonl", "source": { "type": "file_id", "id": "file-9GYS6xbkWgWhmE7VoLUWFg" } } CreateEvalLabelModelGrader: type: object title: LabelModelGrader description: | A LabelModelGrader object which uses a model to assign labels to each item in the evaluation. properties: type: description: The object type, which is always `label_model`. type: string enum: - label_model x-stainless-const: true name: type: string description: The name of the grader. model: type: string description: The model to use for the evaluation. Must support structured outputs. input: type: array description: >- A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. items: $ref: '#/components/schemas/CreateEvalItem' labels: type: array items: type: string description: The labels to classify to each item in the evaluation. passing_labels: type: array items: type: string description: The labels that indicate a passing result. Must be a subset of labels. required: - type - model - input - passing_labels - labels - name x-oaiMeta: name: The eval label model grader object group: evals example: | { "type": "label_model", "model": "gpt-4o-2024-08-06", "input": [ { "role": "system", "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'" }, { "role": "user", "content": "Statement: {{item.response}}" } ], "passing_labels": ["positive"], "labels": ["positive", "neutral", "negative"], "name": "Sentiment label grader" } CreateEvalLogsDataSourceConfig: type: object title: LogsDataSourceConfig description: | A data source config which specifies the metadata property of your logs query. This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. properties: type: type: string enum: - logs default: logs description: The type of data source. Always `logs`. x-stainless-const: true metadata: type: object description: Metadata filters for the logs data source. additionalProperties: true required: - type x-oaiMeta: name: The logs data source object for evals group: evals example: | { "type": "logs", "metadata": { "use_case": "customer_support_agent" } } CreateEvalRequest: type: object title: CreateEvalRequest properties: name: type: string description: The name of the evaluation. metadata: $ref: '#/components/schemas/Metadata' data_source_config: type: object description: >- The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation. anyOf: - $ref: '#/components/schemas/CreateEvalCustomDataSourceConfig' - $ref: '#/components/schemas/CreateEvalLogsDataSourceConfig' - $ref: '#/components/schemas/CreateEvalStoredCompletionsDataSourceConfig' discriminator: propertyName: type testing_criteria: type: array description: >- A list of graders for all eval runs in this group. Graders can reference variables in the data source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's output, use the `sample` namespace (ie, `{{sample.output_text}}`). items: anyOf: - $ref: '#/components/schemas/CreateEvalLabelModelGrader' - $ref: '#/components/schemas/EvalGraderStringCheck' - $ref: '#/components/schemas/EvalGraderTextSimilarity' - $ref: '#/components/schemas/EvalGraderPython' - $ref: '#/components/schemas/EvalGraderScoreModel' discriminator: propertyName: type required: - data_source_config - testing_criteria CreateEvalResponsesRunDataSource: type: object title: ResponsesRunDataSource description: | A ResponsesRunDataSource object describing a model sampling configuration. properties: type: type: string enum: - responses default: responses description: The type of run data source. Always `responses`. input_messages: description: >- Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace. anyOf: - type: object title: InputMessagesTemplate properties: type: type: string enum: - template description: The type of input messages. Always `template`. template: type: array description: >- A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. items: anyOf: - type: object title: ChatMessage properties: role: type: string description: The role of the message (e.g. "system", "assistant", "user"). content: type: string description: The content of the message. required: - role - content - $ref: '#/components/schemas/EvalItem' required: - type - template - type: object title: InputMessagesItemReference properties: type: type: string enum: - item_reference description: The type of input messages. Always `item_reference`. item_reference: type: string description: A reference to a variable in the `item` namespace. Ie, "item.name" required: - type - item_reference discriminator: propertyName: type sampling_params: type: object properties: temperature: type: number description: A higher temperature increases randomness in the outputs. default: 1 max_completion_tokens: type: integer description: The maximum number of tokens in the generated output. top_p: type: number description: An alternative to temperature for nucleus sampling; 1.0 includes all tokens. default: 1 seed: type: integer description: A seed value to initialize the randomness, during sampling. default: 42 tools: type: array description: | An array of tools the model may call while generating a response. You can specify which tool to use by setting the `tool_choice` parameter. The two categories of tools you can provide the model are: - **Built-in tools**: Tools that are provided by OpenAI that extend the model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about [built-in tools](https://platform.openai.com/docs/guides/tools). - **Function calls (custom tools)**: Functions that are defined by you, enabling the model to call your own code. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). items: $ref: '#/components/schemas/Tool' text: type: object description: | Configuration options for a text response from the model. Can be plain text or structured JSON data. Learn more: - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) properties: format: $ref: '#/components/schemas/TextResponseFormatConfiguration' model: type: string description: The name of the model to use for generating completions (e.g. "o3-mini"). source: description: Determines what populates the `item` namespace in this run's data source. anyOf: - $ref: '#/components/schemas/EvalJsonlFileContentSource' - $ref: '#/components/schemas/EvalJsonlFileIdSource' - $ref: '#/components/schemas/EvalResponsesSource' discriminator: propertyName: type required: - type - source x-oaiMeta: name: The completions data source object used to configure an individual run group: eval runs example: | { "name": "gpt-4o-mini-2024-07-18", "data_source": { "type": "responses", "input_messages": { "type": "item_reference", "item_reference": "item.input" }, "model": "gpt-4o-mini-2024-07-18", "source": { "type": "responses", "model": "gpt-4o-mini-2024-07-18" } } } CreateEvalRunRequest: type: object title: CreateEvalRunRequest properties: name: type: string description: The name of the run. metadata: $ref: '#/components/schemas/Metadata' data_source: type: object description: Details about the run's data source. anyOf: - $ref: '#/components/schemas/CreateEvalJsonlRunDataSource' - $ref: '#/components/schemas/CreateEvalCompletionsRunDataSource' - $ref: '#/components/schemas/CreateEvalResponsesRunDataSource' required: - data_source CreateEvalStoredCompletionsDataSourceConfig: type: object title: StoredCompletionsDataSourceConfig description: | Deprecated in favor of LogsDataSourceConfig. properties: type: type: string enum: - stored_completions default: stored_completions description: The type of data source. Always `stored_completions`. x-stainless-const: true metadata: type: object description: Metadata filters for the stored completions data source. additionalProperties: true required: - type deprecated: true x-oaiMeta: name: The stored completions data source object for evals group: evals example: | { "type": "stored_completions", "metadata": { "use_case": "customer_support_agent" } } CreateFileRequest: type: object additionalProperties: false properties: file: description: | The File object (not file name) to be uploaded. type: string format: binary x-oaiMeta: exampleFilePath: fine-tune.jsonl purpose: $ref: '#/components/schemas/FilePurpose' expires_after: $ref: '#/components/schemas/FileExpirationAfter' required: - file - purpose CreateFineTuningCheckpointPermissionRequest: type: object additionalProperties: false properties: project_ids: type: array description: The project identifiers to grant access to. items: type: string required: - project_ids CreateFineTuningJobRequest: type: object properties: model: description: > The name of the model to fine-tune. You can select one of the [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). example: gpt-4o-mini anyOf: - type: string - type: string enum: - babbage-002 - davinci-002 - gpt-3.5-turbo - gpt-4o-mini title: Preset x-oaiTypeLabel: string training_file: description: > The ID of an uploaded file that contains training data. See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. The contents of the file should differ depending on if the model uses the [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) format, or if the fine-tuning method uses the [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format. See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details. type: string example: file-abc123 hyperparameters: type: object description: > The hyperparameters used for the fine-tuning job. This value is now deprecated in favor of `method`, and should be passed in under the `method` parameter. properties: batch_size: description: | Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. default: auto anyOf: - type: string enum: - auto x-stainless-const: true title: Auto - type: integer minimum: 1 maximum: 256 learning_rate_multiplier: description: | Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. anyOf: - type: string enum: - auto x-stainless-const: true title: Auto - type: number minimum: 0 exclusiveMinimum: true n_epochs: description: | The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. default: auto anyOf: - type: string enum: - auto x-stainless-const: true title: Auto - type: integer minimum: 1 maximum: 50 deprecated: true suffix: description: > A string of up to 64 characters that will be added to your fine-tuned model name. For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. type: string minLength: 1 maxLength: 64 default: null nullable: true validation_file: description: > The ID of an uploaded file that contains validation data. If you provide this file, the data is used to generate validation metrics periodically during fine-tuning. These metrics can be viewed in the fine-tuning results file. The same data should not be present in both train and validation files. Your dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`. See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details. type: string nullable: true example: file-abc123 integrations: type: array description: A list of integrations to enable for your fine-tuning job. nullable: true items: type: object required: - type - wandb properties: type: description: > The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported. anyOf: - type: string enum: - wandb x-stainless-const: true wandb: type: object description: > The settings for your integration with Weights and Biases. This payload specifies the project that metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags to your run, and set a default entity (team, username, etc) to be associated with your run. required: - project properties: project: description: | The name of the project that the new run will be created under. type: string example: my-wandb-project name: description: | A display name to set for the run. If not set, we will use the Job ID as the name. nullable: true type: string entity: description: > The entity to use for the run. This allows you to set the team or username of the WandB user that you would like associated with the run. If not set, the default entity for the registered WandB API key is used. nullable: true type: string tags: description: > A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". type: array items: type: string example: custom-tag seed: description: > The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. If a seed is not specified, one will be generated for you. type: integer nullable: true minimum: 0 maximum: 2147483647 example: 42 method: $ref: '#/components/schemas/FineTuneMethod' metadata: $ref: '#/components/schemas/Metadata' required: - model - training_file CreateImageEditRequest: type: object properties: image: anyOf: - type: string format: binary - type: array maxItems: 16 items: type: string format: binary description: | The image(s) to edit. Must be a supported image file or an array of images. For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than 50MB. You can provide up to 16 images. For `dall-e-2`, you can only provide one image, and it should be a square `png` file less than 4MB. x-oaiMeta: exampleFilePath: otter.png prompt: description: >- A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. type: string example: A cute baby sea otter wearing a beret mask: description: >- An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. type: string format: binary x-oaiMeta: exampleFilePath: mask.png background: type: string enum: - transparent - opaque - auto default: auto example: transparent nullable: true description: | Allows to set transparency for the background of the generated image(s). This parameter is only supported for `gpt-image-1`. Must be one of `transparent`, `opaque` or `auto` (default value). When `auto` is used, the model will automatically determine the best background for the image. If `transparent`, the output format needs to support transparency, so it should be set to either `png` (default value) or `webp`. model: anyOf: - type: string - type: string enum: - dall-e-2 - gpt-image-1 x-stainless-const: true x-oaiTypeLabel: string nullable: true description: >- The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used. 'n': type: integer minimum: 1 maximum: 10 default: 1 example: 1 nullable: true description: The number of images to generate. Must be between 1 and 10. size: type: string enum: - 256x256 - 512x512 - 1024x1024 - 1536x1024 - 1024x1536 - auto default: 1024x1024 example: 1024x1024 nullable: true description: >- The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. response_format: type: string enum: - url - b64_json default: url example: url nullable: true description: >- The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images. output_format: type: string enum: - png - jpeg - webp default: png example: png nullable: true description: | The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. The default value is `png`. output_compression: type: integer default: 100 example: 100 nullable: true description: | The compression level (0-100%) for the generated images. This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100. user: type: string example: user-1234 description: > A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). input_fidelity: $ref: '#/components/schemas/ImageInputFidelity' stream: type: boolean default: false example: false nullable: true description: > Edit the image in streaming mode. Defaults to `false`. See the [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information. partial_images: $ref: '#/components/schemas/PartialImages' quality: type: string enum: - standard - low - medium - high - auto default: auto example: high nullable: true description: > The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`. required: - prompt - image CreateImageRequest: type: object properties: prompt: description: >- A text description of the desired image(s). The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`. type: string example: A cute baby sea otter model: anyOf: - type: string - type: string enum: - dall-e-2 - dall-e-3 - gpt-image-1 x-stainless-nominal: false x-oaiTypeLabel: string nullable: true description: >- The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used. 'n': type: integer minimum: 1 maximum: 10 default: 1 example: 1 nullable: true description: >- The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. quality: type: string enum: - standard - hd - low - medium - high - auto default: auto example: medium nullable: true description: | The quality of the image that will be generated. - `auto` (default value) will automatically select the best quality for the given model. - `high`, `medium` and `low` are supported for `gpt-image-1`. - `hd` and `standard` are supported for `dall-e-3`. - `standard` is the only option for `dall-e-2`. response_format: type: string enum: - url - b64_json default: url example: url nullable: true description: >- The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for `gpt-image-1` which will always return base64-encoded images. output_format: type: string enum: - png - jpeg - webp default: png example: png nullable: true description: >- The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. output_compression: type: integer default: 100 example: 100 nullable: true description: >- The compression level (0-100%) for the generated images. This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100. stream: type: boolean default: false example: false nullable: true description: > Generate the image in streaming mode. Defaults to `false`. See the [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information. This parameter is only supported for `gpt-image-1`. partial_images: $ref: '#/components/schemas/PartialImages' size: type: string enum: - auto - 1024x1024 - 1536x1024 - 1024x1536 - 256x256 - 512x512 - 1792x1024 - 1024x1792 default: auto example: 1024x1024 nullable: true description: >- The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. moderation: type: string enum: - low - auto default: auto example: low nullable: true description: >- Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` for less restrictive filtering or `auto` (default value). background: type: string enum: - transparent - opaque - auto default: auto example: transparent nullable: true description: | Allows to set transparency for the background of the generated image(s). This parameter is only supported for `gpt-image-1`. Must be one of `transparent`, `opaque` or `auto` (default value). When `auto` is used, the model will automatically determine the best background for the image. If `transparent`, the output format needs to support transparency, so it should be set to either `png` (default value) or `webp`. style: type: string enum: - vivid - natural default: vivid example: vivid nullable: true description: >- The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. user: type: string example: user-1234 description: > A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). required: - prompt CreateImageVariationRequest: type: object properties: image: description: >- The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. type: string format: binary x-oaiMeta: exampleFilePath: otter.png model: anyOf: - type: string - type: string enum: - dall-e-2 x-stainless-const: true x-oaiTypeLabel: string nullable: true description: The model to use for image generation. Only `dall-e-2` is supported at this time. 'n': type: integer minimum: 1 maximum: 10 default: 1 example: 1 nullable: true description: The number of images to generate. Must be between 1 and 10. response_format: type: string enum: - url - b64_json default: url example: url nullable: true description: >- The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. size: type: string enum: - 256x256 - 512x512 - 1024x1024 default: 1024x1024 example: 1024x1024 nullable: true description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. user: type: string example: user-1234 description: > A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). required: - image CreateMessageRequest: type: object additionalProperties: false required: - role - content properties: role: type: string enum: - user - assistant description: > The role of the entity that is creating the message. Allowed values include: - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. content: anyOf: - type: string description: The text contents of the message. title: Text content - type: array description: >- An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](https://platform.openai.com/docs/models). title: Array of content parts items: anyOf: - $ref: '#/components/schemas/MessageContentImageFileObject' - $ref: '#/components/schemas/MessageContentImageUrlObject' - $ref: '#/components/schemas/MessageRequestContentTextObject' discriminator: propertyName: type minItems: 1 attachments: type: array items: type: object properties: file_id: type: string description: The ID of the file to attach to the message. tools: description: The tools to add this file to. type: array items: anyOf: - $ref: '#/components/schemas/AssistantToolsCode' - $ref: '#/components/schemas/AssistantToolsFileSearchTypeOnly' discriminator: propertyName: type description: A list of files attached to the message, and the tools they should be added to. required: - file_id - tools nullable: true metadata: $ref: '#/components/schemas/Metadata' CreateModelResponseProperties: allOf: - $ref: '#/components/schemas/ModelResponseProperties' - type: object properties: top_logprobs: description: | An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. type: integer minimum: 0 maximum: 20 CreateModerationRequest: type: object properties: input: description: | Input (or inputs) to classify. Can be a single string, an array of strings, or an array of multi-modal input objects similar to other models. anyOf: - type: string description: A string of text to classify for moderation. default: '' example: I want to kill them. - type: array description: An array of strings to classify for moderation. items: type: string default: '' example: I want to kill them. - type: array description: An array of multi-modal inputs to the moderation model. items: anyOf: - $ref: '#/components/schemas/ModerationImageURLInput' - $ref: '#/components/schemas/ModerationTextInput' discriminator: propertyName: type title: Moderation Multi Modal Array model: description: | The content moderation model you would like to use. Learn more in [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about available models [here](https://platform.openai.com/docs/models#moderation). nullable: false anyOf: - type: string - type: string enum: - omni-moderation-latest - omni-moderation-2024-09-26 - text-moderation-latest - text-moderation-stable x-stainless-nominal: false x-oaiTypeLabel: string required: - input CreateModerationResponse: type: object description: Represents if a given text input is potentially harmful. properties: id: type: string description: The unique identifier for the moderation request. model: type: string description: The model used to generate the moderation results. results: type: array description: A list of moderation objects. items: type: object properties: flagged: type: boolean description: Whether any of the below categories are flagged. categories: type: object description: A list of the categories, and whether they are flagged or not. properties: hate: type: boolean description: >- Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment. hate/threatening: type: boolean description: >- Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. harassment: type: boolean description: Content that expresses, incites, or promotes harassing language towards any target. harassment/threatening: type: boolean description: Harassment content that also includes violence or serious harm towards any target. illicit: type: boolean nullable: true description: >- Content that includes instructions or advice that facilitate the planning or execution of wrongdoing, or that gives advice or instruction on how to commit illicit acts. For example, "how to shoplift" would fit this category. illicit/violent: type: boolean nullable: true description: >- Content that includes instructions or advice that facilitate the planning or execution of wrongdoing that also includes violence, or that gives advice or instruction on the procurement of any weapon. self-harm: type: boolean description: >- Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders. self-harm/intent: type: boolean description: >- Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders. self-harm/instructions: type: boolean description: >- Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts. sexual: type: boolean description: >- Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness). sexual/minors: type: boolean description: Sexual content that includes an individual who is under 18 years old. violence: type: boolean description: Content that depicts death, violence, or physical injury. violence/graphic: type: boolean description: Content that depicts death, violence, or physical injury in graphic detail. required: - hate - hate/threatening - harassment - harassment/threatening - illicit - illicit/violent - self-harm - self-harm/intent - self-harm/instructions - sexual - sexual/minors - violence - violence/graphic category_scores: type: object description: A list of the categories along with their scores as predicted by model. properties: hate: type: number description: The score for the category 'hate'. hate/threatening: type: number description: The score for the category 'hate/threatening'. harassment: type: number description: The score for the category 'harassment'. harassment/threatening: type: number description: The score for the category 'harassment/threatening'. illicit: type: number description: The score for the category 'illicit'. illicit/violent: type: number description: The score for the category 'illicit/violent'. self-harm: type: number description: The score for the category 'self-harm'. self-harm/intent: type: number description: The score for the category 'self-harm/intent'. self-harm/instructions: type: number description: The score for the category 'self-harm/instructions'. sexual: type: number description: The score for the category 'sexual'. sexual/minors: type: number description: The score for the category 'sexual/minors'. violence: type: number description: The score for the category 'violence'. violence/graphic: type: number description: The score for the category 'violence/graphic'. required: - hate - hate/threatening - harassment - harassment/threatening - illicit - illicit/violent - self-harm - self-harm/intent - self-harm/instructions - sexual - sexual/minors - violence - violence/graphic category_applied_input_types: type: object description: A list of the categories along with the input type(s) that the score applies to. properties: hate: type: array description: The applied input type(s) for the category 'hate'. items: type: string enum: - text x-stainless-const: true hate/threatening: type: array description: The applied input type(s) for the category 'hate/threatening'. items: type: string enum: - text x-stainless-const: true harassment: type: array description: The applied input type(s) for the category 'harassment'. items: type: string enum: - text x-stainless-const: true harassment/threatening: type: array description: The applied input type(s) for the category 'harassment/threatening'. items: type: string enum: - text x-stainless-const: true illicit: type: array description: The applied input type(s) for the category 'illicit'. items: type: string enum: - text x-stainless-const: true illicit/violent: type: array description: The applied input type(s) for the category 'illicit/violent'. items: type: string enum: - text x-stainless-const: true self-harm: type: array description: The applied input type(s) for the category 'self-harm'. items: type: string enum: - text - image self-harm/intent: type: array description: The applied input type(s) for the category 'self-harm/intent'. items: type: string enum: - text - image self-harm/instructions: type: array description: The applied input type(s) for the category 'self-harm/instructions'. items: type: string enum: - text - image sexual: type: array description: The applied input type(s) for the category 'sexual'. items: type: string enum: - text - image sexual/minors: type: array description: The applied input type(s) for the category 'sexual/minors'. items: type: string enum: - text x-stainless-const: true violence: type: array description: The applied input type(s) for the category 'violence'. items: type: string enum: - text - image violence/graphic: type: array description: The applied input type(s) for the category 'violence/graphic'. items: type: string enum: - text - image required: - hate - hate/threatening - harassment - harassment/threatening - illicit - illicit/violent - self-harm - self-harm/intent - self-harm/instructions - sexual - sexual/minors - violence - violence/graphic required: - flagged - categories - category_scores - category_applied_input_types required: - id - model - results x-oaiMeta: name: The moderation object example: | { "id": "modr-0d9740456c391e43c445bf0f010940c7", "model": "omni-moderation-latest", "results": [ { "flagged": true, "categories": { "harassment": true, "harassment/threatening": true, "sexual": false, "hate": false, "hate/threatening": false, "illicit": false, "illicit/violent": false, "self-harm/intent": false, "self-harm/instructions": false, "self-harm": false, "sexual/minors": false, "violence": true, "violence/graphic": true }, "category_scores": { "harassment": 0.8189693396524255, "harassment/threatening": 0.804985420696006, "sexual": 1.573112165348997e-6, "hate": 0.007562942636942845, "hate/threatening": 0.004208854591835476, "illicit": 0.030535955153511665, "illicit/violent": 0.008925306722380033, "self-harm/intent": 0.00023023930975076432, "self-harm/instructions": 0.0002293869201073356, "self-harm": 0.012598046106750154, "sexual/minors": 2.212566909570261e-8, "violence": 0.9999992735124786, "violence/graphic": 0.843064871157054 }, "category_applied_input_types": { "harassment": [ "text" ], "harassment/threatening": [ "text" ], "sexual": [ "text", "image" ], "hate": [ "text" ], "hate/threatening": [ "text" ], "illicit": [ "text" ], "illicit/violent": [ "text" ], "self-harm/intent": [ "text", "image" ], "self-harm/instructions": [ "text", "image" ], "self-harm": [ "text", "image" ], "sexual/minors": [ "text" ], "violence": [ "text", "image" ], "violence/graphic": [ "text", "image" ] } } ] } CreateResponse: allOf: - $ref: '#/components/schemas/CreateModelResponseProperties' - $ref: '#/components/schemas/ResponseProperties' - type: object properties: input: description: | Text, image, or file inputs to the model, used to generate a response. Learn more: - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - [Image inputs](https://platform.openai.com/docs/guides/images) - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - [Function calling](https://platform.openai.com/docs/guides/function-calling) anyOf: - type: string title: Text input description: | A text input to the model, equivalent to a text input with the `user` role. - type: array title: Input item list description: | A list of one or many input items to the model, containing different content types. items: $ref: '#/components/schemas/InputItem' include: type: array description: | Specify additional output data to include in the model response. Currently supported values are: - `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items. - `computer_call_output.output.image_url`: Include image urls from the computer call output. - `file_search_call.results`: Include the search results of the file search tool call. - `message.input_image.image_url`: Include image urls from the input message. - `message.output_text.logprobs`: Include logprobs with assistant messages. - `reasoning.encrypted_content`: Includes an encrypted version of reasoning tokens in reasoning item outputs. This enables reasoning items to be used in multi-turn conversations when using the Responses API statelessly (like when the `store` parameter is set to `false`, or when an organization is enrolled in the zero data retention program). items: $ref: '#/components/schemas/Includable' nullable: true parallel_tool_calls: type: boolean description: | Whether to allow the model to run tool calls in parallel. default: true nullable: true store: type: boolean description: | Whether to store the generated model response for later retrieval via API. default: true nullable: true instructions: type: string nullable: true description: | A system (or developer) message inserted into the model's context. When using along with `previous_response_id`, the instructions from a previous response will not be carried over to the next response. This makes it simple to swap out system (or developer) messages in new responses. stream: description: > If set to true, the model response data will be streamed to the client as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). See the [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) for more information. type: boolean nullable: true default: false stream_options: $ref: '#/components/schemas/ResponseStreamOptions' CreateRunRequest: type: object additionalProperties: false properties: assistant_id: description: >- The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. type: string model: description: >- The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. anyOf: - type: string - $ref: '#/components/schemas/AssistantSupportedModels' x-oaiTypeLabel: string nullable: true reasoning_effort: $ref: '#/components/schemas/ReasoningEffort' instructions: description: >- Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. type: string nullable: true additional_instructions: description: >- Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. type: string nullable: true additional_messages: description: Adds additional messages to the thread before creating the run. type: array items: $ref: '#/components/schemas/CreateMessageRequest' nullable: true tools: description: >- Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. nullable: true type: array maxItems: 20 items: $ref: '#/components/schemas/AssistantTool' metadata: $ref: '#/components/schemas/Metadata' temperature: type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. stream: type: boolean nullable: true description: > If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. max_prompt_tokens: type: integer nullable: true description: > The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 max_completion_tokens: type: integer nullable: true description: > The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 truncation_strategy: allOf: - $ref: '#/components/schemas/TruncationObject' - nullable: true tool_choice: allOf: - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - nullable: true parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true required: &ref_0 - assistant_id CreateSpeechRequest: type: object additionalProperties: false properties: model: description: > One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. anyOf: - type: string - type: string enum: - tts-1 - tts-1-hd - gpt-4o-mini-tts x-stainless-nominal: false x-oaiTypeLabel: string input: type: string description: The text to generate audio for. The maximum length is 4096 characters. maxLength: 4096 instructions: type: string description: >- Control the voice of your generated audio with additional instructions. Does not work with `tts-1` or `tts-1-hd`. maxLength: 4096 voice: description: >- The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). $ref: '#/components/schemas/VoiceIdsShared' response_format: description: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. default: mp3 type: string enum: - mp3 - opus - aac - flac - wav - pcm speed: description: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default. type: number default: 1 minimum: 0.25 maximum: 4 stream_format: description: >- The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`. type: string default: audio enum: - sse - audio required: - model - input - voice CreateSpeechResponseStreamEvent: anyOf: - $ref: '#/components/schemas/SpeechAudioDeltaEvent' - $ref: '#/components/schemas/SpeechAudioDoneEvent' discriminator: propertyName: type CreateThreadAndRunRequest: type: object additionalProperties: false properties: assistant_id: description: >- The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. type: string thread: $ref: '#/components/schemas/CreateThreadRequest' model: description: >- The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. anyOf: - type: string - type: string enum: - gpt-5 - gpt-5-mini - gpt-5-nano - gpt-5-2025-08-07 - gpt-5-mini-2025-08-07 - gpt-5-nano-2025-08-07 - gpt-4.1 - gpt-4.1-mini - gpt-4.1-nano - gpt-4.1-2025-04-14 - gpt-4.1-mini-2025-04-14 - gpt-4.1-nano-2025-04-14 - gpt-4o - gpt-4o-2024-11-20 - gpt-4o-2024-08-06 - gpt-4o-2024-05-13 - gpt-4o-mini - gpt-4o-mini-2024-07-18 - gpt-4.5-preview - gpt-4.5-preview-2025-02-27 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview - gpt-4-turbo-preview - gpt-4-1106-preview - gpt-4-vision-preview - gpt-4 - gpt-4-0314 - gpt-4-0613 - gpt-4-32k - gpt-4-32k-0314 - gpt-4-32k-0613 - gpt-3.5-turbo - gpt-3.5-turbo-16k - gpt-3.5-turbo-0613 - gpt-3.5-turbo-1106 - gpt-3.5-turbo-0125 - gpt-3.5-turbo-16k-0613 x-oaiTypeLabel: string nullable: true instructions: description: >- Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. type: string nullable: true tools: description: >- Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. nullable: true type: array maxItems: 20 items: $ref: '#/components/schemas/AssistantTool' tool_resources: type: object description: > A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. maxItems: 1 items: type: string nullable: true metadata: $ref: '#/components/schemas/Metadata' temperature: type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. stream: type: boolean nullable: true description: > If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. max_prompt_tokens: type: integer nullable: true description: > The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 max_completion_tokens: type: integer nullable: true description: > The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 truncation_strategy: allOf: - $ref: '#/components/schemas/TruncationObject' - nullable: true tool_choice: allOf: - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - nullable: true parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true required: *ref_0 CreateThreadRequest: type: object description: | Options to create a new thread. If no thread is provided when running a request, an empty thread will be created. additionalProperties: false properties: messages: description: >- A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with. type: array items: $ref: '#/components/schemas/CreateMessageRequest' tool_resources: type: object description: > A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. maxItems: 1 items: type: string vector_stores: type: array description: > A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread. maxItems: 1 items: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. maxItems: 10000 items: type: string chunking_strategy: type: object description: >- The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. anyOf: - type: object title: Auto Chunking Strategy description: >- The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. additionalProperties: false properties: type: type: string description: Always `auto`. enum: - auto x-stainless-const: true required: - type - type: object title: Static Chunking Strategy additionalProperties: false properties: type: type: string description: Always `static`. enum: - static x-stainless-const: true static: type: object additionalProperties: false properties: max_chunk_size_tokens: type: integer minimum: 100 maximum: 4096 description: >- The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. chunk_overlap_tokens: type: integer description: > The number of tokens that overlap between chunks. The default value is `400`. Note that the overlap must not exceed half of `max_chunk_size_tokens`. required: - max_chunk_size_tokens - chunk_overlap_tokens required: - type - static x-stainless-naming: java: type_name: StaticObject kotlin: type_name: StaticObject discriminator: propertyName: type metadata: $ref: '#/components/schemas/Metadata' anyOf: - required: - vector_store_ids - required: - vector_stores nullable: true metadata: $ref: '#/components/schemas/Metadata' CreateTranscriptionRequest: type: object additionalProperties: false properties: file: description: > The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. type: string x-oaiTypeLabel: file format: binary x-oaiMeta: exampleFilePath: speech.mp3 model: description: > ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source Whisper V2 model). example: gpt-4o-transcribe anyOf: - type: string - type: string enum: - whisper-1 - gpt-4o-transcribe - gpt-4o-mini-transcribe x-stainless-const: true x-stainless-nominal: false x-oaiTypeLabel: string language: description: > The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency. type: string prompt: description: > An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language. type: string response_format: $ref: '#/components/schemas/AudioResponseFormat' temperature: description: > The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. type: number default: 0 stream: description: > If set to true, the model response data will be streamed to the client as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). See the [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) for more information. Note: Streaming is not supported for the `whisper-1` model and will be ignored. type: boolean nullable: true default: false chunking_strategy: $ref: '#/components/schemas/TranscriptionChunkingStrategy' timestamp_granularities: description: > The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. type: array items: type: string enum: - word - segment default: - segment include: description: | Additional information to include in the transcription response. `logprobs` will return the log probabilities of the tokens in the response to understand the model's confidence in the transcription. `logprobs` only works with response_format set to `json` and only with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`. type: array items: $ref: '#/components/schemas/TranscriptionInclude' required: - file - model CreateTranscriptionResponseJson: type: object description: Represents a transcription response returned by model, based on the provided input. properties: text: type: string description: The transcribed text. logprobs: type: array optional: true description: > The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array. items: type: object properties: token: type: string description: The token in the transcription. logprob: type: number description: The log probability of the token. bytes: type: array items: type: number description: The bytes of the token. usage: type: object description: Token usage statistics for the request. anyOf: - $ref: '#/components/schemas/TranscriptTextUsageTokens' title: Token Usage - $ref: '#/components/schemas/TranscriptTextUsageDuration' title: Duration Usage discriminator: propertyName: type required: - text x-oaiMeta: name: The transcription object (JSON) group: audio example: | { "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.", "usage": { "type": "tokens", "input_tokens": 14, "input_token_details": { "text_tokens": 10, "audio_tokens": 4 }, "output_tokens": 101, "total_tokens": 115 } } CreateTranscriptionResponseStreamEvent: anyOf: - $ref: '#/components/schemas/TranscriptTextDeltaEvent' - $ref: '#/components/schemas/TranscriptTextDoneEvent' discriminator: propertyName: type CreateTranscriptionResponseVerboseJson: type: object description: Represents a verbose json transcription response returned by model, based on the provided input. properties: language: type: string description: The language of the input audio. duration: type: number description: The duration of the input audio. text: type: string description: The transcribed text. words: type: array description: Extracted words and their corresponding timestamps. items: $ref: '#/components/schemas/TranscriptionWord' segments: type: array description: Segments of the transcribed text and their corresponding details. items: $ref: '#/components/schemas/TranscriptionSegment' usage: $ref: '#/components/schemas/TranscriptTextUsageDuration' required: - language - duration - text x-oaiMeta: name: The transcription object (Verbose JSON) group: audio example: | { "task": "transcribe", "language": "english", "duration": 8.470000267028809, "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", "segments": [ { "id": 0, "seek": 0, "start": 0.0, "end": 3.319999933242798, "text": " The beach was a popular spot on a hot summer day.", "tokens": [ 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530 ], "temperature": 0.0, "avg_logprob": -0.2860786020755768, "compression_ratio": 1.2363636493682861, "no_speech_prob": 0.00985979475080967 }, ... ], "usage": { "type": "duration", "seconds": 9 } } CreateTranslationRequest: type: object additionalProperties: false properties: file: description: > The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. type: string x-oaiTypeLabel: file format: binary x-oaiMeta: exampleFilePath: speech.mp3 model: description: > ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. example: whisper-1 anyOf: - type: string - type: string enum: - whisper-1 x-stainless-const: true x-oaiTypeLabel: string prompt: description: > An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should be in English. type: string response_format: description: > The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. type: string enum: - json - text - srt - verbose_json - vtt default: json temperature: description: > The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. type: number default: 0 required: - file - model CreateTranslationResponseJson: type: object properties: text: type: string required: - text CreateTranslationResponseVerboseJson: type: object properties: language: type: string description: The language of the output translation (always `english`). duration: type: number description: The duration of the input audio. text: type: string description: The translated text. segments: type: array description: Segments of the translated text and their corresponding details. items: $ref: '#/components/schemas/TranscriptionSegment' required: - language - duration - text CreateUploadRequest: type: object additionalProperties: false properties: filename: description: | The name of the file to upload. type: string purpose: description: > The intended purpose of the uploaded file. See the [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). type: string enum: - assistants - batch - fine-tune - vision bytes: description: | The number of bytes in the file you are uploading. type: integer mime_type: description: > The MIME type of the file. This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. type: string expires_after: $ref: '#/components/schemas/FileExpirationAfter' required: - filename - purpose - bytes - mime_type CreateVectorStoreFileBatchRequest: type: object additionalProperties: false properties: file_ids: description: >- A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. type: array minItems: 1 maxItems: 500 items: type: string chunking_strategy: $ref: '#/components/schemas/ChunkingStrategyRequestParam' attributes: $ref: '#/components/schemas/VectorStoreFileAttributes' required: - file_ids CreateVectorStoreFileRequest: type: object additionalProperties: false properties: file_id: description: >- A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. type: string chunking_strategy: $ref: '#/components/schemas/ChunkingStrategyRequestParam' attributes: $ref: '#/components/schemas/VectorStoreFileAttributes' required: - file_id CreateVectorStoreRequest: type: object additionalProperties: false properties: file_ids: description: >- A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. type: array maxItems: 500 items: type: string name: description: The name of the vector store. type: string expires_after: $ref: '#/components/schemas/VectorStoreExpirationAfter' chunking_strategy: $ref: '#/components/schemas/ChunkingStrategyRequestParam' metadata: $ref: '#/components/schemas/Metadata' CustomTool: type: object title: Custom tool description: | A custom tool that processes input using a specified format. Learn more about [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools). properties: type: type: string enum: - custom description: The type of the custom tool. Always `custom`. x-stainless-const: true name: type: string description: The name of the custom tool, used to identify it in tool calls. description: type: string description: | Optional description of the custom tool, used to provide more context. format: description: | The input format for the custom tool. Default is unconstrained text. anyOf: - type: object title: Text format description: Unconstrained free-form text. properties: type: type: string enum: - text description: Unconstrained text format. Always `text`. x-stainless-const: true required: - type additionalProperties: false - type: object title: Grammar format description: A grammar defined by the user. properties: type: type: string enum: - grammar description: Grammar format. Always `grammar`. x-stainless-const: true definition: type: string description: The grammar definition. syntax: type: string description: The syntax of the grammar definition. One of `lark` or `regex`. enum: - lark - regex required: - type - definition - syntax additionalProperties: false discriminator: propertyName: type required: - type - name CustomToolCall: type: object title: Custom tool call description: | A call to a custom tool created by the model. properties: type: type: string enum: - custom_tool_call x-stainless-const: true description: | The type of the custom tool call. Always `custom_tool_call`. id: type: string description: | The unique ID of the custom tool call in the OpenAI platform. call_id: type: string description: | An identifier used to map this custom tool call to a tool call output. name: type: string description: | The name of the custom tool being called. input: type: string description: | The input for the custom tool call generated by the model. required: - type - call_id - name - input CustomToolCallOutput: type: object title: Custom tool call output description: | The output of a custom tool call from your code, being sent back to the model. properties: type: type: string enum: - custom_tool_call_output x-stainless-const: true description: | The type of the custom tool call output. Always `custom_tool_call_output`. id: type: string description: | The unique ID of the custom tool call output in the OpenAI platform. call_id: type: string description: | The call ID, used to map this custom tool call output to a custom tool call. output: type: string description: | The output from the custom tool call generated by your code. required: - type - call_id - output CustomToolChatCompletions: type: object title: Custom tool description: | A custom tool that processes input using a specified format. properties: type: type: string enum: - custom description: The type of the custom tool. Always `custom`. x-stainless-const: true custom: type: object title: Custom tool properties description: | Properties of the custom tool. properties: name: type: string description: The name of the custom tool, used to identify it in tool calls. description: type: string description: | Optional description of the custom tool, used to provide more context. format: description: | The input format for the custom tool. Default is unconstrained text. anyOf: - type: object title: Text format description: Unconstrained free-form text. properties: type: type: string enum: - text description: Unconstrained text format. Always `text`. x-stainless-const: true required: - type additionalProperties: false - type: object title: Grammar format description: A grammar defined by the user. properties: type: type: string enum: - grammar description: Grammar format. Always `grammar`. x-stainless-const: true grammar: type: object title: Grammar format description: Your chosen grammar. properties: definition: type: string description: The grammar definition. syntax: type: string description: The syntax of the grammar definition. One of `lark` or `regex`. enum: - lark - regex required: - definition - syntax required: - type - grammar additionalProperties: false discriminator: propertyName: type required: - name required: - type - custom DeleteAssistantResponse: type: object properties: id: type: string deleted: type: boolean object: type: string enum: - assistant.deleted x-stainless-const: true required: - id - object - deleted DeleteCertificateResponse: type: object properties: object: description: The object type, must be `certificate.deleted`. x-stainless-const: true const: certificate.deleted id: type: string description: The ID of the certificate that was deleted. required: - object - id DeleteFileResponse: type: object properties: id: type: string object: type: string enum: - file x-stainless-const: true deleted: type: boolean required: - id - object - deleted DeleteFineTuningCheckpointPermissionResponse: type: object properties: id: type: string description: The ID of the fine-tuned model checkpoint permission that was deleted. object: type: string description: The object type, which is always "checkpoint.permission". enum: - checkpoint.permission x-stainless-const: true deleted: type: boolean description: Whether the fine-tuned model checkpoint permission was successfully deleted. required: - id - object - deleted DeleteMessageResponse: type: object properties: id: type: string deleted: type: boolean object: type: string enum: - thread.message.deleted x-stainless-const: true required: - id - object - deleted DeleteModelResponse: type: object properties: id: type: string deleted: type: boolean object: type: string required: - id - object - deleted DeleteThreadResponse: type: object properties: id: type: string deleted: type: boolean object: type: string enum: - thread.deleted x-stainless-const: true required: - id - object - deleted DeleteVectorStoreFileResponse: type: object properties: id: type: string deleted: type: boolean object: type: string enum: - vector_store.file.deleted x-stainless-const: true required: - id - object - deleted DeleteVectorStoreResponse: type: object properties: id: type: string deleted: type: boolean object: type: string enum: - vector_store.deleted x-stainless-const: true required: - id - object - deleted DoneEvent: type: object properties: event: type: string enum: - done x-stainless-const: true data: type: string enum: - '[DONE]' x-stainless-const: true required: - event - data description: Occurs when a stream ends. x-oaiMeta: dataDescription: '`data` is `[DONE]`' DoubleClick: type: object title: DoubleClick description: | A double click action. properties: type: type: string enum: - double_click default: double_click description: | Specifies the event type. For a double click action, this property is always set to `double_click`. x-stainless-const: true x: type: integer description: | The x-coordinate where the double click occurred. 'y': type: integer description: | The y-coordinate where the double click occurred. required: - type - x - 'y' Drag: type: object title: Drag description: | A drag action. properties: type: type: string enum: - drag default: drag description: | Specifies the event type. For a drag action, this property is always set to `drag`. x-stainless-const: true path: type: array description: > An array of coordinates representing the path of the drag action. Coordinates will appear as an array of objects, eg ``` [ { x: 100, y: 200 }, { x: 200, y: 300 } ] ``` items: title: Drag path coordinates description: | A series of x/y coordinate pairs in the drag path. $ref: '#/components/schemas/Coordinate' required: - type - path EasyInputMessage: type: object title: Input message description: | A message input to the model with a role indicating instruction following hierarchy. Instructions given with the `developer` or `system` role take precedence over instructions given with the `user` role. Messages with the `assistant` role are presumed to have been generated by the model in previous interactions. properties: role: type: string description: | The role of the message input. One of `user`, `assistant`, `system`, or `developer`. enum: - user - assistant - system - developer content: description: | Text, image, or audio input to the model, used to generate a response. Can also contain previous assistant responses. anyOf: - type: string title: Text input description: | A text input to the model. - $ref: '#/components/schemas/InputMessageContentList' type: type: string description: | The type of the message input. Always `message`. enum: - message x-stainless-const: true required: - role - content Embedding: type: object description: | Represents an embedding vector returned by embedding endpoint. properties: index: type: integer description: The index of the embedding in the list of embeddings. embedding: type: array description: > The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](https://platform.openai.com/docs/guides/embeddings). items: type: number format: float object: type: string description: The object type, which is always "embedding". enum: - embedding x-stainless-const: true required: - index - object - embedding x-oaiMeta: name: The embedding object example: | { "object": "embedding", "embedding": [ 0.0023064255, -0.009327292, .... (1536 floats total for ada-002) -0.0028842222, ], "index": 0 } Error: type: object properties: code: type: string nullable: true message: type: string nullable: false param: type: string nullable: true type: type: string nullable: false required: - type - message - param - code ErrorEvent: type: object properties: event: type: string enum: - error x-stainless-const: true data: $ref: '#/components/schemas/Error' required: - event - data description: >- Occurs when an [error](https://platform.openai.com/docs/guides/error-codes#api-errors) occurs. This can happen due to an internal server error or a timeout. x-oaiMeta: dataDescription: '`data` is an [error](/docs/guides/error-codes#api-errors)' ErrorResponse: type: object properties: error: $ref: '#/components/schemas/Error' required: - error Eval: type: object title: Eval description: | An Eval object with a data source config and testing criteria. An Eval represents a task to be done for your LLM integration. Like: - Improve the quality of my chatbot - See how well my chatbot handles customer support - Check if o4-mini is better at my usecase than gpt-4o properties: object: type: string enum: - eval default: eval description: The object type. x-stainless-const: true id: type: string description: Unique identifier for the evaluation. name: type: string description: The name of the evaluation. example: Chatbot effectiveness Evaluation data_source_config: type: object description: Configuration of data sources used in runs of the evaluation. anyOf: - $ref: '#/components/schemas/EvalCustomDataSourceConfig' - $ref: '#/components/schemas/EvalLogsDataSourceConfig' - $ref: '#/components/schemas/EvalStoredCompletionsDataSourceConfig' discriminator: propertyName: type testing_criteria: description: A list of testing criteria. type: array items: anyOf: - $ref: '#/components/schemas/EvalGraderLabelModel' - $ref: '#/components/schemas/EvalGraderStringCheck' - $ref: '#/components/schemas/EvalGraderTextSimilarity' - $ref: '#/components/schemas/EvalGraderPython' - $ref: '#/components/schemas/EvalGraderScoreModel' created_at: type: integer description: The Unix timestamp (in seconds) for when the eval was created. metadata: $ref: '#/components/schemas/Metadata' required: - id - data_source_config - object - testing_criteria - name - created_at - metadata x-oaiMeta: name: The eval object group: evals example: | { "object": "eval", "id": "eval_67abd54d9b0081909a86353f6fb9317a", "data_source_config": { "type": "custom", "item_schema": { "type": "object", "properties": { "label": {"type": "string"}, }, "required": ["label"] }, "include_sample_schema": true }, "testing_criteria": [ { "name": "My string check grader", "type": "string_check", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "operation": "eq", } ], "name": "External Data Eval", "created_at": 1739314509, "metadata": { "test": "synthetics", } } EvalApiError: type: object title: EvalApiError description: | An object representing an error response from the Eval API. properties: code: type: string description: The error code. message: type: string description: The error message. required: - code - message x-oaiMeta: name: The API error object group: evals example: | { "code": "internal_error", "message": "The eval run failed due to an internal error." } EvalCustomDataSourceConfig: type: object title: CustomDataSourceConfig description: | A CustomDataSourceConfig which specifies the schema of your `item` and optionally `sample` namespaces. The response schema defines the shape of the data that will be: - Used to define your testing criteria and - What data is required when creating a run properties: type: type: string enum: - custom default: custom description: The type of data source. Always `custom`. x-stainless-const: true schema: type: object description: | The json schema for the run data source items. Learn how to build JSON schemas [here](https://json-schema.org/). additionalProperties: true required: - type - schema x-oaiMeta: name: The eval custom data source config object group: evals example: | { "type": "custom", "schema": { "type": "object", "properties": { "item": { "type": "object", "properties": { "label": {"type": "string"}, }, "required": ["label"] } }, "required": ["item"] } } EvalGraderLabelModel: type: object title: LabelModelGrader allOf: - $ref: '#/components/schemas/GraderLabelModel' EvalGraderPython: type: object title: PythonGrader allOf: - $ref: '#/components/schemas/GraderPython' - type: object properties: pass_threshold: type: number description: The threshold for the score. x-oaiMeta: name: Eval Python Grader group: graders example: | { "type": "python", "name": "Example python grader", "image_tag": "2025-05-08", "source": """ def grade(sample: dict, item: dict) -> float: \""" Returns 1.0 if `output_text` equals `label`, otherwise 0.0. \""" output = sample.get("output_text") label = item.get("label") return 1.0 if output == label else 0.0 """, "pass_threshold": 0.8 } EvalGraderScoreModel: type: object title: ScoreModelGrader allOf: - $ref: '#/components/schemas/GraderScoreModel' - type: object properties: pass_threshold: type: number description: The threshold for the score. EvalGraderStringCheck: type: object title: StringCheckGrader allOf: - $ref: '#/components/schemas/GraderStringCheck' EvalGraderTextSimilarity: type: object title: TextSimilarityGrader allOf: - $ref: '#/components/schemas/GraderTextSimilarity' - type: object properties: pass_threshold: type: number description: The threshold for the score. required: - pass_threshold x-oaiMeta: name: Text Similarity Grader group: graders example: | { "type": "text_similarity", "name": "Example text similarity grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "pass_threshold": 0.8, "evaluation_metric": "fuzzy_match" } EvalItem: type: object title: Eval message object description: | A message input to the model with a role indicating instruction following hierarchy. Instructions given with the `developer` or `system` role take precedence over instructions given with the `user` role. Messages with the `assistant` role are presumed to have been generated by the model in previous interactions. properties: role: type: string description: | The role of the message input. One of `user`, `assistant`, `system`, or `developer`. enum: - user - assistant - system - developer content: description: | Inputs to the model - can contain template strings. anyOf: - type: string title: Text input description: | A text input to the model. - $ref: '#/components/schemas/InputTextContent' - type: object title: Output text description: | A text output from the model. properties: type: type: string description: | The type of the output text. Always `output_text`. enum: - output_text x-stainless-const: true text: type: string description: | The text output from the model. required: - type - text - type: object title: Input image description: | An image input to the model. properties: type: type: string description: | The type of the image input. Always `input_image`. enum: - input_image x-stainless-const: true image_url: type: string description: | The URL of the image input. detail: type: string description: > The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. required: - type - image_url - type: array title: An array of Input text and Input image description: | A list of inputs, each of which may be either an input text or input image object. type: type: string description: | The type of the message input. Always `message`. enum: - message x-stainless-const: true required: - role - content EvalJsonlFileContentSource: type: object title: EvalJsonlFileContentSource properties: type: type: string enum: - file_content default: file_content description: The type of jsonl source. Always `file_content`. x-stainless-const: true content: type: array items: type: object properties: item: type: object additionalProperties: true sample: type: object additionalProperties: true required: - item description: The content of the jsonl file. required: - type - content EvalJsonlFileIdSource: type: object title: EvalJsonlFileIdSource properties: type: type: string enum: - file_id default: file_id description: The type of jsonl source. Always `file_id`. x-stainless-const: true id: type: string description: The identifier of the file. required: - type - id EvalList: type: object title: EvalList description: | An object representing a list of evals. properties: object: type: string enum: - list default: list description: | The type of this object. It is always set to "list". x-stainless-const: true data: type: array description: | An array of eval objects. items: $ref: '#/components/schemas/Eval' first_id: type: string description: The identifier of the first eval in the data array. last_id: type: string description: The identifier of the last eval in the data array. has_more: type: boolean description: Indicates whether there are more evals available. required: - object - data - first_id - last_id - has_more x-oaiMeta: name: The eval list object group: evals example: | { "object": "list", "data": [ { "object": "eval", "id": "eval_67abd54d9b0081909a86353f6fb9317a", "data_source_config": { "type": "custom", "schema": { "type": "object", "properties": { "item": { "type": "object", "properties": { "input": { "type": "string" }, "ground_truth": { "type": "string" } }, "required": [ "input", "ground_truth" ] } }, "required": [ "item" ] } }, "testing_criteria": [ { "name": "String check", "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", "type": "string_check", "input": "{{item.input}}", "reference": "{{item.ground_truth}}", "operation": "eq" } ], "name": "External Data Eval", "created_at": 1739314509, "metadata": {}, } ], "first_id": "eval_67abd54d9b0081909a86353f6fb9317a", "last_id": "eval_67abd54d9b0081909a86353f6fb9317a", "has_more": true } EvalLogsDataSourceConfig: type: object title: LogsDataSourceConfig description: > A LogsDataSourceConfig which specifies the metadata property of your logs query. This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The schema returned by this data source config is used to defined what variables are available in your evals. `item` and `sample` are both defined when using this data source config. properties: type: type: string enum: - logs default: logs description: The type of data source. Always `logs`. x-stainless-const: true metadata: $ref: '#/components/schemas/Metadata' schema: type: object description: | The json schema for the run data source items. Learn how to build JSON schemas [here](https://json-schema.org/). additionalProperties: true required: - type - schema x-oaiMeta: name: The logs data source object for evals group: evals example: | { "type": "logs", "metadata": { "language": "english" }, "schema": { "type": "object", "properties": { "item": { "type": "object" }, "sample": { "type": "object" } }, "required": [ "item", "sample" } } EvalResponsesSource: type: object title: EvalResponsesSource description: | A EvalResponsesSource object describing a run data source configuration. properties: type: type: string enum: - responses description: The type of run data source. Always `responses`. metadata: type: object nullable: true description: Metadata filter for the responses. This is a query parameter used to select responses. model: type: string nullable: true description: The name of the model to find responses for. This is a query parameter used to select responses. instructions_search: type: string nullable: true description: >- Optional string to search the 'instructions' field. This is a query parameter used to select responses. created_after: type: integer minimum: 0 nullable: true description: >- Only include items created after this timestamp (inclusive). This is a query parameter used to select responses. created_before: type: integer minimum: 0 nullable: true description: >- Only include items created before this timestamp (inclusive). This is a query parameter used to select responses. reasoning_effort: $ref: '#/components/schemas/ReasoningEffort' nullable: true description: Optional reasoning effort parameter. This is a query parameter used to select responses. temperature: type: number nullable: true description: Sampling temperature. This is a query parameter used to select responses. top_p: type: number nullable: true description: Nucleus sampling parameter. This is a query parameter used to select responses. users: type: array items: type: string nullable: true description: List of user identifiers. This is a query parameter used to select responses. tools: type: array items: type: string nullable: true description: List of tool names. This is a query parameter used to select responses. required: - type x-oaiMeta: name: The run data source object used to configure an individual run group: eval runs example: | { "type": "responses", "model": "gpt-4o-mini-2024-07-18", "temperature": 0.7, "top_p": 1.0, "users": ["user1", "user2"], "tools": ["tool1", "tool2"], "instructions_search": "You are a coding assistant" } EvalRun: type: object title: EvalRun description: | A schema representing an evaluation run. properties: object: type: string enum: - eval.run default: eval.run description: The type of the object. Always "eval.run". x-stainless-const: true id: type: string description: Unique identifier for the evaluation run. eval_id: type: string description: The identifier of the associated evaluation. status: type: string description: The status of the evaluation run. model: type: string description: The model that is evaluated, if applicable. name: type: string description: The name of the evaluation run. created_at: type: integer description: Unix timestamp (in seconds) when the evaluation run was created. report_url: type: string description: The URL to the rendered evaluation run report on the UI dashboard. result_counts: type: object description: Counters summarizing the outcomes of the evaluation run. properties: total: type: integer description: Total number of executed output items. errored: type: integer description: Number of output items that resulted in an error. failed: type: integer description: Number of output items that failed to pass the evaluation. passed: type: integer description: Number of output items that passed the evaluation. required: - total - errored - failed - passed per_model_usage: type: array description: Usage statistics for each model during the evaluation run. items: type: object properties: model_name: type: string description: The name of the model. x-stainless-naming: python: property_name: run_model_name invocation_count: type: integer description: The number of invocations. prompt_tokens: type: integer description: The number of prompt tokens used. completion_tokens: type: integer description: The number of completion tokens generated. total_tokens: type: integer description: The total number of tokens used. cached_tokens: type: integer description: The number of tokens retrieved from cache. required: - model_name - invocation_count - prompt_tokens - completion_tokens - total_tokens - cached_tokens per_testing_criteria_results: type: array description: Results per testing criteria applied during the evaluation run. items: type: object properties: testing_criteria: type: string description: A description of the testing criteria. passed: type: integer description: Number of tests passed for this criteria. failed: type: integer description: Number of tests failed for this criteria. required: - testing_criteria - passed - failed data_source: type: object description: Information about the run's data source. anyOf: - $ref: '#/components/schemas/CreateEvalJsonlRunDataSource' - $ref: '#/components/schemas/CreateEvalCompletionsRunDataSource' - $ref: '#/components/schemas/CreateEvalResponsesRunDataSource' discriminator: propertyName: type metadata: $ref: '#/components/schemas/Metadata' error: $ref: '#/components/schemas/EvalApiError' required: - object - id - eval_id - status - model - name - created_at - report_url - result_counts - per_model_usage - per_testing_criteria_results - data_source - metadata - error x-oaiMeta: name: The eval run object group: evals example: | { "object": "eval.run", "id": "evalrun_67e57965b480819094274e3a32235e4c", "eval_id": "eval_67e579652b548190aaa83ada4b125f47", "report_url": "https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47?run_id=evalrun_67e57965b480819094274e3a32235e4c", "status": "queued", "model": "gpt-4o-mini", "name": "gpt-4o-mini", "created_at": 1743092069, "result_counts": { "total": 0, "errored": 0, "failed": 0, "passed": 0 }, "per_model_usage": null, "per_testing_criteria_results": null, "data_source": { "type": "completions", "source": { "type": "file_content", "content": [ { "item": { "input": "Tech Company Launches Advanced Artificial Intelligence Platform", "ground_truth": "Technology" } }, { "item": { "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", "ground_truth": "Markets" } }, { "item": { "input": "International Summit Addresses Climate Change Strategies", "ground_truth": "World" } }, { "item": { "input": "Major Retailer Reports Record-Breaking Holiday Sales", "ground_truth": "Business" } }, { "item": { "input": "National Team Qualifies for World Championship Finals", "ground_truth": "Sports" } }, { "item": { "input": "Stock Markets Rally After Positive Economic Data Released", "ground_truth": "Markets" } }, { "item": { "input": "Global Manufacturer Announces Merger with Competitor", "ground_truth": "Business" } }, { "item": { "input": "Breakthrough in Renewable Energy Technology Unveiled", "ground_truth": "Technology" } }, { "item": { "input": "World Leaders Sign Historic Climate Agreement", "ground_truth": "World" } }, { "item": { "input": "Professional Athlete Sets New Record in Championship Event", "ground_truth": "Sports" } }, { "item": { "input": "Financial Institutions Adapt to New Regulatory Requirements", "ground_truth": "Business" } }, { "item": { "input": "Tech Conference Showcases Advances in Artificial Intelligence", "ground_truth": "Technology" } }, { "item": { "input": "Global Markets Respond to Oil Price Fluctuations", "ground_truth": "Markets" } }, { "item": { "input": "International Cooperation Strengthened Through New Treaty", "ground_truth": "World" } }, { "item": { "input": "Sports League Announces Revised Schedule for Upcoming Season", "ground_truth": "Sports" } } ] }, "input_messages": { "type": "template", "template": [ { "type": "message", "role": "developer", "content": { "type": "input_text", "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "{{item.input}}" } } ] }, "model": "gpt-4o-mini", "sampling_params": { "seed": 42, "temperature": 1.0, "top_p": 1.0, "max_completions_tokens": 2048 } }, "error": null, "metadata": {} } EvalRunList: type: object title: EvalRunList description: | An object representing a list of runs for an evaluation. properties: object: type: string enum: - list default: list description: | The type of this object. It is always set to "list". x-stainless-const: true data: type: array description: | An array of eval run objects. items: $ref: '#/components/schemas/EvalRun' first_id: type: string description: The identifier of the first eval run in the data array. last_id: type: string description: The identifier of the last eval run in the data array. has_more: type: boolean description: Indicates whether there are more evals available. required: - object - data - first_id - last_id - has_more x-oaiMeta: name: The eval run list object group: evals example: | { "object": "list", "data": [ { "object": "eval.run", "id": "evalrun_67b7fbdad46c819092f6fe7a14189620", "eval_id": "eval_67b7fa9a81a88190ab4aa417e397ea21", "report_url": "https://platform.openai.com/evaluations/eval_67b7fa9a81a88190ab4aa417e397ea21?run_id=evalrun_67b7fbdad46c819092f6fe7a14189620", "status": "completed", "model": "o3-mini", "name": "Academic Assistant", "created_at": 1740110812, "result_counts": { "total": 171, "errored": 0, "failed": 80, "passed": 91 }, "per_model_usage": null, "per_testing_criteria_results": [ { "testing_criteria": "String check grader", "passed": 91, "failed": 80 } ], "run_data_source": { "type": "completions", "template_messages": [ { "type": "message", "role": "system", "content": { "type": "input_text", "text": "You are a helpful assistant." } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "Hello, can you help me with my homework?" } } ], "datasource_reference": null, "model": "o3-mini", "max_completion_tokens": null, "seed": null, "temperature": null, "top_p": null }, "error": null, "metadata": {"test": "synthetics"} } ], "first_id": "evalrun_67abd54d60ec8190832b46859da808f7", "last_id": "evalrun_67abd54d60ec8190832b46859da808f7", "has_more": false } EvalRunOutputItem: type: object title: EvalRunOutputItem description: | A schema representing an evaluation run output item. properties: object: type: string enum: - eval.run.output_item default: eval.run.output_item description: The type of the object. Always "eval.run.output_item". x-stainless-const: true id: type: string description: Unique identifier for the evaluation run output item. run_id: type: string description: The identifier of the evaluation run associated with this output item. eval_id: type: string description: The identifier of the evaluation group. created_at: type: integer description: Unix timestamp (in seconds) when the evaluation run was created. status: type: string description: The status of the evaluation run. datasource_item_id: type: integer description: The identifier for the data source item. datasource_item: type: object description: Details of the input data source item. additionalProperties: true results: type: array description: A list of results from the evaluation run. items: type: object description: A result object. additionalProperties: true sample: type: object description: A sample containing the input and output of the evaluation run. properties: input: type: array description: An array of input messages. items: type: object description: An input message. properties: role: type: string description: The role of the message sender (e.g., system, user, developer). content: type: string description: The content of the message. required: - role - content output: type: array description: An array of output messages. items: type: object properties: role: type: string description: The role of the message (e.g. "system", "assistant", "user"). content: type: string description: The content of the message. finish_reason: type: string description: The reason why the sample generation was finished. model: type: string description: The model used for generating the sample. usage: type: object description: Token usage details for the sample. properties: total_tokens: type: integer description: The total number of tokens used. completion_tokens: type: integer description: The number of completion tokens generated. prompt_tokens: type: integer description: The number of prompt tokens used. cached_tokens: type: integer description: The number of tokens retrieved from cache. required: - total_tokens - completion_tokens - prompt_tokens - cached_tokens error: $ref: '#/components/schemas/EvalApiError' temperature: type: number description: The sampling temperature used. max_completion_tokens: type: integer description: The maximum number of tokens allowed for completion. top_p: type: number description: The top_p value used for sampling. seed: type: integer description: The seed used for generating the sample. required: - input - output - finish_reason - model - usage - error - temperature - max_completion_tokens - top_p - seed required: - object - id - run_id - eval_id - created_at - status - datasource_item_id - datasource_item - results - sample x-oaiMeta: name: The eval run output item object group: evals example: | { "object": "eval.run.output_item", "id": "outputitem_67abd55eb6548190bb580745d5644a33", "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", "created_at": 1739314509, "status": "pass", "datasource_item_id": 137, "datasource_item": { "teacher": "To grade essays, I only check for style, content, and grammar.", "student": "I am a student who is trying to write the best essay." }, "results": [ { "name": "String Check Grader", "type": "string-check-grader", "score": 1.0, "passed": true, } ], "sample": { "input": [ { "role": "system", "content": "You are an evaluator bot..." }, { "role": "user", "content": "You are assessing..." } ], "output": [ { "role": "assistant", "content": "The rubric is not clear nor concise." } ], "finish_reason": "stop", "model": "gpt-4o-2024-08-06", "usage": { "total_tokens": 521, "completion_tokens": 2, "prompt_tokens": 519, "cached_tokens": 0 }, "error": null, "temperature": 1.0, "max_completion_tokens": 2048, "top_p": 1.0, "seed": 42 } } EvalRunOutputItemList: type: object title: EvalRunOutputItemList description: | An object representing a list of output items for an evaluation run. properties: object: type: string enum: - list default: list description: | The type of this object. It is always set to "list". x-stainless-const: true data: type: array description: | An array of eval run output item objects. items: $ref: '#/components/schemas/EvalRunOutputItem' first_id: type: string description: The identifier of the first eval run output item in the data array. last_id: type: string description: The identifier of the last eval run output item in the data array. has_more: type: boolean description: Indicates whether there are more eval run output items available. required: - object - data - first_id - last_id - has_more x-oaiMeta: name: The eval run output item list object group: evals example: | { "object": "list", "data": [ { "object": "eval.run.output_item", "id": "outputitem_67abd55eb6548190bb580745d5644a33", "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", "created_at": 1739314509, "status": "pass", "datasource_item_id": 137, "datasource_item": { "teacher": "To grade essays, I only check for style, content, and grammar.", "student": "I am a student who is trying to write the best essay." }, "results": [ { "name": "String Check Grader", "type": "string-check-grader", "score": 1.0, "passed": true, } ], "sample": { "input": [ { "role": "system", "content": "You are an evaluator bot..." }, { "role": "user", "content": "You are assessing..." } ], "output": [ { "role": "assistant", "content": "The rubric is not clear nor concise." } ], "finish_reason": "stop", "model": "gpt-4o-2024-08-06", "usage": { "total_tokens": 521, "completion_tokens": 2, "prompt_tokens": 519, "cached_tokens": 0 }, "error": null, "temperature": 1.0, "max_completion_tokens": 2048, "top_p": 1.0, "seed": 42 } }, ], "first_id": "outputitem_67abd55eb6548190bb580745d5644a33", "last_id": "outputitem_67abd55eb6548190bb580745d5644a33", "has_more": false } EvalStoredCompletionsDataSourceConfig: type: object title: StoredCompletionsDataSourceConfig description: | Deprecated in favor of LogsDataSourceConfig. properties: type: type: string enum: - stored_completions default: stored_completions description: The type of data source. Always `stored_completions`. x-stainless-const: true metadata: $ref: '#/components/schemas/Metadata' schema: type: object description: | The json schema for the run data source items. Learn how to build JSON schemas [here](https://json-schema.org/). additionalProperties: true required: - type - schema deprecated: true x-oaiMeta: name: The stored completions data source object for evals group: evals example: | { "type": "stored_completions", "metadata": { "language": "english" }, "schema": { "type": "object", "properties": { "item": { "type": "object" }, "sample": { "type": "object" } }, "required": [ "item", "sample" } } EvalStoredCompletionsSource: type: object title: StoredCompletionsRunDataSource description: | A StoredCompletionsRunDataSource configuration describing a set of filters properties: type: type: string enum: - stored_completions default: stored_completions description: The type of source. Always `stored_completions`. x-stainless-const: true metadata: $ref: '#/components/schemas/Metadata' model: type: string nullable: true description: An optional model to filter by (e.g., 'gpt-4o'). created_after: type: integer nullable: true description: An optional Unix timestamp to filter items created after this time. created_before: type: integer nullable: true description: An optional Unix timestamp to filter items created before this time. limit: type: integer nullable: true description: An optional maximum number of items to return. required: - type x-oaiMeta: name: The stored completions data source object used to configure an individual run group: eval runs example: | { "type": "stored_completions", "model": "gpt-4o", "created_after": 1668124800, "created_before": 1668124900, "limit": 100, "metadata": {} } FileExpirationAfter: type: object title: File expiration policy description: >- The expiration policy for a file. By default, files with `purpose=batch` expire after 30 days and all other files are persisted until they are manually deleted. properties: anchor: description: 'Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`.' type: string enum: - created_at x-stainless-const: true seconds: description: >- The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days). type: integer minimum: 3600 maximum: 2592000 required: - anchor - seconds FilePath: type: object title: File path description: | A path to a file. properties: type: type: string description: | The type of the file path. Always `file_path`. enum: - file_path x-stainless-const: true file_id: type: string description: | The ID of the file. index: type: integer description: | The index of the file in the list of files. required: - type - file_id - index FileSearchRanker: type: string description: The ranker to use for the file search. If not specified will use the `auto` ranker. enum: - auto - default_2024_08_21 FileSearchRankingOptions: title: File search tool call ranking options type: object description: > The ranking options for the file search. If not specified, the file search tool will use the `auto` ranker and a score_threshold of 0. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. properties: ranker: $ref: '#/components/schemas/FileSearchRanker' score_threshold: type: number description: >- The score threshold for the file search. All values must be a floating point number between 0 and 1. minimum: 0 maximum: 1 required: - score_threshold FileSearchToolCall: type: object title: File search tool call description: | The results of a file search tool call. See the [file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information. properties: id: type: string description: | The unique ID of the file search tool call. type: type: string enum: - file_search_call description: | The type of the file search tool call. Always `file_search_call`. x-stainless-const: true status: type: string description: | The status of the file search tool call. One of `in_progress`, `searching`, `incomplete` or `failed`, enum: - in_progress - searching - completed - incomplete - failed queries: type: array items: type: string description: | The queries used to search for files. results: type: array description: | The results of the file search tool call. items: type: object properties: file_id: type: string description: | The unique ID of the file. text: type: string description: | The text that was retrieved from the file. filename: type: string description: | The name of the file. attributes: $ref: '#/components/schemas/VectorStoreFileAttributes' score: type: number format: float description: | The relevance score of the file - a value between 0 and 1. nullable: true required: - id - type - status - queries FineTuneChatCompletionRequestAssistantMessage: allOf: - type: object title: Assistant message deprecated: false properties: weight: type: integer enum: - 0 - 1 description: Controls whether the assistant message is trained against (0 or 1) - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' required: - role FineTuneChatRequestInput: type: object description: | The per-line training example of a fine-tuning input file for chat models using the supervised method. Input messages may contain text or image content only. Audio and file input messages are not currently supported for fine-tuning. properties: messages: type: array minItems: 1 items: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestSystemMessage' - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - $ref: '#/components/schemas/FineTuneChatCompletionRequestAssistantMessage' - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' tools: type: array description: A list of tools the model may generate JSON inputs for. items: $ref: '#/components/schemas/ChatCompletionTool' parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' functions: deprecated: true description: A list of functions the model may generate JSON inputs for. type: array minItems: 1 maxItems: 128 items: $ref: '#/components/schemas/ChatCompletionFunctions' x-oaiMeta: name: Training format for chat models using the supervised method example: | { "messages": [ { "role": "user", "content": "What is the weather in San Francisco?" }, { "role": "assistant", "tool_calls": [ { "id": "call_id", "type": "function", "function": { "name": "get_current_weather", "arguments": "{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}" } } ] } ], "parallel_tool_calls": false, "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and country, eg. San Francisco, USA" }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location", "format"] } } } ] } FineTuneDPOHyperparameters: type: object description: The hyperparameters used for the DPO fine-tuning job. properties: beta: description: > The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model. anyOf: - type: string enum: - auto x-stainless-const: true - type: number minimum: 0 maximum: 2 exclusiveMinimum: true batch_size: description: > Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 maximum: 256 learning_rate_multiplier: description: | Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. anyOf: - type: string enum: - auto x-stainless-const: true - type: number minimum: 0 exclusiveMinimum: true n_epochs: description: > The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 maximum: 50 FineTuneDPOMethod: type: object description: Configuration for the DPO fine-tuning method. properties: hyperparameters: $ref: '#/components/schemas/FineTuneDPOHyperparameters' FineTuneMethod: type: object description: The method used for fine-tuning. properties: type: type: string description: The type of method. Is either `supervised`, `dpo`, or `reinforcement`. enum: - supervised - dpo - reinforcement supervised: $ref: '#/components/schemas/FineTuneSupervisedMethod' dpo: $ref: '#/components/schemas/FineTuneDPOMethod' reinforcement: $ref: '#/components/schemas/FineTuneReinforcementMethod' required: - type FineTunePreferenceRequestInput: type: object description: | The per-line training example of a fine-tuning input file for chat models using the dpo method. Input messages may contain text or image content only. Audio and file input messages are not currently supported for fine-tuning. properties: input: type: object properties: messages: type: array minItems: 1 items: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestSystemMessage' - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - $ref: '#/components/schemas/FineTuneChatCompletionRequestAssistantMessage' - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' tools: type: array description: A list of tools the model may generate JSON inputs for. items: $ref: '#/components/schemas/ChatCompletionTool' parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' preferred_output: type: array description: The preferred completion message for the output. maxItems: 1 items: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' non_preferred_output: type: array description: The non-preferred completion message for the output. maxItems: 1 items: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' x-oaiMeta: name: Training format for chat models using the preference method example: | { "input": { "messages": [ { "role": "user", "content": "What is the weather in San Francisco?" } ] }, "preferred_output": [ { "role": "assistant", "content": "The weather in San Francisco is 70 degrees Fahrenheit." } ], "non_preferred_output": [ { "role": "assistant", "content": "The weather in San Francisco is 21 degrees Celsius." } ] } FineTuneReinforcementHyperparameters: type: object description: The hyperparameters used for the reinforcement fine-tuning job. properties: batch_size: description: > Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 maximum: 256 learning_rate_multiplier: description: | Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. anyOf: - type: string enum: - auto x-stainless-const: true - type: number minimum: 0 exclusiveMinimum: true n_epochs: description: > The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 maximum: 50 reasoning_effort: description: | Level of reasoning effort. type: string enum: - default - low - medium - high default: default compute_multiplier: description: | Multiplier on amount of compute used for exploring search space during training. anyOf: - type: string enum: - auto x-stainless-const: true - type: number minimum: 0.00001 maximum: 10 exclusiveMinimum: true eval_interval: description: | The number of training steps between evaluation runs. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 eval_samples: description: | Number of evaluation samples to generate per training step. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 FineTuneReinforcementMethod: type: object description: Configuration for the reinforcement fine-tuning method. properties: grader: type: object description: The grader used for the fine-tuning job. anyOf: - $ref: '#/components/schemas/GraderStringCheck' - $ref: '#/components/schemas/GraderTextSimilarity' - $ref: '#/components/schemas/GraderPython' - $ref: '#/components/schemas/GraderScoreModel' - $ref: '#/components/schemas/GraderMulti' hyperparameters: $ref: '#/components/schemas/FineTuneReinforcementHyperparameters' required: - grader FineTuneReinforcementRequestInput: type: object unevaluatedProperties: true description: > Per-line training example for reinforcement fine-tuning. Note that `messages` and `tools` are the only reserved keywords. Any other arbitrary key-value data can be included on training datapoints and will be available to reference during grading under the `{{ item.XXX }}` template variable. Input messages may contain text or image content only. Audio and file input messages are not currently supported for fine-tuning. required: - messages properties: messages: type: array minItems: 1 items: anyOf: - $ref: '#/components/schemas/ChatCompletionRequestDeveloperMessage' - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - $ref: '#/components/schemas/FineTuneChatCompletionRequestAssistantMessage' - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' tools: type: array description: A list of tools the model may generate JSON inputs for. items: $ref: '#/components/schemas/ChatCompletionTool' x-oaiMeta: name: Training format for reasoning models using the reinforcement method example: | { "messages": [ { "role": "user", "content": "Your task is to take a chemical in SMILES format and predict the number of hydrobond bond donors and acceptors according to Lipinkski's rule. CCN(CC)CCC(=O)c1sc(N)nc1C" }, ], # Any other JSON data can be inserted into an example and referenced during RFT grading "reference_answer": { "donor_bond_counts": 5, "acceptor_bond_counts": 7 } } FineTuneSupervisedHyperparameters: type: object description: The hyperparameters used for the fine-tuning job. properties: batch_size: description: > Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 maximum: 256 learning_rate_multiplier: description: | Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. anyOf: - type: string enum: - auto x-stainless-const: true - type: number minimum: 0 exclusiveMinimum: true n_epochs: description: > The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. default: auto anyOf: - type: string enum: - auto x-stainless-const: true - type: integer minimum: 1 maximum: 50 FineTuneSupervisedMethod: type: object description: Configuration for the supervised fine-tuning method. properties: hyperparameters: $ref: '#/components/schemas/FineTuneSupervisedHyperparameters' FineTuningCheckpointPermission: type: object title: FineTuningCheckpointPermission description: | The `checkpoint.permission` object represents a permission for a fine-tuned model checkpoint. properties: id: type: string description: The permission identifier, which can be referenced in the API endpoints. created_at: type: integer description: The Unix timestamp (in seconds) for when the permission was created. project_id: type: string description: The project identifier that the permission is for. object: type: string description: The object type, which is always "checkpoint.permission". enum: - checkpoint.permission x-stainless-const: true required: - created_at - id - object - project_id x-oaiMeta: name: The fine-tuned model checkpoint permission object example: | { "object": "checkpoint.permission", "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", "created_at": 1712211699, "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" } FineTuningIntegration: type: object title: Fine-Tuning Job Integration required: - type - wandb properties: type: type: string description: The type of the integration being enabled for the fine-tuning job enum: - wandb x-stainless-const: true wandb: type: object description: | The settings for your integration with Weights and Biases. This payload specifies the project that metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags to your run, and set a default entity (team, username, etc) to be associated with your run. required: - project properties: project: description: | The name of the project that the new run will be created under. type: string example: my-wandb-project name: description: | A display name to set for the run. If not set, we will use the Job ID as the name. nullable: true type: string entity: description: > The entity to use for the run. This allows you to set the team or username of the WandB user that you would like associated with the run. If not set, the default entity for the registered WandB API key is used. nullable: true type: string tags: description: > A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". type: array items: type: string example: custom-tag FineTuningJob: type: object title: FineTuningJob description: | The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. properties: id: type: string description: The object identifier, which can be referenced in the API endpoints. created_at: type: integer description: The Unix timestamp (in seconds) for when the fine-tuning job was created. error: type: object nullable: true description: >- For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. properties: code: type: string description: A machine-readable error code. message: type: string description: A human-readable error message. param: type: string description: >- The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. nullable: true required: - code - message - param fine_tuned_model: type: string nullable: true description: >- The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. finished_at: type: integer nullable: true description: >- The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. hyperparameters: type: object description: >- The hyperparameters used for the fine-tuning job. This value will only be returned when running `supervised` jobs. properties: batch_size: nullable: true description: | Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. anyOf: - type: string enum: - auto x-stainless-const: true title: Auto - type: integer minimum: 1 maximum: 256 title: Manual learning_rate_multiplier: description: | Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. anyOf: - type: string enum: - auto x-stainless-const: true title: Auto - type: number minimum: 0 exclusiveMinimum: true n_epochs: description: | The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. default: auto anyOf: - type: string enum: - auto x-stainless-const: true title: Auto - type: integer minimum: 1 maximum: 50 model: type: string description: The base model that is being fine-tuned. object: type: string description: The object type, which is always "fine_tuning.job". enum: - fine_tuning.job x-stainless-const: true organization_id: type: string description: The organization that owns the fine-tuning job. result_files: type: array description: >- The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). items: type: string example: file-abc123 status: type: string description: >- The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. enum: - validating_files - queued - running - succeeded - failed - cancelled trained_tokens: type: integer nullable: true description: >- The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. training_file: type: string description: >- The file ID used for training. You can retrieve the training data with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). validation_file: type: string nullable: true description: >- The file ID used for validation. You can retrieve the validation results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). integrations: type: array nullable: true description: A list of integrations to enable for this fine-tuning job. maxItems: 5 items: anyOf: - $ref: '#/components/schemas/FineTuningIntegration' discriminator: propertyName: type seed: type: integer description: The seed used for the fine-tuning job. estimated_finish: type: integer nullable: true description: >- The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running. method: $ref: '#/components/schemas/FineTuneMethod' metadata: $ref: '#/components/schemas/Metadata' required: - created_at - error - finished_at - fine_tuned_model - hyperparameters - id - model - object - organization_id - result_files - status - trained_tokens - training_file - validation_file - seed x-oaiMeta: name: The fine-tuning job object example: | { "object": "fine_tuning.job", "id": "ftjob-abc123", "model": "davinci-002", "created_at": 1692661014, "finished_at": 1692661190, "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy", "organization_id": "org-123", "result_files": [ "file-abc123" ], "status": "succeeded", "validation_file": null, "training_file": "file-abc123", "hyperparameters": { "n_epochs": 4, "batch_size": 1, "learning_rate_multiplier": 1.0 }, "trained_tokens": 5768, "integrations": [], "seed": 0, "estimated_finish": 0, "method": { "type": "supervised", "supervised": { "hyperparameters": { "n_epochs": 4, "batch_size": 1, "learning_rate_multiplier": 1.0 } } }, "metadata": { "key": "value" } } FineTuningJobCheckpoint: type: object title: FineTuningJobCheckpoint description: > The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use. properties: id: type: string description: The checkpoint identifier, which can be referenced in the API endpoints. created_at: type: integer description: The Unix timestamp (in seconds) for when the checkpoint was created. fine_tuned_model_checkpoint: type: string description: The name of the fine-tuned checkpoint model that is created. step_number: type: integer description: The step number that the checkpoint was created at. metrics: type: object description: Metrics at the step number during the fine-tuning job. properties: step: type: number train_loss: type: number train_mean_token_accuracy: type: number valid_loss: type: number valid_mean_token_accuracy: type: number full_valid_loss: type: number full_valid_mean_token_accuracy: type: number fine_tuning_job_id: type: string description: The name of the fine-tuning job that this checkpoint was created from. object: type: string description: The object type, which is always "fine_tuning.job.checkpoint". enum: - fine_tuning.job.checkpoint x-stainless-const: true required: - created_at - fine_tuning_job_id - fine_tuned_model_checkpoint - id - metrics - object - step_number x-oaiMeta: name: The fine-tuning job checkpoint object example: | { "object": "fine_tuning.job.checkpoint", "id": "ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P", "created_at": 1712211699, "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom_suffix:9ABel2dg:ckpt-step-88", "fine_tuning_job_id": "ftjob-fpbNQ3H1GrMehXRf8cO97xTN", "metrics": { "step": 88, "train_loss": 0.478, "train_mean_token_accuracy": 0.924, "valid_loss": 10.112, "valid_mean_token_accuracy": 0.145, "full_valid_loss": 0.567, "full_valid_mean_token_accuracy": 0.944 }, "step_number": 88 } FineTuningJobEvent: type: object description: Fine-tuning job event object properties: object: type: string description: The object type, which is always "fine_tuning.job.event". enum: - fine_tuning.job.event x-stainless-const: true id: type: string description: The object identifier. created_at: type: integer description: The Unix timestamp (in seconds) for when the fine-tuning job was created. level: type: string description: The log level of the event. enum: - info - warn - error message: type: string description: The message of the event. type: type: string description: The type of event. enum: - message - metrics data: type: object description: The data associated with the event. required: - id - object - created_at - level - message x-oaiMeta: name: The fine-tuning job event object example: | { "object": "fine_tuning.job.event", "id": "ftevent-abc123" "created_at": 1677610602, "level": "info", "message": "Created fine-tuning job", "data": {}, "type": "message" } FunctionObject: type: object properties: description: type: string description: >- A description of what the function does, used by the model to choose when and how to call the function. name: type: string description: >- The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. parameters: $ref: '#/components/schemas/FunctionParameters' strict: type: boolean nullable: true default: false description: >- Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](https://platform.openai.com/docs/guides/function-calling). required: - name FunctionParameters: type: object description: >- The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. Omitting `parameters` defines a function with an empty parameter list. additionalProperties: true FunctionToolCall: type: object title: Function tool call description: > A tool call to run a function. See the [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information. properties: id: type: string description: | The unique ID of the function tool call. type: type: string enum: - function_call description: | The type of the function tool call. Always `function_call`. x-stainless-const: true call_id: type: string description: | The unique ID of the function tool call generated by the model. name: type: string description: | The name of the function to run. arguments: type: string description: | A JSON string of the arguments to pass to the function. status: type: string description: | The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. enum: - in_progress - completed - incomplete required: - type - call_id - name - arguments FunctionToolCallOutput: type: object title: Function tool call output description: | The output of a function tool call. properties: id: type: string description: | The unique ID of the function tool call output. Populated when this item is returned via API. type: type: string enum: - function_call_output description: | The type of the function tool call output. Always `function_call_output`. x-stainless-const: true call_id: type: string description: | The unique ID of the function tool call generated by the model. output: type: string description: | A JSON string of the output of the function tool call. status: type: string description: | The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. enum: - in_progress - completed - incomplete required: - type - call_id - output FunctionToolCallOutputResource: allOf: - $ref: '#/components/schemas/FunctionToolCallOutput' - type: object properties: id: type: string description: | The unique ID of the function call tool output. required: - id FunctionToolCallResource: allOf: - $ref: '#/components/schemas/FunctionToolCall' - type: object properties: id: type: string description: | The unique ID of the function tool call. required: - id GraderLabelModel: type: object title: LabelModelGrader description: | A LabelModelGrader object which uses a model to assign labels to each item in the evaluation. properties: type: description: The object type, which is always `label_model`. type: string enum: - label_model x-stainless-const: true name: type: string description: The name of the grader. model: type: string description: The model to use for the evaluation. Must support structured outputs. input: type: array items: $ref: '#/components/schemas/EvalItem' labels: type: array items: type: string description: The labels to assign to each item in the evaluation. passing_labels: type: array items: type: string description: The labels that indicate a passing result. Must be a subset of labels. required: - type - model - input - passing_labels - labels - name x-oaiMeta: name: Label Model Grader group: graders example: | { "name": "First label grader", "type": "label_model", "model": "gpt-4o-2024-08-06", "input": [ { "type": "message", "role": "system", "content": { "type": "input_text", "text": "Classify the sentiment of the following statement as one of positive, neutral, or negative" } }, { "type": "message", "role": "user", "content": { "type": "input_text", "text": "Statement: {{item.response}}" } } ], "passing_labels": [ "positive" ], "labels": [ "positive", "neutral", "negative" ] } GraderMulti: type: object title: MultiGrader description: A MultiGrader object combines the output of multiple graders to produce a single score. properties: type: type: string enum: - multi default: multi description: The object type, which is always `multi`. x-stainless-const: true name: type: string description: The name of the grader. graders: anyOf: - $ref: '#/components/schemas/GraderStringCheck' - $ref: '#/components/schemas/GraderTextSimilarity' - $ref: '#/components/schemas/GraderPython' - $ref: '#/components/schemas/GraderScoreModel' - $ref: '#/components/schemas/GraderLabelModel' calculate_output: type: string description: A formula to calculate the output based on grader results. required: - name - type - graders - calculate_output x-oaiMeta: name: Multi Grader group: graders example: | { "type": "multi", "name": "example multi grader", "graders": [ { "type": "text_similarity", "name": "example text similarity grader", "input": "The graded text", "reference": "The reference text", "evaluation_metric": "fuzzy_match" }, { "type": "string_check", "name": "Example string check grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "operation": "eq" } ], "calculate_output": "0.5 * text_similarity_score + 0.5 * string_check_score)" } GraderPython: type: object title: PythonGrader description: | A PythonGrader object that runs a python script on the input. properties: type: type: string enum: - python description: The object type, which is always `python`. x-stainless-const: true name: type: string description: The name of the grader. source: type: string description: The source code of the python script. image_tag: type: string description: The image tag to use for the python script. required: - type - name - source x-oaiMeta: name: Python Grader group: graders example: | { "type": "python", "name": "Example python grader", "image_tag": "2025-05-08", "source": """ def grade(sample: dict, item: dict) -> float: \""" Returns 1.0 if `output_text` equals `label`, otherwise 0.0. \""" output = sample.get("output_text") label = item.get("label") return 1.0 if output == label else 0.0 """, } GraderScoreModel: type: object title: ScoreModelGrader description: | A ScoreModelGrader object that uses a model to assign a score to the input. properties: type: type: string enum: - score_model description: The object type, which is always `score_model`. x-stainless-const: true name: type: string description: The name of the grader. model: type: string description: The model to use for the evaluation. sampling_params: type: object description: The sampling parameters for the model. input: type: array items: $ref: '#/components/schemas/EvalItem' description: The input text. This may include template strings. range: type: array items: type: number min_items: 2 max_items: 2 description: The range of the score. Defaults to `[0, 1]`. required: - type - name - input - model x-oaiMeta: name: Score Model Grader group: graders example: | { "type": "score_model", "name": "Example score model grader", "input": [ { "role": "user", "content": ( "Score how close the reference answer is to the model answer. Score 1.0 if they are the same and 0.0 if they are different." " Return just a floating point score\n\n" " Reference answer: {{item.label}}\n\n" " Model answer: {{sample.output_text}}" ), } ], "model": "gpt-4o-2024-08-06", "sampling_params": { "temperature": 1, "top_p": 1, "seed": 42, }, } GraderStringCheck: type: object title: StringCheckGrader description: > A StringCheckGrader object that performs a string comparison between input and reference using a specified operation. properties: type: type: string enum: - string_check description: The object type, which is always `string_check`. x-stainless-const: true name: type: string description: The name of the grader. input: type: string description: The input text. This may include template strings. reference: type: string description: The reference text. This may include template strings. operation: type: string enum: - eq - ne - like - ilike description: The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`. required: - type - name - input - reference - operation x-oaiMeta: name: String Check Grader group: graders example: | { "type": "string_check", "name": "Example string check grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "operation": "eq" } GraderTextSimilarity: type: object title: TextSimilarityGrader description: | A TextSimilarityGrader object which grades text based on similarity metrics. properties: type: type: string enum: - text_similarity default: text_similarity description: The type of grader. x-stainless-const: true name: type: string description: The name of the grader. input: type: string description: The text being graded. reference: type: string description: The text being graded against. evaluation_metric: type: string enum: - cosine - fuzzy_match - bleu - gleu - meteor - rouge_1 - rouge_2 - rouge_3 - rouge_4 - rouge_5 - rouge_l description: | The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. required: - type - name - input - reference - evaluation_metric x-oaiMeta: name: Text Similarity Grader group: graders example: | { "type": "text_similarity", "name": "Example text similarity grader", "input": "{{sample.output_text}}", "reference": "{{item.label}}", "evaluation_metric": "fuzzy_match" } Image: type: object description: Represents the content or the URL of an image generated by the OpenAI API. properties: b64_json: type: string description: >- The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, and only present if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`. url: type: string description: >- When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to `url` (default value). Unsupported for `gpt-image-1`. revised_prompt: type: string description: For `dall-e-3` only, the revised prompt that was used to generate the image. ImageEditCompletedEvent: type: object description: | Emitted when image editing has completed and the final image is available. properties: type: type: string description: | The type of the event. Always `image_edit.completed`. enum: - image_edit.completed x-stainless-const: true b64_json: type: string description: | Base64-encoded final edited image data, suitable for rendering as an image. created_at: type: integer description: | The Unix timestamp when the event was created. size: type: string description: | The size of the edited image. enum: - 1024x1024 - 1024x1536 - 1536x1024 - auto quality: type: string description: | The quality setting for the edited image. enum: - low - medium - high - auto background: type: string description: | The background setting for the edited image. enum: - transparent - opaque - auto output_format: type: string description: | The output format for the edited image. enum: - png - webp - jpeg usage: $ref: '#/components/schemas/ImagesUsage' required: - type - b64_json - created_at - size - quality - background - output_format - usage x-oaiMeta: name: image_edit.completed group: images example: | { "type": "image_edit.completed", "b64_json": "...", "created_at": 1620000000, "size": "1024x1024", "quality": "high", "background": "transparent", "output_format": "png", "usage": { "total_tokens": 100, "input_tokens": 50, "output_tokens": 50, "input_tokens_details": { "text_tokens": 10, "image_tokens": 40 } } } ImageEditPartialImageEvent: type: object description: | Emitted when a partial image is available during image editing streaming. properties: type: type: string description: | The type of the event. Always `image_edit.partial_image`. enum: - image_edit.partial_image x-stainless-const: true b64_json: type: string description: | Base64-encoded partial image data, suitable for rendering as an image. created_at: type: integer description: | The Unix timestamp when the event was created. size: type: string description: | The size of the requested edited image. enum: - 1024x1024 - 1024x1536 - 1536x1024 - auto quality: type: string description: | The quality setting for the requested edited image. enum: - low - medium - high - auto background: type: string description: | The background setting for the requested edited image. enum: - transparent - opaque - auto output_format: type: string description: | The output format for the requested edited image. enum: - png - webp - jpeg partial_image_index: type: integer description: | 0-based index for the partial image (streaming). required: - type - b64_json - created_at - size - quality - background - output_format - partial_image_index x-oaiMeta: name: image_edit.partial_image group: images example: | { "type": "image_edit.partial_image", "b64_json": "...", "created_at": 1620000000, "size": "1024x1024", "quality": "high", "background": "transparent", "output_format": "png", "partial_image_index": 0 } ImageEditStreamEvent: anyOf: - $ref: '#/components/schemas/ImageEditPartialImageEvent' - $ref: '#/components/schemas/ImageEditCompletedEvent' discriminator: propertyName: type ImageGenCompletedEvent: type: object description: | Emitted when image generation has completed and the final image is available. properties: type: type: string description: | The type of the event. Always `image_generation.completed`. enum: - image_generation.completed x-stainless-const: true b64_json: type: string description: | Base64-encoded image data, suitable for rendering as an image. created_at: type: integer description: | The Unix timestamp when the event was created. size: type: string description: | The size of the generated image. enum: - 1024x1024 - 1024x1536 - 1536x1024 - auto quality: type: string description: | The quality setting for the generated image. enum: - low - medium - high - auto background: type: string description: | The background setting for the generated image. enum: - transparent - opaque - auto output_format: type: string description: | The output format for the generated image. enum: - png - webp - jpeg usage: $ref: '#/components/schemas/ImagesUsage' required: - type - b64_json - created_at - size - quality - background - output_format - usage x-oaiMeta: name: image_generation.completed group: images example: | { "type": "image_generation.completed", "b64_json": "...", "created_at": 1620000000, "size": "1024x1024", "quality": "high", "background": "transparent", "output_format": "png", "usage": { "total_tokens": 100, "input_tokens": 50, "output_tokens": 50, "input_tokens_details": { "text_tokens": 10, "image_tokens": 40 } } } ImageGenPartialImageEvent: type: object description: | Emitted when a partial image is available during image generation streaming. properties: type: type: string description: | The type of the event. Always `image_generation.partial_image`. enum: - image_generation.partial_image x-stainless-const: true b64_json: type: string description: | Base64-encoded partial image data, suitable for rendering as an image. created_at: type: integer description: | The Unix timestamp when the event was created. size: type: string description: | The size of the requested image. enum: - 1024x1024 - 1024x1536 - 1536x1024 - auto quality: type: string description: | The quality setting for the requested image. enum: - low - medium - high - auto background: type: string description: | The background setting for the requested image. enum: - transparent - opaque - auto output_format: type: string description: | The output format for the requested image. enum: - png - webp - jpeg partial_image_index: type: integer description: | 0-based index for the partial image (streaming). required: - type - b64_json - created_at - size - quality - background - output_format - partial_image_index x-oaiMeta: name: image_generation.partial_image group: images example: | { "type": "image_generation.partial_image", "b64_json": "...", "created_at": 1620000000, "size": "1024x1024", "quality": "high", "background": "transparent", "output_format": "png", "partial_image_index": 0 } ImageGenStreamEvent: anyOf: - $ref: '#/components/schemas/ImageGenPartialImageEvent' - $ref: '#/components/schemas/ImageGenCompletedEvent' discriminator: propertyName: type ImageGenTool: type: object title: Image generation tool description: | A tool that generates images using a model like `gpt-image-1`. properties: type: type: string enum: - image_generation description: | The type of the image generation tool. Always `image_generation`. x-stainless-const: true model: type: string enum: - gpt-image-1 description: | The image generation model to use. Default: `gpt-image-1`. default: gpt-image-1 quality: type: string enum: - low - medium - high - auto description: | The quality of the generated image. One of `low`, `medium`, `high`, or `auto`. Default: `auto`. default: auto size: type: string enum: - 1024x1024 - 1024x1536 - 1536x1024 - auto description: | The size of the generated image. One of `1024x1024`, `1024x1536`, `1536x1024`, or `auto`. Default: `auto`. default: auto output_format: type: string enum: - png - webp - jpeg description: | The output format of the generated image. One of `png`, `webp`, or `jpeg`. Default: `png`. default: png output_compression: type: integer minimum: 0 maximum: 100 description: | Compression level for the output image. Default: 100. default: 100 moderation: type: string enum: - auto - low description: | Moderation level for the generated image. Default: `auto`. default: auto background: type: string enum: - transparent - opaque - auto description: | Background type for the generated image. One of `transparent`, `opaque`, or `auto`. Default: `auto`. default: auto input_fidelity: $ref: '#/components/schemas/ImageInputFidelity' input_image_mask: type: object description: | Optional mask for inpainting. Contains `image_url` (string, optional) and `file_id` (string, optional). properties: image_url: type: string description: | Base64-encoded mask image. file_id: type: string description: | File ID for the mask image. required: [] additionalProperties: false partial_images: type: integer minimum: 0 maximum: 3 description: | Number of partial images to generate in streaming mode, from 0 (default value) to 3. default: 0 required: - type ImageGenToolCall: type: object title: Image generation call description: | An image generation request made by the model. properties: type: type: string enum: - image_generation_call description: | The type of the image generation call. Always `image_generation_call`. x-stainless-const: true id: type: string description: | The unique ID of the image generation call. status: type: string enum: - in_progress - completed - generating - failed description: | The status of the image generation call. result: type: string description: | The generated image encoded in base64. nullable: true required: - type - id - status - result ImageInputFidelity: type: string enum: - high - low default: low nullable: true description: | Control how much effort the model will exert to match the style and features, especially facial features, of input images. This parameter is only supported for `gpt-image-1`. Supports `high` and `low`. Defaults to `low`. ImagesResponse: type: object title: Image generation response description: The response from the image generation endpoint. properties: created: type: integer description: The Unix timestamp (in seconds) of when the image was created. data: type: array description: The list of generated images. items: $ref: '#/components/schemas/Image' background: type: string description: The background parameter used for the image generation. Either `transparent` or `opaque`. enum: - transparent - opaque output_format: type: string description: The output format of the image generation. Either `png`, `webp`, or `jpeg`. enum: - png - webp - jpeg size: type: string description: The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`. enum: - 1024x1024 - 1024x1536 - 1536x1024 quality: type: string description: The quality of the image generated. Either `low`, `medium`, or `high`. enum: - low - medium - high usage: $ref: '#/components/schemas/ImageGenUsage' required: - created x-oaiMeta: name: The image generation response group: images example: | { "created": 1713833628, "data": [ { "b64_json": "..." } ], "background": "transparent", "output_format": "png", "size": "1024x1024", "quality": "high", "usage": { "total_tokens": 100, "input_tokens": 50, "output_tokens": 50, "input_tokens_details": { "text_tokens": 10, "image_tokens": 40 } } } ImagesUsage: type: object description: | For `gpt-image-1` only, the token usage information for the image generation. required: - total_tokens - input_tokens - output_tokens - input_tokens_details properties: total_tokens: type: integer description: | The total number of tokens (images and text) used for the image generation. input_tokens: type: integer description: The number of tokens (images and text) in the input prompt. output_tokens: type: integer description: The number of image tokens in the output image. input_tokens_details: type: object description: The input tokens detailed information for the image generation. required: - text_tokens - image_tokens properties: text_tokens: type: integer description: The number of text tokens in the input prompt. image_tokens: type: integer description: The number of image tokens in the input prompt. Includable: type: string description: | Specify additional output data to include in the model response. Currently supported values are: - `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items. - `computer_call_output.output.image_url`: Include image urls from the computer call output. - `file_search_call.results`: Include the search results of the file search tool call. - `message.input_image.image_url`: Include image urls from the input message. - `message.output_text.logprobs`: Include logprobs with assistant messages. - `reasoning.encrypted_content`: Includes an encrypted version of reasoning tokens in reasoning item outputs. This enables reasoning items to be used in multi-turn conversations when using the Responses API statelessly (like when the `store` parameter is set to `false`, or when an organization is enrolled in the zero data retention program). enum: - code_interpreter_call.outputs - computer_call_output.output.image_url - file_search_call.results - message.input_image.image_url - message.output_text.logprobs - reasoning.encrypted_content InputAudio: type: object title: Audio input description: | An audio input to the model. properties: type: type: string description: | The type of the input item. Always `input_audio`. enum: - input_audio x-stainless-const: true data: type: string description: | Base64-encoded audio data. format: type: string description: | The format of the audio data. Currently supported formats are `mp3` and `wav`. enum: - mp3 - wav required: - type - data - format InputContent: anyOf: - $ref: '#/components/schemas/InputTextContent' - $ref: '#/components/schemas/InputImageContent' - $ref: '#/components/schemas/InputFileContent' discriminator: propertyName: type InputItem: discriminator: propertyName: type anyOf: - $ref: '#/components/schemas/EasyInputMessage' - type: object title: Item description: | An item representing part of the context for the response to be generated by the model. Can contain text, images, and audio inputs, as well as previous assistant responses and tool call outputs. $ref: '#/components/schemas/Item' - $ref: '#/components/schemas/ItemReferenceParam' InputMessage: type: object title: Input message description: | A message input to the model with a role indicating instruction following hierarchy. Instructions given with the `developer` or `system` role take precedence over instructions given with the `user` role. properties: type: type: string description: | The type of the message input. Always set to `message`. enum: - message x-stainless-const: true role: type: string description: | The role of the message input. One of `user`, `system`, or `developer`. enum: - user - system - developer status: type: string description: | The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. enum: - in_progress - completed - incomplete content: $ref: '#/components/schemas/InputMessageContentList' required: - role - content InputMessageContentList: type: array title: Input item content list description: | A list of one or many input items to the model, containing different content types. items: $ref: '#/components/schemas/InputContent' InputMessageResource: allOf: - $ref: '#/components/schemas/InputMessage' - type: object properties: id: type: string description: | The unique ID of the message input. required: - id Invite: type: object description: Represents an individual `invite` to the organization. properties: object: type: string enum: - organization.invite description: The object type, which is always `organization.invite` x-stainless-const: true id: type: string description: The identifier, which can be referenced in API endpoints email: type: string description: The email address of the individual to whom the invite was sent role: type: string enum: - owner - reader description: '`owner` or `reader`' status: type: string enum: - accepted - expired - pending description: '`accepted`,`expired`, or `pending`' invited_at: type: integer description: The Unix timestamp (in seconds) of when the invite was sent. expires_at: type: integer description: The Unix timestamp (in seconds) of when the invite expires. accepted_at: type: integer description: The Unix timestamp (in seconds) of when the invite was accepted. projects: type: array description: The projects that were granted membership upon acceptance of the invite. items: type: object properties: id: type: string description: Project's public ID role: type: string enum: - member - owner description: Project membership role required: - object - id - email - role - status - invited_at - expires_at x-oaiMeta: name: The invite object example: | { "object": "organization.invite", "id": "invite-abc", "email": "user@example.com", "role": "owner", "status": "accepted", "invited_at": 1711471533, "expires_at": 1711471533, "accepted_at": 1711471533, "projects": [ { "id": "project-xyz", "role": "member" } ] } InviteDeleteResponse: type: object properties: object: type: string enum: - organization.invite.deleted description: The object type, which is always `organization.invite.deleted` x-stainless-const: true id: type: string deleted: type: boolean required: - object - id - deleted InviteListResponse: type: object properties: object: type: string enum: - list description: The object type, which is always `list` x-stainless-const: true data: type: array items: $ref: '#/components/schemas/Invite' first_id: type: string description: The first `invite_id` in the retrieved `list` last_id: type: string description: The last `invite_id` in the retrieved `list` has_more: type: boolean description: The `has_more` property is used for pagination to indicate there are additional results. required: - object - data InviteRequest: type: object properties: email: type: string description: Send an email to this address role: type: string enum: - reader - owner description: '`owner` or `reader`' projects: type: array description: >- An array of projects to which membership is granted at the same time the org invite is accepted. If omitted, the user will be invited to the default project for compatibility with legacy behavior. items: type: object properties: id: type: string description: Project's public ID role: type: string enum: - member - owner description: Project membership role required: - id - role required: - email - role Item: type: object description: | Content item used to generate a response. discriminator: propertyName: type anyOf: - $ref: '#/components/schemas/InputMessage' - $ref: '#/components/schemas/OutputMessage' - $ref: '#/components/schemas/FileSearchToolCall' - $ref: '#/components/schemas/ComputerToolCall' - $ref: '#/components/schemas/ComputerCallOutputItemParam' - $ref: '#/components/schemas/WebSearchToolCall' - $ref: '#/components/schemas/FunctionToolCall' - $ref: '#/components/schemas/FunctionCallOutputItemParam' - $ref: '#/components/schemas/ReasoningItem' - $ref: '#/components/schemas/ImageGenToolCall' - $ref: '#/components/schemas/CodeInterpreterToolCall' - $ref: '#/components/schemas/LocalShellToolCall' - $ref: '#/components/schemas/LocalShellToolCallOutput' - $ref: '#/components/schemas/MCPListTools' - $ref: '#/components/schemas/MCPApprovalRequest' - $ref: '#/components/schemas/MCPApprovalResponse' - $ref: '#/components/schemas/MCPToolCall' - $ref: '#/components/schemas/CustomToolCallOutput' - $ref: '#/components/schemas/CustomToolCall' ItemResource: description: | Content item used to generate a response. discriminator: propertyName: type anyOf: - $ref: '#/components/schemas/InputMessageResource' - $ref: '#/components/schemas/OutputMessage' - $ref: '#/components/schemas/FileSearchToolCall' - $ref: '#/components/schemas/ComputerToolCall' - $ref: '#/components/schemas/ComputerToolCallOutputResource' - $ref: '#/components/schemas/WebSearchToolCall' - $ref: '#/components/schemas/FunctionToolCallResource' - $ref: '#/components/schemas/FunctionToolCallOutputResource' - $ref: '#/components/schemas/ImageGenToolCall' - $ref: '#/components/schemas/CodeInterpreterToolCall' - $ref: '#/components/schemas/LocalShellToolCall' - $ref: '#/components/schemas/LocalShellToolCallOutput' - $ref: '#/components/schemas/MCPListTools' - $ref: '#/components/schemas/MCPApprovalRequest' - $ref: '#/components/schemas/MCPApprovalResponseResource' - $ref: '#/components/schemas/MCPToolCall' KeyPress: type: object title: KeyPress description: | A collection of keypresses the model would like to perform. properties: type: type: string enum: - keypress default: keypress description: | Specifies the event type. For a keypress action, this property is always set to `keypress`. x-stainless-const: true keys: type: array items: type: string description: | One of the keys the model is requesting to be pressed. description: | The combination of keys the model is requesting to be pressed. This is an array of strings, each representing a key. required: - type - keys ListAssistantsResponse: type: object properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/AssistantObject' first_id: type: string example: asst_abc123 last_id: type: string example: asst_abc456 has_more: type: boolean example: false required: - object - data - first_id - last_id - has_more x-oaiMeta: name: List assistants response object group: chat example: | { "object": "list", "data": [ { "id": "asst_abc123", "object": "assistant", "created_at": 1698982736, "name": "Coding Tutor", "description": null, "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" }, { "id": "asst_abc456", "object": "assistant", "created_at": 1698982718, "name": "My Assistant", "description": null, "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" }, { "id": "asst_abc789", "object": "assistant", "created_at": 1698982643, "name": null, "description": null, "model": "gpt-4o", "instructions": null, "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } ], "first_id": "asst_abc123", "last_id": "asst_abc789", "has_more": false } ListAuditLogsResponse: type: object properties: object: type: string enum: - list x-stainless-const: true data: type: array items: $ref: '#/components/schemas/AuditLog' first_id: type: string example: audit_log-defb456h8dks last_id: type: string example: audit_log-hnbkd8s93s has_more: type: boolean required: - object - data - first_id - last_id - has_more ListBatchesResponse: type: object properties: data: type: array items: $ref: '#/components/schemas/Batch' first_id: type: string example: batch_abc123 last_id: type: string example: batch_abc456 has_more: type: boolean object: type: string enum: - list x-stainless-const: true required: - object - data - has_more ListCertificatesResponse: type: object properties: data: type: array items: $ref: '#/components/schemas/Certificate' first_id: type: string example: cert_abc last_id: type: string example: cert_abc has_more: type: boolean object: type: string enum: - list x-stainless-const: true required: - object - data - has_more ListFilesResponse: type: object properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/OpenAIFile' first_id: type: string example: file-abc123 last_id: type: string example: file-abc456 has_more: type: boolean example: false required: - object - data - first_id - last_id - has_more ListFineTuningCheckpointPermissionResponse: type: object properties: data: type: array items: $ref: '#/components/schemas/FineTuningCheckpointPermission' object: type: string enum: - list x-stainless-const: true first_id: type: string nullable: true last_id: type: string nullable: true has_more: type: boolean required: - object - data - has_more ListFineTuningJobCheckpointsResponse: type: object properties: data: type: array items: $ref: '#/components/schemas/FineTuningJobCheckpoint' object: type: string enum: - list x-stainless-const: true first_id: type: string nullable: true last_id: type: string nullable: true has_more: type: boolean required: - object - data - has_more ListFineTuningJobEventsResponse: type: object properties: data: type: array items: $ref: '#/components/schemas/FineTuningJobEvent' object: type: string enum: - list x-stainless-const: true has_more: type: boolean required: - object - data - has_more ListMessagesResponse: properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/MessageObject' first_id: type: string example: msg_abc123 last_id: type: string example: msg_abc123 has_more: type: boolean example: false required: - object - data - first_id - last_id - has_more ListModelsResponse: type: object properties: object: type: string enum: - list x-stainless-const: true data: type: array items: $ref: '#/components/schemas/Model' required: - object - data ListPaginatedFineTuningJobsResponse: type: object properties: data: type: array items: $ref: '#/components/schemas/FineTuningJob' has_more: type: boolean object: type: string enum: - list x-stainless-const: true required: - object - data - has_more ListRunStepsResponse: properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/RunStepObject' first_id: type: string example: step_abc123 last_id: type: string example: step_abc456 has_more: type: boolean example: false required: - object - data - first_id - last_id - has_more ListRunsResponse: type: object properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/RunObject' first_id: type: string example: run_abc123 last_id: type: string example: run_abc456 has_more: type: boolean example: false required: - object - data - first_id - last_id - has_more ListVectorStoreFilesResponse: properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/VectorStoreFileObject' first_id: type: string example: file-abc123 last_id: type: string example: file-abc456 has_more: type: boolean example: false required: - object - data - first_id - last_id - has_more ListVectorStoresResponse: properties: object: type: string example: list data: type: array items: $ref: '#/components/schemas/VectorStoreObject' first_id: type: string example: vs_abc123 last_id: type: string example: vs_abc456 has_more: type: boolean example: false required: - object - data - first_id - last_id - has_more LocalShellExecAction: type: object title: Local shell exec action description: | Execute a shell command on the server. properties: type: type: string enum: - exec description: | The type of the local shell action. Always `exec`. x-stainless-const: true command: type: array items: type: string description: | The command to run. timeout_ms: type: integer description: | Optional timeout in milliseconds for the command. nullable: true working_directory: type: string description: | Optional working directory to run the command in. nullable: true env: type: object additionalProperties: type: string description: | Environment variables to set for the command. user: type: string description: | Optional user to run the command as. nullable: true required: - type - command - env LocalShellTool: type: object title: Local shell tool description: | A tool that allows the model to execute shell commands in a local environment. properties: type: type: string enum: - local_shell description: The type of the local shell tool. Always `local_shell`. x-stainless-const: true required: - type LocalShellToolCall: type: object title: Local shell call description: | A tool call to run a command on the local shell. properties: type: type: string enum: - local_shell_call description: | The type of the local shell call. Always `local_shell_call`. x-stainless-const: true id: type: string description: | The unique ID of the local shell call. call_id: type: string description: | The unique ID of the local shell tool call generated by the model. action: $ref: '#/components/schemas/LocalShellExecAction' status: type: string enum: - in_progress - completed - incomplete description: | The status of the local shell call. required: - type - id - call_id - action - status LocalShellToolCallOutput: type: object title: Local shell call output description: | The output of a local shell tool call. properties: type: type: string enum: - local_shell_call_output description: | The type of the local shell tool call output. Always `local_shell_call_output`. x-stainless-const: true id: type: string description: | The unique ID of the local shell tool call generated by the model. output: type: string description: | A JSON string of the output of the local shell tool call. status: type: string enum: - in_progress - completed - incomplete description: | The status of the item. One of `in_progress`, `completed`, or `incomplete`. nullable: true required: - id - type - call_id - output LogProbProperties: type: object description: | A log probability object. properties: token: type: string description: | The token that was used to generate the log probability. logprob: type: number description: | The log probability of the token. bytes: type: array items: type: integer description: | The bytes that were used to generate the log probability. required: - token - logprob - bytes MCPApprovalRequest: type: object title: MCP approval request description: | A request for human approval of a tool invocation. properties: type: type: string enum: - mcp_approval_request description: | The type of the item. Always `mcp_approval_request`. x-stainless-const: true id: type: string description: | The unique ID of the approval request. server_label: type: string description: | The label of the MCP server making the request. name: type: string description: | The name of the tool to run. arguments: type: string description: | A JSON string of arguments for the tool. required: - type - id - server_label - name - arguments MCPApprovalResponse: type: object title: MCP approval response description: | A response to an MCP approval request. properties: type: type: string enum: - mcp_approval_response description: | The type of the item. Always `mcp_approval_response`. x-stainless-const: true id: type: string description: | The unique ID of the approval response nullable: true approval_request_id: type: string description: | The ID of the approval request being answered. approve: type: boolean description: | Whether the request was approved. reason: type: string description: | Optional reason for the decision. nullable: true required: - type - request_id - approve - approval_request_id MCPApprovalResponseResource: type: object title: MCP approval response description: | A response to an MCP approval request. properties: type: type: string enum: - mcp_approval_response description: | The type of the item. Always `mcp_approval_response`. x-stainless-const: true id: type: string description: | The unique ID of the approval response approval_request_id: type: string description: | The ID of the approval request being answered. approve: type: boolean description: | Whether the request was approved. reason: type: string description: | Optional reason for the decision. nullable: true required: - type - id - request_id - approve - approval_request_id MCPListTools: type: object title: MCP list tools description: | A list of tools available on an MCP server. properties: type: type: string enum: - mcp_list_tools description: | The type of the item. Always `mcp_list_tools`. x-stainless-const: true id: type: string description: | The unique ID of the list. server_label: type: string description: | The label of the MCP server. tools: type: array items: $ref: '#/components/schemas/MCPListToolsTool' description: | The tools available on the server. error: type: string description: | Error message if the server could not list tools. nullable: true required: - type - id - server_label - tools MCPListToolsTool: type: object title: MCP list tools tool description: | A tool available on an MCP server. properties: name: type: string description: | The name of the tool. description: type: string description: | The description of the tool. nullable: true input_schema: type: object description: | The JSON schema describing the tool's input. annotations: type: object description: | Additional annotations about the tool. nullable: true required: - name - input_schema MCPTool: type: object title: MCP tool description: | Give the model access to additional tools via remote Model Context Protocol (MCP) servers. [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp). properties: type: type: string enum: - mcp description: The type of the MCP tool. Always `mcp`. x-stainless-const: true server_label: type: string description: | A label for this MCP server, used to identify it in tool calls. server_url: type: string description: | The URL for the MCP server. server_description: type: string description: | Optional description of the MCP server, used to provide more context. headers: type: object additionalProperties: type: string nullable: true description: | Optional HTTP headers to send to the MCP server. Use for authentication or other purposes. allowed_tools: description: | List of allowed tool names or a filter object. nullable: true anyOf: - type: array title: MCP allowed tools description: A string array of allowed tool names items: type: string - type: object title: MCP allowed tools filter description: | A filter object to specify which tools are allowed. properties: tool_names: type: array title: MCP allowed tools items: type: string description: List of allowed tool names. required: [] additionalProperties: false require_approval: description: Specify which of the MCP server's tools require approval. nullable: true anyOf: - type: object title: MCP tool approval filter properties: always: type: object description: | A list of tools that always require approval. properties: tool_names: type: array items: type: string description: List of tools that require approval. never: type: object description: | A list of tools that never require approval. properties: tool_names: type: array items: type: string description: List of tools that do not require approval. additionalProperties: false - type: string title: MCP tool approval setting description: | Specify a single approval policy for all tools. One of `always` or `never`. When set to `always`, all tools will require approval. When set to `never`, all tools will not require approval. enum: - always - never required: - type - server_label - server_url MCPToolCall: type: object title: MCP tool call description: | An invocation of a tool on an MCP server. properties: type: type: string enum: - mcp_call description: | The type of the item. Always `mcp_call`. x-stainless-const: true id: type: string description: | The unique ID of the tool call. server_label: type: string description: | The label of the MCP server running the tool. name: type: string description: | The name of the tool that was run. arguments: type: string description: | A JSON string of the arguments passed to the tool. output: type: string description: | The output from the tool call. nullable: true error: type: string description: | The error from the tool call, if any. nullable: true required: - type - id - server_label - name - arguments MessageContentImageFileObject: title: Image file type: object description: >- References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a message. properties: type: description: Always `image_file`. type: string enum: - image_file x-stainless-const: true image_file: type: object properties: file_id: description: >- The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. type: string detail: type: string description: >- Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. enum: - auto - low - high default: auto required: - file_id required: - type - image_file MessageContentImageUrlObject: title: Image URL type: object description: References an image URL in the content of a message. properties: type: type: string enum: - image_url description: The type of the content part. x-stainless-const: true image_url: type: object properties: url: type: string description: 'The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' format: uri detail: type: string description: >- Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto` enum: - auto - low - high default: auto required: - url required: - type - image_url MessageContentRefusalObject: title: Refusal type: object description: The refusal content generated by the assistant. properties: type: description: Always `refusal`. type: string enum: - refusal x-stainless-const: true refusal: type: string nullable: false required: - type - refusal MessageContentTextAnnotationsFileCitationObject: title: File citation type: object description: >- A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. properties: type: description: Always `file_citation`. type: string enum: - file_citation x-stainless-const: true text: description: The text in the message content that needs to be replaced. type: string file_citation: type: object properties: file_id: description: The ID of the specific File the citation is from. type: string required: - file_id start_index: type: integer minimum: 0 end_index: type: integer minimum: 0 required: - type - text - file_citation - start_index - end_index MessageContentTextAnnotationsFilePathObject: title: File path type: object description: >- A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. properties: type: description: Always `file_path`. type: string enum: - file_path x-stainless-const: true text: description: The text in the message content that needs to be replaced. type: string file_path: type: object properties: file_id: description: The ID of the file that was generated. type: string required: - file_id start_index: type: integer minimum: 0 end_index: type: integer minimum: 0 required: - type - text - file_path - start_index - end_index MessageContentTextObject: title: Text type: object description: The text content that is part of a message. properties: type: description: Always `text`. type: string enum: - text x-stainless-const: true text: type: object properties: value: description: The data that makes up the text. type: string annotations: type: array items: $ref: '#/components/schemas/TextAnnotation' required: - value - annotations required: - type - text MessageDeltaContentImageFileObject: title: Image file type: object description: >- References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a message. properties: index: type: integer description: The index of the content part in the message. type: description: Always `image_file`. type: string enum: - image_file x-stainless-const: true image_file: type: object properties: file_id: description: >- The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. type: string detail: type: string description: >- Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. enum: - auto - low - high default: auto required: - index - type MessageDeltaContentImageUrlObject: title: Image URL type: object description: References an image URL in the content of a message. properties: index: type: integer description: The index of the content part in the message. type: description: Always `image_url`. type: string enum: - image_url x-stainless-const: true image_url: type: object properties: url: description: 'The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' type: string detail: type: string description: >- Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. enum: - auto - low - high default: auto required: - index - type MessageDeltaContentRefusalObject: title: Refusal type: object description: The refusal content that is part of a message. properties: index: type: integer description: The index of the refusal part in the message. type: description: Always `refusal`. type: string enum: - refusal x-stainless-const: true refusal: type: string required: - index - type MessageDeltaContentTextAnnotationsFileCitationObject: title: File citation type: object description: >- A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. properties: index: type: integer description: The index of the annotation in the text content part. type: description: Always `file_citation`. type: string enum: - file_citation x-stainless-const: true text: description: The text in the message content that needs to be replaced. type: string file_citation: type: object properties: file_id: description: The ID of the specific File the citation is from. type: string quote: description: The specific quote in the file. type: string start_index: type: integer minimum: 0 end_index: type: integer minimum: 0 required: - index - type MessageDeltaContentTextAnnotationsFilePathObject: title: File path type: object description: >- A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. properties: index: type: integer description: The index of the annotation in the text content part. type: description: Always `file_path`. type: string enum: - file_path x-stainless-const: true text: description: The text in the message content that needs to be replaced. type: string file_path: type: object properties: file_id: description: The ID of the file that was generated. type: string start_index: type: integer minimum: 0 end_index: type: integer minimum: 0 required: - index - type MessageDeltaContentTextObject: title: Text type: object description: The text content that is part of a message. properties: index: type: integer description: The index of the content part in the message. type: description: Always `text`. type: string enum: - text x-stainless-const: true text: type: object properties: value: description: The data that makes up the text. type: string annotations: type: array items: $ref: '#/components/schemas/TextAnnotationDelta' required: - index - type MessageDeltaObject: type: object title: Message delta object description: | Represents a message delta i.e. any changed fields on a message during streaming. properties: id: description: The identifier of the message, which can be referenced in API endpoints. type: string object: description: The object type, which is always `thread.message.delta`. type: string enum: - thread.message.delta x-stainless-const: true delta: description: The delta containing the fields that have changed on the Message. type: object properties: role: description: The entity that produced the message. One of `user` or `assistant`. type: string enum: - user - assistant content: description: The content of the message in array of text and/or images. type: array items: $ref: '#/components/schemas/MessageContentDelta' required: - id - object - delta x-oaiMeta: name: The message delta object beta: true example: | { "id": "msg_123", "object": "thread.message.delta", "delta": { "content": [ { "index": 0, "type": "text", "text": { "value": "Hello", "annotations": [] } } ] } } MessageObject: type: object title: The message object description: Represents a message within a [thread](https://platform.openai.com/docs/api-reference/threads). properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: description: The object type, which is always `thread.message`. type: string enum: - thread.message x-stainless-const: true created_at: description: The Unix timestamp (in seconds) for when the message was created. type: integer thread_id: description: >- The [thread](https://platform.openai.com/docs/api-reference/threads) ID that this message belongs to. type: string status: description: The status of the message, which can be either `in_progress`, `incomplete`, or `completed`. type: string enum: - in_progress - incomplete - completed incomplete_details: description: On an incomplete message, details about why the message is incomplete. type: object properties: reason: type: string description: The reason the message is incomplete. enum: - content_filter - max_tokens - run_cancelled - run_expired - run_failed nullable: true required: - reason completed_at: description: The Unix timestamp (in seconds) for when the message was completed. type: integer nullable: true incomplete_at: description: The Unix timestamp (in seconds) for when the message was marked as incomplete. type: integer nullable: true role: description: The entity that produced the message. One of `user` or `assistant`. type: string enum: - user - assistant content: description: The content of the message in array of text and/or images. type: array items: $ref: '#/components/schemas/MessageContent' assistant_id: description: >- If applicable, the ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) that authored this message. type: string nullable: true run_id: description: >- The ID of the [run](https://platform.openai.com/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints. type: string nullable: true attachments: type: array items: type: object properties: file_id: type: string description: The ID of the file to attach to the message. tools: description: The tools to add this file to. type: array items: anyOf: - $ref: '#/components/schemas/AssistantToolsCode' - $ref: '#/components/schemas/AssistantToolsFileSearchTypeOnly' description: A list of files attached to the message, and the tools they were added to. nullable: true metadata: $ref: '#/components/schemas/Metadata' required: - id - object - created_at - thread_id - status - incomplete_details - completed_at - incomplete_at - role - content - assistant_id - run_id - attachments - metadata x-oaiMeta: name: The message object beta: true example: | { "id": "msg_abc123", "object": "thread.message", "created_at": 1698983503, "thread_id": "thread_abc123", "role": "assistant", "content": [ { "type": "text", "text": { "value": "Hi! How can I help you today?", "annotations": [] } } ], "assistant_id": "asst_abc123", "run_id": "run_abc123", "attachments": [], "metadata": {} } MessageRequestContentTextObject: title: Text type: object description: The text content that is part of a message. properties: type: description: Always `text`. type: string enum: - text x-stainless-const: true text: type: string description: Text content to be sent to the model required: - type - text MessageStreamEvent: anyOf: - type: object properties: event: type: string enum: - thread.message.created x-stainless-const: true data: $ref: '#/components/schemas/MessageObject' required: - event - data description: >- Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) is created. x-oaiMeta: dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' - type: object properties: event: type: string enum: - thread.message.in_progress x-stainless-const: true data: $ref: '#/components/schemas/MessageObject' required: - event - data description: >- Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) moves to an `in_progress` state. x-oaiMeta: dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' - type: object properties: event: type: string enum: - thread.message.delta x-stainless-const: true data: $ref: '#/components/schemas/MessageDeltaObject' required: - event - data description: >- Occurs when parts of a [Message](https://platform.openai.com/docs/api-reference/messages/object) are being streamed. x-oaiMeta: dataDescription: '`data` is a [message delta](/docs/api-reference/assistants-streaming/message-delta-object)' - type: object properties: event: type: string enum: - thread.message.completed x-stainless-const: true data: $ref: '#/components/schemas/MessageObject' required: - event - data description: >- Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) is completed. x-oaiMeta: dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' - type: object properties: event: type: string enum: - thread.message.incomplete x-stainless-const: true data: $ref: '#/components/schemas/MessageObject' required: - event - data description: >- Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) ends before it is completed. x-oaiMeta: dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' discriminator: propertyName: event Metadata: type: object description: | Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. additionalProperties: type: string x-oaiTypeLabel: map nullable: true Model: title: Model description: Describes an OpenAI model offering that can be used with the API. properties: id: type: string description: The model identifier, which can be referenced in the API endpoints. created: type: integer description: The Unix timestamp (in seconds) when the model was created. object: type: string description: The object type, which is always "model". enum: - model x-stainless-const: true owned_by: type: string description: The organization that owns the model. required: - id - object - created - owned_by x-oaiMeta: name: The model object example: | { "id": "VAR_chat_model_id", "object": "model", "created": 1686935002, "owned_by": "openai" } ModelIds: anyOf: - $ref: '#/components/schemas/ModelIdsShared' - $ref: '#/components/schemas/ModelIdsResponses' ModelIdsResponses: example: gpt-4o anyOf: - $ref: '#/components/schemas/ModelIdsShared' - type: string title: ResponsesOnlyModel enum: - o1-pro - o1-pro-2025-03-19 - o3-pro - o3-pro-2025-06-10 - o3-deep-research - o3-deep-research-2025-06-26 - o4-mini-deep-research - o4-mini-deep-research-2025-06-26 - computer-use-preview - computer-use-preview-2025-03-11 ModelIdsShared: example: gpt-4o anyOf: - type: string - $ref: '#/components/schemas/ChatModel' ModelResponseProperties: type: object properties: metadata: $ref: '#/components/schemas/Metadata' top_logprobs: description: | An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. type: integer minimum: 0 maximum: 20 nullable: true temperature: type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: | An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. user: type: string example: user-1234 deprecated: true description: > This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations. A stable identifier for your end-users. Used to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). safety_identifier: type: string example: safety-identifier-1234 description: > A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. The IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). prompt_cache_key: type: string example: prompt-cache-key-1234 description: > Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching). service_tier: $ref: '#/components/schemas/ServiceTier' ModifyAssistantRequest: type: object additionalProperties: false properties: model: description: > ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. anyOf: - type: string - $ref: '#/components/schemas/AssistantSupportedModels' reasoning_effort: $ref: '#/components/schemas/ReasoningEffort' name: description: | The name of the assistant. The maximum length is 256 characters. type: string nullable: true maxLength: 256 description: description: | The description of the assistant. The maximum length is 512 characters. type: string nullable: true maxLength: 512 instructions: description: | The system instructions that the assistant uses. The maximum length is 256,000 characters. type: string nullable: true maxLength: 256000 tools: description: > A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. default: [] type: array maxItems: 128 items: $ref: '#/components/schemas/AssistantTool' tool_resources: type: object description: > A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > Overrides the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. maxItems: 1 items: type: string nullable: true metadata: $ref: '#/components/schemas/Metadata' temperature: description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true ModifyCertificateRequest: type: object properties: name: type: string description: The updated name for the certificate required: - name ModifyMessageRequest: type: object additionalProperties: false properties: metadata: $ref: '#/components/schemas/Metadata' ModifyRunRequest: type: object additionalProperties: false properties: metadata: $ref: '#/components/schemas/Metadata' ModifyThreadRequest: type: object additionalProperties: false properties: tool_resources: type: object description: > A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. maxItems: 1 items: type: string nullable: true metadata: $ref: '#/components/schemas/Metadata' Move: type: object title: Move description: | A mouse move action. properties: type: type: string enum: - move default: move description: | Specifies the event type. For a move action, this property is always set to `move`. x-stainless-const: true x: type: integer description: | The x-coordinate to move to. 'y': type: integer description: | The y-coordinate to move to. required: - type - x - 'y' OpenAIFile: title: OpenAIFile description: The `File` object represents a document that has been uploaded to OpenAI. properties: id: type: string description: The file identifier, which can be referenced in the API endpoints. bytes: type: integer description: The size of the file, in bytes. created_at: type: integer description: The Unix timestamp (in seconds) for when the file was created. expires_at: type: integer description: The Unix timestamp (in seconds) for when the file will expire. filename: type: string description: The name of the file. object: type: string description: The object type, which is always `file`. enum: - file x-stainless-const: true purpose: type: string description: >- The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`. enum: - assistants - assistants_output - batch - batch_output - fine-tune - fine-tune-results - vision - user_data status: type: string deprecated: true description: >- Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. enum: - uploaded - processed - error status_details: type: string deprecated: true description: >- Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. required: - id - object - bytes - created_at - filename - purpose - status x-oaiMeta: name: The file object example: | { "id": "file-abc123", "object": "file", "bytes": 120000, "created_at": 1677610602, "expires_at": 1680202602, "filename": "salesOverview.pdf", "purpose": "assistants", } OtherChunkingStrategyResponseParam: type: object title: Other Chunking Strategy description: >- This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API. additionalProperties: false properties: type: type: string description: Always `other`. enum: - other x-stainless-const: true required: - type OutputAudio: type: object title: Output audio description: | An audio output from the model. properties: type: type: string description: | The type of the output audio. Always `output_audio`. enum: - output_audio x-stainless-const: true data: type: string description: | Base64-encoded audio data from the model. transcript: type: string description: | The transcript of the audio data from the model. required: - type - data - transcript OutputContent: anyOf: - $ref: '#/components/schemas/OutputTextContent' - $ref: '#/components/schemas/RefusalContent' discriminator: propertyName: type OutputItem: anyOf: - $ref: '#/components/schemas/OutputMessage' - $ref: '#/components/schemas/FileSearchToolCall' - $ref: '#/components/schemas/FunctionToolCall' - $ref: '#/components/schemas/WebSearchToolCall' - $ref: '#/components/schemas/ComputerToolCall' - $ref: '#/components/schemas/ReasoningItem' - $ref: '#/components/schemas/ImageGenToolCall' - $ref: '#/components/schemas/CodeInterpreterToolCall' - $ref: '#/components/schemas/LocalShellToolCall' - $ref: '#/components/schemas/MCPToolCall' - $ref: '#/components/schemas/MCPListTools' - $ref: '#/components/schemas/MCPApprovalRequest' - $ref: '#/components/schemas/CustomToolCall' discriminator: propertyName: type OutputMessage: type: object title: Output message description: | An output message from the model. properties: id: type: string description: | The unique ID of the output message. x-stainless-go-json: omitzero type: type: string description: | The type of the output message. Always `message`. enum: - message x-stainless-const: true role: type: string description: | The role of the output message. Always `assistant`. enum: - assistant x-stainless-const: true content: type: array description: | The content of the output message. items: $ref: '#/components/schemas/OutputContent' status: type: string description: | The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. enum: - in_progress - completed - incomplete required: - id - type - role - content - status ParallelToolCalls: description: >- Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. type: boolean default: true PartialImages: type: integer maximum: 3 minimum: 0 default: 0 example: 1 nullable: true description: | The number of partial images to generate. This parameter is used for streaming responses that return partial images. Value must be between 0 and 3. When set to 0, the response will be a single image sent in one streaming event. Note that the final image may be sent before the full number of partial images are generated if the full image is generated more quickly. PredictionContent: type: object title: Static Content description: | Static predicted output content, such as the content of a text file that is being regenerated. required: - type - content properties: type: type: string enum: - content description: | The type of the predicted content you want to provide. This type is currently always `content`. x-stainless-const: true content: description: | The content that should be matched when generating a model response. If generated tokens would match this content, the entire model response can be returned much more quickly. anyOf: - type: string title: Text content description: | The content used for a Predicted Output. This is often the text of a file you are regenerating with minor changes. - type: array description: >- An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text inputs. title: Array of content parts items: $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' minItems: 1 Project: type: object description: Represents an individual project. properties: id: type: string description: The identifier, which can be referenced in API endpoints object: type: string enum: - organization.project description: The object type, which is always `organization.project` x-stainless-const: true name: type: string description: The name of the project. This appears in reporting. created_at: type: integer description: The Unix timestamp (in seconds) of when the project was created. archived_at: type: integer nullable: true description: The Unix timestamp (in seconds) of when the project was archived or `null`. status: type: string enum: - active - archived description: '`active` or `archived`' required: - id - object - name - created_at - status x-oaiMeta: name: The project object example: | { "id": "proj_abc", "object": "organization.project", "name": "Project example", "created_at": 1711471533, "archived_at": null, "status": "active" } ProjectApiKey: type: object description: Represents an individual API key in a project. properties: object: type: string enum: - organization.project.api_key description: The object type, which is always `organization.project.api_key` x-stainless-const: true redacted_value: type: string description: The redacted value of the API key name: type: string description: The name of the API key created_at: type: integer description: The Unix timestamp (in seconds) of when the API key was created last_used_at: type: integer description: The Unix timestamp (in seconds) of when the API key was last used. id: type: string description: The identifier, which can be referenced in API endpoints owner: type: object properties: type: type: string enum: - user - service_account description: '`user` or `service_account`' user: $ref: '#/components/schemas/ProjectUser' service_account: $ref: '#/components/schemas/ProjectServiceAccount' required: - object - redacted_value - name - created_at - last_used_at - id - owner x-oaiMeta: name: The project API key object example: | { "object": "organization.project.api_key", "redacted_value": "sk-abc...def", "name": "My API Key", "created_at": 1711471533, "last_used_at": 1711471534, "id": "key_abc", "owner": { "type": "user", "user": { "object": "organization.project.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "created_at": 1711471533 } } } ProjectApiKeyDeleteResponse: type: object properties: object: type: string enum: - organization.project.api_key.deleted x-stainless-const: true id: type: string deleted: type: boolean required: - object - id - deleted ProjectApiKeyListResponse: type: object properties: object: type: string enum: - list x-stainless-const: true data: type: array items: $ref: '#/components/schemas/ProjectApiKey' first_id: type: string last_id: type: string has_more: type: boolean required: - object - data - first_id - last_id - has_more ProjectCreateRequest: type: object properties: name: type: string description: The friendly name of the project, this name appears in reports. required: - name ProjectListResponse: type: object properties: object: type: string enum: - list x-stainless-const: true data: type: array items: $ref: '#/components/schemas/Project' first_id: type: string last_id: type: string has_more: type: boolean required: - object - data - first_id - last_id - has_more ProjectRateLimit: type: object description: Represents a project rate limit config. properties: object: type: string enum: - project.rate_limit description: The object type, which is always `project.rate_limit` x-stainless-const: true id: type: string description: The identifier, which can be referenced in API endpoints. model: type: string description: The model this rate limit applies to. max_requests_per_1_minute: type: integer description: The maximum requests per minute. max_tokens_per_1_minute: type: integer description: The maximum tokens per minute. max_images_per_1_minute: type: integer description: The maximum images per minute. Only present for relevant models. max_audio_megabytes_per_1_minute: type: integer description: The maximum audio megabytes per minute. Only present for relevant models. max_requests_per_1_day: type: integer description: The maximum requests per day. Only present for relevant models. batch_1_day_max_input_tokens: type: integer description: The maximum batch input tokens per day. Only present for relevant models. required: - object - id - model - max_requests_per_1_minute - max_tokens_per_1_minute x-oaiMeta: name: The project rate limit object example: | { "object": "project.rate_limit", "id": "rl_ada", "model": "ada", "max_requests_per_1_minute": 600, "max_tokens_per_1_minute": 150000, "max_images_per_1_minute": 10 } ProjectRateLimitListResponse: type: object properties: object: type: string enum: - list x-stainless-const: true data: type: array items: $ref: '#/components/schemas/ProjectRateLimit' first_id: type: string last_id: type: string has_more: type: boolean required: - object - data - first_id - last_id - has_more ProjectRateLimitUpdateRequest: type: object properties: max_requests_per_1_minute: type: integer description: The maximum requests per minute. max_tokens_per_1_minute: type: integer description: The maximum tokens per minute. max_images_per_1_minute: type: integer description: The maximum images per minute. Only relevant for certain models. max_audio_megabytes_per_1_minute: type: integer description: The maximum audio megabytes per minute. Only relevant for certain models. max_requests_per_1_day: type: integer description: The maximum requests per day. Only relevant for certain models. batch_1_day_max_input_tokens: type: integer description: The maximum batch input tokens per day. Only relevant for certain models. ProjectServiceAccount: type: object description: Represents an individual service account in a project. properties: object: type: string enum: - organization.project.service_account description: The object type, which is always `organization.project.service_account` x-stainless-const: true id: type: string description: The identifier, which can be referenced in API endpoints name: type: string description: The name of the service account role: type: string enum: - owner - member description: '`owner` or `member`' created_at: type: integer description: The Unix timestamp (in seconds) of when the service account was created required: - object - id - name - role - created_at x-oaiMeta: name: The project service account object example: | { "object": "organization.project.service_account", "id": "svc_acct_abc", "name": "Service Account", "role": "owner", "created_at": 1711471533 } ProjectServiceAccountApiKey: type: object properties: object: type: string enum: - organization.project.service_account.api_key description: The object type, which is always `organization.project.service_account.api_key` x-stainless-const: true value: type: string name: type: string created_at: type: integer id: type: string required: - object - value - name - created_at - id ProjectServiceAccountCreateRequest: type: object properties: name: type: string description: The name of the service account being created. required: - name ProjectServiceAccountCreateResponse: type: object properties: object: type: string enum: - organization.project.service_account x-stainless-const: true id: type: string name: type: string role: type: string enum: - member description: Service accounts can only have one role of type `member` x-stainless-const: true created_at: type: integer api_key: $ref: '#/components/schemas/ProjectServiceAccountApiKey' required: - object - id - name - role - created_at - api_key ProjectServiceAccountDeleteResponse: type: object properties: object: type: string enum: - organization.project.service_account.deleted x-stainless-const: true id: type: string deleted: type: boolean required: - object - id - deleted ProjectServiceAccountListResponse: type: object properties: object: type: string enum: - list x-stainless-const: true data: type: array items: $ref: '#/components/schemas/ProjectServiceAccount' first_id: type: string last_id: type: string has_more: type: boolean required: - object - data - first_id - last_id - has_more ProjectUpdateRequest: type: object properties: name: type: string description: The updated name of the project, this name appears in reports. required: - name ProjectUser: type: object description: Represents an individual user in a project. properties: object: type: string enum: - organization.project.user description: The object type, which is always `organization.project.user` x-stainless-const: true id: type: string description: The identifier, which can be referenced in API endpoints name: type: string description: The name of the user email: type: string description: The email address of the user role: type: string enum: - owner - member description: '`owner` or `member`' added_at: type: integer description: The Unix timestamp (in seconds) of when the project was added. required: - object - id - name - email - role - added_at x-oaiMeta: name: The project user object example: | { "object": "organization.project.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } ProjectUserCreateRequest: type: object properties: user_id: type: string description: The ID of the user. role: type: string enum: - owner - member description: '`owner` or `member`' required: - user_id - role ProjectUserDeleteResponse: type: object properties: object: type: string enum: - organization.project.user.deleted x-stainless-const: true id: type: string deleted: type: boolean required: - object - id - deleted ProjectUserListResponse: type: object properties: object: type: string data: type: array items: $ref: '#/components/schemas/ProjectUser' first_id: type: string last_id: type: string has_more: type: boolean required: - object - data - first_id - last_id - has_more ProjectUserUpdateRequest: type: object properties: role: type: string enum: - owner - member description: '`owner` or `member`' required: - role Prompt: type: object nullable: true description: | Reference to a prompt template and its variables. [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). required: - id properties: id: type: string description: The unique identifier of the prompt template to use. version: type: string description: Optional version of the prompt template. nullable: true variables: $ref: '#/components/schemas/ResponsePromptVariables' RealtimeClientEvent: discriminator: propertyName: type description: | A realtime client event. anyOf: - $ref: '#/components/schemas/RealtimeClientEventConversationItemCreate' - $ref: '#/components/schemas/RealtimeClientEventConversationItemDelete' - $ref: '#/components/schemas/RealtimeClientEventConversationItemRetrieve' - $ref: '#/components/schemas/RealtimeClientEventConversationItemTruncate' - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferAppend' - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferClear' - $ref: '#/components/schemas/RealtimeClientEventOutputAudioBufferClear' - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferCommit' - $ref: '#/components/schemas/RealtimeClientEventResponseCancel' - $ref: '#/components/schemas/RealtimeClientEventResponseCreate' - $ref: '#/components/schemas/RealtimeClientEventSessionUpdate' - $ref: '#/components/schemas/RealtimeClientEventTranscriptionSessionUpdate' RealtimeClientEventConversationItemCreate: type: object description: | Add a new Item to the Conversation's context, including messages, function calls, and function call responses. This event can be used both to populate a "history" of the conversation and to add new items mid-stream, but has the current limitation that it cannot populate assistant audio messages. If successful, the server will respond with a `conversation.item.created` event, otherwise an `error` event will be sent. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `conversation.item.create`. x-stainless-const: true const: conversation.item.create previous_item_id: type: string description: | The ID of the preceding item after which the new item will be inserted. If not set, the new item will be appended to the end of the conversation. If set to `root`, the new item will be added to the beginning of the conversation. If set to an existing ID, it allows an item to be inserted mid-conversation. If the ID cannot be found, an error will be returned and the item will not be added. item: $ref: '#/components/schemas/RealtimeConversationItem' required: - type - item x-oaiMeta: name: conversation.item.create group: realtime example: | { "event_id": "event_345", "type": "conversation.item.create", "previous_item_id": null, "item": { "id": "msg_001", "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "Hello, how are you?" } ] } } RealtimeClientEventConversationItemDelete: type: object description: | Send this event when you want to remove any item from the conversation history. The server will respond with a `conversation.item.deleted` event, unless the item does not exist in the conversation history, in which case the server will respond with an error. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `conversation.item.delete`. x-stainless-const: true const: conversation.item.delete item_id: type: string description: The ID of the item to delete. required: - type - item_id x-oaiMeta: name: conversation.item.delete group: realtime example: | { "event_id": "event_901", "type": "conversation.item.delete", "item_id": "msg_003" } RealtimeClientEventConversationItemRetrieve: type: object description: > Send this event when you want to retrieve the server's representation of a specific item in the conversation history. This is useful, for example, to inspect user audio after noise cancellation and VAD. The server will respond with a `conversation.item.retrieved` event, unless the item does not exist in the conversation history, in which case the server will respond with an error. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `conversation.item.retrieve`. x-stainless-const: true const: conversation.item.retrieve item_id: type: string description: The ID of the item to retrieve. required: - type - item_id x-oaiMeta: name: conversation.item.retrieve group: realtime example: | { "event_id": "event_901", "type": "conversation.item.retrieve", "item_id": "msg_003" } RealtimeClientEventConversationItemTruncate: type: object description: | Send this event to truncate a previous assistant message’s audio. The server will produce audio faster than realtime, so this event is useful when the user interrupts to truncate audio that has already been sent to the client but not yet played. This will synchronize the server's understanding of the audio with the client's playback. Truncating audio will delete the server-side text transcript to ensure there is not text in the context that hasn't been heard by the user. If successful, the server will respond with a `conversation.item.truncated` event. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `conversation.item.truncate`. x-stainless-const: true const: conversation.item.truncate item_id: type: string description: | The ID of the assistant message item to truncate. Only assistant message items can be truncated. content_index: type: integer description: The index of the content part to truncate. Set this to 0. audio_end_ms: type: integer description: | Inclusive duration up to which audio is truncated, in milliseconds. If the audio_end_ms is greater than the actual audio duration, the server will respond with an error. required: - type - item_id - content_index - audio_end_ms x-oaiMeta: name: conversation.item.truncate group: realtime example: | { "event_id": "event_678", "type": "conversation.item.truncate", "item_id": "msg_002", "content_index": 0, "audio_end_ms": 1500 } RealtimeClientEventInputAudioBufferAppend: type: object description: | Send this event to append audio bytes to the input audio buffer. The audio buffer is temporary storage you can write to and later commit. In Server VAD mode, the audio buffer is used to detect speech and the server will decide when to commit. When Server VAD is disabled, you must commit the audio buffer manually. The client may choose how much audio to place in each event up to a maximum of 15 MiB, for example streaming smaller chunks from the client may allow the VAD to be more responsive. Unlike made other client events, the server will not send a confirmation response to this event. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `input_audio_buffer.append`. x-stainless-const: true const: input_audio_buffer.append audio: type: string description: | Base64-encoded audio bytes. This must be in the format specified by the `input_audio_format` field in the session configuration. required: - type - audio x-oaiMeta: name: input_audio_buffer.append group: realtime example: | { "event_id": "event_456", "type": "input_audio_buffer.append", "audio": "Base64EncodedAudioData" } RealtimeClientEventInputAudioBufferClear: type: object description: | Send this event to clear the audio bytes in the buffer. The server will respond with an `input_audio_buffer.cleared` event. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `input_audio_buffer.clear`. x-stainless-const: true const: input_audio_buffer.clear required: - type x-oaiMeta: name: input_audio_buffer.clear group: realtime example: | { "event_id": "event_012", "type": "input_audio_buffer.clear" } RealtimeClientEventInputAudioBufferCommit: type: object description: | Send this event to commit the user input audio buffer, which will create a new user message item in the conversation. This event will produce an error if the input audio buffer is empty. When in Server VAD mode, the client does not need to send this event, the server will commit the audio buffer automatically. Committing the input audio buffer will trigger input audio transcription (if enabled in session configuration), but it will not create a response from the model. The server will respond with an `input_audio_buffer.committed` event. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `input_audio_buffer.commit`. x-stainless-const: true const: input_audio_buffer.commit required: - type x-oaiMeta: name: input_audio_buffer.commit group: realtime example: | { "event_id": "event_789", "type": "input_audio_buffer.commit" } RealtimeClientEventOutputAudioBufferClear: type: object description: > **WebRTC Only:** Emit to cut off the current audio response. This will trigger the server to stop generating audio and emit a `output_audio_buffer.cleared` event. This event should be preceded by a `response.cancel` client event to stop the generation of the current response. [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). properties: event_id: type: string description: The unique ID of the client event used for error handling. type: description: The event type, must be `output_audio_buffer.clear`. x-stainless-const: true const: output_audio_buffer.clear required: - type x-oaiMeta: name: output_audio_buffer.clear group: realtime example: | { "event_id": "optional_client_event_id", "type": "output_audio_buffer.clear" } RealtimeClientEventResponseCancel: type: object description: | Send this event to cancel an in-progress response. The server will respond with a `response.done` event with a status of `response.status=cancelled`. If there is no response to cancel, the server will respond with an error. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `response.cancel`. x-stainless-const: true const: response.cancel response_id: type: string description: | A specific response ID to cancel - if not provided, will cancel an in-progress response in the default conversation. required: - type x-oaiMeta: name: response.cancel group: realtime example: | { "event_id": "event_567", "type": "response.cancel" } RealtimeClientEventResponseCreate: type: object description: | This event instructs the server to create a Response, which means triggering model inference. When in Server VAD mode, the server will create Responses automatically. A Response will include at least one Item, and may have two, in which case the second will be a function call. These Items will be appended to the conversation history. The server will respond with a `response.created` event, events for Items and content created, and finally a `response.done` event to indicate the Response is complete. The `response.create` event includes inference configuration like `instructions`, and `temperature`. These fields will override the Session's configuration for this Response only. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `response.create`. x-stainless-const: true const: response.create response: $ref: '#/components/schemas/RealtimeResponseCreateParams' required: - type x-oaiMeta: name: response.create group: realtime example: | { "event_id": "event_234", "type": "response.create", "response": { "modalities": ["text", "audio"], "instructions": "Please assist the user.", "voice": "sage", "output_audio_format": "pcm16", "tools": [ { "type": "function", "name": "calculate_sum", "description": "Calculates the sum of two numbers.", "parameters": { "type": "object", "properties": { "a": { "type": "number" }, "b": { "type": "number" } }, "required": ["a", "b"] } } ], "tool_choice": "auto", "temperature": 0.8, "max_output_tokens": 1024 } } RealtimeClientEventSessionUpdate: type: object description: | Send this event to update the session’s default configuration. The client may send this event at any time to update any field, except for `voice`. However, note that once a session has been initialized with a particular `model`, it can’t be changed to another model using `session.update`. When the server receives a `session.update`, it will respond with a `session.updated` event showing the full, effective configuration. Only the fields that are present are updated. To clear a field like `instructions`, pass an empty string. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `session.update`. x-stainless-const: true const: session.update session: $ref: '#/components/schemas/RealtimeSessionCreateRequest' required: - type - session x-oaiMeta: name: session.update group: realtime example: | { "event_id": "event_123", "type": "session.update", "session": { "modalities": ["text", "audio"], "instructions": "You are a helpful assistant.", "voice": "sage", "input_audio_format": "pcm16", "output_audio_format": "pcm16", "input_audio_transcription": { "model": "whisper-1" }, "turn_detection": { "type": "server_vad", "threshold": 0.5, "prefix_padding_ms": 300, "silence_duration_ms": 500, "create_response": true }, "tools": [ { "type": "function", "name": "get_weather", "description": "Get the current weather...", "parameters": { "type": "object", "properties": { "location": { "type": "string" } }, "required": ["location"] } } ], "tool_choice": "auto", "temperature": 0.8, "max_response_output_tokens": "inf", "speed": 1.1, "tracing": "auto" } } RealtimeClientEventTranscriptionSessionUpdate: type: object description: | Send this event to update a transcription session. properties: event_id: type: string description: Optional client-generated ID used to identify this event. type: description: The event type, must be `transcription_session.update`. x-stainless-const: true const: transcription_session.update session: $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' required: - type - session x-oaiMeta: name: transcription_session.update group: realtime example: | { "type": "transcription_session.update", "session": { "input_audio_format": "pcm16", "input_audio_transcription": { "model": "gpt-4o-transcribe", "prompt": "", "language": "" }, "turn_detection": { "type": "server_vad", "threshold": 0.5, "prefix_padding_ms": 300, "silence_duration_ms": 500, "create_response": true, }, "input_audio_noise_reduction": { "type": "near_field" }, "include": [ "item.input_audio_transcription.logprobs", ] } } RealtimeConversationItem: type: object description: The item to add to the conversation. properties: id: type: string description: | The unique ID of the item, this can be generated by the client to help manage server-side context, but is not required because the server will generate one if not provided. type: type: string enum: - message - function_call - function_call_output description: | The type of the item (`message`, `function_call`, `function_call_output`). object: type: string enum: - realtime.item description: | Identifier for the API object being returned - always `realtime.item`. x-stainless-const: true status: type: string enum: - completed - incomplete - in_progress description: | The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect on the conversation, but are accepted for consistency with the `conversation.item.created` event. role: type: string enum: - user - assistant - system description: | The role of the message sender (`user`, `assistant`, `system`), only applicable for `message` items. content: type: array description: | The content of the message, applicable for `message` items. - Message items of role `system` support only `input_text` content - Message items of role `user` support `input_text` and `input_audio` content - Message items of role `assistant` support `text` content. items: $ref: '#/components/schemas/RealtimeConversationItemContent' call_id: type: string description: | The ID of the function call (for `function_call` and `function_call_output` items). If passed on a `function_call_output` item, the server will check that a `function_call` item with the same ID exists in the conversation history. name: type: string description: | The name of the function being called (for `function_call` items). arguments: type: string description: | The arguments of the function call (for `function_call` items). output: type: string description: | The output of the function call (for `function_call_output` items). RealtimeConversationItemWithReference: type: object description: The item to add to the conversation. properties: id: type: string description: | For an item of type (`message` | `function_call` | `function_call_output`) this field allows the client to assign the unique ID of the item. It is not required because the server will generate one if not provided. For an item of type `item_reference`, this field is required and is a reference to any item that has previously existed in the conversation. type: type: string enum: - message - function_call - function_call_output - item_reference description: | The type of the item (`message`, `function_call`, `function_call_output`, `item_reference`). object: type: string enum: - realtime.item description: | Identifier for the API object being returned - always `realtime.item`. x-stainless-const: true status: type: string enum: - completed - incomplete - in_progress description: | The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect on the conversation, but are accepted for consistency with the `conversation.item.created` event. role: type: string enum: - user - assistant - system description: | The role of the message sender (`user`, `assistant`, `system`), only applicable for `message` items. content: type: array description: | The content of the message, applicable for `message` items. - Message items of role `system` support only `input_text` content - Message items of role `user` support `input_text` and `input_audio` content - Message items of role `assistant` support `text` content. items: type: object properties: type: type: string enum: - input_text - input_audio - item_reference - text description: | The content type (`input_text`, `input_audio`, `item_reference`, `text`). text: type: string description: | The text content, used for `input_text` and `text` content types. id: type: string description: | ID of a previous conversation item to reference (for `item_reference` content types in `response.create` events). These can reference both client and server created items. audio: type: string description: | Base64-encoded audio bytes, used for `input_audio` content type. transcript: type: string description: | The transcript of the audio, used for `input_audio` content type. call_id: type: string description: | The ID of the function call (for `function_call` and `function_call_output` items). If passed on a `function_call_output` item, the server will check that a `function_call` item with the same ID exists in the conversation history. name: type: string description: | The name of the function being called (for `function_call` items). arguments: type: string description: | The arguments of the function call (for `function_call` items). output: type: string description: | The output of the function call (for `function_call_output` items). RealtimeResponse: type: object description: The response resource. properties: id: type: string description: The unique ID of the response. object: description: The object type, must be `realtime.response`. x-stainless-const: true const: realtime.response status: type: string enum: - completed - cancelled - failed - incomplete - in_progress description: | The final status of the response (`completed`, `cancelled`, `failed`, or `incomplete`, `in_progress`). status_details: type: object description: Additional details about the status. properties: type: type: string enum: - completed - cancelled - incomplete - failed description: | The type of error that caused the response to fail, corresponding with the `status` field (`completed`, `cancelled`, `incomplete`, `failed`). reason: type: string enum: - turn_detected - client_cancelled - max_output_tokens - content_filter description: | The reason the Response did not complete. For a `cancelled` Response, one of `turn_detected` (the server VAD detected a new start of speech) or `client_cancelled` (the client sent a cancel event). For an `incomplete` Response, one of `max_output_tokens` or `content_filter` (the server-side safety filter activated and cut off the response). error: type: object description: | A description of the error that caused the response to fail, populated when the `status` is `failed`. properties: type: type: string description: The type of error. code: type: string description: Error code, if any. output: type: array description: The list of output items generated by the response. items: $ref: '#/components/schemas/RealtimeConversationItem' metadata: $ref: '#/components/schemas/Metadata' usage: type: object description: | Usage statistics for the Response, this will correspond to billing. A Realtime API session will maintain a conversation context and append new Items to the Conversation, thus output from previous turns (text and audio tokens) will become the input for later turns. properties: total_tokens: type: integer description: | The total number of tokens in the Response including input and output text and audio tokens. input_tokens: type: integer description: | The number of input tokens used in the Response, including text and audio tokens. output_tokens: type: integer description: | The number of output tokens sent in the Response, including text and audio tokens. input_token_details: type: object description: Details about the input tokens used in the Response. properties: cached_tokens: type: integer description: The number of cached tokens used in the Response. text_tokens: type: integer description: The number of text tokens used in the Response. audio_tokens: type: integer description: The number of audio tokens used in the Response. output_token_details: type: object description: Details about the output tokens used in the Response. properties: text_tokens: type: integer description: The number of text tokens used in the Response. audio_tokens: type: integer description: The number of audio tokens used in the Response. conversation_id: description: | Which conversation the response is added to, determined by the `conversation` field in the `response.create` event. If `auto`, the response will be added to the default conversation and the value of `conversation_id` will be an id like `conv_1234`. If `none`, the response will not be added to any conversation and the value of `conversation_id` will be `null`. If responses are being triggered by server VAD, the response will be added to the default conversation, thus the `conversation_id` will be an id like `conv_1234`. type: string voice: $ref: '#/components/schemas/VoiceIdsShared' description: | The voice the model used to respond. Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. modalities: type: array description: | The set of modalities the model used to respond. If there are multiple modalities, the model will pick one, for example if `modalities` is `["text", "audio"]`, the model could be responding in either text or audio. items: type: string enum: - text - audio output_audio_format: type: string enum: - pcm16 - g711_ulaw - g711_alaw description: | The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. temperature: type: number description: | Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. max_output_tokens: description: | Maximum number of output tokens for a single assistant response, inclusive of tool calls, that was used in this response. anyOf: - type: integer - type: string enum: - inf x-stainless-const: true RealtimeResponseCreateParams: type: object description: Create a new Realtime response with these parameters properties: modalities: type: array description: | The set of modalities the model can respond with. To disable audio, set this to ["text"]. items: type: string enum: - text - audio instructions: type: string description: | The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. "be extremely succinct", "act friendly", "here are examples of good responses") and on audio behavior (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior. Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session. voice: $ref: '#/components/schemas/VoiceIdsShared' description: | The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. output_audio_format: type: string enum: - pcm16 - g711_ulaw - g711_alaw description: | The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. tools: type: array description: Tools (functions) available to the model. items: type: object properties: type: type: string enum: - function description: The type of the tool, i.e. `function`. x-stainless-const: true name: type: string description: The name of the function. description: type: string description: | The description of the function, including guidance on when and how to call it, and guidance about what to tell the user when calling (if anything). parameters: type: object description: Parameters of the function in JSON Schema. tool_choice: type: string description: | How the model chooses tools. Options are `auto`, `none`, `required`, or specify a function, like `{"type": "function", "function": {"name": "my_function"}}`. temperature: type: number description: | Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. max_response_output_tokens: description: | Maximum number of output tokens for a single assistant response, inclusive of tool calls. Provide an integer between 1 and 4096 to limit output tokens, or `inf` for the maximum available tokens for a given model. Defaults to `inf`. anyOf: - type: integer - type: string enum: - inf x-stainless-const: true conversation: description: | Controls which conversation the response is added to. Currently supports `auto` and `none`, with `auto` as the default value. The `auto` value means that the contents of the response will be added to the default conversation. Set this to `none` to create an out-of-band response which will not add items to default conversation. anyOf: - type: string - type: string default: auto enum: - auto - none metadata: $ref: '#/components/schemas/Metadata' input: type: array description: | Input items to include in the prompt for the model. Using this field creates a new context for this Response instead of using the default conversation. An empty array `[]` will clear the context for this Response. Note that this can include references to items from the default conversation. items: $ref: '#/components/schemas/RealtimeConversationItemWithReference' RealtimeServerEvent: discriminator: propertyName: type description: | A realtime server event. anyOf: - $ref: '#/components/schemas/RealtimeServerEventConversationCreated' - $ref: '#/components/schemas/RealtimeServerEventConversationItemCreated' - $ref: '#/components/schemas/RealtimeServerEventConversationItemDeleted' - $ref: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionCompleted' - $ref: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionDelta' - $ref: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionFailed' - $ref: '#/components/schemas/RealtimeServerEventConversationItemRetrieved' - $ref: '#/components/schemas/RealtimeServerEventConversationItemTruncated' - $ref: '#/components/schemas/RealtimeServerEventError' - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferCleared' - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferCommitted' - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStarted' - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStopped' - $ref: '#/components/schemas/RealtimeServerEventRateLimitsUpdated' - $ref: '#/components/schemas/RealtimeServerEventResponseAudioDelta' - $ref: '#/components/schemas/RealtimeServerEventResponseAudioDone' - $ref: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDelta' - $ref: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDone' - $ref: '#/components/schemas/RealtimeServerEventResponseContentPartAdded' - $ref: '#/components/schemas/RealtimeServerEventResponseContentPartDone' - $ref: '#/components/schemas/RealtimeServerEventResponseCreated' - $ref: '#/components/schemas/RealtimeServerEventResponseDone' - $ref: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDelta' - $ref: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDone' - $ref: '#/components/schemas/RealtimeServerEventResponseOutputItemAdded' - $ref: '#/components/schemas/RealtimeServerEventResponseOutputItemDone' - $ref: '#/components/schemas/RealtimeServerEventResponseTextDelta' - $ref: '#/components/schemas/RealtimeServerEventResponseTextDone' - $ref: '#/components/schemas/RealtimeServerEventSessionCreated' - $ref: '#/components/schemas/RealtimeServerEventSessionUpdated' - $ref: '#/components/schemas/RealtimeServerEventTranscriptionSessionUpdated' - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferStarted' - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferStopped' - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferCleared' RealtimeServerEventConversationCreated: type: object description: | Returned when a conversation is created. Emitted right after session creation. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `conversation.created`. x-stainless-const: true const: conversation.created conversation: type: object description: The conversation resource. properties: id: type: string description: The unique ID of the conversation. object: description: The object type, must be `realtime.conversation`. const: realtime.conversation required: - event_id - type - conversation x-oaiMeta: name: conversation.created group: realtime example: | { "event_id": "event_9101", "type": "conversation.created", "conversation": { "id": "conv_001", "object": "realtime.conversation" } } RealtimeServerEventConversationItemCreated: type: object description: | Returned when a conversation item is created. There are several scenarios that produce this event: - The server is generating a Response, which if successful will produce either one or two Items, which will be of type `message` (role `assistant`) or type `function_call`. - The input audio buffer has been committed, either by the client or the server (in `server_vad` mode). The server will take the content of the input audio buffer and add it to a new user message Item. - The client has sent a `conversation.item.create` event to add a new Item to the Conversation. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `conversation.item.created`. x-stainless-const: true const: conversation.item.created previous_item_id: type: string nullable: true description: | The ID of the preceding item in the Conversation context, allows the client to understand the order of the conversation. Can be `null` if the item has no predecessor. item: $ref: '#/components/schemas/RealtimeConversationItem' required: - event_id - type - item x-oaiMeta: name: conversation.item.created group: realtime example: | { "event_id": "event_1920", "type": "conversation.item.created", "previous_item_id": "msg_002", "item": { "id": "msg_003", "object": "realtime.item", "type": "message", "status": "completed", "role": "user", "content": [] } } RealtimeServerEventConversationItemDeleted: type: object description: | Returned when an item in the conversation is deleted by the client with a `conversation.item.delete` event. This event is used to synchronize the server's understanding of the conversation history with the client's view. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `conversation.item.deleted`. x-stainless-const: true const: conversation.item.deleted item_id: type: string description: The ID of the item that was deleted. required: - event_id - type - item_id x-oaiMeta: name: conversation.item.deleted group: realtime example: | { "event_id": "event_2728", "type": "conversation.item.deleted", "item_id": "msg_005" } RealtimeServerEventConversationItemInputAudioTranscriptionCompleted: type: object description: | This event is the output of audio transcription for user audio written to the user audio buffer. Transcription begins when the input audio buffer is committed by the client or server (in `server_vad` mode). Transcription runs asynchronously with Response creation, so this event may come before or after the Response events. Realtime API models accept audio natively, and thus input transcription is a separate process run on a separate ASR (Automatic Speech Recognition) model. The transcript may diverge somewhat from the model's interpretation, and should be treated as a rough guide. properties: event_id: type: string description: The unique ID of the server event. type: type: string enum: - conversation.item.input_audio_transcription.completed description: | The event type, must be `conversation.item.input_audio_transcription.completed`. x-stainless-const: true item_id: type: string description: The ID of the user message item containing the audio. content_index: type: integer description: The index of the content part containing the audio. transcript: type: string description: The transcribed text. logprobs: type: array description: The log probabilities of the transcription. nullable: true items: $ref: '#/components/schemas/LogProbProperties' usage: type: object description: Usage statistics for the transcription. anyOf: - $ref: '#/components/schemas/TranscriptTextUsageTokens' title: Token Usage - $ref: '#/components/schemas/TranscriptTextUsageDuration' title: Duration Usage required: - event_id - type - item_id - content_index - transcript - usage x-oaiMeta: name: conversation.item.input_audio_transcription.completed group: realtime example: | { "event_id": "event_2122", "type": "conversation.item.input_audio_transcription.completed", "item_id": "msg_003", "content_index": 0, "transcript": "Hello, how are you?", "usage": { "type": "tokens", "total_tokens": 48, "input_tokens": 38, "input_token_details": { "text_tokens": 10, "audio_tokens": 28, }, "output_tokens": 10, } } RealtimeServerEventConversationItemInputAudioTranscriptionDelta: type: object description: | Returned when the text value of an input audio transcription content part is updated. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `conversation.item.input_audio_transcription.delta`. x-stainless-const: true const: conversation.item.input_audio_transcription.delta item_id: type: string description: The ID of the item. content_index: type: integer description: The index of the content part in the item's content array. delta: type: string description: The text delta. logprobs: type: array description: The log probabilities of the transcription. nullable: true items: $ref: '#/components/schemas/LogProbProperties' required: - event_id - type - item_id x-oaiMeta: name: conversation.item.input_audio_transcription.delta group: realtime example: | { "type": "conversation.item.input_audio_transcription.delta", "event_id": "event_001", "item_id": "item_001", "content_index": 0, "delta": "Hello" } RealtimeServerEventConversationItemInputAudioTranscriptionFailed: type: object description: | Returned when input audio transcription is configured, and a transcription request for a user message failed. These events are separate from other `error` events so that the client can identify the related Item. properties: event_id: type: string description: The unique ID of the server event. type: type: string enum: - conversation.item.input_audio_transcription.failed description: | The event type, must be `conversation.item.input_audio_transcription.failed`. x-stainless-const: true item_id: type: string description: The ID of the user message item. content_index: type: integer description: The index of the content part containing the audio. error: type: object description: Details of the transcription error. properties: type: type: string description: The type of error. code: type: string description: Error code, if any. message: type: string description: A human-readable error message. param: type: string description: Parameter related to the error, if any. required: - event_id - type - item_id - content_index - error x-oaiMeta: name: conversation.item.input_audio_transcription.failed group: realtime example: | { "event_id": "event_2324", "type": "conversation.item.input_audio_transcription.failed", "item_id": "msg_003", "content_index": 0, "error": { "type": "transcription_error", "code": "audio_unintelligible", "message": "The audio could not be transcribed.", "param": null } } RealtimeServerEventConversationItemRetrieved: type: object description: | Returned when a conversation item is retrieved with `conversation.item.retrieve`. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `conversation.item.retrieved`. x-stainless-const: true const: conversation.item.retrieved item: $ref: '#/components/schemas/RealtimeConversationItem' required: - event_id - type - item x-oaiMeta: name: conversation.item.retrieved group: realtime example: | { "event_id": "event_1920", "type": "conversation.item.created", "previous_item_id": "msg_002", "item": { "id": "msg_003", "object": "realtime.item", "type": "message", "status": "completed", "role": "user", "content": [ { "type": "input_audio", "transcript": "hello how are you", "audio": "base64encodedaudio==" } ] } } RealtimeServerEventConversationItemTruncated: type: object description: | Returned when an earlier assistant audio message item is truncated by the client with a `conversation.item.truncate` event. This event is used to synchronize the server's understanding of the audio with the client's playback. This action will truncate the audio and remove the server-side text transcript to ensure there is no text in the context that hasn't been heard by the user. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `conversation.item.truncated`. x-stainless-const: true const: conversation.item.truncated item_id: type: string description: The ID of the assistant message item that was truncated. content_index: type: integer description: The index of the content part that was truncated. audio_end_ms: type: integer description: | The duration up to which the audio was truncated, in milliseconds. required: - event_id - type - item_id - content_index - audio_end_ms x-oaiMeta: name: conversation.item.truncated group: realtime example: | { "event_id": "event_2526", "type": "conversation.item.truncated", "item_id": "msg_004", "content_index": 0, "audio_end_ms": 1500 } RealtimeServerEventError: type: object description: | Returned when an error occurs, which could be a client problem or a server problem. Most errors are recoverable and the session will stay open, we recommend to implementors to monitor and log error messages by default. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `error`. x-stainless-const: true const: error error: type: object description: Details of the error. required: - type - message properties: type: type: string description: | The type of error (e.g., "invalid_request_error", "server_error"). code: type: string description: Error code, if any. nullable: true message: type: string description: A human-readable error message. param: type: string description: Parameter related to the error, if any. nullable: true event_id: type: string description: | The event_id of the client event that caused the error, if applicable. nullable: true required: - event_id - type - error x-oaiMeta: name: error group: realtime example: | { "event_id": "event_890", "type": "error", "error": { "type": "invalid_request_error", "code": "invalid_event", "message": "The 'type' field is missing.", "param": null, "event_id": "event_567" } } RealtimeServerEventInputAudioBufferCleared: type: object description: | Returned when the input audio buffer is cleared by the client with a `input_audio_buffer.clear` event. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `input_audio_buffer.cleared`. x-stainless-const: true const: input_audio_buffer.cleared required: - event_id - type x-oaiMeta: name: input_audio_buffer.cleared group: realtime example: | { "event_id": "event_1314", "type": "input_audio_buffer.cleared" } RealtimeServerEventInputAudioBufferCommitted: type: object description: | Returned when an input audio buffer is committed, either by the client or automatically in server VAD mode. The `item_id` property is the ID of the user message item that will be created, thus a `conversation.item.created` event will also be sent to the client. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `input_audio_buffer.committed`. x-stainless-const: true const: input_audio_buffer.committed previous_item_id: type: string nullable: true description: | The ID of the preceding item after which the new item will be inserted. Can be `null` if the item has no predecessor. item_id: type: string description: The ID of the user message item that will be created. required: - event_id - type - item_id x-oaiMeta: name: input_audio_buffer.committed group: realtime example: | { "event_id": "event_1121", "type": "input_audio_buffer.committed", "previous_item_id": "msg_001", "item_id": "msg_002" } RealtimeServerEventInputAudioBufferSpeechStarted: type: object description: | Sent by the server when in `server_vad` mode to indicate that speech has been detected in the audio buffer. This can happen any time audio is added to the buffer (unless speech is already detected). The client may want to use this event to interrupt audio playback or provide visual feedback to the user. The client should expect to receive a `input_audio_buffer.speech_stopped` event when speech stops. The `item_id` property is the ID of the user message item that will be created when speech stops and will also be included in the `input_audio_buffer.speech_stopped` event (unless the client manually commits the audio buffer during VAD activation). properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `input_audio_buffer.speech_started`. x-stainless-const: true const: input_audio_buffer.speech_started audio_start_ms: type: integer description: | Milliseconds from the start of all audio written to the buffer during the session when speech was first detected. This will correspond to the beginning of audio sent to the model, and thus includes the `prefix_padding_ms` configured in the Session. item_id: type: string description: | The ID of the user message item that will be created when speech stops. required: - event_id - type - audio_start_ms - item_id x-oaiMeta: name: input_audio_buffer.speech_started group: realtime example: | { "event_id": "event_1516", "type": "input_audio_buffer.speech_started", "audio_start_ms": 1000, "item_id": "msg_003" } RealtimeServerEventInputAudioBufferSpeechStopped: type: object description: | Returned in `server_vad` mode when the server detects the end of speech in the audio buffer. The server will also send an `conversation.item.created` event with the user message item that is created from the audio buffer. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `input_audio_buffer.speech_stopped`. x-stainless-const: true const: input_audio_buffer.speech_stopped audio_end_ms: type: integer description: | Milliseconds since the session started when speech stopped. This will correspond to the end of audio sent to the model, and thus includes the `min_silence_duration_ms` configured in the Session. item_id: type: string description: The ID of the user message item that will be created. required: - event_id - type - audio_end_ms - item_id x-oaiMeta: name: input_audio_buffer.speech_stopped group: realtime example: | { "event_id": "event_1718", "type": "input_audio_buffer.speech_stopped", "audio_end_ms": 2000, "item_id": "msg_003" } RealtimeServerEventOutputAudioBufferCleared: type: object description: > **WebRTC Only:** Emitted when the output audio buffer is cleared. This happens either in VAD mode when the user has interrupted (`input_audio_buffer.speech_started`), or when the client has emitted the `output_audio_buffer.clear` event to manually cut off the current audio response. [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `output_audio_buffer.cleared`. x-stainless-const: true const: output_audio_buffer.cleared response_id: type: string description: The unique ID of the response that produced the audio. required: - event_id - type - response_id x-oaiMeta: name: output_audio_buffer.cleared group: realtime example: | { "event_id": "event_abc123", "type": "output_audio_buffer.cleared", "response_id": "resp_abc123" } RealtimeServerEventOutputAudioBufferStarted: type: object description: > **WebRTC Only:** Emitted when the server begins streaming audio to the client. This event is emitted after an audio content part has been added (`response.content_part.added`) to the response. [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `output_audio_buffer.started`. x-stainless-const: true const: output_audio_buffer.started response_id: type: string description: The unique ID of the response that produced the audio. required: - event_id - type - response_id x-oaiMeta: name: output_audio_buffer.started group: realtime example: | { "event_id": "event_abc123", "type": "output_audio_buffer.started", "response_id": "resp_abc123" } RealtimeServerEventOutputAudioBufferStopped: type: object description: > **WebRTC Only:** Emitted when the output audio buffer has been completely drained on the server, and no more audio is forthcoming. This event is emitted after the full response data has been sent to the client (`response.done`). [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `output_audio_buffer.stopped`. x-stainless-const: true const: output_audio_buffer.stopped response_id: type: string description: The unique ID of the response that produced the audio. required: - event_id - type - response_id x-oaiMeta: name: output_audio_buffer.stopped group: realtime example: | { "event_id": "event_abc123", "type": "output_audio_buffer.stopped", "response_id": "resp_abc123" } RealtimeServerEventRateLimitsUpdated: type: object description: | Emitted at the beginning of a Response to indicate the updated rate limits. When a Response is created some tokens will be "reserved" for the output tokens, the rate limits shown here reflect that reservation, which is then adjusted accordingly once the Response is completed. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `rate_limits.updated`. x-stainless-const: true const: rate_limits.updated rate_limits: type: array description: List of rate limit information. items: type: object properties: name: type: string enum: - requests - tokens description: | The name of the rate limit (`requests`, `tokens`). limit: type: integer description: The maximum allowed value for the rate limit. remaining: type: integer description: The remaining value before the limit is reached. reset_seconds: type: number description: Seconds until the rate limit resets. required: - event_id - type - rate_limits x-oaiMeta: name: rate_limits.updated group: realtime example: | { "event_id": "event_5758", "type": "rate_limits.updated", "rate_limits": [ { "name": "requests", "limit": 1000, "remaining": 999, "reset_seconds": 60 }, { "name": "tokens", "limit": 50000, "remaining": 49950, "reset_seconds": 60 } ] } RealtimeServerEventResponseAudioDelta: type: object description: Returned when the model-generated audio is updated. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.audio.delta`. x-stainless-const: true const: response.audio.delta response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. delta: type: string description: Base64-encoded audio data delta. required: - event_id - type - response_id - item_id - output_index - content_index - delta x-oaiMeta: name: response.audio.delta group: realtime example: | { "event_id": "event_4950", "type": "response.audio.delta", "response_id": "resp_001", "item_id": "msg_008", "output_index": 0, "content_index": 0, "delta": "Base64EncodedAudioDelta" } RealtimeServerEventResponseAudioDone: type: object description: | Returned when the model-generated audio is done. Also emitted when a Response is interrupted, incomplete, or cancelled. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.audio.done`. x-stainless-const: true const: response.audio.done response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. required: - event_id - type - response_id - item_id - output_index - content_index x-oaiMeta: name: response.audio.done group: realtime example: | { "event_id": "event_5152", "type": "response.audio.done", "response_id": "resp_001", "item_id": "msg_008", "output_index": 0, "content_index": 0 } RealtimeServerEventResponseAudioTranscriptDelta: type: object description: | Returned when the model-generated transcription of audio output is updated. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.audio_transcript.delta`. x-stainless-const: true const: response.audio_transcript.delta response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. delta: type: string description: The transcript delta. required: - event_id - type - response_id - item_id - output_index - content_index - delta x-oaiMeta: name: response.audio_transcript.delta group: realtime example: | { "event_id": "event_4546", "type": "response.audio_transcript.delta", "response_id": "resp_001", "item_id": "msg_008", "output_index": 0, "content_index": 0, "delta": "Hello, how can I a" } RealtimeServerEventResponseAudioTranscriptDone: type: object description: | Returned when the model-generated transcription of audio output is done streaming. Also emitted when a Response is interrupted, incomplete, or cancelled. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.audio_transcript.done`. x-stainless-const: true const: response.audio_transcript.done response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. transcript: type: string description: The final transcript of the audio. required: - event_id - type - response_id - item_id - output_index - content_index - transcript x-oaiMeta: name: response.audio_transcript.done group: realtime example: | { "event_id": "event_4748", "type": "response.audio_transcript.done", "response_id": "resp_001", "item_id": "msg_008", "output_index": 0, "content_index": 0, "transcript": "Hello, how can I assist you today?" } RealtimeServerEventResponseContentPartAdded: type: object description: | Returned when a new content part is added to an assistant message item during response generation. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.content_part.added`. x-stainless-const: true const: response.content_part.added response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item to which the content part was added. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. part: type: object description: The content part that was added. properties: type: type: string enum: - text - audio description: The content type ("text", "audio"). text: type: string description: The text content (if type is "text"). audio: type: string description: Base64-encoded audio data (if type is "audio"). transcript: type: string description: The transcript of the audio (if type is "audio"). required: - event_id - type - response_id - item_id - output_index - content_index - part x-oaiMeta: name: response.content_part.added group: realtime example: | { "event_id": "event_3738", "type": "response.content_part.added", "response_id": "resp_001", "item_id": "msg_007", "output_index": 0, "content_index": 0, "part": { "type": "text", "text": "" } } RealtimeServerEventResponseContentPartDone: type: object description: | Returned when a content part is done streaming in an assistant message item. Also emitted when a Response is interrupted, incomplete, or cancelled. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.content_part.done`. x-stainless-const: true const: response.content_part.done response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. part: type: object description: The content part that is done. properties: type: type: string enum: - text - audio description: The content type ("text", "audio"). text: type: string description: The text content (if type is "text"). audio: type: string description: Base64-encoded audio data (if type is "audio"). transcript: type: string description: The transcript of the audio (if type is "audio"). required: - event_id - type - response_id - item_id - output_index - content_index - part x-oaiMeta: name: response.content_part.done group: realtime example: | { "event_id": "event_3940", "type": "response.content_part.done", "response_id": "resp_001", "item_id": "msg_007", "output_index": 0, "content_index": 0, "part": { "type": "text", "text": "Sure, I can help with that." } } RealtimeServerEventResponseCreated: type: object description: | Returned when a new Response is created. The first event of response creation, where the response is in an initial state of `in_progress`. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.created`. x-stainless-const: true const: response.created response: $ref: '#/components/schemas/RealtimeResponse' required: - event_id - type - response x-oaiMeta: name: response.created group: realtime example: | { "event_id": "event_2930", "type": "response.created", "response": { "id": "resp_001", "object": "realtime.response", "status": "in_progress", "status_details": null, "output": [], "usage": null } } RealtimeServerEventResponseDone: type: object description: | Returned when a Response is done streaming. Always emitted, no matter the final state. The Response object included in the `response.done` event will include all output Items in the Response but will omit the raw audio data. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.done`. x-stainless-const: true const: response.done response: $ref: '#/components/schemas/RealtimeResponse' required: - event_id - type - response x-oaiMeta: name: response.done group: realtime example: | { "event_id": "event_3132", "type": "response.done", "response": { "id": "resp_001", "object": "realtime.response", "status": "completed", "status_details": null, "output": [ { "id": "msg_006", "object": "realtime.item", "type": "message", "status": "completed", "role": "assistant", "content": [ { "type": "text", "text": "Sure, how can I assist you today?" } ] } ], "usage": { "total_tokens":275, "input_tokens":127, "output_tokens":148, "input_token_details": { "cached_tokens":384, "text_tokens":119, "audio_tokens":8, "cached_tokens_details": { "text_tokens": 128, "audio_tokens": 256 } }, "output_token_details": { "text_tokens":36, "audio_tokens":112 } } } } RealtimeServerEventResponseFunctionCallArgumentsDelta: type: object description: | Returned when the model-generated function call arguments are updated. properties: event_id: type: string description: The unique ID of the server event. type: description: | The event type, must be `response.function_call_arguments.delta`. x-stainless-const: true const: response.function_call_arguments.delta response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the function call item. output_index: type: integer description: The index of the output item in the response. call_id: type: string description: The ID of the function call. delta: type: string description: The arguments delta as a JSON string. required: - event_id - type - response_id - item_id - output_index - call_id - delta x-oaiMeta: name: response.function_call_arguments.delta group: realtime example: | { "event_id": "event_5354", "type": "response.function_call_arguments.delta", "response_id": "resp_002", "item_id": "fc_001", "output_index": 0, "call_id": "call_001", "delta": "{\"location\": \"San\"" } RealtimeServerEventResponseFunctionCallArgumentsDone: type: object description: | Returned when the model-generated function call arguments are done streaming. Also emitted when a Response is interrupted, incomplete, or cancelled. properties: event_id: type: string description: The unique ID of the server event. type: description: | The event type, must be `response.function_call_arguments.done`. x-stainless-const: true const: response.function_call_arguments.done response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the function call item. output_index: type: integer description: The index of the output item in the response. call_id: type: string description: The ID of the function call. arguments: type: string description: The final arguments as a JSON string. required: - event_id - type - response_id - item_id - output_index - call_id - arguments x-oaiMeta: name: response.function_call_arguments.done group: realtime example: | { "event_id": "event_5556", "type": "response.function_call_arguments.done", "response_id": "resp_002", "item_id": "fc_001", "output_index": 0, "call_id": "call_001", "arguments": "{\"location\": \"San Francisco\"}" } RealtimeServerEventResponseOutputItemAdded: type: object description: Returned when a new Item is created during Response generation. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.output_item.added`. x-stainless-const: true const: response.output_item.added response_id: type: string description: The ID of the Response to which the item belongs. output_index: type: integer description: The index of the output item in the Response. item: $ref: '#/components/schemas/RealtimeConversationItem' required: - event_id - type - response_id - output_index - item x-oaiMeta: name: response.output_item.added group: realtime example: | { "event_id": "event_3334", "type": "response.output_item.added", "response_id": "resp_001", "output_index": 0, "item": { "id": "msg_007", "object": "realtime.item", "type": "message", "status": "in_progress", "role": "assistant", "content": [] } } RealtimeServerEventResponseOutputItemDone: type: object description: | Returned when an Item is done streaming. Also emitted when a Response is interrupted, incomplete, or cancelled. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.output_item.done`. x-stainless-const: true const: response.output_item.done response_id: type: string description: The ID of the Response to which the item belongs. output_index: type: integer description: The index of the output item in the Response. item: $ref: '#/components/schemas/RealtimeConversationItem' required: - event_id - type - response_id - output_index - item x-oaiMeta: name: response.output_item.done group: realtime example: | { "event_id": "event_3536", "type": "response.output_item.done", "response_id": "resp_001", "output_index": 0, "item": { "id": "msg_007", "object": "realtime.item", "type": "message", "status": "completed", "role": "assistant", "content": [ { "type": "text", "text": "Sure, I can help with that." } ] } } RealtimeServerEventResponseTextDelta: type: object description: Returned when the text value of a "text" content part is updated. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.text.delta`. x-stainless-const: true const: response.text.delta response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. delta: type: string description: The text delta. required: - event_id - type - response_id - item_id - output_index - content_index - delta x-oaiMeta: name: response.text.delta group: realtime example: | { "event_id": "event_4142", "type": "response.text.delta", "response_id": "resp_001", "item_id": "msg_007", "output_index": 0, "content_index": 0, "delta": "Sure, I can h" } RealtimeServerEventResponseTextDone: type: object description: | Returned when the text value of a "text" content part is done streaming. Also emitted when a Response is interrupted, incomplete, or cancelled. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `response.text.done`. x-stainless-const: true const: response.text.done response_id: type: string description: The ID of the response. item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item in the response. content_index: type: integer description: The index of the content part in the item's content array. text: type: string description: The final text content. required: - event_id - type - response_id - item_id - output_index - content_index - text x-oaiMeta: name: response.text.done group: realtime example: | { "event_id": "event_4344", "type": "response.text.done", "response_id": "resp_001", "item_id": "msg_007", "output_index": 0, "content_index": 0, "text": "Sure, I can help with that." } RealtimeServerEventSessionCreated: type: object description: | Returned when a Session is created. Emitted automatically when a new connection is established as the first server event. This event will contain the default Session configuration. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `session.created`. x-stainless-const: true const: session.created session: $ref: '#/components/schemas/RealtimeSession' required: - event_id - type - session x-oaiMeta: name: session.created group: realtime example: | { "event_id": "event_1234", "type": "session.created", "session": { "id": "sess_001", "object": "realtime.session", "model": "gpt-4o-realtime-preview", "modalities": ["text", "audio"], "instructions": "...model instructions here...", "voice": "sage", "input_audio_format": "pcm16", "output_audio_format": "pcm16", "input_audio_transcription": null, "turn_detection": { "type": "server_vad", "threshold": 0.5, "prefix_padding_ms": 300, "silence_duration_ms": 200 }, "tools": [], "tool_choice": "auto", "temperature": 0.8, "max_response_output_tokens": "inf", "speed": 1.1, "tracing": "auto" } } RealtimeServerEventSessionUpdated: type: object description: | Returned when a session is updated with a `session.update` event, unless there is an error. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `session.updated`. x-stainless-const: true const: session.updated session: $ref: '#/components/schemas/RealtimeSession' required: - event_id - type - session x-oaiMeta: name: session.updated group: realtime example: | { "event_id": "event_5678", "type": "session.updated", "session": { "id": "sess_001", "object": "realtime.session", "model": "gpt-4o-realtime-preview", "modalities": ["text"], "instructions": "New instructions", "voice": "sage", "input_audio_format": "pcm16", "output_audio_format": "pcm16", "input_audio_transcription": { "model": "whisper-1" }, "turn_detection": null, "tools": [], "tool_choice": "none", "temperature": 0.7, "max_response_output_tokens": 200, "speed": 1.1, "tracing": "auto" } } RealtimeServerEventTranscriptionSessionUpdated: type: object description: | Returned when a transcription session is updated with a `transcription_session.update` event, unless there is an error. properties: event_id: type: string description: The unique ID of the server event. type: description: The event type, must be `transcription_session.updated`. x-stainless-const: true const: transcription_session.updated session: $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' required: - event_id - type - session x-oaiMeta: name: transcription_session.updated group: realtime example: | { "event_id": "event_5678", "type": "transcription_session.updated", "session": { "id": "sess_001", "object": "realtime.transcription_session", "input_audio_format": "pcm16", "input_audio_transcription": { "model": "gpt-4o-transcribe", "prompt": "", "language": "" }, "turn_detection": { "type": "server_vad", "threshold": 0.5, "prefix_padding_ms": 300, "silence_duration_ms": 500, "create_response": true, // "interrupt_response": false -- this will NOT be returned }, "input_audio_noise_reduction": { "type": "near_field" }, "include": [ "item.input_audio_transcription.avg_logprob", ], } } RealtimeSession: type: object description: Realtime session object configuration. properties: id: type: string description: | Unique identifier for the session that looks like `sess_1234567890abcdef`. modalities: description: | The set of modalities the model can respond with. To disable audio, set this to ["text"]. items: type: string enum: - text - audio model: type: string description: | The Realtime model used for this session. enum: - gpt-4o-realtime-preview - gpt-4o-realtime-preview-2024-10-01 - gpt-4o-realtime-preview-2024-12-17 - gpt-4o-realtime-preview-2025-06-03 - gpt-4o-mini-realtime-preview - gpt-4o-mini-realtime-preview-2024-12-17 instructions: type: string description: | The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. "be extremely succinct", "act friendly", "here are examples of good responses") and on audio behavior (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior. Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session. voice: $ref: '#/components/schemas/VoiceIdsShared' description: | The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. input_audio_format: type: string default: pcm16 enum: - pcm16 - g711_ulaw - g711_alaw description: | The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian byte order. output_audio_format: type: string default: pcm16 enum: - pcm16 - g711_ulaw - g711_alaw description: | The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is sampled at a rate of 24kHz. input_audio_transcription: type: object description: > Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service. properties: model: type: string description: > The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`. language: type: string description: | The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency. prompt: type: string description: > An optional text to guide the model's style or continue a previous audio segment. For `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). For `gpt-4o-transcribe` models, the prompt is a free text string, for example "expect words related to technology". turn_detection: type: object description: > Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. Semantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with "uhhm", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency. properties: type: type: string default: server_vad enum: - server_vad - semantic_vad description: | Type of turn detection. eagerness: type: string default: auto enum: - low - medium - high - auto description: > Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. threshold: type: number description: > Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher threshold will require louder audio to activate the model, and thus might perform better in noisy environments. prefix_padding_ms: type: integer description: | Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. silence_duration_ms: type: integer description: > Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. With shorter values the model will respond more quickly, but may jump in on short pauses from the user. create_response: type: boolean default: true description: | Whether or not to automatically generate a response when a VAD stop event occurs. interrupt_response: type: boolean default: true description: | Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event occurs. input_audio_noise_reduction: type: object description: > Configuration for input audio noise reduction. This can be set to `null` to turn off. Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model. Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio. properties: type: type: string enum: - near_field - far_field description: > Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones. speed: type: number default: 1 maximum: 1.5 minimum: 0.25 description: | The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress. tracing: title: Tracing Configuration description: | Configuration options for tracing. Set to null to disable tracing. Once tracing is enabled for a session, the configuration cannot be modified. `auto` will create a trace for the session with default values for the workflow name, group id, and metadata. anyOf: - type: string default: auto description: | Default tracing mode for the session. enum: - auto x-stainless-const: true - type: object title: Tracing Configuration description: | Granular configuration for tracing. properties: workflow_name: type: string description: | The name of the workflow to attach to this trace. This is used to name the trace in the traces dashboard. group_id: type: string description: | The group id to attach to this trace to enable filtering and grouping in the traces dashboard. metadata: type: object description: | The arbitrary metadata to attach to this trace to enable filtering in the traces dashboard. tools: type: array description: Tools (functions) available to the model. items: type: object properties: type: type: string enum: - function description: The type of the tool, i.e. `function`. x-stainless-const: true name: type: string description: The name of the function. description: type: string description: | The description of the function, including guidance on when and how to call it, and guidance about what to tell the user when calling (if anything). parameters: type: object description: Parameters of the function in JSON Schema. tool_choice: type: string default: auto description: | How the model chooses tools. Options are `auto`, `none`, `required`, or specify a function. temperature: type: number default: 0.8 description: > Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a temperature of 0.8 is highly recommended for best performance. max_response_output_tokens: description: | Maximum number of output tokens for a single assistant response, inclusive of tool calls. Provide an integer between 1 and 4096 to limit output tokens, or `inf` for the maximum available tokens for a given model. Defaults to `inf`. anyOf: - type: integer - type: string enum: - inf x-stainless-const: true RealtimeSessionCreateRequest: type: object description: Realtime session object configuration. properties: modalities: description: | The set of modalities the model can respond with. To disable audio, set this to ["text"]. items: type: string enum: - text - audio model: type: string description: | The Realtime model used for this session. enum: - gpt-4o-realtime-preview - gpt-4o-realtime-preview-2024-10-01 - gpt-4o-realtime-preview-2024-12-17 - gpt-4o-realtime-preview-2025-06-03 - gpt-4o-mini-realtime-preview - gpt-4o-mini-realtime-preview-2024-12-17 instructions: type: string description: > The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. "be extremely succinct", "act friendly", "here are examples of good responses") and on audio behavior (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior. Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session. voice: $ref: '#/components/schemas/VoiceIdsShared' description: | The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. input_audio_format: type: string default: pcm16 enum: - pcm16 - g711_ulaw - g711_alaw description: | The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian byte order. output_audio_format: type: string default: pcm16 enum: - pcm16 - g711_ulaw - g711_alaw description: | The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is sampled at a rate of 24kHz. input_audio_transcription: type: object description: > Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service. properties: model: type: string description: > The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`. language: type: string description: | The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency. prompt: type: string description: > An optional text to guide the model's style or continue a previous audio segment. For `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). For `gpt-4o-transcribe` models, the prompt is a free text string, for example "expect words related to technology". turn_detection: type: object description: > Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. Semantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with "uhhm", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency. properties: type: type: string default: server_vad enum: - server_vad - semantic_vad description: | Type of turn detection. eagerness: type: string default: auto enum: - low - medium - high - auto description: > Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. threshold: type: number description: > Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher threshold will require louder audio to activate the model, and thus might perform better in noisy environments. prefix_padding_ms: type: integer description: | Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. silence_duration_ms: type: integer description: > Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. With shorter values the model will respond more quickly, but may jump in on short pauses from the user. create_response: type: boolean default: true description: | Whether or not to automatically generate a response when a VAD stop event occurs. interrupt_response: type: boolean default: true description: | Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event occurs. input_audio_noise_reduction: type: object description: > Configuration for input audio noise reduction. This can be set to `null` to turn off. Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model. Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio. properties: type: type: string enum: - near_field - far_field description: > Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones. speed: type: number default: 1 maximum: 1.5 minimum: 0.25 description: | The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress. tracing: title: Tracing Configuration description: | Configuration options for tracing. Set to null to disable tracing. Once tracing is enabled for a session, the configuration cannot be modified. `auto` will create a trace for the session with default values for the workflow name, group id, and metadata. anyOf: - type: string default: auto description: | Default tracing mode for the session. enum: - auto x-stainless-const: true - type: object title: Tracing Configuration description: | Granular configuration for tracing. properties: workflow_name: type: string description: | The name of the workflow to attach to this trace. This is used to name the trace in the traces dashboard. group_id: type: string description: | The group id to attach to this trace to enable filtering and grouping in the traces dashboard. metadata: type: object description: | The arbitrary metadata to attach to this trace to enable filtering in the traces dashboard. tools: type: array description: Tools (functions) available to the model. items: type: object properties: type: type: string enum: - function description: The type of the tool, i.e. `function`. x-stainless-const: true name: type: string description: The name of the function. description: type: string description: | The description of the function, including guidance on when and how to call it, and guidance about what to tell the user when calling (if anything). parameters: type: object description: Parameters of the function in JSON Schema. tool_choice: type: string default: auto description: | How the model chooses tools. Options are `auto`, `none`, `required`, or specify a function. temperature: type: number default: 0.8 description: > Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a temperature of 0.8 is highly recommended for best performance. max_response_output_tokens: description: | Maximum number of output tokens for a single assistant response, inclusive of tool calls. Provide an integer between 1 and 4096 to limit output tokens, or `inf` for the maximum available tokens for a given model. Defaults to `inf`. anyOf: - type: integer - type: string enum: - inf x-stainless-const: true client_secret: type: object description: | Configuration options for the generated client secret. properties: expires_after: type: object description: | Configuration for the ephemeral token expiration. properties: anchor: type: string enum: - created_at description: > The anchor point for the ephemeral token expiration. Only `created_at` is currently supported. seconds: default: 600 type: integer description: > The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200`. required: - anchor RealtimeSessionCreateResponse: type: object description: | A new Realtime session configuration, with an ephemeral key. Default TTL for keys is one minute. properties: client_secret: type: object description: Ephemeral key returned by the API. properties: value: type: string description: | Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API token, which should only be used server-side. expires_at: type: integer description: | Timestamp for when the token expires. Currently, all tokens expire after one minute. required: - value - expires_at modalities: description: | The set of modalities the model can respond with. To disable audio, set this to ["text"]. items: type: string enum: - text - audio instructions: type: string description: | The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. "be extremely succinct", "act friendly", "here are examples of good responses") and on audio behavior (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior. Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session. voice: $ref: '#/components/schemas/VoiceIdsShared' description: | The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. input_audio_format: type: string description: | The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. output_audio_format: type: string description: | The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. input_audio_transcription: type: object description: | Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously and should be treated as rough guidance rather than the representation understood by the model. properties: model: type: string description: | The model to use for transcription. speed: type: number default: 1 maximum: 1.5 minimum: 0.25 description: | The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress. tracing: title: Tracing Configuration description: | Configuration options for tracing. Set to null to disable tracing. Once tracing is enabled for a session, the configuration cannot be modified. `auto` will create a trace for the session with default values for the workflow name, group id, and metadata. anyOf: - type: string default: auto description: | Default tracing mode for the session. enum: - auto x-stainless-const: true - type: object title: Tracing Configuration description: | Granular configuration for tracing. properties: workflow_name: type: string description: | The name of the workflow to attach to this trace. This is used to name the trace in the traces dashboard. group_id: type: string description: | The group id to attach to this trace to enable filtering and grouping in the traces dashboard. metadata: type: object description: | The arbitrary metadata to attach to this trace to enable filtering in the traces dashboard. turn_detection: type: object description: | Configuration for turn detection. Can be set to `null` to turn off. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. properties: type: type: string description: | Type of turn detection, only `server_vad` is currently supported. threshold: type: number description: | Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher threshold will require louder audio to activate the model, and thus might perform better in noisy environments. prefix_padding_ms: type: integer description: | Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. silence_duration_ms: type: integer description: | Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. With shorter values the model will respond more quickly, but may jump in on short pauses from the user. tools: type: array description: Tools (functions) available to the model. items: type: object properties: type: type: string enum: - function description: The type of the tool, i.e. `function`. x-stainless-const: true name: type: string description: The name of the function. description: type: string description: | The description of the function, including guidance on when and how to call it, and guidance about what to tell the user when calling (if anything). parameters: type: object description: Parameters of the function in JSON Schema. tool_choice: type: string description: | How the model chooses tools. Options are `auto`, `none`, `required`, or specify a function. temperature: type: number description: | Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. max_response_output_tokens: description: | Maximum number of output tokens for a single assistant response, inclusive of tool calls. Provide an integer between 1 and 4096 to limit output tokens, or `inf` for the maximum available tokens for a given model. Defaults to `inf`. anyOf: - type: integer - type: string enum: - inf x-stainless-const: true required: - client_secret x-oaiMeta: name: The session object group: realtime example: | { "id": "sess_001", "object": "realtime.session", "model": "gpt-4o-realtime-preview", "modalities": ["audio", "text"], "instructions": "You are a friendly assistant.", "voice": "alloy", "input_audio_format": "pcm16", "output_audio_format": "pcm16", "input_audio_transcription": { "model": "whisper-1" }, "turn_detection": null, "tools": [], "tool_choice": "none", "temperature": 0.7, "speed": 1.1, "tracing": "auto", "max_response_output_tokens": 200, "client_secret": { "value": "ek_abc123", "expires_at": 1234567890 } } RealtimeTranscriptionSessionCreateRequest: type: object description: Realtime transcription session object configuration. properties: modalities: description: | The set of modalities the model can respond with. To disable audio, set this to ["text"]. items: type: string enum: - text - audio input_audio_format: type: string default: pcm16 enum: - pcm16 - g711_ulaw - g711_alaw description: | The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian byte order. input_audio_transcription: type: object description: > Configuration for input audio transcription. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service. properties: model: type: string description: > The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`. enum: - gpt-4o-transcribe - gpt-4o-mini-transcribe - whisper-1 language: type: string description: | The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency. prompt: type: string description: > An optional text to guide the model's style or continue a previous audio segment. For `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). For `gpt-4o-transcribe` models, the prompt is a free text string, for example "expect words related to technology". turn_detection: type: object description: > Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. Semantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with "uhhm", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency. properties: type: type: string default: server_vad enum: - server_vad - semantic_vad description: | Type of turn detection. eagerness: type: string default: auto enum: - low - medium - high - auto description: > Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. threshold: type: number description: > Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher threshold will require louder audio to activate the model, and thus might perform better in noisy environments. prefix_padding_ms: type: integer description: | Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. silence_duration_ms: type: integer description: > Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. With shorter values the model will respond more quickly, but may jump in on short pauses from the user. create_response: type: boolean default: true description: > Whether or not to automatically generate a response when a VAD stop event occurs. Not available for transcription sessions. interrupt_response: type: boolean default: true description: > Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event occurs. Not available for transcription sessions. input_audio_noise_reduction: type: object description: > Configuration for input audio noise reduction. This can be set to `null` to turn off. Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model. Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio. properties: type: type: string enum: - near_field - far_field description: > Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones. include: type: array items: type: string description: | The set of items to include in the transcription. Current available items are: - `item.input_audio_transcription.logprobs` client_secret: type: object description: | Configuration options for the generated client secret. properties: expires_at: type: object description: | Configuration for the ephemeral token expiration. properties: anchor: default: created_at type: string enum: - created_at description: > The anchor point for the ephemeral token expiration. Only `created_at` is currently supported. seconds: default: 600 type: integer description: > The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200`. RealtimeTranscriptionSessionCreateResponse: type: object description: | A new Realtime transcription session configuration. When a session is created on the server via REST API, the session object also contains an ephemeral key. Default TTL for keys is 10 minutes. This property is not present when a session is updated via the WebSocket API. properties: client_secret: type: object description: | Ephemeral key returned by the API. Only present when the session is created on the server via REST API. properties: value: type: string description: | Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API token, which should only be used server-side. expires_at: type: integer description: | Timestamp for when the token expires. Currently, all tokens expire after one minute. required: - value - expires_at modalities: description: | The set of modalities the model can respond with. To disable audio, set this to ["text"]. items: type: string enum: - text - audio input_audio_format: type: string description: | The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. input_audio_transcription: type: object description: | Configuration of the transcription model. properties: model: type: string description: > The model to use for transcription. Can be `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, or `whisper-1`. enum: - gpt-4o-transcribe - gpt-4o-mini-transcribe - whisper-1 language: type: string description: | The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency. prompt: type: string description: > An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language. turn_detection: type: object description: | Configuration for turn detection. Can be set to `null` to turn off. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech. properties: type: type: string description: | Type of turn detection, only `server_vad` is currently supported. threshold: type: number description: | Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher threshold will require louder audio to activate the model, and thus might perform better in noisy environments. prefix_padding_ms: type: integer description: | Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. silence_duration_ms: type: integer description: | Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. With shorter values the model will respond more quickly, but may jump in on short pauses from the user. required: - client_secret x-oaiMeta: name: The transcription session object group: realtime example: | { "id": "sess_BBwZc7cFV3XizEyKGDCGL", "object": "realtime.transcription_session", "expires_at": 1742188264, "modalities": ["audio", "text"], "turn_detection": { "type": "server_vad", "threshold": 0.5, "prefix_padding_ms": 300, "silence_duration_ms": 200 }, "input_audio_format": "pcm16", "input_audio_transcription": { "model": "gpt-4o-transcribe", "language": null, "prompt": "" }, "client_secret": null } Reasoning: type: object description: | **gpt-5 and o-series models only** Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). title: Reasoning properties: effort: $ref: '#/components/schemas/ReasoningEffort' summary: type: string description: | A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of `auto`, `concise`, or `detailed`. enum: - auto - concise - detailed nullable: true generate_summary: type: string deprecated: true description: | **Deprecated:** use `summary` instead. A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of `auto`, `concise`, or `detailed`. enum: - auto - concise - detailed nullable: true ReasoningEffort: type: string enum: - minimal - low - medium - high default: medium nullable: true description: | Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. ReasoningItem: type: object description: | A description of the chain of thought used by a reasoning model while generating a response. Be sure to include these items in your `input` to the Responses API for subsequent turns of a conversation if you are manually [managing context](https://platform.openai.com/docs/guides/conversation-state). title: Reasoning properties: type: type: string description: | The type of the object. Always `reasoning`. enum: - reasoning x-stainless-const: true id: type: string description: | The unique identifier of the reasoning content. encrypted_content: type: string description: | The encrypted content of the reasoning item - populated when a response is generated with `reasoning.encrypted_content` in the `include` parameter. nullable: true summary: type: array description: | Reasoning summary content. items: type: object properties: type: type: string description: | The type of the object. Always `summary_text`. enum: - summary_text x-stainless-const: true text: type: string description: | A summary of the reasoning output from the model so far. required: - type - text content: type: array description: | Reasoning text content. items: type: object properties: type: type: string description: | The type of the object. Always `reasoning_text`. enum: - reasoning_text x-stainless-const: true text: type: string description: | Reasoning text output from the model. required: - type - text status: type: string description: | The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. enum: - in_progress - completed - incomplete required: - id - summary - type Response: title: The response object allOf: - $ref: '#/components/schemas/ModelResponseProperties' - $ref: '#/components/schemas/ResponseProperties' - type: object properties: id: type: string description: | Unique identifier for this Response. object: type: string description: | The object type of this resource - always set to `response`. enum: - response x-stainless-const: true status: type: string description: | The status of the response generation. One of `completed`, `failed`, `in_progress`, `cancelled`, `queued`, or `incomplete`. enum: - completed - failed - in_progress - cancelled - queued - incomplete created_at: type: number description: | Unix timestamp (in seconds) of when this Response was created. error: $ref: '#/components/schemas/ResponseError' incomplete_details: type: object nullable: true description: | Details about why the response is incomplete. properties: reason: type: string description: The reason why the response is incomplete. enum: - max_output_tokens - content_filter output: type: array description: | An array of content items generated by the model. - The length and order of items in the `output` array is dependent on the model's response. - Rather than accessing the first item in the `output` array and assuming it's an `assistant` message with the content generated by the model, you might consider using the `output_text` property where supported in SDKs. items: $ref: '#/components/schemas/OutputItem' instructions: nullable: true description: | A system (or developer) message inserted into the model's context. When using along with `previous_response_id`, the instructions from a previous response will not be carried over to the next response. This makes it simple to swap out system (or developer) messages in new responses. anyOf: - type: string description: | A text input to the model, equivalent to a text input with the `developer` role. - type: array title: Input item list description: | A list of one or many input items to the model, containing different content types. items: $ref: '#/components/schemas/InputItem' output_text: type: string nullable: true description: | SDK-only convenience property that contains the aggregated text output from all `output_text` items in the `output` array, if any are present. Supported in the Python and JavaScript SDKs. x-oaiSupportedSDKs: - python - javascript x-stainless-skip: true usage: $ref: '#/components/schemas/ResponseUsage' parallel_tool_calls: type: boolean description: | Whether to allow the model to run tool calls in parallel. default: true required: - id - object - created_at - error - incomplete_details - instructions - model - tools - output - parallel_tool_calls - metadata - tool_choice - temperature - top_p ResponseAudioDeltaEvent: type: object description: Emitted when there is a partial audio response. properties: type: type: string description: | The type of the event. Always `response.audio.delta`. enum: - response.audio.delta x-stainless-const: true sequence_number: type: integer description: | A sequence number for this chunk of the stream response. delta: type: string description: | A chunk of Base64 encoded response audio bytes. required: - type - delta - sequence_number x-oaiMeta: name: response.audio.delta group: responses example: | { "type": "response.audio.delta", "response_id": "resp_123", "delta": "base64encoded...", "sequence_number": 1 } ResponseAudioDoneEvent: type: object description: Emitted when the audio response is complete. properties: type: type: string description: | The type of the event. Always `response.audio.done`. enum: - response.audio.done x-stainless-const: true sequence_number: type: integer description: | The sequence number of the delta. required: - type - sequence_number - response_id x-oaiMeta: name: response.audio.done group: responses example: | { "type": "response.audio.done", "response_id": "resp-123", "sequence_number": 1 } ResponseAudioTranscriptDeltaEvent: type: object description: Emitted when there is a partial transcript of audio. properties: type: type: string description: | The type of the event. Always `response.audio.transcript.delta`. enum: - response.audio.transcript.delta x-stainless-const: true delta: type: string description: | The partial transcript of the audio response. sequence_number: type: integer description: The sequence number of this event. required: - type - response_id - delta - sequence_number x-oaiMeta: name: response.audio.transcript.delta group: responses example: | { "type": "response.audio.transcript.delta", "response_id": "resp_123", "delta": " ... partial transcript ... ", "sequence_number": 1 } ResponseAudioTranscriptDoneEvent: type: object description: Emitted when the full audio transcript is completed. properties: type: type: string description: | The type of the event. Always `response.audio.transcript.done`. enum: - response.audio.transcript.done x-stainless-const: true sequence_number: type: integer description: The sequence number of this event. required: - type - response_id - sequence_number x-oaiMeta: name: response.audio.transcript.done group: responses example: | { "type": "response.audio.transcript.done", "response_id": "resp_123", "sequence_number": 1 } ResponseCodeInterpreterCallCodeDeltaEvent: type: object description: Emitted when a partial code snippet is streamed by the code interpreter. properties: type: type: string description: The type of the event. Always `response.code_interpreter_call_code.delta`. enum: - response.code_interpreter_call_code.delta x-stainless-const: true output_index: type: integer description: The index of the output item in the response for which the code is being streamed. item_id: type: string description: The unique identifier of the code interpreter tool call item. delta: type: string description: The partial code snippet being streamed by the code interpreter. sequence_number: type: integer description: The sequence number of this event, used to order streaming events. required: - type - output_index - item_id - delta - sequence_number x-oaiMeta: name: response.code_interpreter_call_code.delta group: responses example: | { "type": "response.code_interpreter_call_code.delta", "output_index": 0, "item_id": "ci_12345", "delta": "print('Hello, world')", "sequence_number": 1 } ResponseCodeInterpreterCallCodeDoneEvent: type: object description: Emitted when the code snippet is finalized by the code interpreter. properties: type: type: string description: The type of the event. Always `response.code_interpreter_call_code.done`. enum: - response.code_interpreter_call_code.done x-stainless-const: true output_index: type: integer description: The index of the output item in the response for which the code is finalized. item_id: type: string description: The unique identifier of the code interpreter tool call item. code: type: string description: The final code snippet output by the code interpreter. sequence_number: type: integer description: The sequence number of this event, used to order streaming events. required: - type - output_index - item_id - code - sequence_number x-oaiMeta: name: response.code_interpreter_call_code.done group: responses example: | { "type": "response.code_interpreter_call_code.done", "output_index": 3, "item_id": "ci_12345", "code": "print('done')", "sequence_number": 1 } ResponseCodeInterpreterCallCompletedEvent: type: object description: Emitted when the code interpreter call is completed. properties: type: type: string description: The type of the event. Always `response.code_interpreter_call.completed`. enum: - response.code_interpreter_call.completed x-stainless-const: true output_index: type: integer description: The index of the output item in the response for which the code interpreter call is completed. item_id: type: string description: The unique identifier of the code interpreter tool call item. sequence_number: type: integer description: The sequence number of this event, used to order streaming events. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.code_interpreter_call.completed group: responses example: | { "type": "response.code_interpreter_call.completed", "output_index": 5, "item_id": "ci_12345", "sequence_number": 1 } ResponseCodeInterpreterCallInProgressEvent: type: object description: Emitted when a code interpreter call is in progress. properties: type: type: string description: The type of the event. Always `response.code_interpreter_call.in_progress`. enum: - response.code_interpreter_call.in_progress x-stainless-const: true output_index: type: integer description: The index of the output item in the response for which the code interpreter call is in progress. item_id: type: string description: The unique identifier of the code interpreter tool call item. sequence_number: type: integer description: The sequence number of this event, used to order streaming events. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.code_interpreter_call.in_progress group: responses example: | { "type": "response.code_interpreter_call.in_progress", "output_index": 0, "item_id": "ci_12345", "sequence_number": 1 } ResponseCodeInterpreterCallInterpretingEvent: type: object description: Emitted when the code interpreter is actively interpreting the code snippet. properties: type: type: string description: The type of the event. Always `response.code_interpreter_call.interpreting`. enum: - response.code_interpreter_call.interpreting x-stainless-const: true output_index: type: integer description: The index of the output item in the response for which the code interpreter is interpreting code. item_id: type: string description: The unique identifier of the code interpreter tool call item. sequence_number: type: integer description: The sequence number of this event, used to order streaming events. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.code_interpreter_call.interpreting group: responses example: | { "type": "response.code_interpreter_call.interpreting", "output_index": 4, "item_id": "ci_12345", "sequence_number": 1 } ResponseCompletedEvent: type: object description: Emitted when the model response is complete. properties: type: type: string description: | The type of the event. Always `response.completed`. enum: - response.completed x-stainless-const: true response: $ref: '#/components/schemas/Response' description: | Properties of the completed response. sequence_number: type: integer description: The sequence number for this event. required: - type - response - sequence_number x-oaiMeta: name: response.completed group: responses example: | { "type": "response.completed", "response": { "id": "resp_123", "object": "response", "created_at": 1740855869, "status": "completed", "error": null, "incomplete_details": null, "input": [], "instructions": null, "max_output_tokens": null, "model": "gpt-4o-mini-2024-07-18", "output": [ { "id": "msg_123", "type": "message", "role": "assistant", "content": [ { "type": "output_text", "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", "annotations": [] } ] } ], "previous_response_id": null, "reasoning_effort": null, "store": false, "temperature": 1, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1, "truncation": "disabled", "usage": { "input_tokens": 0, "output_tokens": 0, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 0 }, "user": null, "metadata": {} }, "sequence_number": 1 } ResponseContentPartAddedEvent: type: object description: Emitted when a new content part is added. properties: type: type: string description: | The type of the event. Always `response.content_part.added`. enum: - response.content_part.added x-stainless-const: true item_id: type: string description: | The ID of the output item that the content part was added to. output_index: type: integer description: | The index of the output item that the content part was added to. content_index: type: integer description: | The index of the content part that was added. part: $ref: '#/components/schemas/OutputContent' description: | The content part that was added. sequence_number: type: integer description: The sequence number of this event. required: - type - item_id - output_index - content_index - part - sequence_number x-oaiMeta: name: response.content_part.added group: responses example: | { "type": "response.content_part.added", "item_id": "msg_123", "output_index": 0, "content_index": 0, "part": { "type": "output_text", "text": "", "annotations": [] }, "sequence_number": 1 } ResponseContentPartDoneEvent: type: object description: Emitted when a content part is done. properties: type: type: string description: | The type of the event. Always `response.content_part.done`. enum: - response.content_part.done x-stainless-const: true item_id: type: string description: | The ID of the output item that the content part was added to. output_index: type: integer description: | The index of the output item that the content part was added to. content_index: type: integer description: | The index of the content part that is done. sequence_number: type: integer description: The sequence number of this event. part: $ref: '#/components/schemas/OutputContent' description: | The content part that is done. required: - type - item_id - output_index - content_index - part - sequence_number x-oaiMeta: name: response.content_part.done group: responses example: | { "type": "response.content_part.done", "item_id": "msg_123", "output_index": 0, "content_index": 0, "sequence_number": 1, "part": { "type": "output_text", "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", "annotations": [] } } ResponseCreatedEvent: type: object description: | An event that is emitted when a response is created. properties: type: type: string description: | The type of the event. Always `response.created`. enum: - response.created x-stainless-const: true response: $ref: '#/components/schemas/Response' description: | The response that was created. sequence_number: type: integer description: The sequence number for this event. required: - type - response - sequence_number x-oaiMeta: name: response.created group: responses example: | { "type": "response.created", "response": { "id": "resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c", "object": "response", "created_at": 1741487325, "status": "in_progress", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4o-2024-08-06", "output": [], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1, "truncation": "disabled", "usage": null, "user": null, "metadata": {} }, "sequence_number": 1 } ResponseCustomToolCallInputDeltaEvent: title: ResponseCustomToolCallInputDelta type: object description: | Event representing a delta (partial update) to the input of a custom tool call. properties: type: type: string enum: - response.custom_tool_call_input.delta description: The event type identifier. x-stainless-const: true sequence_number: type: integer description: The sequence number of this event. output_index: type: integer description: The index of the output this delta applies to. item_id: type: string description: Unique identifier for the API item associated with this event. delta: type: string description: The incremental input data (delta) for the custom tool call. required: - type - output_index - item_id - delta - sequence_number x-oaiMeta: name: response.custom_tool_call_input.delta group: responses example: | { "type": "response.custom_tool_call_input.delta", "output_index": 0, "item_id": "ctc_1234567890abcdef", "delta": "partial input text" } ResponseCustomToolCallInputDoneEvent: title: ResponseCustomToolCallInputDone type: object description: | Event indicating that input for a custom tool call is complete. properties: type: type: string enum: - response.custom_tool_call_input.done description: The event type identifier. x-stainless-const: true sequence_number: type: integer description: The sequence number of this event. output_index: type: integer description: The index of the output this event applies to. item_id: type: string description: Unique identifier for the API item associated with this event. input: type: string description: The complete input data for the custom tool call. required: - type - output_index - item_id - input - sequence_number x-oaiMeta: name: response.custom_tool_call_input.done group: responses example: | { "type": "response.custom_tool_call_input.done", "output_index": 0, "item_id": "ctc_1234567890abcdef", "input": "final complete input text" } ResponseError: type: object description: | An error object returned when the model fails to generate a Response. nullable: true properties: code: $ref: '#/components/schemas/ResponseErrorCode' message: type: string description: | A human-readable description of the error. required: - code - message ResponseErrorCode: type: string description: | The error code for the response. enum: - server_error - rate_limit_exceeded - invalid_prompt - vector_store_timeout - invalid_image - invalid_image_format - invalid_base64_image - invalid_image_url - image_too_large - image_too_small - image_parse_error - image_content_policy_violation - invalid_image_mode - image_file_too_large - unsupported_image_media_type - empty_image_file - failed_to_download_image - image_file_not_found ResponseErrorEvent: type: object description: Emitted when an error occurs. properties: type: type: string description: | The type of the event. Always `error`. enum: - error x-stainless-const: true code: type: string description: | The error code. nullable: true message: type: string description: | The error message. param: type: string description: | The error parameter. nullable: true sequence_number: type: integer description: The sequence number of this event. required: - type - code - message - param - sequence_number x-oaiMeta: name: error group: responses example: | { "type": "error", "code": "ERR_SOMETHING", "message": "Something went wrong", "param": null, "sequence_number": 1 } ResponseFailedEvent: type: object description: | An event that is emitted when a response fails. properties: type: type: string description: | The type of the event. Always `response.failed`. enum: - response.failed x-stainless-const: true sequence_number: type: integer description: The sequence number of this event. response: $ref: '#/components/schemas/Response' description: | The response that failed. required: - type - response - sequence_number x-oaiMeta: name: response.failed group: responses example: | { "type": "response.failed", "response": { "id": "resp_123", "object": "response", "created_at": 1740855869, "status": "failed", "error": { "code": "server_error", "message": "The model failed to generate a response." }, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4o-mini-2024-07-18", "output": [], "previous_response_id": null, "reasoning_effort": null, "store": false, "temperature": 1, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1, "truncation": "disabled", "usage": null, "user": null, "metadata": {} } } ResponseFileSearchCallCompletedEvent: type: object description: Emitted when a file search call is completed (results found). properties: type: type: string description: | The type of the event. Always `response.file_search_call.completed`. enum: - response.file_search_call.completed x-stainless-const: true output_index: type: integer description: | The index of the output item that the file search call is initiated. item_id: type: string description: | The ID of the output item that the file search call is initiated. sequence_number: type: integer description: The sequence number of this event. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.file_search_call.completed group: responses example: | { "type": "response.file_search_call.completed", "output_index": 0, "item_id": "fs_123", "sequence_number": 1 } ResponseFileSearchCallInProgressEvent: type: object description: Emitted when a file search call is initiated. properties: type: type: string description: | The type of the event. Always `response.file_search_call.in_progress`. enum: - response.file_search_call.in_progress x-stainless-const: true output_index: type: integer description: | The index of the output item that the file search call is initiated. item_id: type: string description: | The ID of the output item that the file search call is initiated. sequence_number: type: integer description: The sequence number of this event. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.file_search_call.in_progress group: responses example: | { "type": "response.file_search_call.in_progress", "output_index": 0, "item_id": "fs_123", "sequence_number": 1 } ResponseFileSearchCallSearchingEvent: type: object description: Emitted when a file search is currently searching. properties: type: type: string description: | The type of the event. Always `response.file_search_call.searching`. enum: - response.file_search_call.searching x-stainless-const: true output_index: type: integer description: | The index of the output item that the file search call is searching. item_id: type: string description: | The ID of the output item that the file search call is initiated. sequence_number: type: integer description: The sequence number of this event. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.file_search_call.searching group: responses example: | { "type": "response.file_search_call.searching", "output_index": 0, "item_id": "fs_123", "sequence_number": 1 } ResponseFormatJsonObject: type: object title: JSON object description: | JSON object response format. An older method of generating JSON responses. Using `json_schema` is recommended for models that support it. Note that the model will not generate JSON without a system or user message instructing it to do so. properties: type: type: string description: The type of response format being defined. Always `json_object`. enum: - json_object x-stainless-const: true required: - type ResponseFormatJsonSchema: type: object title: JSON schema description: | JSON Schema response format. Used to generate structured JSON responses. Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). properties: type: type: string description: The type of response format being defined. Always `json_schema`. enum: - json_schema x-stainless-const: true json_schema: type: object title: JSON schema description: | Structured Outputs configuration options, including a JSON Schema. properties: description: type: string description: | A description of what the response format is for, used by the model to determine how to respond in the format. name: type: string description: | The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. schema: $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' strict: type: boolean nullable: true default: false description: | Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). required: - name required: - type - json_schema ResponseFormatJsonSchemaSchema: type: object title: JSON schema description: | The schema for the response format, described as a JSON Schema object. Learn how to build JSON schemas [here](https://json-schema.org/). additionalProperties: true ResponseFormatText: type: object title: Text description: | Default response format. Used to generate text responses. properties: type: type: string description: The type of response format being defined. Always `text`. enum: - text x-stainless-const: true required: - type ResponseFormatTextGrammar: type: object title: Text grammar description: | A custom grammar for the model to follow when generating text. Learn more in the [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars). properties: type: type: string description: The type of response format being defined. Always `grammar`. enum: - grammar x-stainless-const: true grammar: type: string description: The custom grammar for the model to follow. required: - type - grammar ResponseFormatTextPython: type: object title: Python grammar description: | Configure the model to generate valid Python code. See the [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars) for more details. properties: type: type: string description: The type of response format being defined. Always `python`. enum: - python x-stainless-const: true required: - type ResponseFunctionCallArgumentsDeltaEvent: type: object description: Emitted when there is a partial function-call arguments delta. properties: type: type: string description: | The type of the event. Always `response.function_call_arguments.delta`. enum: - response.function_call_arguments.delta x-stainless-const: true item_id: type: string description: | The ID of the output item that the function-call arguments delta is added to. output_index: type: integer description: | The index of the output item that the function-call arguments delta is added to. sequence_number: type: integer description: The sequence number of this event. delta: type: string description: | The function-call arguments delta that is added. required: - type - item_id - output_index - delta - sequence_number x-oaiMeta: name: response.function_call_arguments.delta group: responses example: | { "type": "response.function_call_arguments.delta", "item_id": "item-abc", "output_index": 0, "delta": "{ \"arg\":" "sequence_number": 1 } ResponseFunctionCallArgumentsDoneEvent: type: object description: Emitted when function-call arguments are finalized. properties: type: type: string enum: - response.function_call_arguments.done x-stainless-const: true item_id: type: string description: The ID of the item. output_index: type: integer description: The index of the output item. sequence_number: type: integer description: The sequence number of this event. arguments: type: string description: The function-call arguments. required: - type - item_id - output_index - arguments - sequence_number x-oaiMeta: name: response.function_call_arguments.done group: responses example: | { "type": "response.function_call_arguments.done", "item_id": "item-abc", "output_index": 1, "arguments": "{ \"arg\": 123 }", "sequence_number": 1 } ResponseImageGenCallCompletedEvent: type: object title: ResponseImageGenCallCompletedEvent description: | Emitted when an image generation tool call has completed and the final image is available. properties: type: type: string enum: - response.image_generation_call.completed description: The type of the event. Always 'response.image_generation_call.completed'. x-stainless-const: true output_index: type: integer description: The index of the output item in the response's output array. sequence_number: type: integer description: The sequence number of this event. item_id: type: string description: The unique identifier of the image generation item being processed. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.image_generation_call.completed group: responses example: | { "type": "response.image_generation_call.completed", "output_index": 0, "item_id": "item-123", "sequence_number": 1 } ResponseImageGenCallGeneratingEvent: type: object title: ResponseImageGenCallGeneratingEvent description: | Emitted when an image generation tool call is actively generating an image (intermediate state). properties: type: type: string enum: - response.image_generation_call.generating description: The type of the event. Always 'response.image_generation_call.generating'. x-stainless-const: true output_index: type: integer description: The index of the output item in the response's output array. item_id: type: string description: The unique identifier of the image generation item being processed. sequence_number: type: integer description: The sequence number of the image generation item being processed. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.image_generation_call.generating group: responses example: | { "type": "response.image_generation_call.generating", "output_index": 0, "item_id": "item-123", "sequence_number": 0 } ResponseImageGenCallInProgressEvent: type: object title: ResponseImageGenCallInProgressEvent description: | Emitted when an image generation tool call is in progress. properties: type: type: string enum: - response.image_generation_call.in_progress description: The type of the event. Always 'response.image_generation_call.in_progress'. x-stainless-const: true output_index: type: integer description: The index of the output item in the response's output array. item_id: type: string description: The unique identifier of the image generation item being processed. sequence_number: type: integer description: The sequence number of the image generation item being processed. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.image_generation_call.in_progress group: responses example: | { "type": "response.image_generation_call.in_progress", "output_index": 0, "item_id": "item-123", "sequence_number": 0 } ResponseImageGenCallPartialImageEvent: type: object title: ResponseImageGenCallPartialImageEvent description: | Emitted when a partial image is available during image generation streaming. properties: type: type: string enum: - response.image_generation_call.partial_image description: The type of the event. Always 'response.image_generation_call.partial_image'. x-stainless-const: true output_index: type: integer description: The index of the output item in the response's output array. item_id: type: string description: The unique identifier of the image generation item being processed. sequence_number: type: integer description: The sequence number of the image generation item being processed. partial_image_index: type: integer description: 0-based index for the partial image (backend is 1-based, but this is 0-based for the user). partial_image_b64: type: string description: Base64-encoded partial image data, suitable for rendering as an image. required: - type - output_index - item_id - sequence_number - partial_image_index - partial_image_b64 x-oaiMeta: name: response.image_generation_call.partial_image group: responses example: | { "type": "response.image_generation_call.partial_image", "output_index": 0, "item_id": "item-123", "sequence_number": 0, "partial_image_index": 0, "partial_image_b64": "..." } ResponseInProgressEvent: type: object description: Emitted when the response is in progress. properties: type: type: string description: | The type of the event. Always `response.in_progress`. enum: - response.in_progress x-stainless-const: true response: $ref: '#/components/schemas/Response' description: | The response that is in progress. sequence_number: type: integer description: The sequence number of this event. required: - type - response - sequence_number x-oaiMeta: name: response.in_progress group: responses example: | { "type": "response.in_progress", "response": { "id": "resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c", "object": "response", "created_at": 1741487325, "status": "in_progress", "error": null, "incomplete_details": null, "instructions": null, "max_output_tokens": null, "model": "gpt-4o-2024-08-06", "output": [], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": null, "summary": null }, "store": true, "temperature": 1, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1, "truncation": "disabled", "usage": null, "user": null, "metadata": {} }, "sequence_number": 1 } ResponseIncompleteEvent: type: object description: | An event that is emitted when a response finishes as incomplete. properties: type: type: string description: | The type of the event. Always `response.incomplete`. enum: - response.incomplete x-stainless-const: true response: $ref: '#/components/schemas/Response' description: | The response that was incomplete. sequence_number: type: integer description: The sequence number of this event. required: - type - response - sequence_number x-oaiMeta: name: response.incomplete group: responses example: | { "type": "response.incomplete", "response": { "id": "resp_123", "object": "response", "created_at": 1740855869, "status": "incomplete", "error": null, "incomplete_details": { "reason": "max_tokens" }, "instructions": null, "max_output_tokens": null, "model": "gpt-4o-mini-2024-07-18", "output": [], "previous_response_id": null, "reasoning_effort": null, "store": false, "temperature": 1, "text": { "format": { "type": "text" } }, "tool_choice": "auto", "tools": [], "top_p": 1, "truncation": "disabled", "usage": null, "user": null, "metadata": {} }, "sequence_number": 1 } ResponseItemList: type: object description: A list of Response items. properties: object: description: The type of object returned, must be `list`. x-stainless-const: true const: list data: type: array description: A list of items used to generate this response. items: $ref: '#/components/schemas/ItemResource' has_more: type: boolean description: Whether there are more items available. first_id: type: string description: The ID of the first item in the list. last_id: type: string description: The ID of the last item in the list. required: - object - data - has_more - first_id - last_id x-oaiMeta: name: The input item list group: responses example: | { "object": "list", "data": [ { "id": "msg_abc123", "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "Tell me a three sentence bedtime story about a unicorn." } ] } ], "first_id": "msg_abc123", "last_id": "msg_abc123", "has_more": false } ResponseLogProb: type: object description: | A logprob is the logarithmic probability that the model assigns to producing a particular token at a given position in the sequence. Less-negative (higher) logprob values indicate greater model confidence in that token choice. properties: token: description: A possible text token. type: string logprob: description: | The log probability of this token. type: number top_logprobs: description: | The log probability of the top 20 most likely tokens. type: array items: type: object properties: token: description: A possible text token. type: string logprob: description: The log probability of this token. type: number required: - token - logprob ResponseMCPCallArgumentsDeltaEvent: type: object title: ResponseMCPCallArgumentsDeltaEvent description: | Emitted when there is a delta (partial update) to the arguments of an MCP tool call. properties: type: type: string enum: - response.mcp_call_arguments.delta description: The type of the event. Always 'response.mcp_call_arguments.delta'. x-stainless-const: true output_index: type: integer description: The index of the output item in the response's output array. item_id: type: string description: The unique identifier of the MCP tool call item being processed. delta: type: string description: | A JSON string containing the partial update to the arguments for the MCP tool call. sequence_number: type: integer description: The sequence number of this event. required: - type - output_index - item_id - delta - sequence_number x-oaiMeta: name: response.mcp_call_arguments.delta group: responses example: | { "type": "response.mcp_call_arguments.delta", "output_index": 0, "item_id": "item-abc", "delta": "{", "sequence_number": 1 } ResponseMCPCallArgumentsDoneEvent: type: object title: ResponseMCPCallArgumentsDoneEvent description: | Emitted when the arguments for an MCP tool call are finalized. properties: type: type: string enum: - response.mcp_call_arguments.done description: The type of the event. Always 'response.mcp_call_arguments.done'. x-stainless-const: true output_index: type: integer description: The index of the output item in the response's output array. item_id: type: string description: The unique identifier of the MCP tool call item being processed. arguments: type: string description: | A JSON string containing the finalized arguments for the MCP tool call. sequence_number: type: integer description: The sequence number of this event. required: - type - output_index - item_id - arguments - sequence_number x-oaiMeta: name: response.mcp_call_arguments.done group: responses example: | { "type": "response.mcp_call_arguments.done", "output_index": 0, "item_id": "item-abc", "arguments": "{\"arg1\": \"value1\", \"arg2\": \"value2\"}", "sequence_number": 1 } ResponseMCPCallCompletedEvent: type: object title: ResponseMCPCallCompletedEvent description: | Emitted when an MCP tool call has completed successfully. properties: type: type: string enum: - response.mcp_call.completed description: The type of the event. Always 'response.mcp_call.completed'. x-stainless-const: true item_id: type: string description: The ID of the MCP tool call item that completed. output_index: type: integer description: The index of the output item that completed. sequence_number: type: integer description: The sequence number of this event. required: - type - item_id - output_index - sequence_number x-oaiMeta: name: response.mcp_call.completed group: responses example: | { "type": "response.mcp_call.completed", "sequence_number": 1, "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90", "output_index": 0 } ResponseMCPCallFailedEvent: type: object title: ResponseMCPCallFailedEvent description: | Emitted when an MCP tool call has failed. properties: type: type: string enum: - response.mcp_call.failed description: The type of the event. Always 'response.mcp_call.failed'. x-stainless-const: true item_id: type: string description: The ID of the MCP tool call item that failed. output_index: type: integer description: The index of the output item that failed. sequence_number: type: integer description: The sequence number of this event. required: - type - item_id - output_index - sequence_number x-oaiMeta: name: response.mcp_call.failed group: responses example: | { "type": "response.mcp_call.failed", "sequence_number": 1, "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90", "output_index": 0 } ResponseMCPCallInProgressEvent: type: object title: ResponseMCPCallInProgressEvent description: | Emitted when an MCP tool call is in progress. properties: type: type: string enum: - response.mcp_call.in_progress description: The type of the event. Always 'response.mcp_call.in_progress'. x-stainless-const: true sequence_number: type: integer description: The sequence number of this event. output_index: type: integer description: The index of the output item in the response's output array. item_id: type: string description: The unique identifier of the MCP tool call item being processed. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.mcp_call.in_progress group: responses example: | { "type": "response.mcp_call.in_progress", "sequence_number": 1, "output_index": 0, "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90" } ResponseMCPListToolsCompletedEvent: type: object title: ResponseMCPListToolsCompletedEvent description: | Emitted when the list of available MCP tools has been successfully retrieved. properties: type: type: string enum: - response.mcp_list_tools.completed description: The type of the event. Always 'response.mcp_list_tools.completed'. x-stainless-const: true item_id: type: string description: The ID of the MCP tool call item that produced this output. output_index: type: integer description: The index of the output item that was processed. sequence_number: type: integer description: The sequence number of this event. required: - type - item_id - output_index - sequence_number x-oaiMeta: name: response.mcp_list_tools.completed group: responses example: | { "type": "response.mcp_list_tools.completed", "sequence_number": 1, "output_index": 0, "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" } ResponseMCPListToolsFailedEvent: type: object title: ResponseMCPListToolsFailedEvent description: | Emitted when the attempt to list available MCP tools has failed. properties: type: type: string enum: - response.mcp_list_tools.failed description: The type of the event. Always 'response.mcp_list_tools.failed'. x-stainless-const: true item_id: type: string description: The ID of the MCP tool call item that failed. output_index: type: integer description: The index of the output item that failed. sequence_number: type: integer description: The sequence number of this event. required: - type - item_id - output_index - sequence_number x-oaiMeta: name: response.mcp_list_tools.failed group: responses example: | { "type": "response.mcp_list_tools.failed", "sequence_number": 1, "output_index": 0, "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" } ResponseMCPListToolsInProgressEvent: type: object title: ResponseMCPListToolsInProgressEvent description: | Emitted when the system is in the process of retrieving the list of available MCP tools. properties: type: type: string enum: - response.mcp_list_tools.in_progress description: The type of the event. Always 'response.mcp_list_tools.in_progress'. x-stainless-const: true item_id: type: string description: The ID of the MCP tool call item that is being processed. output_index: type: integer description: The index of the output item that is being processed. sequence_number: type: integer description: The sequence number of this event. required: - type - item_id - output_index - sequence_number x-oaiMeta: name: response.mcp_list_tools.in_progress group: responses example: | { "type": "response.mcp_list_tools.in_progress", "sequence_number": 1, "output_index": 0, "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" } ResponseModalities: type: array nullable: true description: | Output types that you would like the model to generate. Most models are capable of generating text, which is the default: `["text"]` The `gpt-4o-audio-preview` model can also be used to [generate audio](https://platform.openai.com/docs/guides/audio). To request that this model generate both text and audio responses, you can use: `["text", "audio"]` items: type: string enum: - text - audio ResponseOutputItemAddedEvent: type: object description: Emitted when a new output item is added. properties: type: type: string description: | The type of the event. Always `response.output_item.added`. enum: - response.output_item.added x-stainless-const: true output_index: type: integer description: | The index of the output item that was added. sequence_number: type: integer description: | The sequence number of this event. item: $ref: '#/components/schemas/OutputItem' description: | The output item that was added. required: - type - output_index - item - sequence_number x-oaiMeta: name: response.output_item.added group: responses example: | { "type": "response.output_item.added", "output_index": 0, "item": { "id": "msg_123", "status": "in_progress", "type": "message", "role": "assistant", "content": [] }, "sequence_number": 1 } ResponseOutputItemDoneEvent: type: object description: Emitted when an output item is marked done. properties: type: type: string description: | The type of the event. Always `response.output_item.done`. enum: - response.output_item.done x-stainless-const: true output_index: type: integer description: | The index of the output item that was marked done. sequence_number: type: integer description: | The sequence number of this event. item: $ref: '#/components/schemas/OutputItem' description: | The output item that was marked done. required: - type - output_index - item - sequence_number x-oaiMeta: name: response.output_item.done group: responses example: | { "type": "response.output_item.done", "output_index": 0, "item": { "id": "msg_123", "status": "completed", "type": "message", "role": "assistant", "content": [ { "type": "output_text", "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", "annotations": [] } ] }, "sequence_number": 1 } ResponseOutputTextAnnotationAddedEvent: type: object title: ResponseOutputTextAnnotationAddedEvent description: | Emitted when an annotation is added to output text content. properties: type: type: string enum: - response.output_text.annotation.added description: The type of the event. Always 'response.output_text.annotation.added'. x-stainless-const: true item_id: type: string description: The unique identifier of the item to which the annotation is being added. output_index: type: integer description: The index of the output item in the response's output array. content_index: type: integer description: The index of the content part within the output item. annotation_index: type: integer description: The index of the annotation within the content part. sequence_number: type: integer description: The sequence number of this event. annotation: type: object description: The annotation object being added. (See annotation schema for details.) required: - type - item_id - output_index - content_index - annotation_index - annotation - sequence_number x-oaiMeta: name: response.output_text.annotation.added group: responses example: | { "type": "response.output_text.annotation.added", "item_id": "item-abc", "output_index": 0, "content_index": 0, "annotation_index": 0, "annotation": { "type": "text_annotation", "text": "This is a test annotation", "start": 0, "end": 10 }, "sequence_number": 1 } ResponsePromptVariables: type: object title: Prompt Variables description: | Optional map of values to substitute in for variables in your prompt. The substitution values can either be strings, or other Response input types like images or files. x-oaiExpandable: true x-oaiTypeLabel: map nullable: true additionalProperties: x-oaiExpandable: true x-oaiTypeLabel: map anyOf: - type: string - $ref: '#/components/schemas/InputTextContent' - $ref: '#/components/schemas/InputImageContent' - $ref: '#/components/schemas/InputFileContent' ResponseProperties: type: object properties: previous_response_id: type: string description: | The unique ID of the previous response to the model. Use this to create multi-turn conversations. Learn more about [conversation state](https://platform.openai.com/docs/guides/conversation-state). nullable: true model: description: > Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare available models. $ref: '#/components/schemas/ModelIdsResponses' reasoning: $ref: '#/components/schemas/Reasoning' nullable: true background: type: boolean description: | Whether to run the model response in the background. [Learn more](https://platform.openai.com/docs/guides/background). default: false nullable: true max_output_tokens: description: > An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). type: integer nullable: true max_tool_calls: description: > The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored. type: integer nullable: true text: type: object description: | Configuration options for a text response from the model. Can be plain text or structured JSON data. Learn more: - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) properties: format: $ref: '#/components/schemas/TextResponseFormatConfiguration' verbosity: $ref: '#/components/schemas/Verbosity' tools: type: array description: | An array of tools the model may call while generating a response. You can specify which tool to use by setting the `tool_choice` parameter. The two categories of tools you can provide the model are: - **Built-in tools**: Tools that are provided by OpenAI that extend the model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about [built-in tools](https://platform.openai.com/docs/guides/tools). - **Function calls (custom tools)**: Functions that are defined by you, enabling the model to call your own code with strongly typed arguments and outputs. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). You can also use custom tools to call your own code. items: $ref: '#/components/schemas/Tool' tool_choice: description: | How the model should select which tool (or tools) to use when generating a response. See the `tools` parameter to see how to specify which tools the model can call. anyOf: - $ref: '#/components/schemas/ToolChoiceOptions' - $ref: '#/components/schemas/ToolChoiceAllowed' - $ref: '#/components/schemas/ToolChoiceTypes' - $ref: '#/components/schemas/ToolChoiceFunction' - $ref: '#/components/schemas/ToolChoiceMCP' - $ref: '#/components/schemas/ToolChoiceCustom' prompt: $ref: '#/components/schemas/Prompt' truncation: type: string description: | The truncation strategy to use for the model response. - `auto`: If the context of this response and previous ones exceeds the model's context window size, the model will truncate the response to fit the context window by dropping input items in the middle of the conversation. - `disabled` (default): If a model response will exceed the context window size for a model, the request will fail with a 400 error. enum: - auto - disabled nullable: true default: disabled ResponseQueuedEvent: type: object title: ResponseQueuedEvent description: | Emitted when a response is queued and waiting to be processed. properties: type: type: string enum: - response.queued description: The type of the event. Always 'response.queued'. x-stainless-const: true response: $ref: '#/components/schemas/Response' description: The full response object that is queued. sequence_number: type: integer description: The sequence number for this event. required: - type - response - sequence_number x-oaiMeta: name: response.queued group: responses example: | { "type": "response.queued", "response": { "id": "res_123", "status": "queued", "created_at": "2021-01-01T00:00:00Z", "updated_at": "2021-01-01T00:00:00Z" }, "sequence_number": 1 } ResponseReasoningSummaryPartAddedEvent: type: object description: Emitted when a new reasoning summary part is added. properties: type: type: string description: | The type of the event. Always `response.reasoning_summary_part.added`. enum: - response.reasoning_summary_part.added x-stainless-const: true item_id: type: string description: | The ID of the item this summary part is associated with. output_index: type: integer description: | The index of the output item this summary part is associated with. summary_index: type: integer description: | The index of the summary part within the reasoning summary. sequence_number: type: integer description: | The sequence number of this event. part: type: object description: | The summary part that was added. properties: type: type: string description: The type of the summary part. Always `summary_text`. enum: - summary_text x-stainless-const: true text: type: string description: The text of the summary part. required: - type - text required: - type - item_id - output_index - summary_index - part - sequence_number x-oaiMeta: name: response.reasoning_summary_part.added group: responses example: | { "type": "response.reasoning_summary_part.added", "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", "output_index": 0, "summary_index": 0, "part": { "type": "summary_text", "text": "" }, "sequence_number": 1 } ResponseReasoningSummaryPartDoneEvent: type: object description: Emitted when a reasoning summary part is completed. properties: type: type: string description: | The type of the event. Always `response.reasoning_summary_part.done`. enum: - response.reasoning_summary_part.done x-stainless-const: true item_id: type: string description: | The ID of the item this summary part is associated with. output_index: type: integer description: | The index of the output item this summary part is associated with. summary_index: type: integer description: | The index of the summary part within the reasoning summary. sequence_number: type: integer description: | The sequence number of this event. part: type: object description: | The completed summary part. properties: type: type: string description: The type of the summary part. Always `summary_text`. enum: - summary_text x-stainless-const: true text: type: string description: The text of the summary part. required: - type - text required: - type - item_id - output_index - summary_index - part - sequence_number x-oaiMeta: name: response.reasoning_summary_part.done group: responses example: | { "type": "response.reasoning_summary_part.done", "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", "output_index": 0, "summary_index": 0, "part": { "type": "summary_text", "text": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!" }, "sequence_number": 1 } ResponseReasoningSummaryTextDeltaEvent: type: object description: Emitted when a delta is added to a reasoning summary text. properties: type: type: string description: | The type of the event. Always `response.reasoning_summary_text.delta`. enum: - response.reasoning_summary_text.delta x-stainless-const: true item_id: type: string description: | The ID of the item this summary text delta is associated with. output_index: type: integer description: | The index of the output item this summary text delta is associated with. summary_index: type: integer description: | The index of the summary part within the reasoning summary. delta: type: string description: | The text delta that was added to the summary. sequence_number: type: integer description: | The sequence number of this event. required: - type - item_id - output_index - summary_index - delta - sequence_number x-oaiMeta: name: response.reasoning_summary_text.delta group: responses example: | { "type": "response.reasoning_summary_text.delta", "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", "output_index": 0, "summary_index": 0, "delta": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!", "sequence_number": 1 } ResponseReasoningSummaryTextDoneEvent: type: object description: Emitted when a reasoning summary text is completed. properties: type: type: string description: | The type of the event. Always `response.reasoning_summary_text.done`. enum: - response.reasoning_summary_text.done x-stainless-const: true item_id: type: string description: | The ID of the item this summary text is associated with. output_index: type: integer description: | The index of the output item this summary text is associated with. summary_index: type: integer description: | The index of the summary part within the reasoning summary. text: type: string description: | The full text of the completed reasoning summary. sequence_number: type: integer description: | The sequence number of this event. required: - type - item_id - output_index - summary_index - text - sequence_number x-oaiMeta: name: response.reasoning_summary_text.done group: responses example: | { "type": "response.reasoning_summary_text.done", "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", "output_index": 0, "summary_index": 0, "text": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!", "sequence_number": 1 } ResponseReasoningTextDeltaEvent: type: object description: Emitted when a delta is added to a reasoning text. properties: type: type: string description: | The type of the event. Always `response.reasoning_text.delta`. enum: - response.reasoning_text.delta x-stainless-const: true item_id: type: string description: | The ID of the item this reasoning text delta is associated with. output_index: type: integer description: | The index of the output item this reasoning text delta is associated with. content_index: type: integer description: | The index of the reasoning content part this delta is associated with. delta: type: string description: | The text delta that was added to the reasoning content. sequence_number: type: integer description: | The sequence number of this event. required: - type - item_id - output_index - content_index - delta - sequence_number x-oaiMeta: name: response.reasoning_text.delta group: responses example: | { "type": "response.reasoning_text.delta", "item_id": "rs_123", "output_index": 0, "content_index": 0, "delta": "The", "sequence_number": 1 } ResponseReasoningTextDoneEvent: type: object description: Emitted when a reasoning text is completed. properties: type: type: string description: | The type of the event. Always `response.reasoning_text.done`. enum: - response.reasoning_text.done x-stainless-const: true item_id: type: string description: | The ID of the item this reasoning text is associated with. output_index: type: integer description: | The index of the output item this reasoning text is associated with. content_index: type: integer description: | The index of the reasoning content part. text: type: string description: | The full text of the completed reasoning content. sequence_number: type: integer description: | The sequence number of this event. required: - type - item_id - output_index - content_index - text - sequence_number x-oaiMeta: name: response.reasoning_text.done group: responses example: | { "type": "response.reasoning_text.done", "item_id": "rs_123", "output_index": 0, "content_index": 0, "text": "The user is asking...", "sequence_number": 4 } ResponseRefusalDeltaEvent: type: object description: Emitted when there is a partial refusal text. properties: type: type: string description: | The type of the event. Always `response.refusal.delta`. enum: - response.refusal.delta x-stainless-const: true item_id: type: string description: | The ID of the output item that the refusal text is added to. output_index: type: integer description: | The index of the output item that the refusal text is added to. content_index: type: integer description: | The index of the content part that the refusal text is added to. delta: type: string description: | The refusal text that is added. sequence_number: type: integer description: | The sequence number of this event. required: - type - item_id - output_index - content_index - delta - sequence_number x-oaiMeta: name: response.refusal.delta group: responses example: | { "type": "response.refusal.delta", "item_id": "msg_123", "output_index": 0, "content_index": 0, "delta": "refusal text so far", "sequence_number": 1 } ResponseRefusalDoneEvent: type: object description: Emitted when refusal text is finalized. properties: type: type: string description: | The type of the event. Always `response.refusal.done`. enum: - response.refusal.done x-stainless-const: true item_id: type: string description: | The ID of the output item that the refusal text is finalized. output_index: type: integer description: | The index of the output item that the refusal text is finalized. content_index: type: integer description: | The index of the content part that the refusal text is finalized. refusal: type: string description: | The refusal text that is finalized. sequence_number: type: integer description: | The sequence number of this event. required: - type - item_id - output_index - content_index - refusal - sequence_number x-oaiMeta: name: response.refusal.done group: responses example: | { "type": "response.refusal.done", "item_id": "item-abc", "output_index": 1, "content_index": 2, "refusal": "final refusal text", "sequence_number": 1 } ResponseStreamEvent: anyOf: - $ref: '#/components/schemas/ResponseAudioDeltaEvent' - $ref: '#/components/schemas/ResponseAudioDoneEvent' - $ref: '#/components/schemas/ResponseAudioTranscriptDeltaEvent' - $ref: '#/components/schemas/ResponseAudioTranscriptDoneEvent' - $ref: '#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent' - $ref: '#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent' - $ref: '#/components/schemas/ResponseCodeInterpreterCallCompletedEvent' - $ref: '#/components/schemas/ResponseCodeInterpreterCallInProgressEvent' - $ref: '#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent' - $ref: '#/components/schemas/ResponseCompletedEvent' - $ref: '#/components/schemas/ResponseContentPartAddedEvent' - $ref: '#/components/schemas/ResponseContentPartDoneEvent' - $ref: '#/components/schemas/ResponseCreatedEvent' - $ref: '#/components/schemas/ResponseErrorEvent' - $ref: '#/components/schemas/ResponseFileSearchCallCompletedEvent' - $ref: '#/components/schemas/ResponseFileSearchCallInProgressEvent' - $ref: '#/components/schemas/ResponseFileSearchCallSearchingEvent' - $ref: '#/components/schemas/ResponseFunctionCallArgumentsDeltaEvent' - $ref: '#/components/schemas/ResponseFunctionCallArgumentsDoneEvent' - $ref: '#/components/schemas/ResponseInProgressEvent' - $ref: '#/components/schemas/ResponseFailedEvent' - $ref: '#/components/schemas/ResponseIncompleteEvent' - $ref: '#/components/schemas/ResponseOutputItemAddedEvent' - $ref: '#/components/schemas/ResponseOutputItemDoneEvent' - $ref: '#/components/schemas/ResponseReasoningSummaryPartAddedEvent' - $ref: '#/components/schemas/ResponseReasoningSummaryPartDoneEvent' - $ref: '#/components/schemas/ResponseReasoningSummaryTextDeltaEvent' - $ref: '#/components/schemas/ResponseReasoningSummaryTextDoneEvent' - $ref: '#/components/schemas/ResponseReasoningTextDeltaEvent' - $ref: '#/components/schemas/ResponseReasoningTextDoneEvent' - $ref: '#/components/schemas/ResponseRefusalDeltaEvent' - $ref: '#/components/schemas/ResponseRefusalDoneEvent' - $ref: '#/components/schemas/ResponseTextDeltaEvent' - $ref: '#/components/schemas/ResponseTextDoneEvent' - $ref: '#/components/schemas/ResponseWebSearchCallCompletedEvent' - $ref: '#/components/schemas/ResponseWebSearchCallInProgressEvent' - $ref: '#/components/schemas/ResponseWebSearchCallSearchingEvent' - $ref: '#/components/schemas/ResponseImageGenCallCompletedEvent' - $ref: '#/components/schemas/ResponseImageGenCallGeneratingEvent' - $ref: '#/components/schemas/ResponseImageGenCallInProgressEvent' - $ref: '#/components/schemas/ResponseImageGenCallPartialImageEvent' - $ref: '#/components/schemas/ResponseMCPCallArgumentsDeltaEvent' - $ref: '#/components/schemas/ResponseMCPCallArgumentsDoneEvent' - $ref: '#/components/schemas/ResponseMCPCallCompletedEvent' - $ref: '#/components/schemas/ResponseMCPCallFailedEvent' - $ref: '#/components/schemas/ResponseMCPCallInProgressEvent' - $ref: '#/components/schemas/ResponseMCPListToolsCompletedEvent' - $ref: '#/components/schemas/ResponseMCPListToolsFailedEvent' - $ref: '#/components/schemas/ResponseMCPListToolsInProgressEvent' - $ref: '#/components/schemas/ResponseOutputTextAnnotationAddedEvent' - $ref: '#/components/schemas/ResponseQueuedEvent' - $ref: '#/components/schemas/ResponseCustomToolCallInputDeltaEvent' - $ref: '#/components/schemas/ResponseCustomToolCallInputDoneEvent' discriminator: propertyName: type ResponseStreamOptions: description: | Options for streaming responses. Only set this when you set `stream: true`. type: object nullable: true default: null properties: include_obfuscation: type: boolean description: | When true, stream obfuscation will be enabled. Stream obfuscation adds random characters to an `obfuscation` field on streaming delta events to normalize payload sizes as a mitigation to certain side-channel attacks. These obfuscation fields are included by default, but add a small amount of overhead to the data stream. You can set `include_obfuscation` to false to optimize for bandwidth if you trust the network links between your application and the OpenAI API. ResponseTextDeltaEvent: type: object description: Emitted when there is an additional text delta. properties: type: type: string description: | The type of the event. Always `response.output_text.delta`. enum: - response.output_text.delta x-stainless-const: true item_id: type: string description: | The ID of the output item that the text delta was added to. output_index: type: integer description: | The index of the output item that the text delta was added to. content_index: type: integer description: | The index of the content part that the text delta was added to. delta: type: string description: | The text delta that was added. sequence_number: type: integer description: The sequence number for this event. logprobs: type: array description: | The log probabilities of the tokens in the delta. items: $ref: '#/components/schemas/ResponseLogProb' required: - type - item_id - output_index - content_index - delta - sequence_number - logprobs x-oaiMeta: name: response.output_text.delta group: responses example: | { "type": "response.output_text.delta", "item_id": "msg_123", "output_index": 0, "content_index": 0, "delta": "In", "sequence_number": 1 } ResponseTextDoneEvent: type: object description: Emitted when text content is finalized. properties: type: type: string description: | The type of the event. Always `response.output_text.done`. enum: - response.output_text.done x-stainless-const: true item_id: type: string description: | The ID of the output item that the text content is finalized. output_index: type: integer description: | The index of the output item that the text content is finalized. content_index: type: integer description: | The index of the content part that the text content is finalized. text: type: string description: | The text content that is finalized. sequence_number: type: integer description: The sequence number for this event. logprobs: type: array description: | The log probabilities of the tokens in the delta. items: $ref: '#/components/schemas/ResponseLogProb' required: - type - item_id - output_index - content_index - text - sequence_number - logprobs x-oaiMeta: name: response.output_text.done group: responses example: | { "type": "response.output_text.done", "item_id": "msg_123", "output_index": 0, "content_index": 0, "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", "sequence_number": 1 } ResponseUsage: type: object description: | Represents token usage details including input tokens, output tokens, a breakdown of output tokens, and the total tokens used. properties: input_tokens: type: integer description: The number of input tokens. input_tokens_details: type: object description: A detailed breakdown of the input tokens. properties: cached_tokens: type: integer description: | The number of tokens that were retrieved from the cache. [More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching). required: - cached_tokens output_tokens: type: integer description: The number of output tokens. output_tokens_details: type: object description: A detailed breakdown of the output tokens. properties: reasoning_tokens: type: integer description: The number of reasoning tokens. required: - reasoning_tokens total_tokens: type: integer description: The total number of tokens used. required: - input_tokens - input_tokens_details - output_tokens - output_tokens_details - total_tokens ResponseWebSearchCallCompletedEvent: type: object description: Emitted when a web search call is completed. properties: type: type: string description: | The type of the event. Always `response.web_search_call.completed`. enum: - response.web_search_call.completed x-stainless-const: true output_index: type: integer description: | The index of the output item that the web search call is associated with. item_id: type: string description: | Unique ID for the output item associated with the web search call. sequence_number: type: integer description: The sequence number of the web search call being processed. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.web_search_call.completed group: responses example: | { "type": "response.web_search_call.completed", "output_index": 0, "item_id": "ws_123", "sequence_number": 0 } ResponseWebSearchCallInProgressEvent: type: object description: Emitted when a web search call is initiated. properties: type: type: string description: | The type of the event. Always `response.web_search_call.in_progress`. enum: - response.web_search_call.in_progress x-stainless-const: true output_index: type: integer description: | The index of the output item that the web search call is associated with. item_id: type: string description: | Unique ID for the output item associated with the web search call. sequence_number: type: integer description: The sequence number of the web search call being processed. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.web_search_call.in_progress group: responses example: | { "type": "response.web_search_call.in_progress", "output_index": 0, "item_id": "ws_123", "sequence_number": 0 } ResponseWebSearchCallSearchingEvent: type: object description: Emitted when a web search call is executing. properties: type: type: string description: | The type of the event. Always `response.web_search_call.searching`. enum: - response.web_search_call.searching x-stainless-const: true output_index: type: integer description: | The index of the output item that the web search call is associated with. item_id: type: string description: | Unique ID for the output item associated with the web search call. sequence_number: type: integer description: The sequence number of the web search call being processed. required: - type - output_index - item_id - sequence_number x-oaiMeta: name: response.web_search_call.searching group: responses example: | { "type": "response.web_search_call.searching", "output_index": 0, "item_id": "ws_123", "sequence_number": 0 } RunCompletionUsage: type: object description: >- Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). properties: completion_tokens: type: integer description: Number of completion tokens used over the course of the run. prompt_tokens: type: integer description: Number of prompt tokens used over the course of the run. total_tokens: type: integer description: Total number of tokens used (prompt + completion). required: - prompt_tokens - completion_tokens - total_tokens nullable: true RunGraderRequest: type: object title: RunGraderRequest properties: grader: type: object description: The grader used for the fine-tuning job. anyOf: - $ref: '#/components/schemas/GraderStringCheck' - $ref: '#/components/schemas/GraderTextSimilarity' - $ref: '#/components/schemas/GraderPython' - $ref: '#/components/schemas/GraderScoreModel' - $ref: '#/components/schemas/GraderMulti' discriminator: propertyName: type item: type: object description: > The dataset item provided to the grader. This will be used to populate the `item` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details. model_sample: type: string description: > The model sample to be evaluated. This value will be used to populate the `sample` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details. The `output_json` variable will be populated if the model sample is a valid JSON string. required: - grader - model_sample RunGraderResponse: type: object properties: reward: type: number metadata: type: object properties: name: type: string type: type: string errors: type: object properties: formula_parse_error: type: boolean sample_parse_error: type: boolean truncated_observation_error: type: boolean unresponsive_reward_error: type: boolean invalid_variable_error: type: boolean other_error: type: boolean python_grader_server_error: type: boolean python_grader_server_error_type: type: string nullable: true python_grader_runtime_error: type: boolean python_grader_runtime_error_details: type: string nullable: true model_grader_server_error: type: boolean model_grader_refusal_error: type: boolean model_grader_parse_error: type: boolean model_grader_server_error_details: type: string nullable: true required: - formula_parse_error - sample_parse_error - truncated_observation_error - unresponsive_reward_error - invalid_variable_error - other_error - python_grader_server_error - python_grader_server_error_type - python_grader_runtime_error - python_grader_runtime_error_details - model_grader_server_error - model_grader_refusal_error - model_grader_parse_error - model_grader_server_error_details execution_time: type: number scores: type: object additionalProperties: {} token_usage: type: integer nullable: true sampled_model_name: type: string nullable: true required: - name - type - errors - execution_time - scores - token_usage - sampled_model_name sub_rewards: type: object additionalProperties: {} model_grader_token_usage_per_model: type: object additionalProperties: {} required: - reward - metadata - sub_rewards - model_grader_token_usage_per_model RunObject: type: object title: A run on a thread description: Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads). properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: description: The object type, which is always `thread.run`. type: string enum: - thread.run x-stainless-const: true created_at: description: The Unix timestamp (in seconds) for when the run was created. type: integer thread_id: description: >- The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was executed on as a part of this run. type: string assistant_id: description: >- The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for execution of this run. type: string status: $ref: '#/components/schemas/RunStatus' required_action: type: object description: Details on the action required to continue the run. Will be `null` if no action is required. nullable: true properties: type: description: For now, this is always `submit_tool_outputs`. type: string enum: - submit_tool_outputs x-stainless-const: true submit_tool_outputs: type: object description: Details on the tool outputs needed for this run to continue. properties: tool_calls: type: array description: A list of the relevant tool calls. items: $ref: '#/components/schemas/RunToolCallObject' required: - tool_calls required: - type - submit_tool_outputs last_error: type: object description: The last error associated with this run. Will be `null` if there are no errors. nullable: true properties: code: type: string description: One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. enum: - server_error - rate_limit_exceeded - invalid_prompt message: type: string description: A human-readable description of the error. required: - code - message expires_at: description: The Unix timestamp (in seconds) for when the run will expire. type: integer nullable: true started_at: description: The Unix timestamp (in seconds) for when the run was started. type: integer nullable: true cancelled_at: description: The Unix timestamp (in seconds) for when the run was cancelled. type: integer nullable: true failed_at: description: The Unix timestamp (in seconds) for when the run failed. type: integer nullable: true completed_at: description: The Unix timestamp (in seconds) for when the run was completed. type: integer nullable: true incomplete_details: description: Details on why the run is incomplete. Will be `null` if the run is not incomplete. type: object nullable: true properties: reason: description: >- The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. type: string enum: - max_completion_tokens - max_prompt_tokens model: description: >- The model that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run. type: string instructions: description: >- The instructions that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run. type: string tools: description: >- The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run. default: [] type: array maxItems: 20 items: $ref: '#/components/schemas/AssistantTool' metadata: $ref: '#/components/schemas/Metadata' usage: $ref: '#/components/schemas/RunCompletionUsage' temperature: description: The sampling temperature used for this run. If not set, defaults to 1. type: number nullable: true top_p: description: The nucleus sampling value used for this run. If not set, defaults to 1. type: number nullable: true max_prompt_tokens: type: integer nullable: true description: | The maximum number of prompt tokens specified to have been used over the course of the run. minimum: 256 max_completion_tokens: type: integer nullable: true description: | The maximum number of completion tokens specified to have been used over the course of the run. minimum: 256 truncation_strategy: allOf: - $ref: '#/components/schemas/TruncationObject' - nullable: true tool_choice: allOf: - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - nullable: true parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true required: - id - object - created_at - thread_id - assistant_id - status - required_action - last_error - expires_at - started_at - cancelled_at - failed_at - completed_at - model - instructions - tools - metadata - usage - incomplete_details - max_prompt_tokens - max_completion_tokens - truncation_strategy - tool_choice - parallel_tool_calls - response_format x-oaiMeta: name: The run object beta: true example: | { "id": "run_abc123", "object": "thread.run", "created_at": 1698107661, "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "status": "completed", "started_at": 1699073476, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699073498, "last_error": null, "model": "gpt-4o", "instructions": null, "tools": [{"type": "file_search"}, {"type": "code_interpreter"}], "metadata": {}, "incomplete_details": null, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 }, "temperature": 1.0, "top_p": 1.0, "max_prompt_tokens": 1000, "max_completion_tokens": 1000, "truncation_strategy": { "type": "auto", "last_messages": null }, "response_format": "auto", "tool_choice": "auto", "parallel_tool_calls": true } RunStepCompletionUsage: type: object description: >- Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. properties: completion_tokens: type: integer description: Number of completion tokens used over the course of the run step. prompt_tokens: type: integer description: Number of prompt tokens used over the course of the run step. total_tokens: type: integer description: Total number of tokens used (prompt + completion). required: - prompt_tokens - completion_tokens - total_tokens nullable: true RunStepDeltaObject: type: object title: Run step delta object description: | Represents a run step delta i.e. any changed fields on a run step during streaming. properties: id: description: The identifier of the run step, which can be referenced in API endpoints. type: string object: description: The object type, which is always `thread.run.step.delta`. type: string enum: - thread.run.step.delta x-stainless-const: true delta: $ref: '#/components/schemas/RunStepDeltaObjectDelta' required: - id - object - delta x-oaiMeta: name: The run step delta object beta: true example: | { "id": "step_123", "object": "thread.run.step.delta", "delta": { "step_details": { "type": "tool_calls", "tool_calls": [ { "index": 0, "id": "call_123", "type": "code_interpreter", "code_interpreter": { "input": "", "outputs": [] } } ] } } } RunStepDeltaStepDetailsMessageCreationObject: title: Message creation type: object description: Details of the message creation by the run step. properties: type: description: Always `message_creation`. type: string enum: - message_creation x-stainless-const: true message_creation: type: object properties: message_id: type: string description: The ID of the message that was created by this run step. required: - type RunStepDeltaStepDetailsToolCallsCodeObject: title: Code interpreter tool call type: object description: Details of the Code Interpreter tool call the run step was involved in. properties: index: type: integer description: The index of the tool call in the tool calls array. id: type: string description: The ID of the tool call. type: type: string description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. enum: - code_interpreter x-stainless-const: true code_interpreter: type: object description: The Code Interpreter tool call definition. properties: input: type: string description: The input to the Code Interpreter tool call. outputs: type: array description: >- The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. items: type: object anyOf: - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject' - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject' discriminator: propertyName: type required: - index - type RunStepDeltaStepDetailsToolCallsCodeOutputImageObject: title: Code interpreter image output type: object properties: index: type: integer description: The index of the output in the outputs array. type: description: Always `image`. type: string enum: - image x-stainless-const: true image: type: object properties: file_id: description: The [file](https://platform.openai.com/docs/api-reference/files) ID of the image. type: string required: - index - type RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject: title: Code interpreter log output type: object description: Text output from the Code Interpreter tool call as part of a run step. properties: index: type: integer description: The index of the output in the outputs array. type: description: Always `logs`. type: string enum: - logs x-stainless-const: true logs: type: string description: The text output from the Code Interpreter tool call. required: - index - type RunStepDeltaStepDetailsToolCallsFileSearchObject: title: File search tool call type: object properties: index: type: integer description: The index of the tool call in the tool calls array. id: type: string description: The ID of the tool call object. type: type: string description: The type of tool call. This is always going to be `file_search` for this type of tool call. enum: - file_search x-stainless-const: true file_search: type: object description: For now, this is always going to be an empty object. x-oaiTypeLabel: map required: - index - type - file_search RunStepDeltaStepDetailsToolCallsFunctionObject: type: object title: Function tool call properties: index: type: integer description: The index of the tool call in the tool calls array. id: type: string description: The ID of the tool call object. type: type: string description: The type of tool call. This is always going to be `function` for this type of tool call. enum: - function x-stainless-const: true function: type: object description: The definition of the function that was called. properties: name: type: string description: The name of the function. arguments: type: string description: The arguments passed to the function. output: type: string description: >- The output of the function. This will be `null` if the outputs have not been [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet. nullable: true required: - index - type RunStepDeltaStepDetailsToolCallsObject: title: Tool calls type: object description: Details of the tool call. properties: type: description: Always `tool_calls`. type: string enum: - tool_calls x-stainless-const: true tool_calls: type: array description: > An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. items: $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCall' required: - type RunStepDetailsMessageCreationObject: title: Message creation type: object description: Details of the message creation by the run step. properties: type: description: Always `message_creation`. type: string enum: - message_creation x-stainless-const: true message_creation: type: object properties: message_id: type: string description: The ID of the message that was created by this run step. required: - message_id required: - type - message_creation RunStepDetailsToolCallsCodeObject: title: Code Interpreter tool call type: object description: Details of the Code Interpreter tool call the run step was involved in. properties: id: type: string description: The ID of the tool call. type: type: string description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. enum: - code_interpreter x-stainless-const: true code_interpreter: type: object description: The Code Interpreter tool call definition. required: - input - outputs properties: input: type: string description: The input to the Code Interpreter tool call. outputs: type: array description: >- The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. items: type: object anyOf: - $ref: '#/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject' - $ref: '#/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject' discriminator: propertyName: type required: - id - type - code_interpreter RunStepDetailsToolCallsCodeOutputImageObject: title: Code Interpreter image output type: object properties: type: description: Always `image`. type: string enum: - image x-stainless-const: true image: type: object properties: file_id: description: The [file](https://platform.openai.com/docs/api-reference/files) ID of the image. type: string required: - file_id required: - type - image x-stainless-naming: java: type_name: ImageOutput kotlin: type_name: ImageOutput RunStepDetailsToolCallsCodeOutputLogsObject: title: Code Interpreter log output type: object description: Text output from the Code Interpreter tool call as part of a run step. properties: type: description: Always `logs`. type: string enum: - logs x-stainless-const: true logs: type: string description: The text output from the Code Interpreter tool call. required: - type - logs x-stainless-naming: java: type_name: LogsOutput kotlin: type_name: LogsOutput RunStepDetailsToolCallsFileSearchObject: title: File search tool call type: object properties: id: type: string description: The ID of the tool call object. type: type: string description: The type of tool call. This is always going to be `file_search` for this type of tool call. enum: - file_search x-stainless-const: true file_search: type: object description: For now, this is always going to be an empty object. x-oaiTypeLabel: map properties: ranking_options: $ref: '#/components/schemas/RunStepDetailsToolCallsFileSearchRankingOptionsObject' results: type: array description: The results of the file search. items: $ref: '#/components/schemas/RunStepDetailsToolCallsFileSearchResultObject' required: - id - type - file_search RunStepDetailsToolCallsFileSearchRankingOptionsObject: title: File search tool call ranking options type: object description: The ranking options for the file search. properties: ranker: $ref: '#/components/schemas/FileSearchRanker' score_threshold: type: number description: >- The score threshold for the file search. All values must be a floating point number between 0 and 1. minimum: 0 maximum: 1 required: - ranker - score_threshold RunStepDetailsToolCallsFileSearchResultObject: title: File search tool call result type: object description: A result instance of the file search. x-oaiTypeLabel: map properties: file_id: type: string description: The ID of the file that result was found in. file_name: type: string description: The name of the file that result was found in. score: type: number description: The score of the result. All values must be a floating point number between 0 and 1. minimum: 0 maximum: 1 content: type: array description: >- The content of the result that was found. The content is only included if requested via the include query parameter. items: type: object properties: type: type: string description: The type of the content. enum: - text x-stainless-const: true text: type: string description: The text content of the file. required: - file_id - file_name - score RunStepDetailsToolCallsFunctionObject: type: object title: Function tool call properties: id: type: string description: The ID of the tool call object. type: type: string description: The type of tool call. This is always going to be `function` for this type of tool call. enum: - function x-stainless-const: true function: type: object description: The definition of the function that was called. properties: name: type: string description: The name of the function. arguments: type: string description: The arguments passed to the function. output: type: string description: >- The output of the function. This will be `null` if the outputs have not been [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet. nullable: true required: - name - arguments - output required: - id - type - function RunStepDetailsToolCallsObject: title: Tool calls type: object description: Details of the tool call. properties: type: description: Always `tool_calls`. type: string enum: - tool_calls x-stainless-const: true tool_calls: type: array description: > An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. items: $ref: '#/components/schemas/RunStepDetailsToolCall' required: - type - tool_calls RunStepObject: type: object title: Run steps description: | Represents a step in execution of a run. properties: id: description: The identifier of the run step, which can be referenced in API endpoints. type: string object: description: The object type, which is always `thread.run.step`. type: string enum: - thread.run.step x-stainless-const: true created_at: description: The Unix timestamp (in seconds) for when the run step was created. type: integer assistant_id: description: >- The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) associated with the run step. type: string thread_id: description: The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. type: string run_id: description: >- The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that this run step is a part of. type: string type: description: The type of run step, which can be either `message_creation` or `tool_calls`. type: string enum: - message_creation - tool_calls status: description: >- The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`. type: string enum: - in_progress - cancelled - failed - completed - expired step_details: type: object description: The details of the run step. anyOf: - $ref: '#/components/schemas/RunStepDetailsMessageCreationObject' - $ref: '#/components/schemas/RunStepDetailsToolCallsObject' discriminator: propertyName: type last_error: type: object description: The last error associated with this run step. Will be `null` if there are no errors. nullable: true properties: code: type: string description: One of `server_error` or `rate_limit_exceeded`. enum: - server_error - rate_limit_exceeded message: type: string description: A human-readable description of the error. required: - code - message expired_at: description: >- The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. type: integer nullable: true cancelled_at: description: The Unix timestamp (in seconds) for when the run step was cancelled. type: integer nullable: true failed_at: description: The Unix timestamp (in seconds) for when the run step failed. type: integer nullable: true completed_at: description: The Unix timestamp (in seconds) for when the run step completed. type: integer nullable: true metadata: $ref: '#/components/schemas/Metadata' usage: $ref: '#/components/schemas/RunStepCompletionUsage' required: - id - object - created_at - assistant_id - thread_id - run_id - type - status - step_details - last_error - expired_at - cancelled_at - failed_at - completed_at - metadata - usage x-oaiMeta: name: The run step object beta: true example: | { "id": "step_abc123", "object": "thread.run.step", "created_at": 1699063291, "run_id": "run_abc123", "assistant_id": "asst_abc123", "thread_id": "thread_abc123", "type": "message_creation", "status": "completed", "cancelled_at": null, "completed_at": 1699063291, "expired_at": null, "failed_at": null, "last_error": null, "step_details": { "type": "message_creation", "message_creation": { "message_id": "msg_abc123" } }, "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579 } } RunStepStreamEvent: anyOf: - type: object properties: event: type: string enum: - thread.run.step.created x-stainless-const: true data: $ref: '#/components/schemas/RunStepObject' required: - event - data description: >- Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is created. x-oaiMeta: dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - type: object properties: event: type: string enum: - thread.run.step.in_progress x-stainless-const: true data: $ref: '#/components/schemas/RunStepObject' required: - event - data description: >- Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) moves to an `in_progress` state. x-oaiMeta: dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - type: object properties: event: type: string enum: - thread.run.step.delta x-stainless-const: true data: $ref: '#/components/schemas/RunStepDeltaObject' required: - event - data description: >- Occurs when parts of a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) are being streamed. x-oaiMeta: dataDescription: '`data` is a [run step delta](/docs/api-reference/assistants-streaming/run-step-delta-object)' - type: object properties: event: type: string enum: - thread.run.step.completed x-stainless-const: true data: $ref: '#/components/schemas/RunStepObject' required: - event - data description: >- Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is completed. x-oaiMeta: dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - type: object properties: event: type: string enum: - thread.run.step.failed x-stainless-const: true data: $ref: '#/components/schemas/RunStepObject' required: - event - data description: >- Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) fails. x-oaiMeta: dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - type: object properties: event: type: string enum: - thread.run.step.cancelled x-stainless-const: true data: $ref: '#/components/schemas/RunStepObject' required: - event - data description: >- Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is cancelled. x-oaiMeta: dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - type: object properties: event: type: string enum: - thread.run.step.expired x-stainless-const: true data: $ref: '#/components/schemas/RunStepObject' required: - event - data description: >- Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) expires. x-oaiMeta: dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' discriminator: propertyName: event RunStreamEvent: anyOf: - type: object properties: event: type: string enum: - thread.run.created x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: Occurs when a new [run](https://platform.openai.com/docs/api-reference/runs/object) is created. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.queued x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: >- Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a `queued` status. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.in_progress x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: >- Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to an `in_progress` status. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.requires_action x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: >- Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a `requires_action` status. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.completed x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) is completed. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.incomplete x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: >- Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) ends with status `incomplete`. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.failed x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) fails. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.cancelling x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: >- Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a `cancelling` status. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.cancelled x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) is cancelled. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - type: object properties: event: type: string enum: - thread.run.expired x-stainless-const: true data: $ref: '#/components/schemas/RunObject' required: - event - data description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) expires. x-oaiMeta: dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' discriminator: propertyName: event RunToolCallObject: type: object description: Tool call objects properties: id: type: string description: >- The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoint. type: type: string description: The type of tool call the output is required for. For now, this is always `function`. enum: - function x-stainless-const: true function: type: object description: The function definition. properties: name: type: string description: The name of the function. arguments: type: string description: The arguments that the model expects you to pass to the function. required: - name - arguments required: - id - type - function Screenshot: type: object title: Screenshot description: | A screenshot action. properties: type: type: string enum: - screenshot default: screenshot description: | Specifies the event type. For a screenshot action, this property is always set to `screenshot`. x-stainless-const: true required: - type Scroll: type: object title: Scroll description: | A scroll action. properties: type: type: string enum: - scroll default: scroll description: | Specifies the event type. For a scroll action, this property is always set to `scroll`. x-stainless-const: true x: type: integer description: | The x-coordinate where the scroll occurred. 'y': type: integer description: | The y-coordinate where the scroll occurred. scroll_x: type: integer description: | The horizontal scroll distance. scroll_y: type: integer description: | The vertical scroll distance. required: - type - x - 'y' - scroll_x - scroll_y ServiceTier: type: string description: | Specifies the processing type used for serving the request. - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'. - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model. - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier. - When not set, the default behavior is 'auto'. When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter. enum: - auto - default - flex - scale - priority nullable: true default: auto SpeechAudioDeltaEvent: type: object description: Emitted for each chunk of audio data generated during speech synthesis. properties: type: type: string description: | The type of the event. Always `speech.audio.delta`. enum: - speech.audio.delta x-stainless-const: true audio: type: string description: | A chunk of Base64-encoded audio data. required: - type - audio x-oaiMeta: name: Stream Event (speech.audio.delta) group: speech example: | { "type": "speech.audio.delta", "audio": "base64-encoded-audio-data" } SpeechAudioDoneEvent: type: object description: Emitted when the speech synthesis is complete and all audio has been streamed. properties: type: type: string description: | The type of the event. Always `speech.audio.done`. enum: - speech.audio.done x-stainless-const: true usage: type: object description: | Token usage statistics for the request. properties: input_tokens: type: integer description: Number of input tokens in the prompt. output_tokens: type: integer description: Number of output tokens generated. total_tokens: type: integer description: Total number of tokens used (input + output). required: - input_tokens - output_tokens - total_tokens required: - type - usage x-oaiMeta: name: Stream Event (speech.audio.done) group: speech example: | { "type": "speech.audio.done", "usage": { "input_tokens": 14, "output_tokens": 101, "total_tokens": 115 } } StaticChunkingStrategy: type: object additionalProperties: false properties: max_chunk_size_tokens: type: integer minimum: 100 maximum: 4096 description: >- The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. chunk_overlap_tokens: type: integer description: | The number of tokens that overlap between chunks. The default value is `400`. Note that the overlap must not exceed half of `max_chunk_size_tokens`. required: - max_chunk_size_tokens - chunk_overlap_tokens StaticChunkingStrategyRequestParam: type: object title: Static Chunking Strategy description: Customize your own chunking strategy by setting chunk size and chunk overlap. additionalProperties: false properties: type: type: string description: Always `static`. enum: - static x-stainless-const: true static: $ref: '#/components/schemas/StaticChunkingStrategy' required: - type - static StaticChunkingStrategyResponseParam: type: object title: Static Chunking Strategy additionalProperties: false properties: type: type: string description: Always `static`. enum: - static x-stainless-const: true static: $ref: '#/components/schemas/StaticChunkingStrategy' required: - type - static StopConfiguration: description: | Not supported with latest reasoning models `o3` and `o4-mini`. Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. nullable: true anyOf: - type: string default: <|endoftext|> example: |+ nullable: true - type: array minItems: 1 maxItems: 4 items: type: string example: '["\n"]' SubmitToolOutputsRunRequest: type: object additionalProperties: false properties: tool_outputs: description: A list of tools for which the outputs are being submitted. type: array items: type: object properties: tool_call_id: type: string description: >- The ID of the tool call in the `required_action` object within the run object the output is being submitted for. output: type: string description: The output of the tool call to be submitted to continue the run. stream: type: boolean nullable: true description: > If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. required: - tool_outputs TextResponseFormatConfiguration: description: | An object specifying the format that the model must output. Configuring `{ "type": "json_schema" }` enables Structured Outputs, which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). The default format is `{ "type": "text" }` with no additional options. **Not recommended for gpt-4o and newer models:** Setting to `{ "type": "json_object" }` enables the older JSON mode, which ensures the message the model generates is valid JSON. Using `json_schema` is preferred for models that support it. anyOf: - $ref: '#/components/schemas/ResponseFormatText' - $ref: '#/components/schemas/TextResponseFormatJsonSchema' - $ref: '#/components/schemas/ResponseFormatJsonObject' discriminator: propertyName: type TextResponseFormatJsonSchema: type: object title: JSON schema description: | JSON Schema response format. Used to generate structured JSON responses. Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). properties: type: type: string description: The type of response format being defined. Always `json_schema`. enum: - json_schema x-stainless-const: true description: type: string description: | A description of what the response format is for, used by the model to determine how to respond in the format. name: type: string description: | The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. schema: $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' strict: type: boolean nullable: true default: false description: | Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). required: - type - schema - name ThreadObject: type: object title: Thread description: Represents a thread that contains [messages](https://platform.openai.com/docs/api-reference/messages). properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: description: The object type, which is always `thread`. type: string enum: - thread x-stainless-const: true created_at: description: The Unix timestamp (in seconds) for when the thread was created. type: integer tool_resources: type: object description: > A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. maxItems: 1 items: type: string nullable: true metadata: $ref: '#/components/schemas/Metadata' required: - id - object - created_at - tool_resources - metadata x-oaiMeta: name: The thread object beta: true example: | { "id": "thread_abc123", "object": "thread", "created_at": 1698107661, "metadata": {} } ThreadStreamEvent: anyOf: - type: object properties: enabled: type: boolean description: Whether to enable input audio transcription. event: type: string enum: - thread.created x-stainless-const: true data: $ref: '#/components/schemas/ThreadObject' required: - event - data description: >- Occurs when a new [thread](https://platform.openai.com/docs/api-reference/threads/object) is created. x-oaiMeta: dataDescription: '`data` is a [thread](/docs/api-reference/threads/object)' discriminator: propertyName: event ToggleCertificatesRequest: type: object properties: certificate_ids: type: array items: type: string example: cert_abc minItems: 1 maxItems: 10 required: - certificate_ids Tool: description: | A tool that can be used to generate a response. discriminator: propertyName: type anyOf: - $ref: '#/components/schemas/FunctionTool' - $ref: '#/components/schemas/FileSearchTool' - $ref: '#/components/schemas/WebSearchPreviewTool' - $ref: '#/components/schemas/ComputerUsePreviewTool' - $ref: '#/components/schemas/MCPTool' - $ref: '#/components/schemas/CodeInterpreterTool' - $ref: '#/components/schemas/ImageGenTool' - $ref: '#/components/schemas/LocalShellTool' - $ref: '#/components/schemas/CustomTool' ToolChoiceAllowed: type: object title: Allowed tools description: | Constrains the tools available to the model to a pre-defined set. properties: type: type: string enum: - allowed_tools description: Allowed tool configuration type. Always `allowed_tools`. x-stainless-const: true mode: type: string enum: - auto - required description: | Constrains the tools available to the model to a pre-defined set. `auto` allows the model to pick from among the allowed tools and generate a message. `required` requires the model to call one or more of the allowed tools. tools: type: array description: | A list of tool definitions that the model should be allowed to call. For the Responses API, the list of tool definitions might look like: ```json [ { "type": "function", "name": "get_weather" }, { "type": "mcp", "server_label": "deepwiki" }, { "type": "image_generation" } ] ``` items: type: object description: | A tool definition that the model should be allowed to call. additionalProperties: true x-oaiExpandable: false required: - type - mode - tools ToolChoiceCustom: type: object title: Custom tool description: | Use this option to force the model to call a specific custom tool. properties: type: type: string enum: - custom description: For custom tool calling, the type is always `custom`. x-stainless-const: true name: type: string description: The name of the custom tool to call. required: - type - name ToolChoiceFunction: type: object title: Function tool description: | Use this option to force the model to call a specific function. properties: type: type: string enum: - function description: For function calling, the type is always `function`. x-stainless-const: true name: type: string description: The name of the function to call. required: - type - name ToolChoiceMCP: type: object title: MCP tool description: | Use this option to force the model to call a specific tool on a remote MCP server. properties: type: type: string enum: - mcp description: For MCP tools, the type is always `mcp`. x-stainless-const: true server_label: type: string description: | The label of the MCP server to use. name: type: string description: | The name of the tool to call on the server. nullable: true required: - type - server_label ToolChoiceOptions: type: string title: Tool choice mode description: | Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools. enum: - none - auto - required ToolChoiceTypes: type: object title: Hosted tool description: | Indicates that the model should use a built-in tool to generate a response. [Learn more about built-in tools](https://platform.openai.com/docs/guides/tools). properties: type: type: string description: | The type of hosted tool the model should to use. Learn more about [built-in tools](https://platform.openai.com/docs/guides/tools). Allowed values are: - `file_search` - `web_search_preview` - `computer_use_preview` - `code_interpreter` - `image_generation` enum: - file_search - web_search_preview - computer_use_preview - web_search_preview_2025_03_11 - image_generation - code_interpreter required: - type TranscriptTextDeltaEvent: type: object description: >- Emitted when there is an additional text delta. This is also the first event emitted when the transcription starts. Only emitted when you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`. properties: type: type: string description: | The type of the event. Always `transcript.text.delta`. enum: - transcript.text.delta x-stainless-const: true delta: type: string description: | The text delta that was additionally transcribed. logprobs: type: array description: > The log probabilities of the delta. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`. items: type: object properties: token: type: string description: | The token that was used to generate the log probability. logprob: type: number description: | The log probability of the token. bytes: type: array items: type: integer description: | The bytes that were used to generate the log probability. required: - type - delta x-oaiMeta: name: Stream Event (transcript.text.delta) group: transcript example: | { "type": "transcript.text.delta", "delta": " wonderful" } TranscriptTextDoneEvent: type: object description: >- Emitted when the transcription is complete. Contains the complete transcription text. Only emitted when you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`. properties: type: type: string description: | The type of the event. Always `transcript.text.done`. enum: - transcript.text.done x-stainless-const: true text: type: string description: | The text that was transcribed. logprobs: type: array description: > The log probabilities of the individual tokens in the transcription. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`. items: type: object properties: token: type: string description: | The token that was used to generate the log probability. logprob: type: number description: | The log probability of the token. bytes: type: array items: type: integer description: | The bytes that were used to generate the log probability. usage: $ref: '#/components/schemas/TranscriptTextUsageTokens' required: - type - text x-oaiMeta: name: Stream Event (transcript.text.done) group: transcript example: | { "type": "transcript.text.done", "text": "I see skies of blue and clouds of white, the bright blessed days, the dark sacred nights, and I think to myself, what a wonderful world.", "usage": { "type": "tokens", "input_tokens": 14, "input_token_details": { "text_tokens": 10, "audio_tokens": 4 }, "output_tokens": 31, "total_tokens": 45 } } TranscriptTextUsageDuration: type: object title: Duration Usage description: Usage statistics for models billed by audio input duration. properties: type: type: string enum: - duration description: The type of the usage object. Always `duration` for this variant. x-stainless-const: true seconds: type: number description: Duration of the input audio in seconds. required: - type - seconds TranscriptTextUsageTokens: type: object title: Token Usage description: Usage statistics for models billed by token usage. properties: type: type: string enum: - tokens description: The type of the usage object. Always `tokens` for this variant. x-stainless-const: true input_tokens: type: integer description: Number of input tokens billed for this request. input_token_details: type: object description: Details about the input tokens billed for this request. properties: text_tokens: type: integer description: Number of text tokens billed for this request. audio_tokens: type: integer description: Number of audio tokens billed for this request. output_tokens: type: integer description: Number of output tokens generated. total_tokens: type: integer description: Total number of tokens used (input + output). required: - type - input_tokens - output_tokens - total_tokens TranscriptionChunkingStrategy: description: >- Controls how the audio is cut into chunks. When set to `"auto"`, the server first normalizes loudness and then uses voice activity detection (VAD) to choose boundaries. `server_vad` object can be provided to tweak VAD detection parameters manually. If unset, the audio is transcribed as a single block. anyOf: - type: string enum: - auto description: | Automatically set chunking parameters based on the audio. Must be set to `"auto"`. x-stainless-const: true - $ref: '#/components/schemas/VadConfig' nullable: true x-oaiTypeLabel: string TranscriptionInclude: type: string enum: - logprobs TranscriptionSegment: type: object properties: id: type: integer description: Unique identifier of the segment. seek: type: integer description: Seek offset of the segment. start: type: number format: float description: Start time of the segment in seconds. end: type: number format: float description: End time of the segment in seconds. text: type: string description: Text content of the segment. tokens: type: array items: type: integer description: Array of token IDs for the text content. temperature: type: number format: float description: Temperature parameter used for generating the segment. avg_logprob: type: number format: float description: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. compression_ratio: type: number format: float description: >- Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. no_speech_prob: type: number format: float description: >- Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. required: - id - seek - start - end - text - tokens - temperature - avg_logprob - compression_ratio - no_speech_prob TranscriptionWord: type: object properties: word: type: string description: The text content of the word. start: type: number format: float description: Start time of the word in seconds. end: type: number format: float description: End time of the word in seconds. required: - word - start - end TruncationObject: type: object title: Thread Truncation Controls description: >- Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run. properties: type: type: string description: >- The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`. enum: - auto - last_messages last_messages: type: integer description: The number of most recent messages from the thread when constructing the context for the run. minimum: 1 nullable: true required: - type Type: type: object title: Type description: | An action to type in text. properties: type: type: string enum: - type default: type description: | Specifies the event type. For a type action, this property is always set to `type`. x-stainless-const: true text: type: string description: | The text to type. required: - type - text UpdateVectorStoreFileAttributesRequest: type: object additionalProperties: false properties: attributes: $ref: '#/components/schemas/VectorStoreFileAttributes' required: - attributes x-oaiMeta: name: Update vector store file attributes request UpdateVectorStoreRequest: type: object additionalProperties: false properties: name: description: The name of the vector store. type: string nullable: true expires_after: allOf: - $ref: '#/components/schemas/VectorStoreExpirationAfter' - nullable: true metadata: $ref: '#/components/schemas/Metadata' Upload: type: object title: Upload description: | The Upload object can accept byte chunks in the form of Parts. properties: id: type: string description: The Upload unique identifier, which can be referenced in API endpoints. created_at: type: integer description: The Unix timestamp (in seconds) for when the Upload was created. filename: type: string description: The name of the file to be uploaded. bytes: type: integer description: The intended number of bytes to be uploaded. purpose: type: string description: >- The intended purpose of the file. [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for acceptable values. status: type: string description: The status of the Upload. enum: - pending - completed - cancelled - expired expires_at: type: integer description: The Unix timestamp (in seconds) for when the Upload will expire. object: type: string description: The object type, which is always "upload". enum: - upload x-stainless-const: true file: allOf: - $ref: '#/components/schemas/OpenAIFile' - nullable: true description: The ready File object after the Upload is completed. required: - bytes - created_at - expires_at - filename - id - purpose - status - object x-oaiMeta: name: The upload object example: | { "id": "upload_abc123", "object": "upload", "bytes": 2147483648, "created_at": 1719184911, "filename": "training_examples.jsonl", "purpose": "fine-tune", "status": "completed", "expires_at": 1719127296, "file": { "id": "file-xyz321", "object": "file", "bytes": 2147483648, "created_at": 1719186911, "filename": "training_examples.jsonl", "purpose": "fine-tune", } } UploadCertificateRequest: type: object properties: name: type: string description: An optional name for the certificate content: type: string description: The certificate content in PEM format required: - content UploadPart: type: object title: UploadPart description: | The upload Part represents a chunk of bytes we can add to an Upload object. properties: id: type: string description: The upload Part unique identifier, which can be referenced in API endpoints. created_at: type: integer description: The Unix timestamp (in seconds) for when the Part was created. upload_id: type: string description: The ID of the Upload object that this Part was added to. object: type: string description: The object type, which is always `upload.part`. enum: - upload.part x-stainless-const: true required: - created_at - id - object - upload_id x-oaiMeta: name: The upload part object example: | { "id": "part_def456", "object": "upload.part", "created_at": 1719186911, "upload_id": "upload_abc123" } UsageAudioSpeechesResult: type: object description: The aggregated audio speeches usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.audio_speeches.result x-stainless-const: true characters: type: integer description: The number of characters processed. num_model_requests: type: integer description: The count of requests made to the model. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. user_id: type: string nullable: true description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. api_key_id: type: string nullable: true description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. model: type: string nullable: true description: When `group_by=model`, this field provides the model name of the grouped usage result. required: - object - characters - num_model_requests x-oaiMeta: name: Audio speeches usage object example: | { "object": "organization.usage.audio_speeches.result", "characters": 45, "num_model_requests": 1, "project_id": "proj_abc", "user_id": "user-abc", "api_key_id": "key_abc", "model": "tts-1" } UsageAudioTranscriptionsResult: type: object description: The aggregated audio transcriptions usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.audio_transcriptions.result x-stainless-const: true seconds: type: integer description: The number of seconds processed. num_model_requests: type: integer description: The count of requests made to the model. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. user_id: type: string nullable: true description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. api_key_id: type: string nullable: true description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. model: type: string nullable: true description: When `group_by=model`, this field provides the model name of the grouped usage result. required: - object - seconds - num_model_requests x-oaiMeta: name: Audio transcriptions usage object example: | { "object": "organization.usage.audio_transcriptions.result", "seconds": 10, "num_model_requests": 1, "project_id": "proj_abc", "user_id": "user-abc", "api_key_id": "key_abc", "model": "tts-1" } UsageCodeInterpreterSessionsResult: type: object description: The aggregated code interpreter sessions usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.code_interpreter_sessions.result x-stainless-const: true num_sessions: type: integer description: The number of code interpreter sessions. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. required: - object - sessions x-oaiMeta: name: Code interpreter sessions usage object example: | { "object": "organization.usage.code_interpreter_sessions.result", "num_sessions": 1, "project_id": "proj_abc" } UsageCompletionsResult: type: object description: The aggregated completions usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.completions.result x-stainless-const: true input_tokens: type: integer description: >- The aggregated number of text input tokens used, including cached tokens. For customers subscribe to scale tier, this includes scale tier tokens. input_cached_tokens: type: integer description: >- The aggregated number of text input tokens that has been cached from previous requests. For customers subscribe to scale tier, this includes scale tier tokens. output_tokens: type: integer description: >- The aggregated number of text output tokens used. For customers subscribe to scale tier, this includes scale tier tokens. input_audio_tokens: type: integer description: The aggregated number of audio input tokens used, including cached tokens. output_audio_tokens: type: integer description: The aggregated number of audio output tokens used. num_model_requests: type: integer description: The count of requests made to the model. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. user_id: type: string nullable: true description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. api_key_id: type: string nullable: true description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. model: type: string nullable: true description: When `group_by=model`, this field provides the model name of the grouped usage result. batch: type: boolean nullable: true description: When `group_by=batch`, this field tells whether the grouped usage result is batch or not. required: - object - input_tokens - output_tokens - num_model_requests x-oaiMeta: name: Completions usage object example: | { "object": "organization.usage.completions.result", "input_tokens": 5000, "output_tokens": 1000, "input_cached_tokens": 4000, "input_audio_tokens": 300, "output_audio_tokens": 200, "num_model_requests": 5, "project_id": "proj_abc", "user_id": "user-abc", "api_key_id": "key_abc", "model": "gpt-4o-mini-2024-07-18", "batch": false } UsageEmbeddingsResult: type: object description: The aggregated embeddings usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.embeddings.result x-stainless-const: true input_tokens: type: integer description: The aggregated number of input tokens used. num_model_requests: type: integer description: The count of requests made to the model. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. user_id: type: string nullable: true description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. api_key_id: type: string nullable: true description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. model: type: string nullable: true description: When `group_by=model`, this field provides the model name of the grouped usage result. required: - object - input_tokens - num_model_requests x-oaiMeta: name: Embeddings usage object example: | { "object": "organization.usage.embeddings.result", "input_tokens": 20, "num_model_requests": 2, "project_id": "proj_abc", "user_id": "user-abc", "api_key_id": "key_abc", "model": "text-embedding-ada-002-v2" } UsageImagesResult: type: object description: The aggregated images usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.images.result x-stainless-const: true images: type: integer description: The number of images processed. num_model_requests: type: integer description: The count of requests made to the model. source: type: string nullable: true description: >- When `group_by=source`, this field provides the source of the grouped usage result, possible values are `image.generation`, `image.edit`, `image.variation`. size: type: string nullable: true description: When `group_by=size`, this field provides the image size of the grouped usage result. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. user_id: type: string nullable: true description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. api_key_id: type: string nullable: true description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. model: type: string nullable: true description: When `group_by=model`, this field provides the model name of the grouped usage result. required: - object - images - num_model_requests x-oaiMeta: name: Images usage object example: | { "object": "organization.usage.images.result", "images": 2, "num_model_requests": 2, "size": "1024x1024", "source": "image.generation", "project_id": "proj_abc", "user_id": "user-abc", "api_key_id": "key_abc", "model": "dall-e-3" } UsageModerationsResult: type: object description: The aggregated moderations usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.moderations.result x-stainless-const: true input_tokens: type: integer description: The aggregated number of input tokens used. num_model_requests: type: integer description: The count of requests made to the model. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. user_id: type: string nullable: true description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. api_key_id: type: string nullable: true description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. model: type: string nullable: true description: When `group_by=model`, this field provides the model name of the grouped usage result. required: - object - input_tokens - num_model_requests x-oaiMeta: name: Moderations usage object example: | { "object": "organization.usage.moderations.result", "input_tokens": 20, "num_model_requests": 2, "project_id": "proj_abc", "user_id": "user-abc", "api_key_id": "key_abc", "model": "text-moderation" } UsageResponse: type: object properties: object: type: string enum: - page x-stainless-const: true data: type: array items: $ref: '#/components/schemas/UsageTimeBucket' has_more: type: boolean next_page: type: string required: - object - data - has_more - next_page UsageTimeBucket: type: object properties: object: type: string enum: - bucket x-stainless-const: true start_time: type: integer end_time: type: integer result: type: array items: anyOf: - $ref: '#/components/schemas/UsageCompletionsResult' - $ref: '#/components/schemas/UsageEmbeddingsResult' - $ref: '#/components/schemas/UsageModerationsResult' - $ref: '#/components/schemas/UsageImagesResult' - $ref: '#/components/schemas/UsageAudioSpeechesResult' - $ref: '#/components/schemas/UsageAudioTranscriptionsResult' - $ref: '#/components/schemas/UsageVectorStoresResult' - $ref: '#/components/schemas/UsageCodeInterpreterSessionsResult' - $ref: '#/components/schemas/CostsResult' discriminator: propertyName: object required: - object - start_time - end_time - result UsageVectorStoresResult: type: object description: The aggregated vector stores usage details of the specific time bucket. properties: object: type: string enum: - organization.usage.vector_stores.result x-stainless-const: true usage_bytes: type: integer description: The vector stores usage in bytes. project_id: type: string nullable: true description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. required: - object - usage_bytes x-oaiMeta: name: Vector stores usage object example: | { "object": "organization.usage.vector_stores.result", "usage_bytes": 1024, "project_id": "proj_abc" } User: type: object description: Represents an individual `user` within an organization. properties: object: type: string enum: - organization.user description: The object type, which is always `organization.user` x-stainless-const: true id: type: string description: The identifier, which can be referenced in API endpoints name: type: string description: The name of the user email: type: string description: The email address of the user role: type: string enum: - owner - reader description: '`owner` or `reader`' added_at: type: integer description: The Unix timestamp (in seconds) of when the user was added. required: - object - id - name - email - role - added_at x-oaiMeta: name: The user object example: | { "object": "organization.user", "id": "user_abc", "name": "First Last", "email": "user@example.com", "role": "owner", "added_at": 1711471533 } UserDeleteResponse: type: object properties: object: type: string enum: - organization.user.deleted x-stainless-const: true id: type: string deleted: type: boolean required: - object - id - deleted UserListResponse: type: object properties: object: type: string enum: - list x-stainless-const: true data: type: array items: $ref: '#/components/schemas/User' first_id: type: string last_id: type: string has_more: type: boolean required: - object - data - first_id - last_id - has_more UserRoleUpdateRequest: type: object properties: role: type: string enum: - owner - reader description: '`owner` or `reader`' required: - role VadConfig: type: object additionalProperties: false required: - type properties: type: type: string enum: - server_vad description: Must be set to `server_vad` to enable manual chunking using server side VAD. prefix_padding_ms: type: integer default: 300 description: | Amount of audio to include before the VAD detected speech (in milliseconds). silence_duration_ms: type: integer default: 200 description: | Duration of silence to detect speech stop (in milliseconds). With shorter values the model will respond more quickly, but may jump in on short pauses from the user. threshold: type: number default: 0.5 description: | Sensitivity threshold (0.0 to 1.0) for voice activity detection. A higher threshold will require louder audio to activate the model, and thus might perform better in noisy environments. ValidateGraderRequest: type: object title: ValidateGraderRequest properties: grader: type: object description: The grader used for the fine-tuning job. anyOf: - $ref: '#/components/schemas/GraderStringCheck' - $ref: '#/components/schemas/GraderTextSimilarity' - $ref: '#/components/schemas/GraderPython' - $ref: '#/components/schemas/GraderScoreModel' - $ref: '#/components/schemas/GraderMulti' required: - grader ValidateGraderResponse: type: object title: ValidateGraderResponse properties: grader: type: object description: The grader used for the fine-tuning job. anyOf: - $ref: '#/components/schemas/GraderStringCheck' - $ref: '#/components/schemas/GraderTextSimilarity' - $ref: '#/components/schemas/GraderPython' - $ref: '#/components/schemas/GraderScoreModel' - $ref: '#/components/schemas/GraderMulti' VectorStoreExpirationAfter: type: object title: Vector store expiration policy description: The expiration policy for a vector store. properties: anchor: description: 'Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.' type: string enum: - last_active_at x-stainless-const: true days: description: The number of days after the anchor time that the vector store will expire. type: integer minimum: 1 maximum: 365 required: - anchor - days VectorStoreFileAttributes: type: object description: | Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters, booleans, or numbers. maxProperties: 16 propertyNames: type: string maxLength: 64 additionalProperties: anyOf: - type: string maxLength: 512 - type: number - type: boolean x-oaiTypeLabel: map nullable: true VectorStoreFileBatchObject: type: object title: Vector store file batch description: A batch of files attached to a vector store. properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: description: The object type, which is always `vector_store.file_batch`. type: string enum: - vector_store.files_batch x-stainless-const: true created_at: description: The Unix timestamp (in seconds) for when the vector store files batch was created. type: integer vector_store_id: description: >- The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to. type: string status: description: >- The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. type: string enum: - in_progress - completed - cancelled - failed file_counts: type: object properties: in_progress: description: The number of files that are currently being processed. type: integer completed: description: The number of files that have been processed. type: integer failed: description: The number of files that have failed to process. type: integer cancelled: description: The number of files that where cancelled. type: integer total: description: The total number of files. type: integer required: - in_progress - completed - cancelled - failed - total required: - id - object - created_at - vector_store_id - status - file_counts x-oaiMeta: name: The vector store files batch object beta: true example: | { "id": "vsfb_123", "object": "vector_store.files_batch", "created_at": 1698107661, "vector_store_id": "vs_abc123", "status": "completed", "file_counts": { "in_progress": 0, "completed": 100, "failed": 0, "cancelled": 0, "total": 100 } } VectorStoreFileContentResponse: type: object description: Represents the parsed content of a vector store file. properties: object: type: string enum: - vector_store.file_content.page description: The object type, which is always `vector_store.file_content.page` x-stainless-const: true data: type: array description: Parsed content of the file. items: type: object properties: type: type: string description: The content type (currently only `"text"`) text: type: string description: The text content has_more: type: boolean description: Indicates if there are more content pages to fetch. next_page: type: string description: The token for the next page, if any. nullable: true required: - object - data - has_more - next_page VectorStoreFileObject: type: object title: Vector store files description: A list of files attached to a vector store. properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: description: The object type, which is always `vector_store.file`. type: string enum: - vector_store.file x-stainless-const: true usage_bytes: description: >- The total vector store usage in bytes. Note that this may be different from the original file size. type: integer created_at: description: The Unix timestamp (in seconds) for when the vector store file was created. type: integer vector_store_id: description: >- The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to. type: string status: description: >- The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. type: string enum: - in_progress - completed - cancelled - failed last_error: type: object description: The last error associated with this vector store file. Will be `null` if there are no errors. nullable: true properties: code: type: string description: One of `server_error` or `rate_limit_exceeded`. enum: - server_error - unsupported_file - invalid_file message: type: string description: A human-readable description of the error. required: - code - message chunking_strategy: $ref: '#/components/schemas/ChunkingStrategyResponse' attributes: $ref: '#/components/schemas/VectorStoreFileAttributes' required: - id - object - usage_bytes - created_at - vector_store_id - status - last_error x-oaiMeta: name: The vector store file object beta: true example: | { "id": "file-abc123", "object": "vector_store.file", "usage_bytes": 1234, "created_at": 1698107661, "vector_store_id": "vs_abc123", "status": "completed", "last_error": null, "chunking_strategy": { "type": "static", "static": { "max_chunk_size_tokens": 800, "chunk_overlap_tokens": 400 } } } VectorStoreObject: type: object title: Vector store description: A vector store is a collection of processed files can be used by the `file_search` tool. properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: description: The object type, which is always `vector_store`. type: string enum: - vector_store x-stainless-const: true created_at: description: The Unix timestamp (in seconds) for when the vector store was created. type: integer name: description: The name of the vector store. type: string usage_bytes: description: The total number of bytes used by the files in the vector store. type: integer file_counts: type: object properties: in_progress: description: The number of files that are currently being processed. type: integer completed: description: The number of files that have been successfully processed. type: integer failed: description: The number of files that have failed to process. type: integer cancelled: description: The number of files that were cancelled. type: integer total: description: The total number of files. type: integer required: - in_progress - completed - failed - cancelled - total status: description: >- The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. type: string enum: - expired - in_progress - completed expires_after: $ref: '#/components/schemas/VectorStoreExpirationAfter' expires_at: description: The Unix timestamp (in seconds) for when the vector store will expire. type: integer nullable: true last_active_at: description: The Unix timestamp (in seconds) for when the vector store was last active. type: integer nullable: true metadata: $ref: '#/components/schemas/Metadata' required: - id - object - usage_bytes - created_at - status - last_active_at - name - file_counts - metadata x-oaiMeta: name: The vector store object example: | { "id": "vs_123", "object": "vector_store", "created_at": 1698107661, "usage_bytes": 123456, "last_active_at": 1698107661, "name": "my_vector_store", "status": "completed", "file_counts": { "in_progress": 0, "completed": 100, "cancelled": 0, "failed": 0, "total": 100 }, "last_used_at": 1698107661 } VectorStoreSearchRequest: type: object additionalProperties: false properties: query: description: A query string for a search anyOf: - type: string - type: array items: type: string description: A list of queries to search for. minItems: 1 rewrite_query: description: Whether to rewrite the natural language query for vector search. type: boolean default: false max_num_results: description: The maximum number of results to return. This number should be between 1 and 50 inclusive. type: integer default: 10 minimum: 1 maximum: 50 filters: description: A filter to apply based on file attributes. anyOf: - $ref: '#/components/schemas/ComparisonFilter' - $ref: '#/components/schemas/CompoundFilter' ranking_options: description: Ranking options for search. type: object additionalProperties: false properties: ranker: description: Enable re-ranking; set to `none` to disable, which can help reduce latency. type: string enum: - none - auto - default-2024-11-15 default: auto score_threshold: type: number minimum: 0 maximum: 1 default: 0 required: - query x-oaiMeta: name: Vector store search request VectorStoreSearchResultContentObject: type: object additionalProperties: false properties: type: description: The type of content. type: string enum: - text text: description: The text content returned from search. type: string required: - type - text x-oaiMeta: name: Vector store search result content object VectorStoreSearchResultItem: type: object additionalProperties: false properties: file_id: type: string description: The ID of the vector store file. filename: type: string description: The name of the vector store file. score: type: number description: The similarity score for the result. minimum: 0 maximum: 1 attributes: $ref: '#/components/schemas/VectorStoreFileAttributes' content: type: array description: Content chunks from the file. items: $ref: '#/components/schemas/VectorStoreSearchResultContentObject' required: - file_id - filename - score - attributes - content x-oaiMeta: name: Vector store search result item VectorStoreSearchResultsPage: type: object additionalProperties: false properties: object: type: string enum: - vector_store.search_results.page description: The object type, which is always `vector_store.search_results.page` x-stainless-const: true search_query: type: array items: type: string description: The query used for this search. minItems: 1 data: type: array description: The list of search result items. items: $ref: '#/components/schemas/VectorStoreSearchResultItem' has_more: type: boolean description: Indicates if there are more results to fetch. next_page: type: string description: The token for the next page, if any. nullable: true required: - object - search_query - data - has_more - next_page x-oaiMeta: name: Vector store search results page Verbosity: type: string enum: - low - medium - high default: medium nullable: true description: | Constrains the verbosity of the model's response. Lower values will result in more concise responses, while higher values will result in more verbose responses. Currently supported values are `low`, `medium`, and `high`. VoiceIdsShared: example: ash anyOf: - type: string - type: string enum: - alloy - ash - ballad - coral - echo - sage - shimmer - verse Wait: type: object title: Wait description: | A wait action. properties: type: type: string enum: - wait default: wait description: | Specifies the event type. For a wait action, this property is always set to `wait`. x-stainless-const: true required: - type WebSearchActionFind: type: object title: Find action description: | Action type "find": Searches for a pattern within a loaded page. properties: type: type: string enum: - find description: | The action type. x-stainless-const: true url: type: string format: uri description: | The URL of the page searched for the pattern. pattern: type: string description: | The pattern or text to search for within the page. required: - type - url - pattern WebSearchActionOpenPage: type: object title: Open page action description: | Action type "open_page" - Opens a specific URL from search results. properties: type: type: string enum: - open_page description: | The action type. x-stainless-const: true url: type: string format: uri description: | The URL opened by the model. required: - type - url WebSearchActionSearch: type: object title: Search action description: | Action type "search" - Performs a web search query. properties: type: type: string enum: - search description: | The action type. x-stainless-const: true query: type: string description: | The search query. required: - type - query WebSearchContextSize: type: string description: | High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default. enum: - low - medium - high default: medium WebSearchLocation: type: object title: Web search location description: Approximate location parameters for the search. properties: country: type: string description: | The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. region: type: string description: | Free text input for the region of the user, e.g. `California`. city: type: string description: | Free text input for the city of the user, e.g. `San Francisco`. timezone: type: string description: | The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. WebSearchToolCall: type: object title: Web search tool call description: | The results of a web search tool call. See the [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information. properties: id: type: string description: | The unique ID of the web search tool call. type: type: string enum: - web_search_call description: | The type of the web search tool call. Always `web_search_call`. x-stainless-const: true status: type: string description: | The status of the web search tool call. enum: - in_progress - searching - completed - failed action: type: object description: | An object describing the specific action taken in this web search call. Includes details on how the model used the web (search, open_page, find). anyOf: - $ref: '#/components/schemas/WebSearchActionSearch' - $ref: '#/components/schemas/WebSearchActionOpenPage' - $ref: '#/components/schemas/WebSearchActionFind' discriminator: propertyName: type required: - id - type - status - action WebhookBatchCancelled: type: object title: batch.cancelled description: | Sent when a batch API request has been cancelled. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the batch API request was cancelled. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the batch API request. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `batch.cancelled`. enum: - batch.cancelled x-stainless-const: true x-oaiMeta: name: batch.cancelled group: webhook-events example: | { "id": "evt_abc123", "type": "batch.cancelled", "created_at": 1719168000, "data": { "id": "batch_abc123" } } WebhookBatchCompleted: type: object title: batch.completed description: | Sent when a batch API request has been completed. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the batch API request was completed. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the batch API request. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `batch.completed`. enum: - batch.completed x-stainless-const: true x-oaiMeta: name: batch.completed group: webhook-events example: | { "id": "evt_abc123", "type": "batch.completed", "created_at": 1719168000, "data": { "id": "batch_abc123" } } WebhookBatchExpired: type: object title: batch.expired description: | Sent when a batch API request has expired. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the batch API request expired. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the batch API request. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `batch.expired`. enum: - batch.expired x-stainless-const: true x-oaiMeta: name: batch.expired group: webhook-events example: | { "id": "evt_abc123", "type": "batch.expired", "created_at": 1719168000, "data": { "id": "batch_abc123" } } WebhookBatchFailed: type: object title: batch.failed description: | Sent when a batch API request has failed. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the batch API request failed. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the batch API request. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `batch.failed`. enum: - batch.failed x-stainless-const: true x-oaiMeta: name: batch.failed group: webhook-events example: | { "id": "evt_abc123", "type": "batch.failed", "created_at": 1719168000, "data": { "id": "batch_abc123" } } WebhookEvalRunCanceled: type: object title: eval.run.canceled description: | Sent when an eval run has been canceled. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the eval run was canceled. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the eval run. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `eval.run.canceled`. enum: - eval.run.canceled x-stainless-const: true x-oaiMeta: name: eval.run.canceled group: webhook-events example: | { "id": "evt_abc123", "type": "eval.run.canceled", "created_at": 1719168000, "data": { "id": "evalrun_abc123" } } WebhookEvalRunFailed: type: object title: eval.run.failed description: | Sent when an eval run has failed. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the eval run failed. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the eval run. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `eval.run.failed`. enum: - eval.run.failed x-stainless-const: true x-oaiMeta: name: eval.run.failed group: webhook-events example: | { "id": "evt_abc123", "type": "eval.run.failed", "created_at": 1719168000, "data": { "id": "evalrun_abc123" } } WebhookEvalRunSucceeded: type: object title: eval.run.succeeded description: | Sent when an eval run has succeeded. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the eval run succeeded. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the eval run. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `eval.run.succeeded`. enum: - eval.run.succeeded x-stainless-const: true x-oaiMeta: name: eval.run.succeeded group: webhook-events example: | { "id": "evt_abc123", "type": "eval.run.succeeded", "created_at": 1719168000, "data": { "id": "evalrun_abc123" } } WebhookFineTuningJobCancelled: type: object title: fine_tuning.job.cancelled description: | Sent when a fine-tuning job has been cancelled. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the fine-tuning job was cancelled. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the fine-tuning job. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `fine_tuning.job.cancelled`. enum: - fine_tuning.job.cancelled x-stainless-const: true x-oaiMeta: name: fine_tuning.job.cancelled group: webhook-events example: | { "id": "evt_abc123", "type": "fine_tuning.job.cancelled", "created_at": 1719168000, "data": { "id": "ftjob_abc123" } } WebhookFineTuningJobFailed: type: object title: fine_tuning.job.failed description: | Sent when a fine-tuning job has failed. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the fine-tuning job failed. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the fine-tuning job. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `fine_tuning.job.failed`. enum: - fine_tuning.job.failed x-stainless-const: true x-oaiMeta: name: fine_tuning.job.failed group: webhook-events example: | { "id": "evt_abc123", "type": "fine_tuning.job.failed", "created_at": 1719168000, "data": { "id": "ftjob_abc123" } } WebhookFineTuningJobSucceeded: type: object title: fine_tuning.job.succeeded description: | Sent when a fine-tuning job has succeeded. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the fine-tuning job succeeded. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the fine-tuning job. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `fine_tuning.job.succeeded`. enum: - fine_tuning.job.succeeded x-stainless-const: true x-oaiMeta: name: fine_tuning.job.succeeded group: webhook-events example: | { "id": "evt_abc123", "type": "fine_tuning.job.succeeded", "created_at": 1719168000, "data": { "id": "ftjob_abc123" } } WebhookResponseCancelled: type: object title: response.cancelled description: | Sent when a background response has been cancelled. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the model response was cancelled. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the model response. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `response.cancelled`. enum: - response.cancelled x-stainless-const: true x-oaiMeta: name: response.cancelled group: webhook-events example: | { "id": "evt_abc123", "type": "response.cancelled", "created_at": 1719168000, "data": { "id": "resp_abc123" } } WebhookResponseCompleted: type: object title: response.completed description: | Sent when a background response has been completed. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the model response was completed. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the model response. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `response.completed`. enum: - response.completed x-stainless-const: true x-oaiMeta: name: response.completed group: webhook-events example: | { "id": "evt_abc123", "type": "response.completed", "created_at": 1719168000, "data": { "id": "resp_abc123" } } WebhookResponseFailed: type: object title: response.failed description: | Sent when a background response has failed. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the model response failed. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the model response. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `response.failed`. enum: - response.failed x-stainless-const: true x-oaiMeta: name: response.failed group: webhook-events example: | { "id": "evt_abc123", "type": "response.failed", "created_at": 1719168000, "data": { "id": "resp_abc123" } } WebhookResponseIncomplete: type: object title: response.incomplete description: | Sent when a background response has been interrupted. required: - created_at - id - data - type properties: created_at: type: integer description: | The Unix timestamp (in seconds) of when the model response was interrupted. id: type: string description: | The unique ID of the event. data: type: object description: | Event data payload. required: - id properties: id: type: string description: | The unique ID of the model response. object: type: string description: | The object of the event. Always `event`. enum: - event x-stainless-const: true type: type: string description: | The type of the event. Always `response.incomplete`. enum: - response.incomplete x-stainless-const: true x-oaiMeta: name: response.incomplete group: webhook-events example: | { "id": "evt_abc123", "type": "response.incomplete", "created_at": 1719168000, "data": { "id": "resp_abc123" } } InputTextContent: properties: type: type: string enum: - input_text description: The type of the input item. Always `input_text`. default: input_text x-stainless-const: true text: type: string description: The text input to the model. type: object required: - type - text title: Input text description: A text input to the model. InputImageContent: properties: type: type: string enum: - input_image description: The type of the input item. Always `input_image`. default: input_image x-stainless-const: true image_url: anyOf: - type: string description: >- The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL. - type: 'null' file_id: anyOf: - type: string description: The ID of the file to be sent to the model. - type: 'null' detail: type: string enum: - low - high - auto description: >- The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. type: object required: - type - detail title: Input image description: >- An image input to the model. Learn about [image inputs](https://platform.openai.com/docs/guides/vision). InputFileContent: properties: type: type: string enum: - input_file description: The type of the input item. Always `input_file`. default: input_file x-stainless-const: true file_id: anyOf: - type: string description: The ID of the file to be sent to the model. - type: 'null' filename: type: string description: The name of the file to be sent to the model. file_url: type: string description: The URL of the file to be sent to the model. file_data: type: string description: | The content of the file to be sent to the model. type: object required: - type title: Input file description: A file input to the model. FunctionTool: properties: type: type: string enum: - function description: The type of the function tool. Always `function`. default: function x-stainless-const: true name: type: string description: The name of the function to call. description: anyOf: - type: string description: >- A description of the function. Used by the model to determine whether or not to call the function. - type: 'null' parameters: anyOf: - additionalProperties: {} type: object description: A JSON schema object describing the parameters of the function. - type: 'null' strict: anyOf: - type: boolean description: Whether to enforce strict parameter validation. Default `true`. - type: 'null' type: object required: - type - name - strict - parameters title: Function description: >- Defines a function in your own code the model can choose to call. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). RankingOptions: properties: ranker: type: string enum: - auto - default-2024-11-15 description: The ranker to use for the file search. score_threshold: type: number description: >- The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results. type: object required: [] Filters: anyOf: - $ref: '#/components/schemas/ComparisonFilter' - $ref: '#/components/schemas/CompoundFilter' FileSearchTool: properties: type: type: string enum: - file_search description: The type of the file search tool. Always `file_search`. default: file_search x-stainless-const: true vector_store_ids: items: type: string type: array description: The IDs of the vector stores to search. max_num_results: type: integer description: The maximum number of results to return. This number should be between 1 and 50 inclusive. ranking_options: $ref: '#/components/schemas/RankingOptions' description: Ranking options for search. filters: anyOf: - $ref: '#/components/schemas/Filters' description: A filter to apply. - type: 'null' type: object required: - type - vector_store_ids title: File search description: >- A tool that searches for relevant content from uploaded files. Learn more about the [file search tool](https://platform.openai.com/docs/guides/tools-file-search). ApproximateLocation: properties: type: type: string enum: - approximate description: The type of location approximation. Always `approximate`. default: approximate x-stainless-const: true country: anyOf: - type: string description: >- The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. - type: 'null' region: anyOf: - type: string description: Free text input for the region of the user, e.g. `California`. - type: 'null' city: anyOf: - type: string description: Free text input for the city of the user, e.g. `San Francisco`. - type: 'null' timezone: anyOf: - type: string description: >- The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. - type: 'null' type: object required: - type WebSearchPreviewTool: properties: type: type: string enum: - web_search_preview - web_search_preview_2025_03_11 description: The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. default: web_search_preview x-stainless-const: true user_location: anyOf: - $ref: '#/components/schemas/ApproximateLocation' description: The user's location. - type: 'null' search_context_size: type: string enum: - low - medium - high description: >- High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default. type: object required: - type title: Web search preview description: >- This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search). ComputerUsePreviewTool: properties: type: type: string enum: - computer_use_preview description: The type of the computer use tool. Always `computer_use_preview`. default: computer_use_preview x-stainless-const: true environment: type: string enum: - windows - mac - linux - ubuntu - browser description: The type of computer environment to control. display_width: type: integer description: The width of the computer display. display_height: type: integer description: The height of the computer display. type: object required: - type - environment - display_width - display_height title: Computer use preview description: >- A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use). ImageGenInputUsageDetails: properties: text_tokens: type: integer description: The number of text tokens in the input prompt. image_tokens: type: integer description: The number of image tokens in the input prompt. type: object required: - text_tokens - image_tokens title: Input usage details description: The input tokens detailed information for the image generation. ImageGenUsage: properties: input_tokens: type: integer description: The number of tokens (images and text) in the input prompt. total_tokens: type: integer description: The total number of tokens (images and text) used for the image generation. output_tokens: type: integer description: The number of output tokens generated by the model. input_tokens_details: $ref: '#/components/schemas/ImageGenInputUsageDetails' type: object required: - input_tokens - total_tokens - output_tokens - input_tokens_details title: Image generation usage description: For `gpt-image-1` only, the token usage information for the image generation. FileCitationBody: properties: type: type: string enum: - file_citation description: The type of the file citation. Always `file_citation`. default: file_citation x-stainless-const: true file_id: type: string description: The ID of the file. index: type: integer description: The index of the file in the list of files. filename: type: string description: The filename of the file cited. type: object required: - type - file_id - index - filename title: File citation description: A citation to a file. UrlCitationBody: properties: type: type: string enum: - url_citation description: The type of the URL citation. Always `url_citation`. default: url_citation x-stainless-const: true url: type: string description: The URL of the web resource. start_index: type: integer description: The index of the first character of the URL citation in the message. end_index: type: integer description: The index of the last character of the URL citation in the message. title: type: string description: The title of the web resource. type: object required: - type - url - start_index - end_index - title title: URL citation description: A citation for a web resource used to generate a model response. ContainerFileCitationBody: properties: type: type: string enum: - container_file_citation description: The type of the container file citation. Always `container_file_citation`. default: container_file_citation x-stainless-const: true container_id: type: string description: The ID of the container file. file_id: type: string description: The ID of the file. start_index: type: integer description: The index of the first character of the container file citation in the message. end_index: type: integer description: The index of the last character of the container file citation in the message. filename: type: string description: The filename of the container file cited. type: object required: - type - container_id - file_id - start_index - end_index - filename title: Container file citation description: A citation for a container file used to generate a model response. Annotation: discriminator: propertyName: type anyOf: - $ref: '#/components/schemas/FileCitationBody' - $ref: '#/components/schemas/UrlCitationBody' - $ref: '#/components/schemas/ContainerFileCitationBody' - $ref: '#/components/schemas/FilePath' TopLogProb: properties: token: type: string logprob: type: number bytes: items: type: integer type: array type: object required: - token - logprob - bytes title: Top log probability description: The top log probability of a token. LogProb: properties: token: type: string logprob: type: number bytes: items: type: integer type: array top_logprobs: items: $ref: '#/components/schemas/TopLogProb' type: array type: object required: - token - logprob - bytes - top_logprobs title: Log probability description: The log probability of a token. OutputTextContent: properties: type: type: string enum: - output_text description: The type of the output text. Always `output_text`. default: output_text x-stainless-const: true text: type: string description: The text output from the model. annotations: items: $ref: '#/components/schemas/Annotation' type: array description: The annotations of the text output. logprobs: items: $ref: '#/components/schemas/LogProb' type: array type: object required: - type - text - annotations title: Output text description: A text output from the model. RefusalContent: properties: type: type: string enum: - refusal description: The type of the refusal. Always `refusal`. default: refusal x-stainless-const: true refusal: type: string description: The refusal explanation from the model. type: object required: - type - refusal title: Refusal description: A refusal from the model. ComputerCallSafetyCheckParam: properties: id: type: string description: The ID of the pending safety check. code: anyOf: - type: string description: The type of the pending safety check. - type: 'null' message: anyOf: - type: string description: Details about the pending safety check. - type: 'null' type: object required: - id description: A pending safety check for the computer call. ComputerCallOutputItemParam: properties: id: anyOf: - type: string description: The ID of the computer tool call output. - type: 'null' call_id: type: string maxLength: 64 minLength: 1 description: The ID of the computer tool call that produced the output. type: type: string enum: - computer_call_output description: The type of the computer tool call output. Always `computer_call_output`. default: computer_call_output x-stainless-const: true output: $ref: '#/components/schemas/ComputerScreenshotImage' acknowledged_safety_checks: anyOf: - items: $ref: '#/components/schemas/ComputerCallSafetyCheckParam' type: array description: The safety checks reported by the API that have been acknowledged by the developer. - type: 'null' status: anyOf: - type: string enum: - in_progress - completed - incomplete description: >- The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. - type: 'null' type: object required: - call_id - type - output title: Computer tool call output description: The output of a computer tool call. FunctionCallOutputItemParam: properties: id: anyOf: - type: string description: The unique ID of the function tool call output. Populated when this item is returned via API. - type: 'null' call_id: type: string maxLength: 64 minLength: 1 description: The unique ID of the function tool call generated by the model. type: type: string enum: - function_call_output description: The type of the function tool call output. Always `function_call_output`. default: function_call_output x-stainless-const: true output: type: string maxLength: 10485760 description: A JSON string of the output of the function tool call. status: anyOf: - type: string enum: - in_progress - completed - incomplete description: >- The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. - type: 'null' type: object required: - call_id - type - output title: Function tool call output description: The output of a function tool call. ItemReferenceParam: properties: type: anyOf: - type: string enum: - item_reference description: The type of item to reference. Always `item_reference`. default: item_reference x-stainless-const: true - type: 'null' id: type: string description: The ID of the item to reference. type: object required: - id title: Item reference description: An internal identifier for an item to reference. RealtimeConversationItemContent: type: object properties: type: type: string enum: - input_text - input_audio - item_reference - text - audio description: | The content type (`input_text`, `input_audio`, `item_reference`, `text`, `audio`). text: type: string description: | The text content, used for `input_text` and `text` content types. id: type: string description: | ID of a previous conversation item to reference (for `item_reference` content types in `response.create` events). These can reference both client and server created items. audio: type: string description: | Base64-encoded audio bytes, used for `input_audio` content type. transcript: type: string description: | The transcript of the audio, used for `input_audio` and `audio` content types. RealtimeConnectParams: type: object properties: model: type: string required: - model ModerationImageURLInput: type: object description: An object describing an image to classify. properties: type: description: Always `image_url`. type: string enum: - image_url x-stainless-const: true image_url: type: object description: Contains either an image URL or a data URL for a base64 encoded image. properties: url: type: string description: Either a URL of the image or the base64 encoded image data. format: uri example: https://example.com/image.jpg required: - url required: - type - image_url ModerationTextInput: type: object description: An object describing text to classify. properties: type: description: Always `text`. type: string enum: - text x-stainless-const: true text: description: A string of text to classify. type: string example: I want to kill them required: - type - text ChunkingStrategyResponse: type: object description: The strategy used to chunk the file. anyOf: - $ref: '#/components/schemas/StaticChunkingStrategyResponseParam' - $ref: '#/components/schemas/OtherChunkingStrategyResponseParam' discriminator: propertyName: type FilePurpose: description: > The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets type: string enum: - assistants - batch - fine-tune - vision - user_data - evals BatchError: type: object properties: code: type: string description: An error code identifying the error type. message: type: string description: A human-readable message providing more details about the error. param: type: string description: The name of the parameter that caused the error, if applicable. nullable: true line: type: integer description: The line number of the input file where the error occurred, if applicable. nullable: true BatchRequestCounts: type: object properties: total: type: integer description: Total number of requests in the batch. completed: type: integer description: Number of requests that have been completed successfully. failed: type: integer description: Number of requests that have failed. required: - total - completed - failed description: The request counts for different statuses within the batch. AssistantTool: anyOf: - $ref: '#/components/schemas/AssistantToolsCode' - $ref: '#/components/schemas/AssistantToolsFileSearch' - $ref: '#/components/schemas/AssistantToolsFunction' discriminator: propertyName: type TextAnnotationDelta: anyOf: - $ref: '#/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject' - $ref: '#/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject' discriminator: propertyName: type TextAnnotation: anyOf: - $ref: '#/components/schemas/MessageContentTextAnnotationsFileCitationObject' - $ref: '#/components/schemas/MessageContentTextAnnotationsFilePathObject' discriminator: propertyName: type RunStepDetailsToolCall: anyOf: - $ref: '#/components/schemas/RunStepDetailsToolCallsCodeObject' - $ref: '#/components/schemas/RunStepDetailsToolCallsFileSearchObject' - $ref: '#/components/schemas/RunStepDetailsToolCallsFunctionObject' discriminator: propertyName: type RunStepDeltaStepDetailsToolCall: anyOf: - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject' - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject' - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject' discriminator: propertyName: type MessageContent: anyOf: - $ref: '#/components/schemas/MessageContentImageFileObject' - $ref: '#/components/schemas/MessageContentImageUrlObject' - $ref: '#/components/schemas/MessageContentTextObject' - $ref: '#/components/schemas/MessageContentRefusalObject' discriminator: propertyName: type MessageContentDelta: anyOf: - $ref: '#/components/schemas/MessageDeltaContentImageFileObject' - $ref: '#/components/schemas/MessageDeltaContentTextObject' - $ref: '#/components/schemas/MessageDeltaContentRefusalObject' - $ref: '#/components/schemas/MessageDeltaContentImageUrlObject' discriminator: propertyName: type ChatModel: type: string enum: - gpt-5 - gpt-5-mini - gpt-5-nano - gpt-5-2025-08-07 - gpt-5-mini-2025-08-07 - gpt-5-nano-2025-08-07 - gpt-5-chat-latest - gpt-4.1 - gpt-4.1-mini - gpt-4.1-nano - gpt-4.1-2025-04-14 - gpt-4.1-mini-2025-04-14 - gpt-4.1-nano-2025-04-14 - o4-mini - o4-mini-2025-04-16 - o3 - o3-2025-04-16 - o3-mini - o3-mini-2025-01-31 - o1 - o1-2024-12-17 - o1-preview - o1-preview-2024-09-12 - o1-mini - o1-mini-2024-09-12 - gpt-4o - gpt-4o-2024-11-20 - gpt-4o-2024-08-06 - gpt-4o-2024-05-13 - gpt-4o-audio-preview - gpt-4o-audio-preview-2024-10-01 - gpt-4o-audio-preview-2024-12-17 - gpt-4o-audio-preview-2025-06-03 - gpt-4o-mini-audio-preview - gpt-4o-mini-audio-preview-2024-12-17 - gpt-4o-search-preview - gpt-4o-mini-search-preview - gpt-4o-search-preview-2025-03-11 - gpt-4o-mini-search-preview-2025-03-11 - chatgpt-4o-latest - codex-mini-latest - gpt-4o-mini - gpt-4o-mini-2024-07-18 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview - gpt-4-turbo-preview - gpt-4-1106-preview - gpt-4-vision-preview - gpt-4 - gpt-4-0314 - gpt-4-0613 - gpt-4-32k - gpt-4-32k-0314 - gpt-4-32k-0613 - gpt-3.5-turbo - gpt-3.5-turbo-16k - gpt-3.5-turbo-0301 - gpt-3.5-turbo-0613 - gpt-3.5-turbo-1106 - gpt-3.5-turbo-0125 - gpt-3.5-turbo-16k-0613 x-stainless-nominal: false CreateThreadAndRunRequestWithoutStream: type: object additionalProperties: false properties: assistant_id: description: >- The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. type: string thread: $ref: '#/components/schemas/CreateThreadRequest' model: description: >- The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. anyOf: - type: string - type: string enum: - gpt-5 - gpt-5-mini - gpt-5-nano - gpt-5-2025-08-07 - gpt-5-mini-2025-08-07 - gpt-5-nano-2025-08-07 - gpt-4.1 - gpt-4.1-mini - gpt-4.1-nano - gpt-4.1-2025-04-14 - gpt-4.1-mini-2025-04-14 - gpt-4.1-nano-2025-04-14 - gpt-4o - gpt-4o-2024-11-20 - gpt-4o-2024-08-06 - gpt-4o-2024-05-13 - gpt-4o-mini - gpt-4o-mini-2024-07-18 - gpt-4.5-preview - gpt-4.5-preview-2025-02-27 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview - gpt-4-turbo-preview - gpt-4-1106-preview - gpt-4-vision-preview - gpt-4 - gpt-4-0314 - gpt-4-0613 - gpt-4-32k - gpt-4-32k-0314 - gpt-4-32k-0613 - gpt-3.5-turbo - gpt-3.5-turbo-16k - gpt-3.5-turbo-0613 - gpt-3.5-turbo-1106 - gpt-3.5-turbo-0125 - gpt-3.5-turbo-16k-0613 x-oaiTypeLabel: string nullable: true instructions: description: >- Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. type: string nullable: true tools: description: >- Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. nullable: true type: array maxItems: 20 items: $ref: '#/components/schemas/AssistantTool' tool_resources: type: object description: > A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: code_interpreter: type: object properties: file_ids: type: array description: > A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] maxItems: 20 items: type: string file_search: type: object properties: vector_store_ids: type: array description: > The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. maxItems: 1 items: type: string nullable: true metadata: $ref: '#/components/schemas/Metadata' temperature: type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. max_prompt_tokens: type: integer nullable: true description: > The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 max_completion_tokens: type: integer nullable: true description: > The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 truncation_strategy: allOf: - $ref: '#/components/schemas/TruncationObject' - nullable: true tool_choice: allOf: - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - nullable: true parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true required: *ref_0 CreateRunRequestWithoutStream: type: object additionalProperties: false properties: assistant_id: description: >- The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. type: string model: description: >- The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. anyOf: - type: string - $ref: '#/components/schemas/AssistantSupportedModels' x-oaiTypeLabel: string nullable: true reasoning_effort: $ref: '#/components/schemas/ReasoningEffort' instructions: description: >- Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. type: string nullable: true additional_instructions: description: >- Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. type: string nullable: true additional_messages: description: Adds additional messages to the thread before creating the run. type: array items: $ref: '#/components/schemas/CreateMessageRequest' nullable: true tools: description: >- Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. nullable: true type: array maxItems: 20 items: $ref: '#/components/schemas/AssistantTool' metadata: $ref: '#/components/schemas/Metadata' temperature: type: number minimum: 0 maximum: 2 default: 1 example: 1 nullable: true description: > What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. top_p: type: number minimum: 0 maximum: 1 default: 1 example: 1 nullable: true description: > An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. max_prompt_tokens: type: integer nullable: true description: > The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 max_completion_tokens: type: integer nullable: true description: > The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. minimum: 256 truncation_strategy: allOf: - $ref: '#/components/schemas/TruncationObject' - nullable: true tool_choice: allOf: - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - nullable: true parallel_tool_calls: $ref: '#/components/schemas/ParallelToolCalls' response_format: $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true required: *ref_0 SubmitToolOutputsRunRequestWithoutStream: type: object additionalProperties: false properties: tool_outputs: description: A list of tools for which the outputs are being submitted. type: array items: type: object properties: tool_call_id: type: string description: >- The ID of the tool call in the `required_action` object within the run object the output is being submitted for. output: type: string description: The output of the tool call to be submitted to continue the run. required: - tool_outputs RunStatus: description: >- The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`. type: string enum: - queued - in_progress - requires_action - cancelling - cancelled - failed - completed - incomplete - expired RunStepDeltaObjectDelta: description: The delta containing the fields that have changed on the run step. type: object properties: step_details: type: object description: The details of the run step. anyOf: - $ref: '#/components/schemas/RunStepDeltaStepDetailsMessageCreationObject' - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsObject' discriminator: propertyName: type securitySchemes: ApiKeyAuth: type: http scheme: bearer x-oaiMeta: navigationGroups: - id: responses title: Responses - id: webhooks title: Webhooks - id: endpoints title: Platform APIs - id: vector_stores title: Vector stores - id: containers title: Containers - id: realtime title: Realtime beta: true - id: chat title: Chat Completions - id: assistants title: Assistants beta: true - id: administration title: Administration - id: legacy title: Legacy groups: - id: responses title: Responses description: | OpenAI's most advanced interface for generating model responses. Supports text and image inputs, and text outputs. Create stateful interactions with the model, using the output of previous responses as input. Extend the model's capabilities with built-in tools for file search, web search, computer use, and more. Allow the model access to external systems and data using function calling. Related guides: - [Quickstart](https://platform.openai.com/docs/quickstart?api-mode=responses) - [Text inputs and outputs](https://platform.openai.com/docs/guides/text?api-mode=responses) - [Image inputs](https://platform.openai.com/docs/guides/images?api-mode=responses) - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses) - [Function calling](https://platform.openai.com/docs/guides/function-calling?api-mode=responses) - [Conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses) - [Extend the models with tools](https://platform.openai.com/docs/guides/tools?api-mode=responses) navigationGroup: responses sections: - type: endpoint key: createResponse path: create - type: endpoint key: getResponse path: get - type: endpoint key: deleteResponse path: delete - type: endpoint key: cancelResponse path: cancel - type: endpoint key: listInputItems path: input-items - type: object key: Response path: object - type: object key: ResponseItemList path: list - id: responses-streaming title: Streaming description: > When you [create a Response](https://platform.openai.com/docs/api-reference/responses/create) with `stream` set to `true`, the server will emit server-sent events to the client as the Response is generated. This section contains the events that are emitted by the server. [Learn more about streaming responses](https://platform.openai.com/docs/guides/streaming-responses?api-mode=responses). navigationGroup: responses sections: - type: object key: ResponseCreatedEvent path: - type: object key: ResponseInProgressEvent path: - type: object key: ResponseCompletedEvent path: - type: object key: ResponseFailedEvent path: - type: object key: ResponseIncompleteEvent path: - type: object key: ResponseOutputItemAddedEvent path: - type: object key: ResponseOutputItemDoneEvent path: - type: object key: ResponseContentPartAddedEvent path: - type: object key: ResponseContentPartDoneEvent path: - type: object key: ResponseTextDeltaEvent path: - type: object key: ResponseTextDoneEvent path: - type: object key: ResponseRefusalDeltaEvent path: - type: object key: ResponseRefusalDoneEvent path: - type: object key: ResponseFunctionCallArgumentsDeltaEvent path: - type: object key: ResponseFunctionCallArgumentsDoneEvent path: - type: object key: ResponseFileSearchCallInProgressEvent path: - type: object key: ResponseFileSearchCallSearchingEvent path: - type: object key: ResponseFileSearchCallCompletedEvent path: - type: object key: ResponseWebSearchCallInProgressEvent path: - type: object key: ResponseWebSearchCallSearchingEvent path: - type: object key: ResponseWebSearchCallCompletedEvent path: - type: object key: ResponseReasoningSummaryPartAddedEvent path: - type: object key: ResponseReasoningSummaryPartDoneEvent path: - type: object key: ResponseReasoningSummaryTextDeltaEvent path: - type: object key: ResponseReasoningSummaryTextDoneEvent path: - type: object key: ResponseReasoningTextDeltaEvent path: - type: object key: ResponseReasoningTextDoneEvent path: - type: object key: ResponseImageGenCallCompletedEvent path: - type: object key: ResponseImageGenCallGeneratingEvent path: - type: object key: ResponseImageGenCallInProgressEvent path: - type: object key: ResponseImageGenCallPartialImageEvent path: - type: object key: ResponseMCPCallArgumentsDeltaEvent path: - type: object key: ResponseMCPCallArgumentsDoneEvent path: - type: object key: ResponseMCPCallCompletedEvent path: - type: object key: ResponseMCPCallFailedEvent path: - type: object key: ResponseMCPCallInProgressEvent path: - type: object key: ResponseMCPListToolsCompletedEvent path: - type: object key: ResponseMCPListToolsFailedEvent path: - type: object key: ResponseMCPListToolsInProgressEvent path: - type: object key: ResponseCodeInterpreterCallInProgressEvent path: - type: object key: ResponseCodeInterpreterCallInterpretingEvent path: - type: object key: ResponseCodeInterpreterCallCompletedEvent path: - type: object key: ResponseCodeInterpreterCallCodeDeltaEvent path: - type: object key: ResponseCodeInterpreterCallCodeDoneEvent path: - type: object key: ResponseOutputTextAnnotationAddedEvent path: - type: object key: ResponseQueuedEvent path: - type: object key: ResponseCustomToolCallInputDeltaEvent path: - type: object key: ResponseCustomToolCallInputDoneEvent path: - type: object key: ResponseErrorEvent path: - id: webhook-events title: Webhook Events description: | Webhooks are HTTP requests sent by OpenAI to a URL you specify when certain events happen during the course of API usage. [Learn more about webhooks](https://platform.openai.com/docs/guides/webhooks). navigationGroup: webhooks sections: - type: object key: WebhookResponseCompleted path: - type: object key: WebhookResponseCancelled path: - type: object key: WebhookResponseFailed path: - type: object key: WebhookResponseIncomplete path: - type: object key: WebhookBatchCompleted path: - type: object key: WebhookBatchCancelled path: - type: object key: WebhookBatchExpired path: - type: object key: WebhookBatchFailed path: - type: object key: WebhookFineTuningJobSucceeded path: - type: object key: WebhookFineTuningJobFailed path: - type: object key: WebhookFineTuningJobCancelled path: - type: object key: WebhookEvalRunSucceeded path: - type: object key: WebhookEvalRunFailed path: - type: object key: WebhookEvalRunCanceled path: - id: audio title: Audio description: | Learn how to turn audio into text or text into audio. Related guide: [Speech to text](https://platform.openai.com/docs/guides/speech-to-text) navigationGroup: endpoints sections: - type: endpoint key: createSpeech path: createSpeech - type: endpoint key: createTranscription path: createTranscription - type: endpoint key: createTranslation path: createTranslation - type: object key: CreateTranscriptionResponseJson path: json-object - type: object key: CreateTranscriptionResponseVerboseJson path: verbose-json-object - type: object key: SpeechAudioDeltaEvent path: speech-audio-delta-event - type: object key: SpeechAudioDoneEvent path: speech-audio-done-event - type: object key: TranscriptTextDeltaEvent path: transcript-text-delta-event - type: object key: TranscriptTextDoneEvent path: transcript-text-done-event - id: images title: Images description: | Given a prompt and/or an input image, the model will generate a new image. Related guide: [Image generation](https://platform.openai.com/docs/guides/images) navigationGroup: endpoints sections: - type: endpoint key: createImage path: create - type: endpoint key: createImageEdit path: createEdit - type: endpoint key: createImageVariation path: createVariation - type: object key: ImagesResponse path: object - id: images-streaming title: Image Streaming description: | Stream image generation and editing in real time with server-sent events. [Learn more about image streaming](https://platform.openai.com/docs/guides/image-generation). navigationGroup: endpoints sections: - type: object key: ImageGenPartialImageEvent path: - type: object key: ImageGenCompletedEvent path: - type: object key: ImageEditPartialImageEvent path: - type: object key: ImageEditCompletedEvent path: - id: embeddings title: Embeddings description: > Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. Related guide: [Embeddings](https://platform.openai.com/docs/guides/embeddings) navigationGroup: endpoints sections: - type: endpoint key: createEmbedding path: create - type: object key: Embedding path: object - id: evals title: Evals description: | Create, manage, and run evals in the OpenAI platform. Related guide: [Evals](https://platform.openai.com/docs/guides/evals) navigationGroup: endpoints sections: - type: endpoint key: createEval path: create - type: endpoint key: getEval path: get - type: endpoint key: updateEval path: update - type: endpoint key: deleteEval path: delete - type: endpoint key: listEvals path: list - type: endpoint key: getEvalRuns path: getRuns - type: endpoint key: getEvalRun path: getRun - type: endpoint key: createEvalRun path: createRun - type: endpoint key: cancelEvalRun path: cancelRun - type: endpoint key: deleteEvalRun path: deleteRun - type: endpoint key: getEvalRunOutputItem path: getRunOutputItem - type: endpoint key: getEvalRunOutputItems path: getRunOutputItems - type: object key: Eval path: object - type: object key: EvalRun path: run-object - type: object key: EvalRunOutputItem path: run-output-item-object - id: fine-tuning title: Fine-tuning description: | Manage fine-tuning jobs to tailor a model to your specific training data. Related guide: [Fine-tune models](https://platform.openai.com/docs/guides/fine-tuning) navigationGroup: endpoints sections: - type: endpoint key: createFineTuningJob path: create - type: endpoint key: listPaginatedFineTuningJobs path: list - type: endpoint key: listFineTuningEvents path: list-events - type: endpoint key: listFineTuningJobCheckpoints path: list-checkpoints - type: endpoint key: listFineTuningCheckpointPermissions path: list-permissions - type: endpoint key: createFineTuningCheckpointPermission path: create-permission - type: endpoint key: deleteFineTuningCheckpointPermission path: delete-permission - type: endpoint key: retrieveFineTuningJob path: retrieve - type: endpoint key: cancelFineTuningJob path: cancel - type: endpoint key: resumeFineTuningJob path: resume - type: endpoint key: pauseFineTuningJob path: pause - type: object key: FineTuneChatRequestInput path: chat-input - type: object key: FineTunePreferenceRequestInput path: preference-input - type: object key: FineTuneReinforcementRequestInput path: reinforcement-input - type: object key: FineTuningJob path: object - type: object key: FineTuningJobEvent path: event-object - type: object key: FineTuningJobCheckpoint path: checkpoint-object - type: object key: FineTuningCheckpointPermission path: permission-object - id: graders title: Graders description: | Manage and run graders in the OpenAI platform. Related guide: [Graders](https://platform.openai.com/docs/guides/graders) navigationGroup: endpoints sections: - type: object key: GraderStringCheck path: string-check - type: object key: GraderTextSimilarity path: text-similarity - type: object key: GraderScoreModel path: score-model - type: object key: GraderLabelModel path: label-model - type: object key: GraderPython path: python - type: object key: GraderMulti path: multi - type: endpoint key: runGrader path: run - type: endpoint key: validateGrader path: validate beta: true - id: batch title: Batch description: > Create large batches of API requests for asynchronous processing. The Batch API returns completions within 24 hours for a 50% discount. Related guide: [Batch](https://platform.openai.com/docs/guides/batch) navigationGroup: endpoints sections: - type: endpoint key: createBatch path: create - type: endpoint key: retrieveBatch path: retrieve - type: endpoint key: cancelBatch path: cancel - type: endpoint key: listBatches path: list - type: object key: Batch path: object - type: object key: BatchRequestInput path: request-input - type: object key: BatchRequestOutput path: request-output - id: files title: Files description: > Files are used to upload documents that can be used with features like [Assistants](https://platform.openai.com/docs/api-reference/assistants), [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning), and [Batch API](https://platform.openai.com/docs/guides/batch). navigationGroup: endpoints sections: - type: endpoint key: createFile path: create - type: endpoint key: listFiles path: list - type: endpoint key: retrieveFile path: retrieve - type: endpoint key: deleteFile path: delete - type: endpoint key: downloadFile path: retrieve-contents - type: object key: OpenAIFile path: object - id: uploads title: Uploads description: | Allows you to upload large files in multiple parts. navigationGroup: endpoints sections: - type: endpoint key: createUpload path: create - type: endpoint key: addUploadPart path: add-part - type: endpoint key: completeUpload path: complete - type: endpoint key: cancelUpload path: cancel - type: object key: Upload path: object - type: object key: UploadPart path: part-object - id: models title: Models description: > List and describe the various models available in the API. You can refer to the [Models](https://platform.openai.com/docs/models) documentation to understand what models are available and the differences between them. navigationGroup: endpoints sections: - type: endpoint key: listModels path: list - type: endpoint key: retrieveModel path: retrieve - type: endpoint key: deleteModel path: delete - type: object key: Model path: object - id: moderations title: Moderations description: > Given text and/or image inputs, classifies if those inputs are potentially harmful across several categories. Related guide: [Moderations](https://platform.openai.com/docs/guides/moderation) navigationGroup: endpoints sections: - type: endpoint key: createModeration path: create - type: object key: CreateModerationResponse path: object - id: vector-stores title: Vector stores description: > Vector stores power semantic search for the Retrieval API and the `file_search` tool in the Responses and Assistants APIs. Related guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search) navigationGroup: vector_stores sections: - type: endpoint key: createVectorStore path: create - type: endpoint key: listVectorStores path: list - type: endpoint key: getVectorStore path: retrieve - type: endpoint key: modifyVectorStore path: modify - type: endpoint key: deleteVectorStore path: delete - type: endpoint key: searchVectorStore path: search - type: object key: VectorStoreObject path: object - id: vector-stores-files title: Vector store files description: | Vector store files represent files inside a vector store. Related guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search) navigationGroup: vector_stores sections: - type: endpoint key: createVectorStoreFile path: createFile - type: endpoint key: listVectorStoreFiles path: listFiles - type: endpoint key: getVectorStoreFile path: getFile - type: endpoint key: retrieveVectorStoreFileContent path: getContent - type: endpoint key: updateVectorStoreFileAttributes path: updateAttributes - type: endpoint key: deleteVectorStoreFile path: deleteFile - type: object key: VectorStoreFileObject path: file-object - id: vector-stores-file-batches title: Vector store file batches description: | Vector store file batches represent operations to add multiple files to a vector store. Related guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search) navigationGroup: vector_stores sections: - type: endpoint key: createVectorStoreFileBatch path: createBatch - type: endpoint key: getVectorStoreFileBatch path: getBatch - type: endpoint key: cancelVectorStoreFileBatch path: cancelBatch - type: endpoint key: listFilesInVectorStoreBatch path: listBatchFiles - type: object key: VectorStoreFileBatchObject path: batch-object - id: containers title: Containers description: | Create and manage containers for use with the Code Interpreter tool. navigationGroup: containers sections: - type: endpoint key: CreateContainer path: createContainers - type: endpoint key: ListContainers path: listContainers - type: endpoint key: RetrieveContainer path: retrieveContainer - type: endpoint key: DeleteContainer path: deleteContainer - type: object key: ContainerResource path: object - id: container-files title: Container Files description: | Create and manage container files for use with the Code Interpreter tool. navigationGroup: containers sections: - type: endpoint key: CreateContainerFile path: createContainerFile - type: endpoint key: ListContainerFiles path: listContainerFiles - type: endpoint key: RetrieveContainerFile path: retrieveContainerFile - type: endpoint key: RetrieveContainerFileContent path: retrieveContainerFileContent - type: endpoint key: DeleteContainerFile path: deleteContainerFile - type: object key: ContainerFileResource path: object - id: realtime title: Realtime beta: true description: | Communicate with a GPT-4o class model in real time using WebRTC or WebSockets. Supports text and audio inputs and ouputs, along with audio transcriptions. [Learn more about the Realtime API](https://platform.openai.com/docs/guides/realtime). navigationGroup: realtime - id: realtime-sessions title: Session tokens description: | REST API endpoint to generate ephemeral session tokens for use in client-side applications. navigationGroup: realtime sections: - type: endpoint key: create-realtime-session path: create - type: endpoint key: create-realtime-transcription-session path: create-transcription - type: object key: RealtimeSessionCreateResponse path: session_object - type: object key: RealtimeTranscriptionSessionCreateResponse path: transcription_session_object - id: realtime-client-events title: Client events description: | These are events that the OpenAI Realtime WebSocket server will accept from the client. navigationGroup: realtime sections: - type: object key: RealtimeClientEventSessionUpdate path: - type: object key: RealtimeClientEventInputAudioBufferAppend path: - type: object key: RealtimeClientEventInputAudioBufferCommit path: - type: object key: RealtimeClientEventInputAudioBufferClear path: - type: object key: RealtimeClientEventConversationItemCreate path: - type: object key: RealtimeClientEventConversationItemRetrieve path: - type: object key: RealtimeClientEventConversationItemTruncate path: - type: object key: RealtimeClientEventConversationItemDelete path: - type: object key: RealtimeClientEventResponseCreate path: - type: object key: RealtimeClientEventResponseCancel path: - type: object key: RealtimeClientEventTranscriptionSessionUpdate path: - type: object key: RealtimeClientEventOutputAudioBufferClear path: - id: realtime-server-events title: Server events description: | These are events emitted from the OpenAI Realtime WebSocket server to the client. navigationGroup: realtime sections: - type: object key: RealtimeServerEventError path: - type: object key: RealtimeServerEventSessionCreated path: - type: object key: RealtimeServerEventSessionUpdated path: - type: object key: RealtimeServerEventConversationCreated path: - type: object key: RealtimeServerEventConversationItemCreated path: - type: object key: RealtimeServerEventConversationItemRetrieved path: - type: object key: RealtimeServerEventConversationItemInputAudioTranscriptionCompleted path: - type: object key: RealtimeServerEventConversationItemInputAudioTranscriptionDelta path: - type: object key: RealtimeServerEventConversationItemInputAudioTranscriptionFailed path: - type: object key: RealtimeServerEventConversationItemTruncated path: - type: object key: RealtimeServerEventConversationItemDeleted path: - type: object key: RealtimeServerEventInputAudioBufferCommitted path: - type: object key: RealtimeServerEventInputAudioBufferCleared path: - type: object key: RealtimeServerEventInputAudioBufferSpeechStarted path: - type: object key: RealtimeServerEventInputAudioBufferSpeechStopped path: - type: object key: RealtimeServerEventResponseCreated path: - type: object key: RealtimeServerEventResponseDone path: - type: object key: RealtimeServerEventResponseOutputItemAdded path: - type: object key: RealtimeServerEventResponseOutputItemDone path: - type: object key: RealtimeServerEventResponseContentPartAdded path: - type: object key: RealtimeServerEventResponseContentPartDone path: - type: object key: RealtimeServerEventResponseTextDelta path: - type: object key: RealtimeServerEventResponseTextDone path: - type: object key: RealtimeServerEventResponseAudioTranscriptDelta path: - type: object key: RealtimeServerEventResponseAudioTranscriptDone path: - type: object key: RealtimeServerEventResponseAudioDelta path: - type: object key: RealtimeServerEventResponseAudioDone path: - type: object key: RealtimeServerEventResponseFunctionCallArgumentsDelta path: - type: object key: RealtimeServerEventResponseFunctionCallArgumentsDone path: - type: object key: RealtimeServerEventTranscriptionSessionUpdated path: - type: object key: RealtimeServerEventRateLimitsUpdated path: - type: object key: RealtimeServerEventOutputAudioBufferStarted path: - type: object key: RealtimeServerEventOutputAudioBufferStopped path: - type: object key: RealtimeServerEventOutputAudioBufferCleared path: - id: chat title: Chat Completions description: > The Chat Completions API endpoint will generate a model response from a list of messages comprising a conversation. Related guides: - [Quickstart](https://platform.openai.com/docs/quickstart?api-mode=chat) - [Text inputs and outputs](https://platform.openai.com/docs/guides/text?api-mode=chat) - [Image inputs](https://platform.openai.com/docs/guides/images?api-mode=chat) - [Audio inputs and outputs](https://platform.openai.com/docs/guides/audio?api-mode=chat) - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=chat) - [Function calling](https://platform.openai.com/docs/guides/function-calling?api-mode=chat) - [Conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=chat) **Starting a new project?** We recommend trying [Responses](https://platform.openai.com/docs/api-reference/responses) to take advantage of the latest OpenAI platform features. Compare [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). navigationGroup: chat sections: - type: endpoint key: createChatCompletion path: create - type: endpoint key: getChatCompletion path: get - type: endpoint key: getChatCompletionMessages path: getMessages - type: endpoint key: listChatCompletions path: list - type: endpoint key: updateChatCompletion path: update - type: endpoint key: deleteChatCompletion path: delete - type: object key: CreateChatCompletionResponse path: object - type: object key: ChatCompletionList path: list-object - type: object key: ChatCompletionMessageList path: message-list - id: chat-streaming title: Streaming description: | Stream Chat Completions in real time. Receive chunks of completions returned from the model using server-sent events. [Learn more](https://platform.openai.com/docs/guides/streaming-responses?api-mode=chat). navigationGroup: chat sections: - type: object key: CreateChatCompletionStreamResponse path: streaming - id: assistants title: Assistants beta: true description: | Build assistants that can call models and use tools to perform tasks. [Get started with the Assistants API](https://platform.openai.com/docs/assistants) navigationGroup: assistants sections: - type: endpoint key: createAssistant path: createAssistant - type: endpoint key: listAssistants path: listAssistants - type: endpoint key: getAssistant path: getAssistant - type: endpoint key: modifyAssistant path: modifyAssistant - type: endpoint key: deleteAssistant path: deleteAssistant - type: object key: AssistantObject path: object - id: threads title: Threads beta: true description: | Create threads that assistants can interact with. Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) navigationGroup: assistants sections: - type: endpoint key: createThread path: createThread - type: endpoint key: getThread path: getThread - type: endpoint key: modifyThread path: modifyThread - type: endpoint key: deleteThread path: deleteThread - type: object key: ThreadObject path: object - id: messages title: Messages beta: true description: | Create messages within threads Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) navigationGroup: assistants sections: - type: endpoint key: createMessage path: createMessage - type: endpoint key: listMessages path: listMessages - type: endpoint key: getMessage path: getMessage - type: endpoint key: modifyMessage path: modifyMessage - type: endpoint key: deleteMessage path: deleteMessage - type: object key: MessageObject path: object - id: runs title: Runs beta: true description: | Represents an execution run on a thread. Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) navigationGroup: assistants sections: - type: endpoint key: createRun path: createRun - type: endpoint key: createThreadAndRun path: createThreadAndRun - type: endpoint key: listRuns path: listRuns - type: endpoint key: getRun path: getRun - type: endpoint key: modifyRun path: modifyRun - type: endpoint key: submitToolOuputsToRun path: submitToolOutputs - type: endpoint key: cancelRun path: cancelRun - type: object key: RunObject path: object - id: run-steps title: Run steps beta: true description: | Represents the steps (model and tool calls) taken during the run. Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) navigationGroup: assistants sections: - type: endpoint key: listRunSteps path: listRunSteps - type: endpoint key: getRunStep path: getRunStep - type: object key: RunStepObject path: step-object - id: assistants-streaming title: Streaming beta: true description: > Stream the result of executing a Run or resuming a Run after submitting tool outputs. You can stream events from the [Create Thread and Run](https://platform.openai.com/docs/api-reference/runs/createThreadAndRun), [Create Run](https://platform.openai.com/docs/api-reference/runs/createRun), and [Submit Tool Outputs](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoints by passing `"stream": true`. The response will be a [Server-Sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) stream. Our Node and Python SDKs provide helpful utilities to make streaming easy. Reference the [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) to learn more. navigationGroup: assistants sections: - type: object key: MessageDeltaObject path: message-delta-object - type: object key: RunStepDeltaObject path: run-step-delta-object - type: object key: AssistantStreamEvent path: events - id: administration title: Administration description: > Programmatically manage your organization. The Audit Logs endpoint provides a log of all actions taken in the organization for security and monitoring purposes. To access these endpoints please generate an Admin API Key through the [API Platform Organization overview](/organization/admin-keys). Admin API keys cannot be used for non-administration endpoints. For best practices on setting up your organization, please refer to this [guide](https://platform.openai.com/docs/guides/production-best-practices#setting-up-your-organization) navigationGroup: administration - id: admin-api-keys title: Admin API Keys description: > Admin API keys enable Organization Owners to programmatically manage various aspects of their organization, including users, projects, and API keys. These keys provide administrative capabilities, such as creating, updating, and deleting users; managing projects; and overseeing API key lifecycles. Key Features of Admin API Keys: - User Management: Invite new users, update roles, and remove users from the organization. - Project Management: Create, update, archive projects, and manage user assignments within projects. - API Key Oversight: List, retrieve, and delete API keys associated with projects. Only Organization Owners have the authority to create and utilize Admin API keys. To manage these keys, Organization Owners can navigate to the Admin Keys section of their API Platform dashboard. For direct access to the Admin Keys management page, Organization Owners can use the following link: [https://platform.openai.com/settings/organization/admin-keys](https://platform.openai.com/settings/organization/admin-keys) It's crucial to handle Admin API keys with care due to their elevated permissions. Adhering to best practices, such as regular key rotation and assigning appropriate permissions, enhances security and ensures proper governance within the organization. navigationGroup: administration sections: - type: endpoint key: admin-api-keys-list path: list - type: endpoint key: admin-api-keys-create path: create - type: endpoint key: admin-api-keys-get path: listget - type: endpoint key: admin-api-keys-delete path: delete - type: object key: AdminApiKey path: object - id: invite title: Invites description: Invite and manage invitations for an organization. navigationGroup: administration sections: - type: endpoint key: list-invites path: list - type: endpoint key: inviteUser path: create - type: endpoint key: retrieve-invite path: retrieve - type: endpoint key: delete-invite path: delete - type: object key: Invite path: object - id: users title: Users description: | Manage users and their role in an organization. navigationGroup: administration sections: - type: endpoint key: list-users path: list - type: endpoint key: modify-user path: modify - type: endpoint key: retrieve-user path: retrieve - type: endpoint key: delete-user path: delete - type: object key: User path: object - id: projects title: Projects description: | Manage the projects within an orgnanization includes creation, updating, and archiving or projects. The Default project cannot be archived. navigationGroup: administration sections: - type: endpoint key: list-projects path: list - type: endpoint key: create-project path: create - type: endpoint key: retrieve-project path: retrieve - type: endpoint key: modify-project path: modify - type: endpoint key: archive-project path: archive - type: object key: Project path: object - id: project-users title: Project users description: | Manage users within a project, including adding, updating roles, and removing users. navigationGroup: administration sections: - type: endpoint key: list-project-users path: list - type: endpoint key: create-project-user path: create - type: endpoint key: retrieve-project-user path: retrieve - type: endpoint key: modify-project-user path: modify - type: endpoint key: delete-project-user path: delete - type: object key: ProjectUser path: object - id: project-service-accounts title: Project service accounts description: > Manage service accounts within a project. A service account is a bot user that is not associated with a user. If a user leaves an organization, their keys and membership in projects will no longer work. Service accounts do not have this limitation. However, service accounts can also be deleted from a project. navigationGroup: administration sections: - type: endpoint key: list-project-service-accounts path: list - type: endpoint key: create-project-service-account path: create - type: endpoint key: retrieve-project-service-account path: retrieve - type: endpoint key: delete-project-service-account path: delete - type: object key: ProjectServiceAccount path: object - id: project-api-keys title: Project API keys description: > Manage API keys for a given project. Supports listing and deleting keys for users. This API does not allow issuing keys for users, as users need to authorize themselves to generate keys. navigationGroup: administration sections: - type: endpoint key: list-project-api-keys path: list - type: endpoint key: retrieve-project-api-key path: retrieve - type: endpoint key: delete-project-api-key path: delete - type: object key: ProjectApiKey path: object - id: project-rate-limits title: Project rate limits description: > Manage rate limits per model for projects. Rate limits may be configured to be equal to or lower than the organization's rate limits. navigationGroup: administration sections: - type: endpoint key: list-project-rate-limits path: list - type: endpoint key: update-project-rate-limits path: update - type: object key: ProjectRateLimit path: object - id: audit-logs title: Audit logs description: > Logs of user actions and configuration changes within this organization. To log events, an Organization Owner must activate logging in the [Data Controls Settings](/settings/organization/data-controls/data-retention). Once activated, for security reasons, logging cannot be deactivated. navigationGroup: administration sections: - type: endpoint key: list-audit-logs path: list - type: object key: AuditLog path: object - id: usage title: Usage description: > The **Usage API** provides detailed insights into your activity across the OpenAI API. It also includes a separate [Costs endpoint](https://platform.openai.com/docs/api-reference/usage/costs), which offers visibility into your spend, breaking down consumption by invoice line items and project IDs. While the Usage API delivers granular usage data, it may not always reconcile perfectly with the Costs due to minor differences in how usage and spend are recorded. For financial purposes, we recommend using the [Costs endpoint](https://platform.openai.com/docs/api-reference/usage/costs) or the [Costs tab](/settings/organization/usage) in the Usage Dashboard, which will reconcile back to your billing invoice. navigationGroup: administration sections: - type: endpoint key: usage-completions path: completions - type: object key: UsageCompletionsResult path: completions_object - type: endpoint key: usage-embeddings path: embeddings - type: object key: UsageEmbeddingsResult path: embeddings_object - type: endpoint key: usage-moderations path: moderations - type: object key: UsageModerationsResult path: moderations_object - type: endpoint key: usage-images path: images - type: object key: UsageImagesResult path: images_object - type: endpoint key: usage-audio-speeches path: audio_speeches - type: object key: UsageAudioSpeechesResult path: audio_speeches_object - type: endpoint key: usage-audio-transcriptions path: audio_transcriptions - type: object key: UsageAudioTranscriptionsResult path: audio_transcriptions_object - type: endpoint key: usage-vector-stores path: vector_stores - type: object key: UsageVectorStoresResult path: vector_stores_object - type: endpoint key: usage-code-interpreter-sessions path: code_interpreter_sessions - type: object key: UsageCodeInterpreterSessionsResult path: code_interpreter_sessions_object - type: endpoint key: usage-costs path: costs - type: object key: CostsResult path: costs_object - id: certificates beta: true title: Certificates description: > Manage Mutual TLS certificates across your organization and projects. [Learn more about Mutual TLS.](https://help.openai.com/en/articles/10876024-openai-mutual-tls-beta-program) navigationGroup: administration sections: - type: endpoint key: uploadCertificate path: uploadCertificate - type: endpoint key: getCertificate path: getCertificate - type: endpoint key: modifyCertificate path: modifyCertificate - type: endpoint key: deleteCertificate path: deleteCertificate - type: endpoint key: listOrganizationCertificates path: listOrganizationCertificates - type: endpoint key: listProjectCertificates path: listProjectCertificates - type: endpoint key: activateOrganizationCertificates path: activateOrganizationCertificates - type: endpoint key: deactivateOrganizationCertificates path: deactivateOrganizationCertificates - type: endpoint key: activateProjectCertificates path: activateProjectCertificates - type: endpoint key: deactivateProjectCertificates path: deactivateProjectCertificates - type: object key: Certificate path: object - id: completions title: Completions legacy: true navigationGroup: legacy description: > Given a prompt, the model will return one or more predicted completions along with the probabilities of alternative tokens at each position. Most developer should use our [Chat Completions API](https://platform.openai.com/docs/guides/text-generation#text-generation-models) to leverage our best and newest models. sections: - type: endpoint key: createCompletion path: create - type: object key: CreateCompletionResponse path: object ================================================ FILE: specs/3.1.x/opencode.yaml ================================================ openapi: 3.1.1 info: title: opencode description: opencode api version: 1.0.0 paths: /global/health: get: operationId: global.health summary: Get health description: Get health information about the OpenCode server. responses: '200': description: Health information content: application/json: schema: type: object properties: healthy: type: boolean const: true version: type: string required: - healthy - version x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.global.health({ ... }) /global/event: get: operationId: global.event summary: Get global events description: Subscribe to global events from the OpenCode system using server-sent events. responses: '200': description: Event stream content: text/event-stream: schema: $ref: '#/components/schemas/GlobalEvent' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.global.event({ ... }) /global/dispose: post: operationId: global.dispose summary: Dispose instance description: Clean up and dispose all OpenCode instances, releasing all resources. responses: '200': description: Global disposed content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.global.dispose({ ... }) /project: get: operationId: project.list parameters: - in: query name: directory schema: type: string summary: List all projects description: Get a list of projects that have been opened with OpenCode. responses: '200': description: List of projects content: application/json: schema: type: array items: $ref: '#/components/schemas/Project' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.project.list({ ... }) /project/current: get: operationId: project.current parameters: - in: query name: directory schema: type: string summary: Get current project description: Retrieve the currently active project that OpenCode is working with. responses: '200': description: Current project information content: application/json: schema: $ref: '#/components/schemas/Project' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.project.current({ ... }) /project/{projectID}: patch: operationId: project.update parameters: - in: query name: directory schema: type: string - in: path name: projectID schema: type: string required: true summary: Update project description: Update project properties such as name, icon and color. responses: '200': description: Updated project information content: application/json: schema: $ref: '#/components/schemas/Project' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: name: type: string icon: type: object properties: url: type: string color: type: string x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.project.update({ ... }) /pty: get: operationId: pty.list parameters: - in: query name: directory schema: type: string summary: List PTY sessions description: Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode. responses: '200': description: List of sessions content: application/json: schema: type: array items: $ref: '#/components/schemas/Pty' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.pty.list({ ... }) post: operationId: pty.create parameters: - in: query name: directory schema: type: string summary: Create PTY session description: Create a new pseudo-terminal (PTY) session for running shell commands and processes. responses: '200': description: Created session content: application/json: schema: $ref: '#/components/schemas/Pty' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: command: type: string args: type: array items: type: string cwd: type: string title: type: string env: type: object propertyNames: type: string additionalProperties: type: string x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.pty.create({ ... }) /pty/{ptyID}: get: operationId: pty.get parameters: - in: query name: directory schema: type: string - in: path name: ptyID schema: type: string required: true summary: Get PTY session description: Retrieve detailed information about a specific pseudo-terminal (PTY) session. responses: '200': description: Session info content: application/json: schema: $ref: '#/components/schemas/Pty' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.pty.get({ ... }) put: operationId: pty.update parameters: - in: query name: directory schema: type: string - in: path name: ptyID schema: type: string required: true summary: Update PTY session description: Update properties of an existing pseudo-terminal (PTY) session. responses: '200': description: Updated session content: application/json: schema: $ref: '#/components/schemas/Pty' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: title: type: string size: type: object properties: rows: type: number cols: type: number required: - rows - cols x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.pty.update({ ... }) delete: operationId: pty.remove parameters: - in: query name: directory schema: type: string - in: path name: ptyID schema: type: string required: true summary: Remove PTY session description: Remove and terminate a specific pseudo-terminal (PTY) session. responses: '200': description: Session removed content: application/json: schema: type: boolean '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.pty.remove({ ... }) /pty/{ptyID}/connect: get: operationId: pty.connect parameters: - in: query name: directory schema: type: string - in: path name: ptyID schema: type: string required: true summary: Connect to PTY session description: Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time. responses: '200': description: Connected session content: application/json: schema: type: boolean '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.pty.connect({ ... }) /config: get: operationId: config.get parameters: - in: query name: directory schema: type: string summary: Get configuration description: Retrieve the current OpenCode configuration settings and preferences. responses: '200': description: Get config info content: application/json: schema: $ref: '#/components/schemas/Config' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.config.get({ ... }) patch: operationId: config.update parameters: - in: query name: directory schema: type: string summary: Update configuration description: Update OpenCode configuration settings and preferences. responses: '200': description: Successfully updated config content: application/json: schema: $ref: '#/components/schemas/Config' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: $ref: '#/components/schemas/Config' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.config.update({ ... }) /experimental/tool/ids: get: operationId: tool.ids parameters: - in: query name: directory schema: type: string summary: List tool IDs description: Get a list of all available tool IDs, including both built-in tools and dynamically registered tools. responses: '200': description: Tool IDs content: application/json: schema: $ref: '#/components/schemas/ToolIDs' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tool.ids({ ... }) /experimental/tool: get: operationId: tool.list parameters: - in: query name: directory schema: type: string - in: query name: provider schema: type: string required: true - in: query name: model schema: type: string required: true summary: List tools description: Get a list of available tools with their JSON schema parameters for a specific provider and model combination. responses: '200': description: Tools content: application/json: schema: $ref: '#/components/schemas/ToolList' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tool.list({ ... }) /instance/dispose: post: operationId: instance.dispose parameters: - in: query name: directory schema: type: string summary: Dispose instance description: Clean up and dispose the current OpenCode instance, releasing all resources. responses: '200': description: Instance disposed content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.instance.dispose({ ... }) /path: get: operationId: path.get parameters: - in: query name: directory schema: type: string summary: Get paths description: Retrieve the current working directory and related path information for the OpenCode instance. responses: '200': description: Path content: application/json: schema: $ref: '#/components/schemas/Path' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.path.get({ ... }) /vcs: get: operationId: vcs.get parameters: - in: query name: directory schema: type: string summary: Get VCS info description: Retrieve version control system (VCS) information for the current project, such as git branch. responses: '200': description: VCS info content: application/json: schema: $ref: '#/components/schemas/VcsInfo' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.vcs.get({ ... }) /session: get: operationId: session.list parameters: - in: query name: directory schema: type: string summary: List sessions description: Get a list of all OpenCode sessions, sorted by most recently updated. responses: '200': description: List of sessions content: application/json: schema: type: array items: $ref: '#/components/schemas/Session' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.list({ ... }) post: operationId: session.create parameters: - in: query name: directory schema: type: string summary: Create session description: Create a new OpenCode session for interacting with AI assistants and managing conversations. responses: '200': description: Successfully created session content: application/json: schema: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: parentID: type: string pattern: ^ses.* title: type: string permission: $ref: '#/components/schemas/PermissionRuleset' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.create({ ... }) /session/status: get: operationId: session.status parameters: - in: query name: directory schema: type: string summary: Get session status description: Retrieve the current status of all sessions, including active, idle, and completed states. responses: '200': description: Get session status content: application/json: schema: type: object propertyNames: type: string additionalProperties: $ref: '#/components/schemas/SessionStatus' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.status({ ... }) /session/{sessionID}: get: operationId: session.get parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string pattern: ^ses.* required: true summary: Get session description: Retrieve detailed information about a specific OpenCode session. tags: - Session responses: '200': description: Get session content: application/json: schema: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.get({ ... }) delete: operationId: session.delete parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string pattern: ^ses.* required: true summary: Delete session description: Delete a session and permanently remove all associated data, including messages and history. responses: '200': description: Successfully deleted session content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.delete({ ... }) patch: operationId: session.update parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true summary: Update session description: Update properties of an existing session, such as title or other metadata. responses: '200': description: Successfully updated session content: application/json: schema: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: title: type: string time: type: object properties: archived: type: number x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.update({ ... }) /session/{sessionID}/children: get: operationId: session.children parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string pattern: ^ses.* required: true summary: Get session children tags: - Session description: Retrieve all child sessions that were forked from the specified parent session. responses: '200': description: List of children content: application/json: schema: type: array items: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.children({ ... }) /session/{sessionID}/todo: get: operationId: session.todo parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID summary: Get session todos description: Retrieve the todo list associated with a specific session, showing tasks and action items. responses: '200': description: Todo list content: application/json: schema: type: array items: $ref: '#/components/schemas/Todo' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.todo({ ... }) /session/{sessionID}/init: post: operationId: session.init parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID summary: Initialize session description: Analyze the current application and create an AGENTS.md file with project-specific agent configurations. responses: '200': description: '200' content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: modelID: type: string providerID: type: string messageID: type: string pattern: ^msg.* required: - modelID - providerID - messageID x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.init({ ... }) /session/{sessionID}/fork: post: operationId: session.fork parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string pattern: ^ses.* required: true summary: Fork session description: Create a new session by forking an existing session at a specific message point. responses: '200': description: '200' content: application/json: schema: $ref: '#/components/schemas/Session' requestBody: content: application/json: schema: type: object properties: messageID: type: string pattern: ^msg.* x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.fork({ ... }) /session/{sessionID}/abort: post: operationId: session.abort parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true summary: Abort session description: Abort an active session and stop any ongoing AI processing or command execution. responses: '200': description: Aborted session content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.abort({ ... }) /session/{sessionID}/share: post: operationId: session.share parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true summary: Share session description: Create a shareable link for a session, allowing others to view the conversation. responses: '200': description: Successfully shared session content: application/json: schema: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.share({ ... }) delete: operationId: session.unshare parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string pattern: ^ses.* required: true summary: Unshare session description: Remove the shareable link for a session, making it private again. responses: '200': description: Successfully unshared session content: application/json: schema: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.unshare({ ... }) /session/{sessionID}/diff: get: operationId: session.diff parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID - in: query name: messageID schema: type: string pattern: ^msg.* summary: Get session diff description: Get all file changes (diffs) made during this session. responses: '200': description: List of diffs content: application/json: schema: type: array items: $ref: '#/components/schemas/FileDiff' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.diff({ ... }) /session/{sessionID}/summarize: post: operationId: session.summarize parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID summary: Summarize session description: Generate a concise summary of the session using AI compaction to preserve key information. responses: '200': description: Summarized session content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: providerID: type: string modelID: type: string auto: default: false type: boolean required: - providerID - modelID x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.summarize({ ... }) /session/{sessionID}/message: get: operationId: session.messages parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID - in: query name: limit schema: type: number summary: Get session messages description: Retrieve all messages in a session, including user prompts and AI responses. responses: '200': description: List of messages content: application/json: schema: type: array items: type: object properties: info: $ref: '#/components/schemas/Message' parts: type: array items: $ref: '#/components/schemas/Part' required: - info - parts '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.messages({ ... }) post: operationId: session.prompt parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID summary: Send message description: Create and send a new message to a session, streaming the AI response. responses: '200': description: Created message content: application/json: schema: type: object properties: info: $ref: '#/components/schemas/AssistantMessage' parts: type: array items: $ref: '#/components/schemas/Part' required: - info - parts '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: messageID: type: string pattern: ^msg.* model: type: object properties: providerID: type: string modelID: type: string required: - providerID - modelID agent: type: string noReply: type: boolean tools: description: '@deprecated tools and permissions have been merged, you can set permissions on the session itself now' type: object propertyNames: type: string additionalProperties: type: boolean system: type: string variant: type: string parts: type: array items: anyOf: - $ref: '#/components/schemas/TextPartInput' - $ref: '#/components/schemas/FilePartInput' - $ref: '#/components/schemas/AgentPartInput' - $ref: '#/components/schemas/SubtaskPartInput' required: - parts x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.prompt({ ... }) /session/{sessionID}/message/{messageID}: get: operationId: session.message parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID - in: path name: messageID schema: type: string required: true description: Message ID summary: Get message description: Retrieve a specific message from a session by its message ID. responses: '200': description: Message content: application/json: schema: type: object properties: info: $ref: '#/components/schemas/Message' parts: type: array items: $ref: '#/components/schemas/Part' required: - info - parts '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.message({ ... }) /session/{sessionID}/message/{messageID}/part/{partID}: delete: operationId: part.delete parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID - in: path name: messageID schema: type: string required: true description: Message ID - in: path name: partID schema: type: string required: true description: Part ID description: Delete a part from a message responses: '200': description: Successfully deleted part content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.part.delete({ ... }) patch: operationId: part.update parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID - in: path name: messageID schema: type: string required: true description: Message ID - in: path name: partID schema: type: string required: true description: Part ID description: Update a part in a message responses: '200': description: Successfully updated part content: application/json: schema: $ref: '#/components/schemas/Part' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: $ref: '#/components/schemas/Part' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.part.update({ ... }) /session/{sessionID}/prompt_async: post: operationId: session.prompt_async parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID summary: Send async message description: Create and send a new message to a session asynchronously, starting the session if needed and returning immediately. responses: '204': description: Prompt accepted '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: messageID: type: string pattern: ^msg.* model: type: object properties: providerID: type: string modelID: type: string required: - providerID - modelID agent: type: string noReply: type: boolean tools: description: '@deprecated tools and permissions have been merged, you can set permissions on the session itself now' type: object propertyNames: type: string additionalProperties: type: boolean system: type: string variant: type: string parts: type: array items: anyOf: - $ref: '#/components/schemas/TextPartInput' - $ref: '#/components/schemas/FilePartInput' - $ref: '#/components/schemas/AgentPartInput' - $ref: '#/components/schemas/SubtaskPartInput' required: - parts x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.prompt_async({ ... }) /session/{sessionID}/command: post: operationId: session.command parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID summary: Send command description: Send a new command to a session for execution by the AI assistant. responses: '200': description: Created message content: application/json: schema: type: object properties: info: $ref: '#/components/schemas/AssistantMessage' parts: type: array items: $ref: '#/components/schemas/Part' required: - info - parts '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: messageID: type: string pattern: ^msg.* agent: type: string model: type: string arguments: type: string command: type: string variant: type: string required: - arguments - command x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.command({ ... }) /session/{sessionID}/shell: post: operationId: session.shell parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true description: Session ID summary: Run shell command description: Execute a shell command within the session context and return the AI's response. responses: '200': description: Created message content: application/json: schema: $ref: '#/components/schemas/AssistantMessage' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: agent: type: string model: type: object properties: providerID: type: string modelID: type: string required: - providerID - modelID command: type: string required: - agent - command x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.shell({ ... }) /session/{sessionID}/revert: post: operationId: session.revert parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true summary: Revert message description: Revert a specific message in a session, undoing its effects and restoring the previous state. responses: '200': description: Updated session content: application/json: schema: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: messageID: type: string pattern: ^msg.* partID: type: string pattern: ^prt.* required: - messageID x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.revert({ ... }) /session/{sessionID}/unrevert: post: operationId: session.unrevert parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true summary: Restore reverted messages description: Restore all previously reverted messages in a session. responses: '200': description: Updated session content: application/json: schema: $ref: '#/components/schemas/Session' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.session.unrevert({ ... }) /session/{sessionID}/permissions/{permissionID}: post: operationId: permission.respond parameters: - in: query name: directory schema: type: string - in: path name: sessionID schema: type: string required: true - in: path name: permissionID schema: type: string required: true summary: Respond to permission deprecated: true description: Approve or deny a permission request from the AI assistant. responses: '200': description: Permission processed successfully content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: response: type: string enum: - once - always - reject required: - response x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.permission.respond({ ... }) /permission/{requestID}/reply: post: operationId: permission.reply parameters: - in: query name: directory schema: type: string - in: path name: requestID schema: type: string required: true summary: Respond to permission request description: Approve or deny a permission request from the AI assistant. responses: '200': description: Permission processed successfully content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: reply: type: string enum: - once - always - reject required: - reply x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.permission.reply({ ... }) /permission: get: operationId: permission.list parameters: - in: query name: directory schema: type: string summary: List pending permissions description: Get all pending permission requests across all sessions. responses: '200': description: List of pending permissions content: application/json: schema: type: array items: $ref: '#/components/schemas/PermissionRequest' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.permission.list({ ... }) /command: get: operationId: command.list parameters: - in: query name: directory schema: type: string summary: List commands description: Get a list of all available commands in the OpenCode system. responses: '200': description: List of commands content: application/json: schema: type: array items: $ref: '#/components/schemas/Command' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.command.list({ ... }) /config/providers: get: operationId: config.providers parameters: - in: query name: directory schema: type: string summary: List config providers description: Get a list of all configured AI providers and their default models. responses: '200': description: List of providers content: application/json: schema: type: object properties: providers: type: array items: $ref: '#/components/schemas/Provider' default: type: object propertyNames: type: string additionalProperties: type: string required: - providers - default x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.config.providers({ ... }) /provider: get: operationId: provider.list parameters: - in: query name: directory schema: type: string summary: List providers description: Get a list of all available AI providers, including both available and connected ones. responses: '200': description: List of providers content: application/json: schema: type: object properties: all: type: array items: type: object properties: api: type: string name: type: string env: type: array items: type: string id: type: string npm: type: string models: type: object propertyNames: type: string additionalProperties: type: object properties: id: type: string name: type: string family: type: string release_date: type: string attachment: type: boolean reasoning: type: boolean temperature: type: boolean tool_call: type: boolean interleaved: anyOf: - type: boolean const: true - type: object properties: field: type: string enum: - reasoning_content - reasoning_details required: - field additionalProperties: false cost: type: object properties: input: type: number output: type: number cache_read: type: number cache_write: type: number context_over_200k: type: object properties: input: type: number output: type: number cache_read: type: number cache_write: type: number required: - input - output required: - input - output limit: type: object properties: context: type: number output: type: number required: - context - output modalities: type: object properties: input: type: array items: type: string enum: - text - audio - image - video - pdf output: type: array items: type: string enum: - text - audio - image - video - pdf required: - input - output experimental: type: boolean status: type: string enum: - alpha - beta - deprecated options: type: object propertyNames: type: string additionalProperties: {} headers: type: object propertyNames: type: string additionalProperties: type: string provider: type: object properties: npm: type: string required: - npm variants: type: object propertyNames: type: string additionalProperties: type: object propertyNames: type: string additionalProperties: {} required: - id - name - release_date - attachment - reasoning - temperature - tool_call - limit - options required: - name - env - id - models default: type: object propertyNames: type: string additionalProperties: type: string connected: type: array items: type: string required: - all - default - connected x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.provider.list({ ... }) /provider/auth: get: operationId: provider.auth parameters: - in: query name: directory schema: type: string summary: Get provider auth methods description: Retrieve available authentication methods for all AI providers. responses: '200': description: Provider auth methods content: application/json: schema: type: object propertyNames: type: string additionalProperties: type: array items: $ref: '#/components/schemas/ProviderAuthMethod' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.provider.auth({ ... }) /provider/{providerID}/oauth/authorize: post: operationId: provider.oauth.authorize parameters: - in: query name: directory schema: type: string - in: path name: providerID schema: type: string required: true description: Provider ID summary: OAuth authorize description: Initiate OAuth authorization for a specific AI provider to get an authorization URL. responses: '200': description: Authorization URL and method content: application/json: schema: $ref: '#/components/schemas/ProviderAuthAuthorization' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: method: description: Auth method index type: number required: - method x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.provider.oauth.authorize({ ... }) /provider/{providerID}/oauth/callback: post: operationId: provider.oauth.callback parameters: - in: query name: directory schema: type: string - in: path name: providerID schema: type: string required: true description: Provider ID summary: OAuth callback description: Handle the OAuth callback from a provider after user authorization. responses: '200': description: OAuth callback processed successfully content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: method: description: Auth method index type: number code: description: OAuth authorization code type: string required: - method x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.provider.oauth.callback({ ... }) /find: get: operationId: find.text parameters: - in: query name: directory schema: type: string - in: query name: pattern schema: type: string required: true summary: Find text description: Search for text patterns across files in the project using ripgrep. responses: '200': description: Matches content: application/json: schema: type: array items: type: object properties: path: type: object properties: text: type: string required: - text lines: type: object properties: text: type: string required: - text line_number: type: number absolute_offset: type: number submatches: type: array items: type: object properties: match: type: object properties: text: type: string required: - text start: type: number end: type: number required: - match - start - end required: - path - lines - line_number - absolute_offset - submatches x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.find.text({ ... }) /find/file: get: operationId: find.files parameters: - in: query name: directory schema: type: string - in: query name: query schema: type: string required: true - in: query name: dirs schema: type: string enum: - 'true' - 'false' - in: query name: type schema: type: string enum: - file - directory - in: query name: limit schema: type: integer minimum: 1 maximum: 200 summary: Find files description: Search for files or directories by name or pattern in the project directory. responses: '200': description: File paths content: application/json: schema: type: array items: type: string x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.find.files({ ... }) /find/symbol: get: operationId: find.symbols parameters: - in: query name: directory schema: type: string - in: query name: query schema: type: string required: true summary: Find symbols description: Search for workspace symbols like functions, classes, and variables using LSP. responses: '200': description: Symbols content: application/json: schema: type: array items: $ref: '#/components/schemas/Symbol' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.find.symbols({ ... }) /file: get: operationId: file.list parameters: - in: query name: directory schema: type: string - in: query name: path schema: type: string required: true summary: List files description: List files and directories in a specified path. responses: '200': description: Files and directories content: application/json: schema: type: array items: $ref: '#/components/schemas/FileNode' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.file.list({ ... }) /file/content: get: operationId: file.read parameters: - in: query name: directory schema: type: string - in: query name: path schema: type: string required: true summary: Read file description: Read the content of a specified file. responses: '200': description: File content content: application/json: schema: $ref: '#/components/schemas/FileContent' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.file.read({ ... }) /file/status: get: operationId: file.status parameters: - in: query name: directory schema: type: string summary: Get file status description: Get the git status of all files in the project. responses: '200': description: File status content: application/json: schema: type: array items: $ref: '#/components/schemas/File' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.file.status({ ... }) /log: post: operationId: app.log parameters: - in: query name: directory schema: type: string summary: Write log description: Write a log entry to the server logs with specified level and metadata. responses: '200': description: Log entry written successfully content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: service: description: Service name for the log entry type: string level: description: Log level type: string enum: - debug - info - error - warn message: description: Log message type: string extra: description: Additional metadata for the log entry type: object propertyNames: type: string additionalProperties: {} required: - service - level - message x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.app.log({ ... }) /agent: get: operationId: app.agents parameters: - in: query name: directory schema: type: string summary: List agents description: Get a list of all available AI agents in the OpenCode system. responses: '200': description: List of agents content: application/json: schema: type: array items: $ref: '#/components/schemas/Agent' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.app.agents({ ... }) /mcp: get: operationId: mcp.status parameters: - in: query name: directory schema: type: string summary: Get MCP status description: Get the status of all Model Context Protocol (MCP) servers. responses: '200': description: MCP server status content: application/json: schema: type: object propertyNames: type: string additionalProperties: $ref: '#/components/schemas/MCPStatus' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.status({ ... }) post: operationId: mcp.add parameters: - in: query name: directory schema: type: string summary: Add MCP server description: Dynamically add a new Model Context Protocol (MCP) server to the system. responses: '200': description: MCP server added successfully content: application/json: schema: type: object propertyNames: type: string additionalProperties: $ref: '#/components/schemas/MCPStatus' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: name: type: string config: anyOf: - $ref: '#/components/schemas/McpLocalConfig' - $ref: '#/components/schemas/McpRemoteConfig' required: - name - config x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.add({ ... }) /mcp/{name}/auth: post: operationId: mcp.auth.start parameters: - in: query name: directory schema: type: string - schema: type: string in: path name: name required: true summary: Start MCP OAuth description: Start OAuth authentication flow for a Model Context Protocol (MCP) server. responses: '200': description: OAuth flow started content: application/json: schema: type: object properties: authorizationUrl: description: URL to open in browser for authorization type: string required: - authorizationUrl '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.auth.start({ ... }) delete: operationId: mcp.auth.remove parameters: - in: query name: directory schema: type: string - schema: type: string in: path name: name required: true summary: Remove MCP OAuth description: Remove OAuth credentials for an MCP server responses: '200': description: OAuth credentials removed content: application/json: schema: type: object properties: success: type: boolean const: true required: - success '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.auth.remove({ ... }) /mcp/{name}/auth/callback: post: operationId: mcp.auth.callback parameters: - in: query name: directory schema: type: string - schema: type: string in: path name: name required: true summary: Complete MCP OAuth description: Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code. responses: '200': description: OAuth authentication completed content: application/json: schema: $ref: '#/components/schemas/MCPStatus' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' requestBody: content: application/json: schema: type: object properties: code: description: Authorization code from OAuth callback type: string required: - code x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.auth.callback({ ... }) /mcp/{name}/auth/authenticate: post: operationId: mcp.auth.authenticate parameters: - in: query name: directory schema: type: string - schema: type: string in: path name: name required: true summary: Authenticate MCP OAuth description: Start OAuth flow and wait for callback (opens browser) responses: '200': description: OAuth authentication completed content: application/json: schema: $ref: '#/components/schemas/MCPStatus' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/NotFoundError' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.auth.authenticate({ ... }) /mcp/{name}/connect: post: operationId: mcp.connect parameters: - in: query name: directory schema: type: string - in: path name: name schema: type: string required: true description: Connect an MCP server responses: '200': description: MCP server connected successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.connect({ ... }) /mcp/{name}/disconnect: post: operationId: mcp.disconnect parameters: - in: query name: directory schema: type: string - in: path name: name schema: type: string required: true description: Disconnect an MCP server responses: '200': description: MCP server disconnected successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.mcp.disconnect({ ... }) /lsp: get: operationId: lsp.status parameters: - in: query name: directory schema: type: string summary: Get LSP status description: Get LSP server status responses: '200': description: LSP server status content: application/json: schema: type: array items: $ref: '#/components/schemas/LSPStatus' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.lsp.status({ ... }) /formatter: get: operationId: formatter.status parameters: - in: query name: directory schema: type: string summary: Get formatter status description: Get formatter status responses: '200': description: Formatter status content: application/json: schema: type: array items: $ref: '#/components/schemas/FormatterStatus' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.formatter.status({ ... }) /tui/append-prompt: post: operationId: tui.appendPrompt parameters: - in: query name: directory schema: type: string summary: Append TUI prompt description: Append prompt to the TUI responses: '200': description: Prompt processed successfully content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: text: type: string required: - text x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.appendPrompt({ ... }) /tui/open-help: post: operationId: tui.openHelp parameters: - in: query name: directory schema: type: string summary: Open help dialog description: Open the help dialog in the TUI to display user assistance information. responses: '200': description: Help dialog opened successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.openHelp({ ... }) /tui/open-sessions: post: operationId: tui.openSessions parameters: - in: query name: directory schema: type: string summary: Open sessions dialog description: Open the session dialog responses: '200': description: Session dialog opened successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.openSessions({ ... }) /tui/open-themes: post: operationId: tui.openThemes parameters: - in: query name: directory schema: type: string summary: Open themes dialog description: Open the theme dialog responses: '200': description: Theme dialog opened successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.openThemes({ ... }) /tui/open-models: post: operationId: tui.openModels parameters: - in: query name: directory schema: type: string summary: Open models dialog description: Open the model dialog responses: '200': description: Model dialog opened successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.openModels({ ... }) /tui/submit-prompt: post: operationId: tui.submitPrompt parameters: - in: query name: directory schema: type: string summary: Submit TUI prompt description: Submit the prompt responses: '200': description: Prompt submitted successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.submitPrompt({ ... }) /tui/clear-prompt: post: operationId: tui.clearPrompt parameters: - in: query name: directory schema: type: string summary: Clear TUI prompt description: Clear the prompt responses: '200': description: Prompt cleared successfully content: application/json: schema: type: boolean x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.clearPrompt({ ... }) /tui/execute-command: post: operationId: tui.executeCommand parameters: - in: query name: directory schema: type: string summary: Execute TUI command description: Execute a TUI command (e.g. agent_cycle) responses: '200': description: Command executed successfully content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: type: object properties: command: type: string required: - command x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.executeCommand({ ... }) /tui/show-toast: post: operationId: tui.showToast parameters: - in: query name: directory schema: type: string summary: Show TUI toast description: Show a toast notification in the TUI responses: '200': description: Toast notification shown successfully content: application/json: schema: type: boolean requestBody: content: application/json: schema: type: object properties: title: type: string message: type: string variant: type: string enum: - info - success - warning - error duration: description: Duration in milliseconds default: 5000 type: number required: - message - variant x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.showToast({ ... }) /tui/publish: post: operationId: tui.publish parameters: - in: query name: directory schema: type: string summary: Publish TUI event description: Publish a TUI event responses: '200': description: Event published successfully content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: anyOf: - $ref: '#/components/schemas/Event.tui.prompt.append' - $ref: '#/components/schemas/Event.tui.command.execute' - $ref: '#/components/schemas/Event.tui.toast.show' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.publish({ ... }) /tui/control/next: get: operationId: tui.control.next parameters: - in: query name: directory schema: type: string summary: Get next TUI request description: Retrieve the next TUI (Terminal User Interface) request from the queue for processing. responses: '200': description: Next TUI request content: application/json: schema: type: object properties: path: type: string body: {} required: - path - body x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.control.next({ ... }) /tui/control/response: post: operationId: tui.control.response parameters: - in: query name: directory schema: type: string summary: Submit TUI response description: Submit a response to the TUI request queue to complete a pending request. responses: '200': description: Response submitted successfully content: application/json: schema: type: boolean requestBody: content: application/json: schema: {} x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.tui.control.response({ ... }) /auth/{providerID}: put: operationId: auth.set parameters: - in: query name: directory schema: type: string - in: path name: providerID schema: type: string required: true summary: Set auth credentials description: Set authentication credentials responses: '200': description: Successfully set authentication credentials content: application/json: schema: type: boolean '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/BadRequestError' requestBody: content: application/json: schema: $ref: '#/components/schemas/Auth' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.auth.set({ ... }) /event: get: operationId: event.subscribe parameters: - in: query name: directory schema: type: string summary: Subscribe to events description: Get events responses: '200': description: Event stream content: text/event-stream: schema: $ref: '#/components/schemas/Event' x-codeSamples: - lang: js source: |- import { createOpencodeClient } from "@opencode-ai/sdk const client = createOpencodeClient() await client.event.subscribe({ ... }) components: schemas: Event.installation.updated: type: object properties: type: type: string const: installation.updated properties: type: object properties: version: type: string required: - version required: - type - properties Event.installation.update-available: type: object properties: type: type: string const: installation.update-available properties: type: object properties: version: type: string required: - version required: - type - properties Project: type: object properties: id: type: string worktree: type: string vcs: type: string const: git name: type: string icon: type: object properties: url: type: string color: type: string time: type: object properties: created: type: number updated: type: number initialized: type: number required: - created - updated required: - id - worktree - time Event.project.updated: type: object properties: type: type: string const: project.updated properties: $ref: '#/components/schemas/Project' required: - type - properties Event.server.instance.disposed: type: object properties: type: type: string const: server.instance.disposed properties: type: object properties: directory: type: string required: - directory required: - type - properties Event.lsp.client.diagnostics: type: object properties: type: type: string const: lsp.client.diagnostics properties: type: object properties: serverID: type: string path: type: string required: - serverID - path required: - type - properties Event.lsp.updated: type: object properties: type: type: string const: lsp.updated properties: type: object properties: {} required: - type - properties FileDiff: type: object properties: file: type: string before: type: string after: type: string additions: type: number deletions: type: number required: - file - before - after - additions - deletions UserMessage: type: object properties: id: type: string sessionID: type: string role: type: string const: user time: type: object properties: created: type: number required: - created summary: type: object properties: title: type: string body: type: string diffs: type: array items: $ref: '#/components/schemas/FileDiff' required: - diffs agent: type: string model: type: object properties: providerID: type: string modelID: type: string required: - providerID - modelID system: type: string tools: type: object propertyNames: type: string additionalProperties: type: boolean variant: type: string required: - id - sessionID - role - time - agent - model ProviderAuthError: type: object properties: name: type: string const: ProviderAuthError data: type: object properties: providerID: type: string message: type: string required: - providerID - message required: - name - data UnknownError: type: object properties: name: type: string const: UnknownError data: type: object properties: message: type: string required: - message required: - name - data MessageOutputLengthError: type: object properties: name: type: string const: MessageOutputLengthError data: type: object properties: {} required: - name - data MessageAbortedError: type: object properties: name: type: string const: MessageAbortedError data: type: object properties: message: type: string required: - message required: - name - data APIError: type: object properties: name: type: string const: APIError data: type: object properties: message: type: string statusCode: type: number isRetryable: type: boolean responseHeaders: type: object propertyNames: type: string additionalProperties: type: string responseBody: type: string metadata: type: object propertyNames: type: string additionalProperties: type: string required: - message - isRetryable required: - name - data AssistantMessage: type: object properties: id: type: string sessionID: type: string role: type: string const: assistant time: type: object properties: created: type: number completed: type: number required: - created error: anyOf: - $ref: '#/components/schemas/ProviderAuthError' - $ref: '#/components/schemas/UnknownError' - $ref: '#/components/schemas/MessageOutputLengthError' - $ref: '#/components/schemas/MessageAbortedError' - $ref: '#/components/schemas/APIError' parentID: type: string modelID: type: string providerID: type: string mode: type: string agent: type: string path: type: object properties: cwd: type: string root: type: string required: - cwd - root summary: type: boolean cost: type: number tokens: type: object properties: input: type: number output: type: number reasoning: type: number cache: type: object properties: read: type: number write: type: number required: - read - write required: - input - output - reasoning - cache finish: type: string required: - id - sessionID - role - time - parentID - modelID - providerID - mode - agent - path - cost - tokens Message: anyOf: - $ref: '#/components/schemas/UserMessage' - $ref: '#/components/schemas/AssistantMessage' Event.message.updated: type: object properties: type: type: string const: message.updated properties: type: object properties: info: $ref: '#/components/schemas/Message' required: - info required: - type - properties Event.message.removed: type: object properties: type: type: string const: message.removed properties: type: object properties: sessionID: type: string messageID: type: string required: - sessionID - messageID required: - type - properties TextPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: text text: type: string synthetic: type: boolean ignored: type: boolean time: type: object properties: start: type: number end: type: number required: - start metadata: type: object propertyNames: type: string additionalProperties: {} required: - id - sessionID - messageID - type - text ReasoningPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: reasoning text: type: string metadata: type: object propertyNames: type: string additionalProperties: {} time: type: object properties: start: type: number end: type: number required: - start required: - id - sessionID - messageID - type - text - time FilePartSourceText: type: object properties: value: type: string start: type: integer minimum: -9007199254740991 maximum: 9007199254740991 end: type: integer minimum: -9007199254740991 maximum: 9007199254740991 required: - value - start - end FileSource: type: object properties: text: $ref: '#/components/schemas/FilePartSourceText' type: type: string const: file path: type: string required: - text - type - path Range: type: object properties: start: type: object properties: line: type: number character: type: number required: - line - character end: type: object properties: line: type: number character: type: number required: - line - character required: - start - end SymbolSource: type: object properties: text: $ref: '#/components/schemas/FilePartSourceText' type: type: string const: symbol path: type: string range: $ref: '#/components/schemas/Range' name: type: string kind: type: integer minimum: -9007199254740991 maximum: 9007199254740991 required: - text - type - path - range - name - kind FilePartSource: anyOf: - $ref: '#/components/schemas/FileSource' - $ref: '#/components/schemas/SymbolSource' FilePart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: file mime: type: string filename: type: string url: type: string source: $ref: '#/components/schemas/FilePartSource' required: - id - sessionID - messageID - type - mime - url ToolStatePending: type: object properties: status: type: string const: pending input: type: object propertyNames: type: string additionalProperties: {} raw: type: string required: - status - input - raw ToolStateRunning: type: object properties: status: type: string const: running input: type: object propertyNames: type: string additionalProperties: {} title: type: string metadata: type: object propertyNames: type: string additionalProperties: {} time: type: object properties: start: type: number required: - start required: - status - input - time ToolStateCompleted: type: object properties: status: type: string const: completed input: type: object propertyNames: type: string additionalProperties: {} output: type: string title: type: string metadata: type: object propertyNames: type: string additionalProperties: {} time: type: object properties: start: type: number end: type: number compacted: type: number required: - start - end attachments: type: array items: $ref: '#/components/schemas/FilePart' required: - status - input - output - title - metadata - time ToolStateError: type: object properties: status: type: string const: error input: type: object propertyNames: type: string additionalProperties: {} error: type: string metadata: type: object propertyNames: type: string additionalProperties: {} time: type: object properties: start: type: number end: type: number required: - start - end required: - status - input - error - time ToolState: anyOf: - $ref: '#/components/schemas/ToolStatePending' - $ref: '#/components/schemas/ToolStateRunning' - $ref: '#/components/schemas/ToolStateCompleted' - $ref: '#/components/schemas/ToolStateError' ToolPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: tool callID: type: string tool: type: string state: $ref: '#/components/schemas/ToolState' metadata: type: object propertyNames: type: string additionalProperties: {} required: - id - sessionID - messageID - type - callID - tool - state StepStartPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: step-start snapshot: type: string required: - id - sessionID - messageID - type StepFinishPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: step-finish reason: type: string snapshot: type: string cost: type: number tokens: type: object properties: input: type: number output: type: number reasoning: type: number cache: type: object properties: read: type: number write: type: number required: - read - write required: - input - output - reasoning - cache required: - id - sessionID - messageID - type - reason - cost - tokens SnapshotPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: snapshot snapshot: type: string required: - id - sessionID - messageID - type - snapshot PatchPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: patch hash: type: string files: type: array items: type: string required: - id - sessionID - messageID - type - hash - files AgentPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: agent name: type: string source: type: object properties: value: type: string start: type: integer minimum: -9007199254740991 maximum: 9007199254740991 end: type: integer minimum: -9007199254740991 maximum: 9007199254740991 required: - value - start - end required: - id - sessionID - messageID - type - name RetryPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: retry attempt: type: number error: $ref: '#/components/schemas/APIError' time: type: object properties: created: type: number required: - created required: - id - sessionID - messageID - type - attempt - error - time CompactionPart: type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: compaction auto: type: boolean required: - id - sessionID - messageID - type - auto Part: anyOf: - $ref: '#/components/schemas/TextPart' - type: object properties: id: type: string sessionID: type: string messageID: type: string type: type: string const: subtask prompt: type: string description: type: string agent: type: string command: type: string required: - id - sessionID - messageID - type - prompt - description - agent - $ref: '#/components/schemas/ReasoningPart' - $ref: '#/components/schemas/FilePart' - $ref: '#/components/schemas/ToolPart' - $ref: '#/components/schemas/StepStartPart' - $ref: '#/components/schemas/StepFinishPart' - $ref: '#/components/schemas/SnapshotPart' - $ref: '#/components/schemas/PatchPart' - $ref: '#/components/schemas/AgentPart' - $ref: '#/components/schemas/RetryPart' - $ref: '#/components/schemas/CompactionPart' Event.message.part.updated: type: object properties: type: type: string const: message.part.updated properties: type: object properties: part: $ref: '#/components/schemas/Part' delta: type: string required: - part required: - type - properties Event.message.part.removed: type: object properties: type: type: string const: message.part.removed properties: type: object properties: sessionID: type: string messageID: type: string partID: type: string required: - sessionID - messageID - partID required: - type - properties PermissionRequest: type: object properties: id: type: string pattern: ^per.* sessionID: type: string pattern: ^ses.* permission: type: string patterns: type: array items: type: string metadata: type: object propertyNames: type: string additionalProperties: {} always: type: array items: type: string tool: type: object properties: messageID: type: string callID: type: string required: - messageID - callID required: - id - sessionID - permission - patterns - metadata - always Event.permission.asked: type: object properties: type: type: string const: permission.asked properties: $ref: '#/components/schemas/PermissionRequest' required: - type - properties Event.permission.replied: type: object properties: type: type: string const: permission.replied properties: type: object properties: sessionID: type: string requestID: type: string reply: type: string enum: - once - always - reject required: - sessionID - requestID - reply required: - type - properties SessionStatus: anyOf: - type: object properties: type: type: string const: idle required: - type - type: object properties: type: type: string const: retry attempt: type: number message: type: string next: type: number required: - type - attempt - message - next - type: object properties: type: type: string const: busy required: - type Event.session.status: type: object properties: type: type: string const: session.status properties: type: object properties: sessionID: type: string status: $ref: '#/components/schemas/SessionStatus' required: - sessionID - status required: - type - properties Event.session.idle: type: object properties: type: type: string const: session.idle properties: type: object properties: sessionID: type: string required: - sessionID required: - type - properties Event.session.compacted: type: object properties: type: type: string const: session.compacted properties: type: object properties: sessionID: type: string required: - sessionID required: - type - properties Event.file.edited: type: object properties: type: type: string const: file.edited properties: type: object properties: file: type: string required: - file required: - type - properties Todo: type: object properties: content: description: Brief description of the task type: string status: description: 'Current status of the task: pending, in_progress, completed, cancelled' type: string priority: description: 'Priority level of the task: high, medium, low' type: string id: description: Unique identifier for the todo item type: string required: - content - status - priority - id Event.todo.updated: type: object properties: type: type: string const: todo.updated properties: type: object properties: sessionID: type: string todos: type: array items: $ref: '#/components/schemas/Todo' required: - sessionID - todos required: - type - properties Event.tui.prompt.append: type: object properties: type: type: string const: tui.prompt.append properties: type: object properties: text: type: string required: - text required: - type - properties Event.tui.command.execute: type: object properties: type: type: string const: tui.command.execute properties: type: object properties: command: anyOf: - type: string enum: - session.list - session.new - session.share - session.interrupt - session.compact - session.page.up - session.page.down - session.half.page.up - session.half.page.down - session.first - session.last - prompt.clear - prompt.submit - agent.cycle - type: string required: - command required: - type - properties Event.tui.toast.show: type: object properties: type: type: string const: tui.toast.show properties: type: object properties: title: type: string message: type: string variant: type: string enum: - info - success - warning - error duration: description: Duration in milliseconds default: 5000 type: number required: - message - variant required: - type - properties Event.mcp.tools.changed: type: object properties: type: type: string const: mcp.tools.changed properties: type: object properties: server: type: string required: - server required: - type - properties Event.command.executed: type: object properties: type: type: string const: command.executed properties: type: object properties: name: type: string sessionID: type: string pattern: ^ses.* arguments: type: string messageID: type: string pattern: ^msg.* required: - name - sessionID - arguments - messageID required: - type - properties PermissionAction: type: string enum: - allow - deny - ask PermissionRule: type: object properties: permission: type: string pattern: type: string action: $ref: '#/components/schemas/PermissionAction' required: - permission - pattern - action PermissionRuleset: type: array items: $ref: '#/components/schemas/PermissionRule' Session: type: object properties: id: type: string pattern: ^ses.* projectID: type: string directory: type: string parentID: type: string pattern: ^ses.* summary: type: object properties: additions: type: number deletions: type: number files: type: number diffs: type: array items: $ref: '#/components/schemas/FileDiff' required: - additions - deletions - files share: type: object properties: url: type: string required: - url title: type: string version: type: string time: type: object properties: created: type: number updated: type: number compacting: type: number archived: type: number required: - created - updated permission: $ref: '#/components/schemas/PermissionRuleset' revert: type: object properties: messageID: type: string partID: type: string snapshot: type: string diff: type: string required: - messageID required: - id - projectID - directory - title - version - time Event.session.created: type: object properties: type: type: string const: session.created properties: type: object properties: info: $ref: '#/components/schemas/Session' required: - info required: - type - properties Event.session.updated: type: object properties: type: type: string const: session.updated properties: type: object properties: info: $ref: '#/components/schemas/Session' required: - info required: - type - properties Event.session.deleted: type: object properties: type: type: string const: session.deleted properties: type: object properties: info: $ref: '#/components/schemas/Session' required: - info required: - type - properties Event.session.diff: type: object properties: type: type: string const: session.diff properties: type: object properties: sessionID: type: string diff: type: array items: $ref: '#/components/schemas/FileDiff' required: - sessionID - diff required: - type - properties Event.session.error: type: object properties: type: type: string const: session.error properties: type: object properties: sessionID: type: string error: anyOf: - $ref: '#/components/schemas/ProviderAuthError' - $ref: '#/components/schemas/UnknownError' - $ref: '#/components/schemas/MessageOutputLengthError' - $ref: '#/components/schemas/MessageAbortedError' - $ref: '#/components/schemas/APIError' required: - type - properties Event.file.watcher.updated: type: object properties: type: type: string const: file.watcher.updated properties: type: object properties: file: type: string event: anyOf: - type: string const: add - type: string const: change - type: string const: unlink required: - file - event required: - type - properties Event.vcs.branch.updated: type: object properties: type: type: string const: vcs.branch.updated properties: type: object properties: branch: type: string required: - type - properties Pty: type: object properties: id: type: string pattern: ^pty.* title: type: string command: type: string args: type: array items: type: string cwd: type: string status: type: string enum: - running - exited pid: type: number required: - id - title - command - args - cwd - status - pid Event.pty.created: type: object properties: type: type: string const: pty.created properties: type: object properties: info: $ref: '#/components/schemas/Pty' required: - info required: - type - properties Event.pty.updated: type: object properties: type: type: string const: pty.updated properties: type: object properties: info: $ref: '#/components/schemas/Pty' required: - info required: - type - properties Event.pty.exited: type: object properties: type: type: string const: pty.exited properties: type: object properties: id: type: string pattern: ^pty.* exitCode: type: number required: - id - exitCode required: - type - properties Event.pty.deleted: type: object properties: type: type: string const: pty.deleted properties: type: object properties: id: type: string pattern: ^pty.* required: - id required: - type - properties Event.server.connected: type: object properties: type: type: string const: server.connected properties: type: object properties: {} required: - type - properties Event.global.disposed: type: object properties: type: type: string const: global.disposed properties: type: object properties: {} required: - type - properties Event: anyOf: - $ref: '#/components/schemas/Event.installation.updated' - $ref: '#/components/schemas/Event.installation.update-available' - $ref: '#/components/schemas/Event.project.updated' - $ref: '#/components/schemas/Event.server.instance.disposed' - $ref: '#/components/schemas/Event.lsp.client.diagnostics' - $ref: '#/components/schemas/Event.lsp.updated' - $ref: '#/components/schemas/Event.message.updated' - $ref: '#/components/schemas/Event.message.removed' - $ref: '#/components/schemas/Event.message.part.updated' - $ref: '#/components/schemas/Event.message.part.removed' - $ref: '#/components/schemas/Event.permission.asked' - $ref: '#/components/schemas/Event.permission.replied' - $ref: '#/components/schemas/Event.session.status' - $ref: '#/components/schemas/Event.session.idle' - $ref: '#/components/schemas/Event.session.compacted' - $ref: '#/components/schemas/Event.file.edited' - $ref: '#/components/schemas/Event.todo.updated' - $ref: '#/components/schemas/Event.tui.prompt.append' - $ref: '#/components/schemas/Event.tui.command.execute' - $ref: '#/components/schemas/Event.tui.toast.show' - $ref: '#/components/schemas/Event.mcp.tools.changed' - $ref: '#/components/schemas/Event.command.executed' - $ref: '#/components/schemas/Event.session.created' - $ref: '#/components/schemas/Event.session.updated' - $ref: '#/components/schemas/Event.session.deleted' - $ref: '#/components/schemas/Event.session.diff' - $ref: '#/components/schemas/Event.session.error' - $ref: '#/components/schemas/Event.file.watcher.updated' - $ref: '#/components/schemas/Event.vcs.branch.updated' - $ref: '#/components/schemas/Event.pty.created' - $ref: '#/components/schemas/Event.pty.updated' - $ref: '#/components/schemas/Event.pty.exited' - $ref: '#/components/schemas/Event.pty.deleted' - $ref: '#/components/schemas/Event.server.connected' - $ref: '#/components/schemas/Event.global.disposed' GlobalEvent: type: object properties: directory: type: string payload: $ref: '#/components/schemas/Event' required: - directory - payload BadRequestError: type: object properties: data: {} errors: type: array items: type: object propertyNames: type: string additionalProperties: {} success: type: boolean const: false required: - data - errors - success NotFoundError: type: object properties: name: type: string const: NotFoundError data: type: object properties: message: type: string required: - message required: - name - data KeybindsConfig: description: Custom keybind configurations type: object properties: leader: description: Leader key for keybind combinations default: ctrl+x type: string app_exit: description: Exit the application default: ctrl+c,ctrl+d,q type: string editor_open: description: Open external editor default: e type: string theme_list: description: List available themes default: t type: string sidebar_toggle: description: Toggle sidebar default: b type: string scrollbar_toggle: description: Toggle session scrollbar default: none type: string username_toggle: description: Toggle username visibility default: none type: string status_view: description: View status default: s type: string session_export: description: Export session to editor default: x type: string session_new: description: Create a new session default: n type: string session_list: description: List all sessions default: l type: string session_timeline: description: Show session timeline default: g type: string session_fork: description: Fork session from message default: none type: string session_rename: description: Rename session default: none type: string session_share: description: Share current session default: none type: string session_unshare: description: Unshare current session default: none type: string session_interrupt: description: Interrupt current session default: escape type: string session_compact: description: Compact the session default: c type: string messages_page_up: description: Scroll messages up by one page default: pageup type: string messages_page_down: description: Scroll messages down by one page default: pagedown type: string messages_half_page_up: description: Scroll messages up by half page default: ctrl+alt+u type: string messages_half_page_down: description: Scroll messages down by half page default: ctrl+alt+d type: string messages_first: description: Navigate to first message default: ctrl+g,home type: string messages_last: description: Navigate to last message default: ctrl+alt+g,end type: string messages_next: description: Navigate to next message default: none type: string messages_previous: description: Navigate to previous message default: none type: string messages_last_user: description: Navigate to last user message default: none type: string messages_copy: description: Copy message default: y type: string messages_undo: description: Undo message default: u type: string messages_redo: description: Redo message default: r type: string messages_toggle_conceal: description: Toggle code block concealment in messages default: h type: string tool_details: description: Toggle tool details visibility default: none type: string model_list: description: List available models default: m type: string model_cycle_recent: description: Next recently used model default: f2 type: string model_cycle_recent_reverse: description: Previous recently used model default: shift+f2 type: string model_cycle_favorite: description: Next favorite model default: none type: string model_cycle_favorite_reverse: description: Previous favorite model default: none type: string command_list: description: List available commands default: ctrl+p type: string agent_list: description: List agents default: a type: string agent_cycle: description: Next agent default: tab type: string agent_cycle_reverse: description: Previous agent default: shift+tab type: string variant_cycle: description: Cycle model variants default: ctrl+t type: string input_clear: description: Clear input field default: ctrl+c type: string input_paste: description: Paste from clipboard default: ctrl+v type: string input_submit: description: Submit input default: return type: string input_newline: description: Insert newline in input default: shift+return,ctrl+return,alt+return,ctrl+j type: string input_move_left: description: Move cursor left in input default: left,ctrl+b type: string input_move_right: description: Move cursor right in input default: right,ctrl+f type: string input_move_up: description: Move cursor up in input default: up type: string input_move_down: description: Move cursor down in input default: down type: string input_select_left: description: Select left in input default: shift+left type: string input_select_right: description: Select right in input default: shift+right type: string input_select_up: description: Select up in input default: shift+up type: string input_select_down: description: Select down in input default: shift+down type: string input_line_home: description: Move to start of line in input default: ctrl+a type: string input_line_end: description: Move to end of line in input default: ctrl+e type: string input_select_line_home: description: Select to start of line in input default: ctrl+shift+a type: string input_select_line_end: description: Select to end of line in input default: ctrl+shift+e type: string input_visual_line_home: description: Move to start of visual line in input default: alt+a type: string input_visual_line_end: description: Move to end of visual line in input default: alt+e type: string input_select_visual_line_home: description: Select to start of visual line in input default: alt+shift+a type: string input_select_visual_line_end: description: Select to end of visual line in input default: alt+shift+e type: string input_buffer_home: description: Move to start of buffer in input default: home type: string input_buffer_end: description: Move to end of buffer in input default: end type: string input_select_buffer_home: description: Select to start of buffer in input default: shift+home type: string input_select_buffer_end: description: Select to end of buffer in input default: shift+end type: string input_delete_line: description: Delete line in input default: ctrl+shift+d type: string input_delete_to_line_end: description: Delete to end of line in input default: ctrl+k type: string input_delete_to_line_start: description: Delete to start of line in input default: ctrl+u type: string input_backspace: description: Backspace in input default: backspace,shift+backspace type: string input_delete: description: Delete character in input default: ctrl+d,delete,shift+delete type: string input_undo: description: Undo in input default: ctrl+-,super+z type: string input_redo: description: Redo in input default: ctrl+.,super+shift+z type: string input_word_forward: description: Move word forward in input default: alt+f,alt+right,ctrl+right type: string input_word_backward: description: Move word backward in input default: alt+b,alt+left,ctrl+left type: string input_select_word_forward: description: Select word forward in input default: alt+shift+f,alt+shift+right type: string input_select_word_backward: description: Select word backward in input default: alt+shift+b,alt+shift+left type: string input_delete_word_forward: description: Delete word forward in input default: alt+d,alt+delete,ctrl+delete type: string input_delete_word_backward: description: Delete word backward in input default: ctrl+w,ctrl+backspace,alt+backspace type: string history_previous: description: Previous history item default: up type: string history_next: description: Next history item default: down type: string session_child_cycle: description: Next child session default: right type: string session_child_cycle_reverse: description: Previous child session default: left type: string session_parent: description: Go to parent session default: up type: string terminal_suspend: description: Suspend terminal default: ctrl+z type: string terminal_title_toggle: description: Toggle terminal title default: none type: string tips_toggle: description: Toggle tips on home screen default: h type: string additionalProperties: false LogLevel: description: Log level type: string enum: - DEBUG - INFO - WARN - ERROR ServerConfig: description: Server configuration for opencode serve and web commands type: object properties: port: description: Port to listen on type: integer exclusiveMinimum: 0 maximum: 9007199254740991 hostname: description: Hostname to listen on type: string mdns: description: Enable mDNS service discovery type: boolean cors: description: Additional domains to allow for CORS type: array items: type: string additionalProperties: false PermissionActionConfig: type: string enum: - ask - allow - deny PermissionObjectConfig: type: object propertyNames: type: string additionalProperties: $ref: '#/components/schemas/PermissionActionConfig' PermissionRuleConfig: anyOf: - $ref: '#/components/schemas/PermissionActionConfig' - $ref: '#/components/schemas/PermissionObjectConfig' PermissionConfig: anyOf: - type: object properties: read: $ref: '#/components/schemas/PermissionRuleConfig' edit: $ref: '#/components/schemas/PermissionRuleConfig' glob: $ref: '#/components/schemas/PermissionRuleConfig' grep: $ref: '#/components/schemas/PermissionRuleConfig' list: $ref: '#/components/schemas/PermissionRuleConfig' bash: $ref: '#/components/schemas/PermissionRuleConfig' task: $ref: '#/components/schemas/PermissionRuleConfig' external_directory: $ref: '#/components/schemas/PermissionRuleConfig' todowrite: $ref: '#/components/schemas/PermissionActionConfig' todoread: $ref: '#/components/schemas/PermissionActionConfig' webfetch: $ref: '#/components/schemas/PermissionActionConfig' websearch: $ref: '#/components/schemas/PermissionActionConfig' codesearch: $ref: '#/components/schemas/PermissionActionConfig' lsp: $ref: '#/components/schemas/PermissionRuleConfig' doom_loop: $ref: '#/components/schemas/PermissionActionConfig' additionalProperties: $ref: '#/components/schemas/PermissionRuleConfig' - $ref: '#/components/schemas/PermissionActionConfig' AgentConfig: type: object properties: model: type: string temperature: type: number top_p: type: number prompt: type: string tools: description: "@deprecated Use 'permission' field instead" type: object propertyNames: type: string additionalProperties: type: boolean disable: type: boolean description: description: Description of when to use the agent type: string mode: type: string enum: - subagent - primary - all options: type: object propertyNames: type: string additionalProperties: {} color: description: 'Hex color code for the agent (e.g., #FF5733)' type: string pattern: ^#[0-9a-fA-F]{6}$ steps: description: Maximum number of agentic iterations before forcing text-only response type: integer exclusiveMinimum: 0 maximum: 9007199254740991 maxSteps: description: "@deprecated Use 'steps' field instead." type: integer exclusiveMinimum: 0 maximum: 9007199254740991 permission: $ref: '#/components/schemas/PermissionConfig' additionalProperties: {} ProviderConfig: type: object properties: api: type: string name: type: string env: type: array items: type: string id: type: string npm: type: string models: type: object propertyNames: type: string additionalProperties: type: object properties: id: type: string name: type: string family: type: string release_date: type: string attachment: type: boolean reasoning: type: boolean temperature: type: boolean tool_call: type: boolean interleaved: anyOf: - type: boolean const: true - type: object properties: field: type: string enum: - reasoning_content - reasoning_details required: - field additionalProperties: false cost: type: object properties: input: type: number output: type: number cache_read: type: number cache_write: type: number context_over_200k: type: object properties: input: type: number output: type: number cache_read: type: number cache_write: type: number required: - input - output required: - input - output limit: type: object properties: context: type: number output: type: number required: - context - output modalities: type: object properties: input: type: array items: type: string enum: - text - audio - image - video - pdf output: type: array items: type: string enum: - text - audio - image - video - pdf required: - input - output experimental: type: boolean status: type: string enum: - alpha - beta - deprecated options: type: object propertyNames: type: string additionalProperties: {} headers: type: object propertyNames: type: string additionalProperties: type: string provider: type: object properties: npm: type: string required: - npm variants: description: Variant-specific configuration type: object propertyNames: type: string additionalProperties: type: object properties: disabled: description: Disable this variant for the model type: boolean additionalProperties: {} whitelist: type: array items: type: string blacklist: type: array items: type: string options: type: object properties: apiKey: type: string baseURL: type: string enterpriseUrl: description: GitHub Enterprise URL for copilot authentication type: string setCacheKey: description: Enable promptCacheKey for this provider (default false) type: boolean timeout: description: Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout. anyOf: - description: Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout. type: integer exclusiveMinimum: 0 maximum: 9007199254740991 - description: Disable timeout for this provider entirely. type: boolean const: false additionalProperties: {} additionalProperties: false McpLocalConfig: type: object properties: type: description: Type of MCP server connection type: string const: local command: description: Command and arguments to run the MCP server type: array items: type: string environment: description: Environment variables to set when running the MCP server type: object propertyNames: type: string additionalProperties: type: string enabled: description: Enable or disable the MCP server on startup type: boolean timeout: description: Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. type: integer exclusiveMinimum: 0 maximum: 9007199254740991 required: - type - command additionalProperties: false McpOAuthConfig: type: object properties: clientId: description: OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted. type: string clientSecret: description: OAuth client secret (if required by the authorization server) type: string scope: description: OAuth scopes to request during authorization type: string additionalProperties: false McpRemoteConfig: type: object properties: type: description: Type of MCP server connection type: string const: remote url: description: URL of the remote MCP server type: string enabled: description: Enable or disable the MCP server on startup type: boolean headers: description: Headers to send with the request type: object propertyNames: type: string additionalProperties: type: string oauth: description: OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection. anyOf: - $ref: '#/components/schemas/McpOAuthConfig' - type: boolean const: false timeout: description: Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified. type: integer exclusiveMinimum: 0 maximum: 9007199254740991 required: - type - url additionalProperties: false LayoutConfig: description: '@deprecated Always uses stretch layout.' type: string enum: - auto - stretch Config: type: object properties: $schema: description: JSON schema reference for configuration validation type: string theme: description: Theme name to use for the interface type: string keybinds: $ref: '#/components/schemas/KeybindsConfig' logLevel: $ref: '#/components/schemas/LogLevel' tui: description: TUI specific settings type: object properties: scroll_speed: description: TUI scroll speed type: number minimum: 0.001 scroll_acceleration: description: Scroll acceleration settings type: object properties: enabled: description: Enable scroll acceleration type: boolean required: - enabled diff_style: description: "Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column" type: string enum: - auto - stacked server: $ref: '#/components/schemas/ServerConfig' command: description: Command configuration, see https://opencode.ai/docs/commands type: object propertyNames: type: string additionalProperties: type: object properties: template: type: string description: type: string agent: type: string model: type: string subtask: type: boolean required: - template watcher: type: object properties: ignore: type: array items: type: string plugin: type: array items: type: string snapshot: type: boolean share: description: Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing type: string enum: - manual - auto - disabled autoshare: description: "@deprecated Use 'share' field instead. Share newly created sessions automatically" type: boolean autoupdate: description: Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications anyOf: - type: boolean - type: string const: notify disabled_providers: description: Disable providers that are loaded automatically type: array items: type: string enabled_providers: description: When set, ONLY these providers will be enabled. All other providers will be ignored type: array items: type: string model: description: Model to use in the format of provider/model, eg anthropic/claude-2 type: string small_model: description: Small model to use for tasks like title generation in the format of provider/model type: string default_agent: description: Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid. type: string username: description: Custom username to display in conversations instead of system username type: string mode: description: '@deprecated Use `agent` field instead.' type: object properties: build: $ref: '#/components/schemas/AgentConfig' plan: $ref: '#/components/schemas/AgentConfig' additionalProperties: $ref: '#/components/schemas/AgentConfig' agent: description: Agent configuration, see https://opencode.ai/docs/agent type: object properties: plan: $ref: '#/components/schemas/AgentConfig' build: $ref: '#/components/schemas/AgentConfig' general: $ref: '#/components/schemas/AgentConfig' explore: $ref: '#/components/schemas/AgentConfig' title: $ref: '#/components/schemas/AgentConfig' summary: $ref: '#/components/schemas/AgentConfig' compaction: $ref: '#/components/schemas/AgentConfig' additionalProperties: $ref: '#/components/schemas/AgentConfig' provider: description: Custom provider configurations and model overrides type: object propertyNames: type: string additionalProperties: $ref: '#/components/schemas/ProviderConfig' mcp: description: MCP (Model Context Protocol) server configurations type: object propertyNames: type: string additionalProperties: anyOf: - $ref: '#/components/schemas/McpLocalConfig' - $ref: '#/components/schemas/McpRemoteConfig' formatter: anyOf: - type: boolean const: false - type: object propertyNames: type: string additionalProperties: type: object properties: disabled: type: boolean command: type: array items: type: string environment: type: object propertyNames: type: string additionalProperties: type: string extensions: type: array items: type: string lsp: anyOf: - type: boolean const: false - type: object propertyNames: type: string additionalProperties: anyOf: - type: object properties: disabled: type: boolean const: true required: - disabled - type: object properties: command: type: array items: type: string extensions: type: array items: type: string disabled: type: boolean env: type: object propertyNames: type: string additionalProperties: type: string initialization: type: object propertyNames: type: string additionalProperties: {} required: - command instructions: description: Additional instruction files or patterns to include type: array items: type: string layout: $ref: '#/components/schemas/LayoutConfig' permission: $ref: '#/components/schemas/PermissionConfig' tools: type: object propertyNames: type: string additionalProperties: type: boolean enterprise: type: object properties: url: description: Enterprise URL type: string compaction: type: object properties: auto: description: 'Enable automatic compaction when context is full (default: true)' type: boolean prune: description: 'Enable pruning of old tool outputs (default: true)' type: boolean experimental: type: object properties: hook: type: object properties: file_edited: type: object propertyNames: type: string additionalProperties: type: array items: type: object properties: command: type: array items: type: string environment: type: object propertyNames: type: string additionalProperties: type: string required: - command session_completed: type: array items: type: object properties: command: type: array items: type: string environment: type: object propertyNames: type: string additionalProperties: type: string required: - command chatMaxRetries: description: Number of retries for chat completions on failure type: number disable_paste_summary: type: boolean batch_tool: description: Enable the batch tool type: boolean openTelemetry: description: Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag) type: boolean primary_tools: description: Tools that should only be available to primary agents. type: array items: type: string continue_loop_on_deny: description: Continue the agent loop when a tool call is denied type: boolean mcp_timeout: description: Timeout in milliseconds for model context protocol (MCP) requests type: integer exclusiveMinimum: 0 maximum: 9007199254740991 additionalProperties: false ToolIDs: type: array items: type: string ToolListItem: type: object properties: id: type: string description: type: string parameters: {} required: - id - description - parameters ToolList: type: array items: $ref: '#/components/schemas/ToolListItem' Path: type: object properties: home: type: string state: type: string config: type: string worktree: type: string directory: type: string required: - home - state - config - worktree - directory VcsInfo: type: object properties: branch: type: string required: - branch TextPartInput: type: object properties: id: type: string type: type: string const: text text: type: string synthetic: type: boolean ignored: type: boolean time: type: object properties: start: type: number end: type: number required: - start metadata: type: object propertyNames: type: string additionalProperties: {} required: - type - text FilePartInput: type: object properties: id: type: string type: type: string const: file mime: type: string filename: type: string url: type: string source: $ref: '#/components/schemas/FilePartSource' required: - type - mime - url AgentPartInput: type: object properties: id: type: string type: type: string const: agent name: type: string source: type: object properties: value: type: string start: type: integer minimum: -9007199254740991 maximum: 9007199254740991 end: type: integer minimum: -9007199254740991 maximum: 9007199254740991 required: - value - start - end required: - type - name SubtaskPartInput: type: object properties: id: type: string type: type: string const: subtask prompt: type: string description: type: string agent: type: string command: type: string required: - type - prompt - description - agent Command: type: object properties: name: type: string description: type: string agent: type: string model: type: string mcp: type: boolean template: anyOf: - type: string - type: string subtask: type: boolean hints: type: array items: type: string required: - name - template - hints Model: type: object properties: id: type: string providerID: type: string api: type: object properties: id: type: string url: type: string npm: type: string required: - id - url - npm name: type: string family: type: string capabilities: type: object properties: temperature: type: boolean reasoning: type: boolean attachment: type: boolean toolcall: type: boolean input: type: object properties: text: type: boolean audio: type: boolean image: type: boolean video: type: boolean pdf: type: boolean required: - text - audio - image - video - pdf output: type: object properties: text: type: boolean audio: type: boolean image: type: boolean video: type: boolean pdf: type: boolean required: - text - audio - image - video - pdf interleaved: anyOf: - type: boolean - type: object properties: field: type: string enum: - reasoning_content - reasoning_details required: - field required: - temperature - reasoning - attachment - toolcall - input - output - interleaved cost: type: object properties: input: type: number output: type: number cache: type: object properties: read: type: number write: type: number required: - read - write experimentalOver200K: type: object properties: input: type: number output: type: number cache: type: object properties: read: type: number write: type: number required: - read - write required: - input - output - cache required: - input - output - cache limit: type: object properties: context: type: number output: type: number required: - context - output status: type: string enum: - alpha - beta - deprecated - active options: type: object propertyNames: type: string additionalProperties: {} headers: type: object propertyNames: type: string additionalProperties: type: string release_date: type: string variants: type: object propertyNames: type: string additionalProperties: type: object propertyNames: type: string additionalProperties: {} required: - id - providerID - api - name - capabilities - cost - limit - status - options - headers - release_date Provider: type: object properties: id: type: string name: type: string source: type: string enum: - env - config - custom - api env: type: array items: type: string key: type: string options: type: object propertyNames: type: string additionalProperties: {} models: type: object propertyNames: type: string additionalProperties: $ref: '#/components/schemas/Model' required: - id - name - source - env - options - models ProviderAuthMethod: type: object properties: type: anyOf: - type: string const: oauth - type: string const: api label: type: string required: - type - label ProviderAuthAuthorization: type: object properties: url: type: string method: anyOf: - type: string const: auto - type: string const: code instructions: type: string required: - url - method - instructions Symbol: type: object properties: name: type: string kind: type: number location: type: object properties: uri: type: string range: $ref: '#/components/schemas/Range' required: - uri - range required: - name - kind - location FileNode: type: object properties: name: type: string path: type: string absolute: type: string type: type: string enum: - file - directory ignored: type: boolean required: - name - path - absolute - type - ignored FileContent: type: object properties: type: type: string const: text content: type: string diff: type: string patch: type: object properties: oldFileName: type: string newFileName: type: string oldHeader: type: string newHeader: type: string hunks: type: array items: type: object properties: oldStart: type: number oldLines: type: number newStart: type: number newLines: type: number lines: type: array items: type: string required: - oldStart - oldLines - newStart - newLines - lines index: type: string required: - oldFileName - newFileName - hunks encoding: type: string const: base64 mimeType: type: string required: - type - content File: type: object properties: path: type: string added: type: integer minimum: -9007199254740991 maximum: 9007199254740991 removed: type: integer minimum: -9007199254740991 maximum: 9007199254740991 status: type: string enum: - added - deleted - modified required: - path - added - removed - status Agent: type: object properties: name: type: string description: type: string mode: type: string enum: - subagent - primary - all native: type: boolean hidden: type: boolean topP: type: number temperature: type: number color: type: string permission: $ref: '#/components/schemas/PermissionRuleset' model: type: object properties: modelID: type: string providerID: type: string required: - modelID - providerID prompt: type: string options: type: object propertyNames: type: string additionalProperties: {} steps: type: integer exclusiveMinimum: 0 maximum: 9007199254740991 required: - name - mode - permission - options MCPStatusConnected: type: object properties: status: type: string const: connected required: - status MCPStatusDisabled: type: object properties: status: type: string const: disabled required: - status MCPStatusFailed: type: object properties: status: type: string const: failed error: type: string required: - status - error MCPStatusNeedsAuth: type: object properties: status: type: string const: needs_auth required: - status MCPStatusNeedsClientRegistration: type: object properties: status: type: string const: needs_client_registration error: type: string required: - status - error MCPStatus: anyOf: - $ref: '#/components/schemas/MCPStatusConnected' - $ref: '#/components/schemas/MCPStatusDisabled' - $ref: '#/components/schemas/MCPStatusFailed' - $ref: '#/components/schemas/MCPStatusNeedsAuth' - $ref: '#/components/schemas/MCPStatusNeedsClientRegistration' LSPStatus: type: object properties: id: type: string name: type: string root: type: string status: anyOf: - type: string const: connected - type: string const: error required: - id - name - root - status FormatterStatus: type: object properties: name: type: string extensions: type: array items: type: string enabled: type: boolean required: - name - extensions - enabled OAuth: type: object properties: type: type: string const: oauth refresh: type: string access: type: string expires: type: number enterpriseUrl: type: string required: - type - refresh - access - expires ApiAuth: type: object properties: type: type: string const: api key: type: string required: - type - key WellKnownAuth: type: object properties: type: type: string const: wellknown key: type: string token: type: string required: - type - key - token Auth: anyOf: - $ref: '#/components/schemas/OAuth' - $ref: '#/components/schemas/ApiAuth' - $ref: '#/components/schemas/WellKnownAuth' ================================================ FILE: specs/3.1.x/operation-204.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 operation 204 example", "version": "1" }, "paths": { "/foo": { "post": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "string" } } } }, "204": { "description": "Created" } } } } } } ================================================ FILE: specs/3.1.x/orpc.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 oRPC example version: 1 paths: /users: get: tags: - users operationId: getUsers summary: Get all users parameters: - name: limit in: query description: Maximum number of users to return required: false schema: type: integer default: 10 - name: offset in: query description: Number of users to skip required: false schema: type: integer default: 0 responses: '200': description: List of users content: application/json: schema: type: array items: $ref: '#/components/schemas/User' post: tags: - users operationId: createUser summary: Create a new user requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateUserInput' responses: '201': description: User created content: application/json: schema: $ref: '#/components/schemas/User' /users/{userId}: get: tags: - users operationId: getUserById summary: Get a user by ID parameters: - name: userId in: path description: User ID required: true schema: type: string responses: '200': description: User found content: application/json: schema: $ref: '#/components/schemas/User' put: tags: - users operationId: updateUser summary: Update a user parameters: - name: userId in: path description: User ID required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/UpdateUserInput' responses: '200': description: User updated content: application/json: schema: $ref: '#/components/schemas/User' delete: tags: - users operationId: deleteUser summary: Delete a user parameters: - name: userId in: path description: User ID required: true schema: type: string - name: X-Request-Id in: header description: Request ID for tracing required: false schema: type: string responses: '204': description: User deleted /posts: get: tags: - posts operationId: getPosts summary: Get all posts parameters: - name: authorId in: query description: Filter by author ID required: false schema: type: string - name: status in: query description: Filter by status required: false schema: type: string enum: - draft - published - archived responses: '200': description: List of posts content: application/json: schema: type: array items: $ref: '#/components/schemas/Post' post: tags: - posts operationId: createPost summary: Create a new post parameters: - name: X-Author-Id in: header description: Author ID required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreatePostInput' responses: '201': description: Post created content: application/json: schema: $ref: '#/components/schemas/Post' /posts/{postId}: get: tags: - posts operationId: getPostById summary: Get a post by ID parameters: - name: postId in: path description: Post ID required: true schema: type: string - name: includeComments in: query description: Include comments in response required: false schema: type: boolean default: false responses: '200': description: Post found content: application/json: schema: $ref: '#/components/schemas/Post' components: schemas: User: type: object required: - id - email - name properties: id: type: string email: type: string format: email name: type: string createdAt: type: string format: date-time CreateUserInput: type: object required: - email - name properties: email: type: string format: email name: type: string password: type: string minLength: 8 UpdateUserInput: type: object properties: email: type: string format: email name: type: string Post: type: object required: - id - title - content - authorId properties: id: type: string title: type: string content: type: string authorId: type: string status: type: string enum: - draft - published - archived createdAt: type: string format: date-time CreatePostInput: type: object required: - title - content properties: title: type: string content: type: string status: type: string enum: - draft - published default: draft ================================================ FILE: specs/3.1.x/pagination-ref.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 pagination ref example version: 1 paths: /foo: get: parameters: - in: query name: foo required: true schema: $ref: '#/components/schemas/Bar' responses: '200': description: OK content: '*/*': schema: type: number post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Foo' required: true responses: '200': description: OK components: schemas: Foo: properties: page: anyOf: - type: integer minimum: 1.0 - type: 'null' default: 1 type: object Bar: properties: page: type: - integer - 'null' format: int32 minimum: 0 size: type: - integer - 'null' format: int32 minimum: 1 sort: type: - array - 'null' items: type: string required: - page - size - sort type: object ================================================ FILE: specs/3.1.x/parameter-explode-false.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 parameter explode false example", "version": "1" }, "paths": { "/foo": { "post": { "parameters": [ { "name": "foo", "in": "query", "explode": false, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "default": { "description": "OK" } } } } } } ================================================ FILE: specs/3.1.x/parameter-tuple.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 parameter tuple example", "version": "1" }, "paths": { "/foo": { "post": { "parameters": [ { "name": "tuple", "in": "query", "schema": { "type": "array", "minItems": 4, "maxItems": 4, "items": { "type": "number" } } } ], "responses": { "default": { "description": "OK" } } } } } } ================================================ FILE: specs/3.1.x/parser-filters.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 parser filters example version: 1 paths: /v1/foo: post: deprecated: true tags: - foo - bar parameters: - $ref: '#/components/parameters/Foo' requestBody: $ref: '#/components/requestBodies/Foo' responses: '200': content: '*/*': schema: $ref: '#/components/schemas/Foo' description: OK put: tags: - bar requestBody: $ref: '#/components/requestBodies/Bar' responses: '200': content: '*/*': schema: $ref: '#/components/schemas/Baz' description: OK /v2/bar: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Bar' required: true responses: '200': content: '*/*': schema: $ref: '#/components/schemas/Bar' description: OK components: parameters: Foo: name: foo in: query description: Query parameter required: false schema: type: string requestBodies: Foo: required: true description: POST /foo payload content: 'application/json': schema: type: object properties: foo: $ref: '#/components/schemas/Bar' Bar: required: true description: PUT /foo payload content: 'application/json': schema: type: object properties: foo: $ref: '#/components/schemas/Foo' schemas: Foo: type: object properties: foo: $ref: '#/components/schemas/Bar' Bar: type: object properties: bar: $ref: '#/components/schemas/Baz' Baz: type: object properties: baz: type: string Orphan: type: object properties: orphan: type: string ================================================ FILE: specs/3.1.x/pattern-properties.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 pattern properties example", "version": "1" }, "paths": { "/pattern-test": { "post": { "summary": "Test pattern properties", "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PatternPropertiesTest" } } } }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PatternPropertiesResponse" } } } } } } } }, "components": { "schemas": { "PatternPropertiesTest": { "type": "object", "properties": { "id": { "type": "string" }, "metadata": { "$ref": "#/components/schemas/MetadataObject" } }, "additionalProperties": false }, "MetadataObject": { "type": "object", "properties": { "name": { "type": "string" }, "description": { "type": "string" } }, "patternProperties": { "^meta_": { "type": "string", "description": "Any property starting with 'meta_' must be a string" }, "^config_": { "type": "object", "properties": { "value": { "type": "string" }, "enabled": { "type": "boolean" } }, "additionalProperties": false }, "^tag_[a-zA-Z0-9_]+$": { "type": "string", "description": "Tag properties must match pattern and be strings" }, "^[0-9]+_item$": { "type": "array", "items": { "type": "string" }, "description": "Numbered item properties must be arrays of strings" } }, "additionalProperties": false }, "NestedPatternObject": { "type": "object", "properties": { "base": { "type": "string" } }, "patternProperties": { "^nested_": { "type": "object", "patternProperties": { "^sub_": { "type": "string" } }, "additionalProperties": false } }, "additionalProperties": false }, "UnionPatternObject": { "type": "object", "properties": { "type": { "type": "string", "enum": ["user", "admin", "guest"] } }, "patternProperties": { "^user_": { "oneOf": [ { "type": "string" }, { "type": "number" } ] }, "^admin_": { "allOf": [ { "type": "object" }, { "properties": { "level": { "type": "number", "minimum": 1, "maximum": 10 } } } ] } }, "additionalProperties": false }, "PatternPropertiesResponse": { "type": "object", "properties": { "success": { "type": "boolean" }, "data": { "$ref": "#/components/schemas/MetadataObject" } }, "additionalProperties": false } } } } ================================================ FILE: specs/3.1.x/ref-deep.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 ref deep example version: '1' paths: /foo: get: responses: '200': description: OK content: application/json: schema: type: array items: type: object properties: foo: type: integer bar: type: string post: responses: '200': description: OK content: application/json: schema: type: object properties: foo: $ref: '#/paths/~1foo/get/responses/200/content/application~1json/schema/items' bar: type: string components: schemas: Foo: type: object properties: foo: type: array items: type: object properties: baz: type: string bar: type: array items: type: object properties: baz: type: string Bar: type: object properties: foo: type: array items: $ref: '#/components/schemas/Foo/properties/foo/items' bar: type: array items: $ref: '#/components/schemas/Foo/properties/bar/items' ================================================ FILE: specs/3.1.x/ref-type.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 ref type example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Foo", "type": ["object", "null"] } } } } } } } }, "components": { "schemas": { "Foo": { "properties": { "foo": { "items": { "properties": { "baz": { "$ref": "#/components/schemas/Bar", "type": ["object", "null"] } }, "required": ["baz"], "type": "object" }, "type": "array" } }, "required": ["foo"], "type": "object" }, "Bar": { "properties": { "bar": { "type": "integer" } }, "required": ["bar"], "type": "object" } } } } ================================================ FILE: specs/3.1.x/required-all-of-ref.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.0.0" }, "components": { "schemas": { "Foo": { "type": "object", "properties": { "foo": { "type": "string" }, "baz": { "type": "string" } } }, "Bar": { "type": "object", "allOf": [ { "$ref": "#/components/schemas/Foo" } ], "properties": { "bar": { "type": "number" } }, "required": ["foo", "bar", "baz"] } } } } ================================================ FILE: specs/3.1.x/required-any-of-ref.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.0.0" }, "components": { "schemas": { "Foo": { "type": "object", "properties": { "foo": { "type": "string" }, "baz": { "type": "string" } } }, "Bar": { "type": "object", "anyOf": [ { "$ref": "#/components/schemas/Foo" } ], "properties": { "bar": { "type": "number" } }, "required": ["foo", "bar", "baz"] } } } } ================================================ FILE: specs/3.1.x/required-one-of-ref.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.0.0" }, "components": { "schemas": { "Foo": { "type": "object", "properties": { "foo": { "type": "string" }, "baz": { "type": "string" } } }, "Bar": { "type": "object", "oneOf": [ { "$ref": "#/components/schemas/Foo" } ], "properties": { "bar": { "type": "number" } }, "required": ["foo", "bar", "baz"] } } } } ================================================ FILE: specs/3.1.x/schema-const.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 schema const example version: 1 components: schemas: Foo: properties: foo: const: foo type: string bar: const: 3.2 type: number baz: const: -1 type: integer qux: const: true type: boolean quux: const: [1, 2, 3, 'foo', true] type: array corge: const: foo: 1 bar: true baz: grault type: object garply: const: 10n format: int64 type: integer # Integer format const examples - number type numberInt8: const: 100 format: int8 type: number numberInt16: const: 1000 format: int16 type: number numberInt32: const: 100000 format: int32 type: number numberInt64: const: 1000000000000 format: int64 type: number numberUint8: const: 200 format: uint8 type: number numberUint16: const: 50000 format: uint16 type: number numberUint32: const: 3000000000 format: uint32 type: number numberUint64: const: 18000000000000000000 format: uint64 type: number # Integer format const examples - integer type integerInt8: const: -100 format: int8 type: integer integerInt16: const: -1000 format: int16 type: integer integerInt32: const: -100000 format: int32 type: integer integerInt64: const: -1000000000000 format: int64 type: integer integerUint8: const: 255 format: uint8 type: integer integerUint16: const: 65535 format: uint16 type: integer integerUint32: const: 4294967295 format: uint32 type: integer integerUint64: const: 18446744073709551615n format: uint64 type: integer # Integer format const examples - string type (only for 64-bit formats) stringInt64: const: '-9223372036854775808' format: int64 type: string stringUint64: const: '18446744073709551615' format: uint64 type: string type: object ================================================ FILE: specs/3.1.x/sdk-instance.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 sdk instance example version: 1 paths: /foo: get: tags: - fooBaz responses: '200': content: '*/*': schema: type: string description: OK post: tags: - fooBaz operationId: foo.-post responses: '200': content: '*/*': schema: type: string description: OK put: tags: - fooBaz operationId: /foo/-put/ responses: '200': content: '*/*': schema: type: string description: OK /foo/bar: get: tags: - barBaz responses: '200': content: '*/*': schema: type: string description: OK post: tags: - fooBaz - barBaz operationId: foo.bar.post responses: '200': content: '*/*': schema: type: string description: OK put: tags: - fooBaz - barBaz operationId: /foo/bar/put/ responses: '200': content: '*/*': schema: type: string description: OK ================================================ FILE: specs/3.1.x/sdk-nested-classes.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 sdk nested classes example version: 1 paths: /business/providers/domains: get: tags: - business - providers - domains operationId: business.providers.domains.get responses: '200': content: '*/*': schema: type: string description: OK post: tags: - providers - domains - business operationId: business.providers.domains.post responses: '200': content: '*/*': schema: type: string description: OK put: tags: - domains responses: '200': content: '*/*': schema: type: string description: OK /locations/businesses: get: tags: - locations - business operationId: business.get responses: '200': content: '*/*': schema: type: string description: OK /locations: get: tags: - locations operationId: get responses: '200': content: '*/*': schema: type: string description: OK ================================================ FILE: specs/3.1.x/sdk-nested-conflict.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 sdk nested conflict example version: 1 paths: /v1/providers: get: operationId: providers.list summary: List Providers tags: - providers /v1/tenants/{tenantId}/providers: get: operationId: tenants.providers.list summary: List Tenant Providers tags: - tenants - tenantProviders parameters: - name: tenantId in: path required: true schema: type: string description: Tenant ID ================================================ FILE: specs/3.1.x/sdk-signatures.yaml ================================================ openapi: 3.1.0 info: title: SDK signatures version: 1.0.0 paths: /no-params: get: operationId: noParams summary: No parameters responses: '200': description: OK /one-path/{id}: get: operationId: onePath summary: One path parameter parameters: - name: id in: path required: true schema: type: string responses: '200': description: OK /one-query: get: operationId: oneQuery summary: One query parameter parameters: - name: search in: query schema: type: string responses: '200': description: OK /multiple-params/{id}: post: operationId: multipleParams summary: Path, query, header, and body parameters: - name: id in: path required: true schema: type: string - name: filter in: query schema: type: string - name: X-Request-Id in: header schema: type: string requestBody: required: true content: application/json: schema: type: object properties: foo: type: string responses: '200': description: OK /conflict/{foo}: get: operationId: conflict summary: Conflicting parameter names parameters: - name: foo in: path required: true schema: type: string - name: foo in: query schema: type: string - name: foo in: header schema: type: string responses: '200': description: OK /body-only: post: operationId: bodyOnly summary: Only body parameter requestBody: required: true content: application/json: schema: type: object properties: bar: type: string responses: '200': description: OK /optional-params: get: operationId: optionalParams summary: Optional query and header parameters: - name: q in: query required: false schema: type: string - name: X-Optional in: header required: false schema: type: string responses: '200': description: OK /reserved-keywords/{default}: get: operationId: reservedKeywords summary: Reserved keyword as parameter parameters: - name: default in: path required: true schema: type: string - name: default in: query schema: type: string responses: '200': description: OK /non-ascii/{æøå}: get: operationId: nonAscii summary: Non-ASCII parameter names parameters: - name: æøå in: path required: true schema: type: string - name: öôê in: query schema: type: string responses: '200': description: OK /array-params: get: operationId: arrayParams summary: Array parameters parameters: - name: tags in: query schema: type: array items: type: string responses: '200': description: OK /cookie-param: get: operationId: cookieParam summary: Cookie parameter parameters: - name: session in: cookie schema: type: string responses: '200': description: OK ================================================ FILE: specs/3.1.x/security-api-key.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 security api key example version: '1' paths: /foo: get: responses: '200': description: OK security: - foo: [] /bar: get: responses: '200': description: OK security: - bar: [] - MutualTLS: [] components: securitySchemes: foo: in: query name: foo type: apiKey bar: in: cookie name: bar type: apiKey MutualTLS: type: mutualTLS ================================================ FILE: specs/3.1.x/security-http-bearer.json ================================================ { "openapi": "3.1.1", "info": { "title": "OpenAPI 3.1.1 security bearer example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK" } }, "security": [ { "foo": [] } ] } } }, "components": { "securitySchemes": { "foo": { "bearerFormat": "JWT", "scheme": "bearer", "type": "http" } } } } ================================================ FILE: specs/3.1.x/security-oauth2.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 security oauth2 example version: '1' paths: /foo: get: responses: '200': description: OK security: - foo: [] components: securitySchemes: foo: flows: authorizationCode: authorizationUrl: '/' tokenUrl: '/' scopes: {} clientCredentials: tokenUrl: '/' scopes: {} implicit: authorizationUrl: '/' scopes: {} password: scopes: {} tokenUrl: '/' type: 'oauth2' ================================================ FILE: specs/3.1.x/security-open-id-connect.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 security OpenID Connect example version: '1' paths: /foo: get: responses: '200': description: OK security: - foo: [] components: securitySchemes: foo: openIdConnectUrl: 'https://example.com/.well-known/openid-configuration' type: 'openIdConnect' ================================================ FILE: specs/3.1.x/servers.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 servers example version: 1 servers: - url: https://foo.com/v1 description: foo - url: /v1 paths: /foo: get: responses: '200': content: '*/*': schema: type: string description: OK ================================================ FILE: specs/3.1.x/sse-post.yaml ================================================ openapi: 3.1.0 info: title: SSE POST test version: 1.0.0 paths: /events/subscribe: post: operationId: subscribeToEventStream summary: Subscribe to event stream responses: '200': description: Event stream content: text/event-stream: schema: type: object /events/list: get: operationId: listEvents summary: List events responses: '200': description: OK content: application/json: schema: type: array items: type: string ================================================ FILE: specs/3.1.x/string-with-format.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 string with format example version: '1' components: schemas: Foo: properties: foo: items: anyOf: - type: string format: binary - type: string type: array ================================================ FILE: specs/3.1.x/string-with-guid-format.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 string with GUID format example version: '1' paths: /foo/{guidId}: get: operationId: getFoo parameters: - name: guidId in: path required: true schema: type: string format: guid responses: '200': description: OK ================================================ FILE: specs/3.1.x/time-format.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 time format example version: '1' paths: /search: get: summary: Search with time parameter parameters: - name: start_time in: query description: Start time in HH:MM:SS format schema: type: string format: time - name: end_time in: query description: End time in HH:MM:SS format required: true schema: type: string format: time responses: '200': description: Success content: application/json: schema: type: object properties: result: type: string scheduled_time: type: string format: time ================================================ FILE: specs/3.1.x/transformers-all-of.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 transformers all of example version: 1 paths: /foo: get: responses: '200': content: '*/*': schema: $ref: '#/components/schemas/Foo' description: OK components: schemas: Foo: type: object properties: foo: type: array items: $ref: '#/components/schemas/Bar' required: - foo Bar: type: object properties: foo: type: array items: oneOf: - $ref: '#/components/schemas/Baz' bar: type: string enum: - foo - bar - baz required: - foo - bar Baz: type: object allOf: - $ref: '#/components/schemas/Qux' - type: object properties: foo: format: int32 type: integer bar: format: date-time type: string baz: type: string enum: - foo - bar - baz qux: format: int32 type: integer required: - foo - bar - baz - qux Qux: type: object discriminator: propertyName: id properties: foo: type: integer format: int32 bar: type: number baz: format: date-time type: string id: type: string required: - foo - bar - id ================================================ FILE: specs/3.1.x/transformers-allof-response-wrapper.json ================================================ { "openapi": "3.1.0", "info": { "title": "Test Paginated Response", "version": "1.0.0" }, "servers": [ { "url": "{protocol}://specs", "variables": { "protocol": { "default": "https", "enum": ["http", "https"] } } } ], "components": { "schemas": { "PaginatedResponse": { "type": "object", "properties": { "meta": { "type": "object", "properties": { "page": { "type": "number" }, "limit": { "type": "number" }, "total": { "type": "number" }, "totalPages": { "type": "number" } } } } }, "RepositorySecret": { "type": "object", "properties": { "id": { "type": "number" }, "name": { "type": "string" }, "createdAt": { "format": "date-time", "type": "string" }, "updatedAt": { "format": "date-time", "type": "string" } }, "required": ["id", "name", "createdAt", "updatedAt"] } } }, "paths": { "/secrets": { "get": { "operationId": "listSecrets", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "title": "PaginatedResponseRepositorySecret", "allOf": [ { "$ref": "#/components/schemas/PaginatedResponse" }, { "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/RepositorySecret" } } } } ] } } } } } } }, "/secrets/{id}": { "post": { "operationId": "createSecret", "responses": { "201": { "description": "Created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RepositorySecret" } } } } } } } } } ================================================ FILE: specs/3.1.x/transformers-any-of-null.json ================================================ { "openapi": "3.1.1", "info": { "title": "OpenAPI 3.1.1 transformers any of null example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Foo" } } } } } } } }, "/polls": { "get": { "operationId": "getPoll", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Poll" } } } } } } }, "/polls/nullable": { "get": { "operationId": "getNullablePoll", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "anyOf": [ { "$ref": "#/components/schemas/Poll" }, { "type": "null" } ] } } } } } } }, "/api/nested-date-object": { "get": { "operationId": "nestedDateObject", "responses": { "200": { "description": "Object with nested date", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/NestedDateObject" } } } } } } } }, "components": { "schemas": { "Poll": { "type": "object", "properties": { "id": { "type": "integer" }, "createdAt": { "type": "string", "format": "date-time" } }, "required": ["id", "createdAt"] }, "NestedDateObject": { "description": "Object with a nested date structure", "type": "object", "properties": { "foo": { "type": "object", "properties": { "bar": { "type": "string", "format": "date-time" } } } } }, "Foo": { "type": "object", "properties": { "foo": { "type": "string", "format": "date-time" }, "bar": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "baz": { "anyOf": [ { "type": ["string", "null"], "format": "date-time" } ] }, "requiredQux": { "anyOf": [ { "type": ["string", "null"], "format": "date-time" } ] } }, "required": ["requiredQux"] } } } } ================================================ FILE: specs/3.1.x/transformers-array.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 transformers array example", "version": "1" }, "paths": { "/foo": { "get": { "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "foo": { "type": "array", "items": { "type": "object", "properties": { "baz": { "type": "string", "format": "date-time" } }, "required": ["baz"] } } }, "required": ["foo"] } } } } } } } } } ================================================ FILE: specs/3.1.x/transformers-one-of-discriminated.yaml ================================================ openapi: 3.1.1 info: title: Example API version: 1.0.0 paths: /rules: get: operationId: listRules responses: '200': description: Rules response content: application/json: schema: type: object required: - rules properties: rules: type: array items: $ref: '#/components/schemas/Rule' components: schemas: Rule: type: object required: - id - then properties: id: type: string createdAt: type: string format: date-time then: $ref: '#/components/schemas/Then' Then: description: Action to take when rule conditions are met oneOf: - $ref: '#/components/schemas/DirectAction' - $ref: '#/components/schemas/RoundRobinAction' - $ref: '#/components/schemas/CategoryAction' - $ref: '#/components/schemas/StatusAction' discriminator: propertyName: type mapping: direct: '#/components/schemas/DirectAction' round-robin: '#/components/schemas/RoundRobinAction' category: '#/components/schemas/CategoryAction' status: '#/components/schemas/StatusAction' DirectAction: type: object required: [type, assignee] properties: type: type: string const: direct assignee: type: string RoundRobinAction: type: object required: [type, id, items] properties: type: type: string const: round-robin id: type: string items: type: array items: type: string CategoryAction: type: object required: [type, category] properties: type: type: string const: category category: type: string StatusAction: type: object required: [type, status] properties: type: type: string const: status status: type: string ================================================ FILE: specs/3.1.x/transformers-recursive.json ================================================ { "openapi": "3.1.0", "info": { "title": "Recursive Schema Test", "version": "1.0.0" }, "paths": { "/tree": { "get": { "operationId": "getTree", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/TreeNode" } } } } } } } } }, "components": { "schemas": { "TreeNode": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "createdAt": { "type": "string", "format": "date-time" }, "children": { "type": "array", "items": { "$ref": "#/components/schemas/TreeNode" } } } } } } } ================================================ FILE: specs/3.1.x/transformers.json ================================================ { "openapi": "3.1.0", "info": { "title": "swagger", "version": "v1.0" }, "servers": [ { "url": "http://localhost:3000/base" } ], "paths": { "/api/model-with-dates": { "post": { "operationId": "parentModelWithDates", "responses": { "200": { "description": "Success", "content": { "application/json; type=collection": { "schema": { "$ref": "#/components/schemas/ParentModelWithDates" } } } }, "201": { "description": "Success", "content": { "application/json; type=collection": { "schema": { "$ref": "#/components/schemas/ParentModelWithDates" } } } } } }, "put": { "operationId": "modelWithDates", "responses": { "200": { "description": "Success", "content": { "application/json; type=collection": { "schema": { "$ref": "#/components/schemas/ModelWithDates" } } } } } } }, "/api/model-with-dates-array": { "put": { "operationId": "modelWithDatesArray", "responses": { "200": { "description": "Success", "content": { "application/json; type=collection": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ModelWithDates" } } } } } } } }, "/api/array-of-dates": { "put": { "operationId": "arrayOfDates", "responses": { "200": { "description": "Success", "content": { "application/json; type=collection": { "schema": { "type": "array", "items": { "type": "string", "format": "date-time" } } } } } } } }, "/api/multiple-responses": { "put": { "operationId": "multiple-responses", "responses": { "200": { "description": "Updated", "content": { "application/json; type=collection": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ModelWithDates" } } } } }, "201": { "description": "Created", "content": { "application/json; type=collection": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/SimpleModel" } } } } } } } }, "/api/no-response-transformer": { "put": { "responses": { "200": { "description": "Updated", "content": { "application/json; type=collection": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/SimpleModel" } } } } } } } }, "/api/simple-date-response": { "post": { "responses": { "200": { "description": "Simple date string", "content": { "application/json": { "schema": { "type": "string", "format": "date-time" } } } } } }, "put": { "responses": { "200": { "description": "Simple date string ref", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/DateString" } } } } } } } }, "components": { "schemas": { "DateString": { "type": "string", "format": "date-time" }, "SimpleModel": { "description": "This is a model that contains a some dates", "type": "object", "required": ["id", "name", "enabled"], "properties": { "id": { "type": "number" }, "name": { "maxLength": 255, "type": "string" }, "enabled": { "type": "boolean", "readOnly": true } } }, "ModelWithDates": { "description": "This is a model that contains a some dates", "type": "object", "required": ["id", "name", "enabled", "modified"], "properties": { "id": { "type": "number" }, "name": { "maxLength": 255, "type": "string" }, "enabled": { "type": "boolean", "readOnly": true }, "modified": { "type": "string", "format": "date-time", "readOnly": true }, "expires": { "type": "string", "format": "date", "readOnly": true } } }, "ParentModelWithDates": { "description": "This is a model that contains a some dates and arrays", "type": "object", "required": ["id", "name"], "properties": { "id": { "type": "number" }, "modified": { "type": "string", "format": "date-time", "readOnly": true }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/ModelWithDates" } }, "item": { "$ref": "#/components/schemas/ModelWithDates" }, "nullable-date": { "type": "array", "items": { "anyOf": [{ "type": "string", "format": "date-time" }, { "type": "null" }] } }, "simpleItems": { "type": "array", "items": { "$ref": "#/components/schemas/SimpleModel" } }, "simpleItem": { "$ref": "#/components/schemas/SimpleModel" }, "dates": { "type": "array", "items": { "type": "string", "format": "date-time" } }, "strings": { "type": "array", "items": { "type": "string" } } } } } } } ================================================ FILE: specs/3.1.x/transforms-read-write-nested.yaml ================================================ openapi: 3.0.3 info: title: writeOnly repro version: 1.0.0 paths: /items: post: operationId: item_create requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateItemRequest' responses: '201': description: Created components: schemas: CreateItemRequest: type: object required: - payload properties: payload: $ref: '#/components/schemas/Payload' Payload: type: object required: - kind - encoded properties: kind: type: string enum: [jpeg] encoded: type: string writeOnly: true description: Data required on write ================================================ FILE: specs/3.1.x/transforms-read-write-response.yaml ================================================ openapi: 3.0.3 info: title: readOnly response test version: 1.0.0 paths: /items: get: operationId: item_list responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ItemListResponse' components: schemas: ItemListResponse: type: object required: - items properties: items: type: array items: $ref: '#/components/schemas/Item' Item: type: object required: - id - name properties: id: type: string readOnly: true description: Server-generated ID name: type: string created_at: type: string format: date-time readOnly: true description: Server-generated timestamp ================================================ FILE: specs/3.1.x/transforms-read-write-unevaluated.yaml ================================================ openapi: 3.1.0 info: title: readOnly map property with unevaluatedProperties version: 1.0.0 paths: /x: get: operationId: getX responses: '200': description: ok content: application/json: schema: $ref: '#/components/schemas/DisposableEmail' post: operationId: createX requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/DisposableEmail' responses: '200': description: ok content: application/json: schema: $ref: '#/components/schemas/DisposableEmail' components: schemas: DisposableEmail: type: object required: - domain - disposable - metadata properties: domain: type: string disposable: type: boolean readOnly: true metadata: type: object unevaluatedProperties: {} ================================================ FILE: specs/3.1.x/transforms-read-write.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 transforms read write example version: 1 paths: /foo-read-write: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/FooReadWrite' required: true responses: '200': content: '*/*': schema: $ref: '#/components/schemas/FooReadWrite' description: OK /foo-read: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/FooRead' required: true responses: '200': content: '*/*': schema: $ref: '#/components/schemas/FooRead' description: OK /foo-write: post: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/FooWrite' required: true responses: '200': content: '*/*': schema: $ref: '#/components/schemas/FooWrite' description: OK put: parameters: - $ref: '#/components/parameters/Foo' requestBody: $ref: '#/components/requestBodies/Foo' responses: '200': $ref: '#/components/responses/Foo' components: parameters: Foo: name: foo in: query description: Query parameter required: false schema: type: string requestBodies: Foo: required: true description: PUT /foo-write payload content: 'application/json': schema: type: object properties: foo: $ref: '#/components/schemas/BarRead' responses: Foo: content: '*/*': schema: $ref: '#/components/schemas/FooWrite' description: OK schemas: FooReadWrite: allOf: - $ref: '#/components/schemas/BarRead' - type: object properties: foo: writeOnly: true type: string FooRead: allOf: - $ref: '#/components/schemas/BarRead' - type: object properties: foo: readOnly: true type: string FooWrite: allOf: - $ref: '#/components/schemas/BarWrite' - type: object properties: foo: writeOnly: true type: string BarRead: anyOf: - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/QuxAllWrite' - $ref: '#/components/schemas/QuxAllRead' - type: object properties: bar: readOnly: true type: string BarWrite: anyOf: - $ref: '#/components/schemas/Baz' - $ref: '#/components/schemas/QuxAllWrite' - $ref: '#/components/schemas/QuxAllRead' - type: object properties: bar: writeOnly: true type: string Baz: type: object properties: baz: type: string QuxAllWrite: type: object properties: baz: writeOnly: true type: string QuxAllRead: type: object properties: baz: readOnly: true type: string Quux: type: object properties: baz: type: array items: $ref: '#/components/schemas/Baz' qux: $ref: '#/components/schemas/QuxAllRead' Corge: type: object properties: foo: type: object properties: baz: type: boolean writeOnly: true bar: type: object properties: baz: type: boolean readOnly: true FooReadWriteRef: type: object properties: foo: $ref: '#/components/schemas/FooReadWrite' bar: $ref: '#/components/schemas/FooReadWriteRef' FooReadWriteRef2: $ref: '#/components/schemas/FooReadWrite' ================================================ FILE: specs/3.1.x/transforms-schemas-name.yaml ================================================ openapi: 3.1.0 info: title: Schema Name Transform Test version: 1.0.0 paths: /users: get: summary: Get users responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/User_v1_0_0_User' /posts: post: summary: Create post requestBody: content: application/json: schema: $ref: '#/components/schemas/Post_v2_1_3_Post' responses: '201': description: Created content: application/json: schema: $ref: '#/components/schemas/Post_v2_1_3_Post' components: schemas: User_v1_0_0_User: type: object properties: id: type: string name: type: string profile: $ref: '#/components/schemas/UserProfile_v1_0_0_UserProfile' UserProfile_v1_0_0_UserProfile: type: object properties: bio: type: string avatar: type: string Post_v2_1_3_Post: type: object properties: id: type: string title: type: string author: $ref: '#/components/schemas/User_v1_0_0_User' comments: type: array items: $ref: '#/components/schemas/Comment_v1_5_2_Comment' Comment_v1_5_2_Comment: type: object properties: id: type: string text: type: string author: $ref: '#/components/schemas/User_v1_0_0_User' ================================================ FILE: specs/3.1.x/type-format.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 type format example version: 1 paths: /foo: post: responses: '200': description: OK content: 'application/json': schema: $ref: '#/components/schemas/Foo' components: schemas: Foo: type: object properties: bar: type: integer foo: default: 0 format: int64 type: integer id: type: string format: typeid example: 'user_123' required: - id - foo Bar: type: object required: - foo properties: foo: type: integer additionalProperties: type: integer ================================================ FILE: specs/3.1.x/type-invalid.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 type invalid example", "version": "1" }, "components": { "schemas": { "Foo": { "type": "invalid" } } } } ================================================ FILE: specs/3.1.x/union-types.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 union types example", "version": "1" }, "components": { "schemas": { "Foo": { "type": "object", "properties": { "bar": { "type": ["number", "boolean", "string"] } } } } } } ================================================ FILE: specs/3.1.x/validators-bigint-min-max.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 validators bigint min max example", "version": "1" }, "components": { "schemas": { "Foo": { "properties": { "foo": { "format": "int64", "maximum": 100, "minimum": 0, "type": "integer" } }, "type": "object" } } } } ================================================ FILE: specs/3.1.x/validators-circular-ref-2.yaml ================================================ openapi: 3.1.1 info: title: OpenAPI 3.1.1 validators circular ref 2 example version: 1 components: schemas: Foo: additionalProperties: false properties: foo: $ref: '#/components/schemas/Bar' required: - foo type: object Bar: additionalProperties: false properties: bar: items: $ref: '#/components/schemas/Bar' type: - array - 'null' required: - bar type: object ================================================ FILE: specs/3.1.x/validators-circular-ref.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 validators circular reference example", "version": "1" }, "components": { "schemas": { "Foo": { "properties": { "foo": { "$ref": "#/components/schemas/Bar" } }, "type": "object" }, "Bar": { "properties": { "bar": { "items": { "$ref": "#/components/schemas/Bar" }, "type": "array" } }, "type": "object" }, "Baz": { "$ref": "#/components/schemas/Qux" }, "Qux": { "description": "description caused circular reference error", "$ref": "#/components/schemas/Baz" } } } } ================================================ FILE: specs/3.1.x/validators-string-constraints-union.json ================================================ { "openapi": "3.1.0", "info": { "title": "String Constraints Union Test", "version": "1.0.0" }, "components": { "schemas": { "LocaleOrLanguage": { "anyOf": [ { "type": "string", "minLength": 5, "maxLength": 5, "description": "Combination of ISO 639-1 and ISO 3166-1 alpha-2 separated by a hyphen." }, { "type": "string", "minLength": 2, "maxLength": 2, "description": "ISO 639-1 language code." } ] } } } } ================================================ FILE: specs/3.1.x/validators-union-merge.json ================================================ { "openapi": "3.1.0", "info": { "title": "OpenAPI 3.1.0 validators union merge example", "version": "1" }, "components": { "schemas": { "User": { "allOf": [ { "$ref": "#/components/schemas/Contact" }, { "properties": { "username": { "type": "string" } }, "required": ["username"], "type": "object" } ] }, "Contact": { "oneOf": [ { "properties": { "email": { "type": "string" } }, "required": ["email"], "type": "object" }, { "properties": { "phone": { "type": "string" } }, "required": ["phone"], "type": "object" } ] }, "PetStore": { "type": "object", "required": ["animals"], "properties": { "animals": { "type": "array", "items": { "type": "object", "required": ["name", "details"], "properties": { "name": { "type": "string" }, "type": { "type": "string", "enum": ["dog", "cat"], "default": "dog" }, "details": { "oneOf": [ { "$ref": "#/components/schemas/DogDetails" }, { "$ref": "#/components/schemas/CatDetails" } ] } } } } } }, "DogDetails": { "type": "object", "required": ["breed", "barkVolume"], "properties": { "breed": { "type": "string" }, "barkVolume": { "type": "integer", "minimum": 1, "maximum": 10 } } }, "CatDetails": { "type": "object", "required": ["furLength", "purrs"], "properties": { "furLength": { "type": "string", "enum": ["short", "medium", "long"] }, "purrs": { "type": "boolean" } } } } } } ================================================ FILE: specs/3.1.x/validators.yaml ================================================ openapi: 3.1.0 info: title: OpenAPI 3.1.0 validators example version: '1' paths: /foo: patch: parameters: - $ref: '#/components/parameters/Foo' - in: query name: bar required: false schema: $ref: '#/components/schemas/Bar' - in: query name: baz required: false schema: properties: baz: type: string type: object - in: query name: qux required: false schema: format: date type: string - in: query name: quux required: false schema: format: date-time type: string requestBody: content: 'application/json': schema: properties: foo: type: string type: object required: true responses: '200': description: OK post: requestBody: $ref: '#/components/requestBodies/Foo' responses: '200': description: OK components: parameters: Foo: description: 'This is Foo parameter.' name: foo in: query required: false schema: type: string requestBodies: Foo: required: true content: 'application/json': schema: type: object properties: foo: $ref: '#/components/schemas/Bar' schemas: Foo: default: null description: 'This is Foo schema.' properties: foo: description: 'This is foo property.' pattern: ^\d{3}-\d{2}-\d{4}$ type: string bar: $ref: '#/components/schemas/Bar' baz: description: 'This is baz property.' items: $ref: '#/components/schemas/Foo' type: array qux: description: 'This is qux property.' default: 0 exclusiveMinimum: 0 type: integer type: - object - 'null' Bar: description: 'This is Bar schema.' properties: foo: $ref: '#/components/schemas/Foo' type: object Baz: default: baz pattern: foo\nbar readOnly: true type: string Qux: additionalProperties: properties: qux: type: string type: object type: object ================================================ FILE: specs/3.1.x/zoom-video-sdk.json ================================================ { "openapi": "3.1.0", "info": { "title": "Video SDK", "description": "**Subscribe to webhook events** \n\nOn your [Video SDK account page on the App Marketplace](/docs/video-sdk/developer-accounts/), under **Add feature**, toggle **Event Subscriptions** to subscribe to events [using webhooks](/docs/api/rest/webhook-reference/).\n\n Configure webhooks to send [Video SDK events](/docs/video-sdk/webhooks/) to your server as HTTP POST requests. This is useful for tracking events or building out business logic. For example, when you receive a Video SDK session ended webhook, you could kick off an email to thank the participants for joining. \n\nSee [Make API requests](/docs/video-sdk/api-request/) for details or our [webhook sample code (Node.js)](https://github.com/zoom/webhook-sample).", "version": "1.0.0" }, "webhooks": { "session.user_phone_callout_ringing": { "post": { "tags": ["session"], "operationId": "session.user_phone_callout_ringing", "requestBody": { "description": "# session.user_phone_callout_ringing\n\nThe **Invited party's phone (call out) ringing** event is triggered every time a user's phone is ringing when they were invited to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Invited party's phone (call out) ringing** subscription enabled under the **Session** event.\n\n\n\n\n**Event type**: `session.user_phone_callout_ringing`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited user.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_ringing\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited user.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_ringing\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } } } } }, "session.user_room_system_callout_ringing": { "post": { "tags": ["session"], "operationId": "session.user_room_system_callout_ringing", "requestBody": { "description": "# session.user_room_system_callout_ringing\n\nThe **Invited party's phone (call out) ringing in Zoom room** event is triggered every time a user's phone is ringing when they were invited to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n* A valid **Event Notification Endpoint URL**.\n* The **Invited party's phone (call out) ringing in Zoom room** subscription enabled under the **Session** event.\n\n\n\n**Event type**: `session.user_room_system_callout_ringing`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_ringing\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_ringing\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } } } } }, "session.recording_started": { "post": { "tags": ["session"], "operationId": "session.recording_started", "requestBody": { "description": "# session.recording_started\n---\n\nEvent: `session.recording_started`\n\n## Event description\n\nThe **Session recording started** event is triggered every time a recording is started by one of your app users or account users.\n\nOnly a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n * A valid Event Notification Endpoint URL.\n * **Session recording started** subscription enabled under the **Recording** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_started` event notification:\n\n\n\n**Event type**: `session.recording_started`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_started"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_started\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_started"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_started\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } } } } }, "session.recording_resumed": { "post": { "tags": ["session"], "operationId": "session.recording_resumed", "requestBody": { "description": "# session.recording_resumed\n---\n\nEvent: `session.recording_resumed`\n\n## Event description\n\nThe **Session recording resumed** event is triggered every time a previously paused recording of a session is resumed.\n\nOnly a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n * A valid Event Notification Endpoint URL.\n * **Session recording resumed** subscription enabled under the **Recording** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_resumed` event notification:\n\n\n\n**Event type**: `session.recording_resumed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_resumed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_resumed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_resumed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_resumed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } } } } }, "session.live_streaming_stopped": { "post": { "tags": ["session"], "operationId": "session.live_streaming_stopped", "requestBody": { "description": "# session.live_streaming_stopped\n---\n\n\nThe Session Live Streaming Stopped event is triggered every time a user stops a live stream.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your app with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* **Session Live Streaming Stopped** subscription enabled under the **Video SDK** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.live_streaming_stopped` event notification:\n\n\n\n**Event type**: `session.live_streaming_stopped`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.live_streaming_stopped"], "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "id", "session_id", "session_name", "start_time", "live_streaming" ], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" }, "live_streaming": { "type": "object", "description": "Information about the participant.", "required": ["service", "custom_live_streaming_settings", "date_time"], "properties": { "service": { "type": "string", "description": "The name of the Live Streaming service.", "enum": [ "Facebook", "Workplace_by_Facebook", "YouTube", "Custom_Live_Streaming_Service" ] }, "custom_live_streaming_settings": { "type": "object", "description": "The live stream settings.", "required": ["stream_url", "stream_key", "page_url"], "properties": { "stream_url": { "type": "string", "description": "The stream's URL." }, "stream_key": { "type": "string", "description": "The stream's Key." }, "page_url": { "type": "string", "description": "The live stream's page URL." }, "resolution": { "type": "string", "description": "The number of pixels in each dimension that the video camera can display." } } }, "date_time": { "type": "string", "description": "The live stream's stop time.", "format": "date-time" } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.live_streaming_stopped\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:03:32Z\",\n \"live_streaming\": {\n \"service\": \"Custom_Live_Streaming_Service\",\n \"custom_live_streaming_settings\": {\n \"stream_url\": \"https://example.com/livestream\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"page_url\": \"https://example.com/livestream/123\",\n\t\t \"resolution\": \"1080p\"\n },\n \"date_time\": \"2021-08-02T12:22:45Z\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.live_streaming_stopped"], "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "id", "session_id", "session_name", "start_time", "live_streaming" ], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" }, "live_streaming": { "type": "object", "description": "Information about the participant.", "required": [ "service", "custom_live_streaming_settings", "date_time" ], "properties": { "service": { "type": "string", "description": "The name of the Live Streaming service.", "enum": [ "Facebook", "Workplace_by_Facebook", "YouTube", "Custom_Live_Streaming_Service" ] }, "custom_live_streaming_settings": { "type": "object", "description": "The live stream settings.", "required": ["stream_url", "stream_key", "page_url"], "properties": { "stream_url": { "type": "string", "description": "The stream's URL." }, "stream_key": { "type": "string", "description": "The stream's Key." }, "page_url": { "type": "string", "description": "The live stream's page URL." }, "resolution": { "type": "string", "description": "The number of pixels in each dimension that the video camera can display." } } }, "date_time": { "type": "string", "description": "The live stream's stop time.", "format": "date-time" } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.live_streaming_stopped\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:03:32Z\",\n \"live_streaming\": {\n \"service\": \"Custom_Live_Streaming_Service\",\n \"custom_live_streaming_settings\": {\n \"stream_url\": \"https://example.com/livestream\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"page_url\": \"https://example.com/livestream/123\",\n\t\t \"resolution\": \"1080p\"\n },\n \"date_time\": \"2021-08-02T12:22:45Z\"\n }\n }\n }\n}" } } } } } } } }, "session.stream_ingestion_stopped": { "post": { "tags": ["session"], "operationId": "session.stream_ingestion_stopped", "requestBody": { "description": "# session.stream_ingestion_stopped\nZoom triggers the **Session stream ingestion stopped** event every time a user stops sending live incoming streams.\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Session stream ingestion stopped** subscription enabled under the **Video SDK** event.\n\n\n**Event type**: `session.stream_ingestion_stopped`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_stopped"], "description": "Event name." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_stopped\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_stopped"], "description": "Event name." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_stopped\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } } } } }, "session.user_room_system_callout_rejected": { "post": { "tags": ["session"], "operationId": "session.user_room_system_callout_rejected", "requestBody": { "description": "# session.user_room_system_callout_rejected\n\nThe **Invited party rejected a session invitation through phone (call out) via Zoom room** event is triggered every time a user rejects an invitation to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n* A valid **Event Notification Endpoint URL**.\n* The **Invited party rejected a session invitation through phone (call out) via Zoom room** subscription enabled under the **Session** event.\n\n\n\n**Event type**: `session.user_room_system_callout_rejected`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_rejected\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_rejected\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } } } } }, "session.alert": { "post": { "tags": ["session"], "operationId": "session.alert", "requestBody": { "description": "# session.alert\n---\n\n\nThe Session Alert event is triggered every time a service issue is encountered during a session in your account.\n\nThe following quality metrics can trigger an alert:\n\n* Unstable audio quality\n* Unstable video quality\n* Unstable screen share quality\n* High CPU occupation\n* Call Reconnection\n\n## Prerequisites\nEvent Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* Session Alert subscription enabled under the Video SDK event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.alert` event notification:\n\n\n**Event type**: `session.alert`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.alert"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "issues"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "issues": { "type": "array", "items": { "type": "string", "enum": [ "Unstable audio quality", "Unstable video quality", "Unstable screen share quality", "High CPU occupation", "Call Reconnection" ] }, "description": "Issues that occurred during the session." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.alert\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"account_id\": \"EFgHiJABC000DEfGHI\",\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"issues\": \"Unstable audio quality\"\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.alert"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "issues"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "issues": { "type": "array", "items": { "type": "string", "enum": [ "Unstable audio quality", "Unstable video quality", "Unstable screen share quality", "High CPU occupation", "Call Reconnection" ] }, "description": "Issues that occurred during the session." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.alert\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"account_id\": \"EFgHiJABC000DEfGHI\",\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"issues\": \"Unstable audio quality\"\n }\n }\n}" } } } } } } } }, "session.sharing_ended": { "post": { "tags": ["session"], "operationId": "session.sharing_ended", "requestBody": { "description": "# session.sharing_ended\n---\n\n\nThe Session Sharing Ended event is triggered every time a user stops sharing the screen during a session.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* **Session Sharing Ended** subscription enabled under the **Video SDK** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.sharing_ended` event notification:\n\n\n\n**Event type**: `session.sharing_ended`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.sharing_ended"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "sharing_details"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "sharing_details": { "type": "object", "description": "Information about the session's screen sharing.", "required": ["content", "date_time"], "properties": { "content": { "type": "string", "description": "The type of shared content:\n* application — An application. For example, a web browser.\n* whiteboard — The Zoom [whiteboard](https://support.zoom.us/hc/en-us/articles/205677665-Sharing-a-whiteboard).\n* desktop — A user's desktop.\n* unknown — An unrecognized application, such as a third party app.", "enum": ["application", "whiteboard", "desktop", "unknown"] }, "date_time": { "type": "string", "format": "date-time", "description": "The session's screen sharing date and time." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.sharing_ended\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"username\",\n \"user_key\": \"ASD74dfDI854\",\n \"sharing_details\": {\n \"content\": \"application\",\n \"date_time\": \"2021-07-16T17:19:11Z\"\n }\n }\n },\n \"account_id\": \"EFgHiJABC000DEfGHI\"\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.sharing_ended"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "sharing_details"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "sharing_details": { "type": "object", "description": "Information about the session's screen sharing.", "required": ["content", "date_time"], "properties": { "content": { "type": "string", "description": "The type of shared content:\n* application — An application. For example, a web browser.\n* whiteboard — The Zoom [whiteboard](https://support.zoom.us/hc/en-us/articles/205677665-Sharing-a-whiteboard).\n* desktop — A user's desktop.\n* unknown — An unrecognized application, such as a third party app.", "enum": ["application", "whiteboard", "desktop", "unknown"] }, "date_time": { "type": "string", "format": "date-time", "description": "The session's screen sharing date and time." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.sharing_ended\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"username\",\n \"user_key\": \"ASD74dfDI854\",\n \"sharing_details\": {\n \"content\": \"application\",\n \"date_time\": \"2021-07-16T17:19:11Z\"\n }\n }\n },\n \"account_id\": \"EFgHiJABC000DEfGHI\"\n }\n}" } } } } } } } }, "session.recording_paused": { "post": { "tags": ["session"], "operationId": "session.recording_paused", "requestBody": { "description": "# session.recording_paused\n---\n\nEvent: `session.recording_paused`\n\n## Event description\n\nThe **Session recording paused** event is triggered every time a recording is paused by one of your app or account users.\n\nOnly a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n * A valid Event Notification Endpoint URL.\n * \"**Session recording paused**\" subscription enabled under the **Recording** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_paused` event notification:\n\n\n\n**Event type**: `session.recording_paused`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_paused"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_paused\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_paused"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_paused\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } } } } }, "session.ended": { "post": { "tags": ["session"], "operationId": "session.ended", "requestBody": { "description": "# session.ended\n---\n\n\nThe Session Ended event is triggered when the host ends the session, or when all users have left the session.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your app with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* **Session Ended** subscription enabled under the **Video SDK** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.ended` event notification:\n\n\n\n**Event type**: `session.ended`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.ended"], "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp at which the event occurred, in milliseconds since epoch. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["id", "session_id", "session_name", "start_time", "end_time"], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" }, "end_time": { "type": "string", "description": "The session's end time.", "format": "date-time" } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.ended\",\n \"event_ts\": 1627906944384,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:22:24Z\",\n \"end_time\": \"2021-08-02T13:22:24Z\"\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.ended"], "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp at which the event occurred, in milliseconds since epoch. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "id", "session_id", "session_name", "start_time", "end_time" ], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" }, "end_time": { "type": "string", "description": "The session's end time.", "format": "date-time" } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.ended\",\n \"event_ts\": 1627906944384,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:22:24Z\",\n \"end_time\": \"2021-08-02T13:22:24Z\"\n }\n }\n}" } } } } } } } }, "session.started": { "post": { "tags": ["session"], "operationId": "session.started", "requestBody": { "description": "# session.started\n---\n\n\nThe Session Start event is triggered when the first user (including host and co-host) joins.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your app with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* **Session Started** subscription enabled under the **Video SDK** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.started` event notification:\n\n\n\n**Event type**: `session.started`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.started"], "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["id", "session_id", "session_name", "start_time"], "properties": { "id": { "type": "string", "description": "The session's ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.started\",\n \"event_ts\": 1627906944384,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:22:24Z\"\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.started"], "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["id", "session_id", "session_name", "start_time"], "properties": { "id": { "type": "string", "description": "The session's ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.started\",\n \"event_ts\": 1627906944384,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:22:24Z\"\n }\n }\n}" } } } } } } } }, "session.stream_ingestion_unbind": { "post": { "tags": ["session"], "operationId": "session.stream_ingestion_unbind", "requestBody": { "description": "# session.stream_ingestion_unbind\nZoom triggers the **Session stream ingestion unbind** event every time a session unbinds a stream key.\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Session stream ingestion unbind** subscription enabled under the **Video SDK** event.\n\n\n**Event type**: `session.stream_ingestion_unbind`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_unbind"], "description": "Event name." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_unbind\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_unbind"], "description": "Event name." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_unbind\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } } } } }, "session.live_streaming_started": { "post": { "tags": ["session"], "operationId": "session.live_streaming_started", "requestBody": { "description": "# session.live_streaming_started\n---\n\n\nThe Session Live Streaming Started event is triggered every time a user starts a live stream.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your app with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* **Session Live Streaming Started** subscription enabled under the **Video SDK** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.live_streaming_started` event notification:\n\n\n\n**Event type**: `session.live_streaming_started`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.live_streaming_started"], "description": "Name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "id", "session_id", "session_name", "start_time", "live_streaming" ], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" }, "live_streaming": { "type": "object", "description": "Information about the participant.", "required": ["service", "custom_live_streaming_settings", "date_time"], "properties": { "service": { "type": "string", "description": "The name of the Live Streaming service.", "enum": [ "Facebook", "Workplace_by_Facebook", "YouTube", "Custom_Live_Streaming_Service" ] }, "custom_live_streaming_settings": { "type": "object", "description": "The live stream settings.", "required": ["stream_url", "stream_key", "page_url"], "properties": { "stream_url": { "type": "string", "description": "The stream's URL." }, "stream_key": { "type": "string", "description": "The stream's key." }, "page_url": { "type": "string", "description": "The live stream's page URL." }, "resolution": { "type": "string", "description": "The number of pixels in each dimension that the video camera can display." } } }, "date_time": { "type": "string", "description": "The live stream's start time.", "format": "date-time" } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.live_streaming_started\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:03:32Z\",\n \"live_streaming\": {\n \"service\": \"Custom_Live_Streaming_Service\",\n \"custom_live_streaming_settings\": {\n \"stream_url\": \"https://example.com/livestream\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"page_url\": \"https://example.com/livestream/123\",\n\t\t \"resolution\": \"1080p\"\n },\n \"date_time\": \"2021-08-02T12:22:45Z\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.live_streaming_started"], "description": "Name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) at which the event occurred. The value of this field is returned in long(int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "id", "session_id", "session_name", "start_time", "live_streaming" ], "properties": { "id": { "type": "string", "description": "The session ID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "description": "The session's start time.", "format": "date-time" }, "live_streaming": { "type": "object", "description": "Information about the participant.", "required": [ "service", "custom_live_streaming_settings", "date_time" ], "properties": { "service": { "type": "string", "description": "The name of the Live Streaming service.", "enum": [ "Facebook", "Workplace_by_Facebook", "YouTube", "Custom_Live_Streaming_Service" ] }, "custom_live_streaming_settings": { "type": "object", "description": "The live stream settings.", "required": ["stream_url", "stream_key", "page_url"], "properties": { "stream_url": { "type": "string", "description": "The stream's URL." }, "stream_key": { "type": "string", "description": "The stream's key." }, "page_url": { "type": "string", "description": "The live stream's page URL." }, "resolution": { "type": "string", "description": "The number of pixels in each dimension that the video camera can display." } } }, "date_time": { "type": "string", "description": "The live stream's start time.", "format": "date-time" } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.live_streaming_started\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"id\": \"BrgGrWeZSwaXkLBTpvmmvg==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-08-02T12:03:32Z\",\n \"live_streaming\": {\n \"service\": \"Custom_Live_Streaming_Service\",\n \"custom_live_streaming_settings\": {\n \"stream_url\": \"https://example.com/livestream\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"page_url\": \"https://example.com/livestream/123\",\n\t\t \"resolution\": \"1080p\"\n },\n \"date_time\": \"2021-08-02T12:22:45Z\"\n }\n }\n }\n}" } } } } } } } }, "session.user_room_system_callout_missed": { "post": { "tags": ["session"], "operationId": "session.user_room_system_callout_missed", "requestBody": { "description": "# session.user_room_system_callout_missed\n\nThe **Invited party missed a session invitation through phone (call out) via Zoom room** event is triggered every time an invitation to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035) times out.\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n* A valid **Event Notification Endpoint URL**.\n* The **Invited party missed a session invitation through phone (call out) via Zoom room** subscription enabled under the **Session** event.\n\n\n\n**Event type**: `session.user_room_system_callout_missed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_missed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_missed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } } } } }, "session.user_phone_callout_accepted": { "post": { "tags": ["session"], "operationId": "session.user_phone_callout_accepted", "requestBody": { "description": "# session.user_phone_callout_accepted\n\nThe **Invited party answered a session invitation through phone (call out)** event is triggered every time a user accepts an invitation to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Invited party answered a session invitation through phone (call out)** subscription enabled under the **Session** event.\n\n\n\n**Event type**: `session.user_phone_callout_accepted`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_accepted\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_accepted\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } } } } }, "session.user_left": { "post": { "tags": ["session"], "operationId": "session.user_left", "requestBody": { "description": "# session.user_left\n\n\nThe Session User Left event is triggered every time a user (including host and co-host) leaves a session.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* Session User Left subscription enabled under the Video SDK event.\n\n\n\n**Event type**: `session.user_left`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.user_left"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "leave_time", "participant_uuid"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "leave_time": { "type": "string", "description": "The time at which the user left the session.", "format": "date-time" }, "leave_reason": { "type": "string", "description": "The reason why the user left the session, where $name is the participant's username: \n* $name left the session. \n* $name got disconnected from the session. \n* Host ended the session. \n* Host closed the session. \n* Host started a new session. \n* Network connection error. \n* Host did not join. \n* Exceeded free session minutes limit. \n* Removed by host. \n* Unknown reason. \n* Leave waiting room. \n* Removed by host from waiting room.", "x-enum": [ "$name left the session.", "$name got disconnected from the session.", "Host ended the session.", "Host closed the session.", "Host started a new session.", "Network connection error.", "Host did not join.", "Exceeded free session minutes limit.", "Removed by host.", "Unknown reason.", "Leave waiting room.", "Removed by host from waiting room." ] }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "phone_number": { "type": "string", "description": "Phone number of participant joined via PSTN." }, "participant_uuid": { "type": "string", "description": "The participant's UUID. This value is assigned to a participant upon joining a session and is only valid for the session's duration." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_left\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"account_id\": \"EFgHiJABC000DEfGHI\",\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"example\",\n \"leave_time\": \"2021-07-16T17:19:11Z\",\n \"leave_reason\": \"Jill Chill left the session.
    Reason: Host ended the session.\",\n \"user_key\": \"ASD74dfDI854\",\n \"phone_number\": \"8615250064084\",\n \"participant_uuid\": \"55555AAAiAAAAAiAiAiiAii\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.user_left"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "leave_time", "participant_uuid"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "leave_time": { "type": "string", "description": "The time at which the user left the session.", "format": "date-time" }, "leave_reason": { "type": "string", "description": "The reason why the user left the session, where $name is the participant's username: \n* $name left the session. \n* $name got disconnected from the session. \n* Host ended the session. \n* Host closed the session. \n* Host started a new session. \n* Network connection error. \n* Host did not join. \n* Exceeded free session minutes limit. \n* Removed by host. \n* Unknown reason. \n* Leave waiting room. \n* Removed by host from waiting room.", "x-enum": [ "$name left the session.", "$name got disconnected from the session.", "Host ended the session.", "Host closed the session.", "Host started a new session.", "Network connection error.", "Host did not join.", "Exceeded free session minutes limit.", "Removed by host.", "Unknown reason.", "Leave waiting room.", "Removed by host from waiting room." ] }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "phone_number": { "type": "string", "description": "Phone number of participant joined via PSTN." }, "participant_uuid": { "type": "string", "description": "The participant's UUID. This value is assigned to a participant upon joining a session and is only valid for the session's duration." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_left\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"account_id\": \"EFgHiJABC000DEfGHI\",\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"example\",\n \"leave_time\": \"2021-07-16T17:19:11Z\",\n \"leave_reason\": \"Jill Chill left the session.
    Reason: Host ended the session.\",\n \"user_key\": \"ASD74dfDI854\",\n \"phone_number\": \"8615250064084\",\n \"participant_uuid\": \"55555AAAiAAAAAiAiAiiAii\"\n }\n }\n }\n}" } } } } } } } }, "session.sharing_started": { "post": { "tags": ["session"], "operationId": "session.sharing_started", "requestBody": { "description": "# session.sharing_started\n\n\nThe Session Sharing Started event is triggered every time a user starts sharing the screen during a session.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* **Session Sharing Started** subscription enabled under the **Video SDK** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.sharing_started` event notification:\n\n\n\n**Event type**: `session.sharing_started`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.sharing_started"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "sharing_details"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "sharing_details": { "type": "object", "description": "Information about the session's screen sharing.", "required": ["content", "date_time"], "properties": { "content": { "type": "string", "description": "The type of shared content:\n* application — An application. For example, a web browser.\n* whiteboard — The Zoom [whiteboard](https://support.zoom.us/hc/en-us/articles/205677665-Sharing-a-whiteboard).\n* desktop — A user's desktop.\n* unknown — An unrecognized application, such as a third party app.", "enum": ["application", "whiteboard", "desktop", "unknown"] }, "date_time": { "type": "string", "format": "date-time", "description": "The session's screen sharing date and time." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.sharing_started\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"object\": {\n \"id\": \"4118UHIiRCAAAtBlDkcVyw==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"username\",\n \"user_key\": \"ASD74dfDI854\",\n \"sharing_details\": {\n \"date_time\": \"2019-07-16T17:19:11Z\",\n \"content\": \"application\"\n }\n }\n },\n \"account_id\": \"EPeQtiABC000VYxHMA\"\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.sharing_started"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "sharing_details"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "sharing_details": { "type": "object", "description": "Information about the session's screen sharing.", "required": ["content", "date_time"], "properties": { "content": { "type": "string", "description": "The type of shared content:\n* application — An application. For example, a web browser.\n* whiteboard — The Zoom [whiteboard](https://support.zoom.us/hc/en-us/articles/205677665-Sharing-a-whiteboard).\n* desktop — A user's desktop.\n* unknown — An unrecognized application, such as a third party app.", "enum": ["application", "whiteboard", "desktop", "unknown"] }, "date_time": { "type": "string", "format": "date-time", "description": "The session's screen sharing date and time." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.sharing_started\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"object\": {\n \"id\": \"4118UHIiRCAAAtBlDkcVyw==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"username\",\n \"user_key\": \"ASD74dfDI854\",\n \"sharing_details\": {\n \"date_time\": \"2019-07-16T17:19:11Z\",\n \"content\": \"application\"\n }\n }\n },\n \"account_id\": \"EPeQtiABC000VYxHMA\"\n }\n}" } } } } } } } }, "session.user_phone_callout_canceled": { "post": { "tags": ["session"], "operationId": "session.user_phone_callout_canceled", "requestBody": { "description": "# session.user_phone_callout_canceled\nThe **Invited party's phone (call out) canceled** event is triggered every time the inviter cancels the call out when they were invited to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Invited party's phone (call out) canceled** subscription enabled under the **Session** event.\n\n\n**Event type**: `session.user_phone_callout_canceled`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "participant" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_canceled\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "participant" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_canceled\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } } } } }, "session.recording_transcript_completed": { "post": { "tags": ["session"], "operationId": "session.recording_transcript_completed", "requestBody": { "description": "# session.recording_transcript_completed\n---\n\nEvent: `session.recording_transcript_completed`\n\n## Event description\n\nThe **Session recording transcript completed** event is triggered every time the transcript of the recording of a session becomes available to view or download.\n\nOnly a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n * A valid Event Notification Endpoint URL.\n * Session recording transcript completed subscription enabled under the Recording event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_transcript_completed` event notification:\n\n\n\n**Event type**: `session.recording_transcript_completed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "download_token", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_transcript_completed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "download_token": { "type": "string", "description": "A generated token used to download the recording. The download token only lasts for 24 hours after its creation and you can only download the file within 24 hours of receiving the event notification. You can either pass the download_token as a Bearer token in the Authorization header of your HTTP request (recommended) or include it as a query parameter. See the following for examples. \n\n **Using an Authorization header (Recommended)** \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {download_token} \\\n --header 'content-type: application/json'\n \n\n**Using a query parameter** \n\n \n{download_url}/?access_token={download_token}\n \n\n For example: https://zoom.us/recording/download/123456?access_token=abcdefgh" }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_files" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the \"Add a timestamp to the recording\" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile.\n
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format.\n\n
    \n\nA recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    \n\tid, status, file_size, recording_type.", "enum": [ "MP4", "M4A", "CHAT", "TRANSCRIPT", "CSV", "CC", "TB", "CHAT_MESSAGE", "TIMELINE" ] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4", "M4A", "TXT", "VTT", "CSV", "JSON", "JPG"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). You can either pass the generated JWT as a Bearer token in the Authorization header of your HTTP request (recommended) or include it as a query parameter at the end of the URL. See the following for examples. \n\n **Using an Authorization header (Recommended)** \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n \n\n**Using a query parameter** \n\n \n{download_url}/?access_token={download_token}\n \n\n For example: https://{base-domain}/recording/download/{path-to-file-download}?access_token={JWT}." }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": [ "shared_screen_with_speaker_view(CC)", "shared_screen_with_speaker_view", "shared_screen_with_gallery_view", "gallery_view", "shared_screen", "audio_only", "audio_transcript", "chat_file", "active_speaker", "host_video", "audio_only_each_participant", "cc_transcript", "closed_caption", "poll", "timeline", "thumbnail", "chat_message" ] } } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_transcript_completed\",\n \"event_ts\": 1626230691572,\n \"download_token\": \"abJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwczovL2V2ZW50Lnpvb20udXMiLCJhY2NvdW50SWQiOiJNdDZzdjR1MFRBeVBrd2dzTDJseGlBIiwiYXVkIjoiaHR0cHM6Ly9vYXV0aC56b29tLnVzIiwibWlkIjoieFp3SEc0c3BRU2VuekdZWG16dnpiUT09IiwiZXhwIjoxNjI2MTM5NTA3LCJ1c2VySWQiOiJEWUhyZHBqclMzdWFPZjdkUGtrZzh3In0.a6KetiC6BlkDhf1dP4KBGUE1bb2brMeraoD45yhFx0eSSSTFdkHQnsKmlJQ-hdo9Zy-4vQw3rOxlyoHv583JyZ\",\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_files\": [\n {\n \"id\": \"ed6c2f27-2ae7-42f4-b3d0-835b493e4fa8\",\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\",\n \"recording_type\": \"audio_only\",\n \"file_type\": \"TRANSCRIPT\",\n \"file_size\": 246560,\n \"file_extension\": \"M4A\",\n \"download_url\": \"https://example.com/recording/download/Qg75t7xZBtEbAkjdlgbfdngBBBB\",\n \"status\": \"completed\",\n \"recording_type\": \"audio_transcript\"\n }\n ]\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "download_token", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_transcript_completed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "download_token": { "type": "string", "description": "A generated token used to download the recording. The download token only lasts for 24 hours after its creation and you can only download the file within 24 hours of receiving the event notification. You can either pass the download_token as a Bearer token in the Authorization header of your HTTP request (recommended) or include it as a query parameter. See the following for examples. \n\n **Using an Authorization header (Recommended)** \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {download_token} \\\n --header 'content-type: application/json'\n \n\n**Using a query parameter** \n\n \n{download_url}/?access_token={download_token}\n \n\n For example: https://zoom.us/recording/download/123456?access_token=abcdefgh" }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_files" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the \"Add a timestamp to the recording\" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile.\n
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format.\n\n
    \n\nA recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    \n\tid, status, file_size, recording_type.", "enum": [ "MP4", "M4A", "CHAT", "TRANSCRIPT", "CSV", "CC", "TB", "CHAT_MESSAGE", "TIMELINE" ] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4", "M4A", "TXT", "VTT", "CSV", "JSON", "JPG"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). You can either pass the generated JWT as a Bearer token in the Authorization header of your HTTP request (recommended) or include it as a query parameter at the end of the URL. See the following for examples. \n\n **Using an Authorization header (Recommended)** \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n \n\n**Using a query parameter** \n\n \n{download_url}/?access_token={download_token}\n \n\n For example: https://{base-domain}/recording/download/{path-to-file-download}?access_token={JWT}." }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": [ "shared_screen_with_speaker_view(CC)", "shared_screen_with_speaker_view", "shared_screen_with_gallery_view", "gallery_view", "shared_screen", "audio_only", "audio_transcript", "chat_file", "active_speaker", "host_video", "audio_only_each_participant", "cc_transcript", "closed_caption", "poll", "timeline", "thumbnail", "chat_message" ] } } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_transcript_completed\",\n \"event_ts\": 1626230691572,\n \"download_token\": \"abJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwczovL2V2ZW50Lnpvb20udXMiLCJhY2NvdW50SWQiOiJNdDZzdjR1MFRBeVBrd2dzTDJseGlBIiwiYXVkIjoiaHR0cHM6Ly9vYXV0aC56b29tLnVzIiwibWlkIjoieFp3SEc0c3BRU2VuekdZWG16dnpiUT09IiwiZXhwIjoxNjI2MTM5NTA3LCJ1c2VySWQiOiJEWUhyZHBqclMzdWFPZjdkUGtrZzh3In0.a6KetiC6BlkDhf1dP4KBGUE1bb2brMeraoD45yhFx0eSSSTFdkHQnsKmlJQ-hdo9Zy-4vQw3rOxlyoHv583JyZ\",\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_files\": [\n {\n \"id\": \"ed6c2f27-2ae7-42f4-b3d0-835b493e4fa8\",\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\",\n \"recording_type\": \"audio_only\",\n \"file_type\": \"TRANSCRIPT\",\n \"file_size\": 246560,\n \"file_extension\": \"M4A\",\n \"download_url\": \"https://example.com/recording/download/Qg75t7xZBtEbAkjdlgbfdngBBBB\",\n \"status\": \"completed\",\n \"recording_type\": \"audio_transcript\"\n }\n ]\n }\n }\n}" } } } } } } } }, "session.recording_deleted": { "post": { "tags": ["session"], "operationId": "session.recording_deleted", "requestBody": { "description": "# session.recording_deleted\n---\n\nEvent: `session.recording_deleted`\n\n## Event description\n\nThe **Session recording permanently deleted** event is triggered every time one of your app users or account users permanently deletes a cloud recording.\n\nWhen a user initially deletes a recording, it is sent to the trash. At this stage, the recording can still be recovered for up to 30 days after deletion. To permanently delete a recording, users must delete it from the trash. Users can permanently delete a recording using:\n\n* The [Delete session's recording API](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingDelete) **with the delete query parameter** or\n* The Zoom web portal. See [Video SDK account](https://developers.zoom.us/docs/video-sdk/account/) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n\t* A valid Event Notification Endpoint URL.\n\t* \"**Session recording permanently deleted**\" subscription enabled under the **Recording** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_deleted` event notification:\n\n\n\n**Event type**: `session.recording_deleted`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_deleted"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "operator", "operator_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "operator": { "type": "string", "format": "email", "description": "The email address of the user who deleted the recording." }, "operator_id": { "type": "string", "description": "The user ID of the user who deleted the recording." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_deleted\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n\t\"operator\" : \"user@example.com\",\n\t\"operator_id\" : \"I7zp-pYbTl22Z29H796Ixg\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_deleted"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "operator", "operator_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "operator": { "type": "string", "format": "email", "description": "The email address of the user who deleted the recording." }, "operator_id": { "type": "string", "description": "The user ID of the user who deleted the recording." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_deleted\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n\t\"operator\" : \"user@example.com\",\n\t\"operator_id\" : \"I7zp-pYbTl22Z29H796Ixg\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } } } } }, "session.user_room_system_callout_failed": { "post": { "tags": ["session"], "operationId": "session.user_room_system_callout_failed", "requestBody": { "description": "# session.user_room_system_callout_failed\n\nThe **Session invitation through phone (call out) via Zoom room failed** event is triggered every time an invitation to [join a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035) fails.\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n* A valid **Event Notification Endpoint URL**.\n* The **Session invitation through phone (call out) via Zoom room failed** subscription enabled under the **Session** event.\n\n\n\n**Event type**: `session.user_room_system_callout_failed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "reason_type", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "reason_type": { "type": "integer", "description": "reason type for failure: \n* 1 — Encryption_Fail. \n* 2 — Disconnected_By_Remote. \n* 3 — Retry. \n* 4 — Bad_Seq. \n* 5 — Call_Limit. \n* 6 — Not_Registered. \n* 7 — Timeout. \n* 8 — Bad_Addr. \n* 9 — Unreachable \n* 10 — Disconnect_By_Local \n* 11 — Server_Internal_Error \n* 12 — Exceed_Free_Port \n* 13 — Connect_Error \n* 14 — Proxy_Connect_Error \n* 0 — Other_Failed_Reason.", "enum": [0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 14] }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_failed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"reason_type\": 1,\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "reason_type", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "reason_type": { "type": "integer", "description": "reason type for failure: \n* 1 — Encryption_Fail. \n* 2 — Disconnected_By_Remote. \n* 3 — Retry. \n* 4 — Bad_Seq. \n* 5 — Call_Limit. \n* 6 — Not_Registered. \n* 7 — Timeout. \n* 8 — Bad_Addr. \n* 9 — Unreachable \n* 10 — Disconnect_By_Local \n* 11 — Server_Internal_Error \n* 12 — Exceed_Free_Port \n* 13 — Connect_Error \n* 14 — Proxy_Connect_Error \n* 0 — Other_Failed_Reason.", "enum": [0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 14] }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_failed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"reason_type\": 1,\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } } } } }, "session.recording_completed": { "post": { "tags": ["session"], "operationId": "session.recording_completed", "requestBody": { "description": "# session.recording_completed\n---\n\nEvent: `session.recording_completed`\n\n## Event description\n\nThe **Session recording completed** event is triggered every time a recording of a session becomes available to view and/or download.\n\nOnly a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n * A valid Event Notification Endpoint URL.\n * Session recording completed subscription enabled under the Recording event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_completed` event notification:\n\n\n\n**Event type**: `session.recording_completed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "download_token", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_completed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "download_token": { "type": "string", "description": "A generated token used to download the recording. The download token only lasts for 24 hours after its creation and you can only download the file within 24 hours of receiving the event notification. Pass the download_token as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {download_token} \\\n --header 'content-type: application/json'\n" }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_files" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the \"Add a timestamp to the recording\" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile.\n
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format.\n\n
    \n\nA recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    \n\tid, status, file_size, recording_type.", "enum": [ "MP4", "M4A", "CHAT", "TRANSCRIPT", "CSV", "CC", "TB", "CHAT_MESSAGE" ] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4", "M4A", "TXT", "VTT", "CSV", "JSON", "JPG"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n" }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": [ "shared_screen_with_speaker_view(CC)", "shared_screen_with_speaker_view", "shared_screen_with_gallery_view", "gallery_view", "shared_screen", "audio_only", "audio_transcript", "chat_file", "active_speaker", "host_video", "audio_only_each_participant", "cc_transcript", "closed_caption", "poll", "timeline", "thumbnail", "chat_message" ] } } } }, "participant_audio_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the \"Add a timestamp to the recording\" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile.\n
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format.\n\n
    \n\nA recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    \n\tid, status, file_size, recording_type.", "enum": [ "MP4", "M4A", "CHAT", "TRANSCRIPT", "CSV", "CC", "TB", "CHAT_MESSAGE" ] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4", "M4A", "TXT", "VTT", "CSV", "JSON", "JPG"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n" }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": [ "shared_screen_with_speaker_view(CC)", "shared_screen_with_speaker_view", "shared_screen_with_gallery_view", "gallery_view", "shared_screen", "audio_only", "audio_transcript", "chat_file", "active_speaker", "host_video", "audio_only_each_participant", "cc_transcript", "closed_caption", "poll", "timeline", "thumbnail", "chat_message" ] }, "user_id": { "type": "string", "description": "The participant's session user ID. This value is assigned to a participant upon joining a session and is only valid for the duration of the session." }, "user_key": { "type": "string", "description": "The participant's SDK identifier. Set with the user_identity key in the Video SDK JWT payload. This value can be alphanumeric, up to a maximum length of 35 characters." } } } }, "participant_video_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.", "enum": ["MP4"] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n" }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": ["individual_user", "individual_shared_screen"] }, "user_id": { "type": "string", "description": "The participant's session user ID. This value is assigned to a participant upon joining a session and is only valid for the duration of the session." }, "user_key": { "type": "string", "description": "The participant's SDK identifier. Set with the user_identity key in the Video SDK JWT payload. This value can be alphanumeric, up to a maximum length of 35 characters." } } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_completed\",\n \"event_ts\": 1626230691572,\n \"download_token\": \"abJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwczovL2V2ZW50Lnpvb20udXMiLCJhY2NvdW50SWQiOiJNdDZzdjR1MFRBeVBrd2dzTDJseGlBIiwiYXVkIjoiaHR0cHM6Ly9vYXV0aC56b29tLnVzIiwibWlkIjoieFp3SEc0c3BRU2VuekdZWG16dnpiUT09IiwiZXhwIjoxNjI2MTM5NTA3LCJ1c2VySWQiOiJEWUhyZHBqclMzdWFPZjdkUGtrZzh3In0.a6KetiC6BlkDhf1dP4KBGUE1bb2brMeraoD45yhFx0eSSSTFdkHQnsKmlJQ-hdo9Zy-4vQw3rOxlyoHv583JyZ\",\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_files\": [\n {\n \"id\": \"ed6c2f27-2ae7-42f4-b3d0-835b493e4fa8\",\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\",\n \"recording_type\": \"audio_only\",\n \"file_type\": \"M4A\",\n \"file_size\": 246560,\n \"file_extension\": \"M4A\",\n \"download_url\": \"https://example.com/recording/download/Qg75t7xZBtEbAkjdlgbfdngBBBB\",\n \"status\": \"completed\",\n \"recording_type\": \"audio_only\"\n }\n ],\n \"participant_audio_files\": [\n {\n \"id\": \"ed6c2f27-2ae7-42f4-b3d0-835b493e4fa8\",\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\",\n \"file_type\": \"M4A\",\n \"file_name\": \"MyRecording\",\n \"file_size\": 246560,\n \"file_extension\": \"MP4\",\n \"download_url\": \"https://example.com/recording/download/Qg75t7xZBtEbAkjdlgbfdngAAAA\",\n \"status\": \"completed\",\n \"recording_type\": \"audio_only\",\n \"user_id\": \"16778240\",\n \"user_key\": \"key1\"\n }\n ],\n \"participant_video_files\": [\n {\n \"id\": \"0a564312-edf7-495e-b916-6873a7b32c50\",\n \"status\": \"completed\",\n \"recording_start\": \"2022-12-06T01:01:30Z\",\n \"recording_end\": \"2022-12-06T01:10:32Z\",\n \"file_type\": \"MP4\",\n \"file_size\": 1200500,\n \"download_url\": \"https://example.com/rec/download/cWfE3Ye3UUFgTxbBcii5t\",\n \"recording_type\": \"individual_shared_screen\",\n \"file_name\": \"Separated Share Video - user@example.com\",\n \"file_extension\": \"MP4\",\n \"user_id\": \"16778240\",\n \"user_key\": \"key1\"\n }\n ]\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "download_token", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_completed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "download_token": { "type": "string", "description": "A generated token used to download the recording. The download token only lasts for 24 hours after its creation and you can only download the file within 24 hours of receiving the event notification. Pass the download_token as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {download_token} \\\n --header 'content-type: application/json'\n" }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_files" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the \"Add a timestamp to the recording\" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile.\n
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format.\n\n
    \n\nA recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    \n\tid, status, file_size, recording_type.", "enum": [ "MP4", "M4A", "CHAT", "TRANSCRIPT", "CSV", "CC", "TB", "CHAT_MESSAGE" ] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4", "M4A", "TXT", "VTT", "CSV", "JSON", "JPG"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n" }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": [ "shared_screen_with_speaker_view(CC)", "shared_screen_with_speaker_view", "shared_screen_with_gallery_view", "gallery_view", "shared_screen", "audio_only", "audio_transcript", "chat_file", "active_speaker", "host_video", "audio_only_each_participant", "cc_transcript", "closed_caption", "poll", "timeline", "thumbnail", "chat_message" ] } } } }, "participant_audio_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.
    M4A Audio-only file of the recording.
    TIMELINE: Timestamp file of the recording in JSON file format. To get a timeline file, the \"Add a timestamp to the recording\" setting must be enabled in the [recording settings](https://support.zoom.us/hc/en-us/articles/360060316092). The time will display in the host's timezone, set on their Zoom profile.\n
    TRANSCRIPT: Transcription file of the recording in VTT format.
    CHAT: A TXT file containing in-session chat messages that were sent during the session.
    CC: File containing closed captions of the recording in VTT file format.
    CSV: File containing polling data in csv format.\n\n
    \n\nA recording file object with file type of either CC or TIMELINE **does not have** the following properties:
    \n\tid, status, file_size, recording_type.", "enum": [ "MP4", "M4A", "CHAT", "TRANSCRIPT", "CSV", "CC", "TB", "CHAT_MESSAGE" ] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4", "M4A", "TXT", "VTT", "CSV", "JSON", "JPG"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n" }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": [ "shared_screen_with_speaker_view(CC)", "shared_screen_with_speaker_view", "shared_screen_with_gallery_view", "gallery_view", "shared_screen", "audio_only", "audio_transcript", "chat_file", "active_speaker", "host_video", "audio_only_each_participant", "cc_transcript", "closed_caption", "poll", "timeline", "thumbnail", "chat_message" ] }, "user_id": { "type": "string", "description": "The participant's session user ID. This value is assigned to a participant upon joining a session and is only valid for the duration of the session." }, "user_key": { "type": "string", "description": "The participant's SDK identifier. Set with the user_identity key in the Video SDK JWT payload. This value can be alphanumeric, up to a maximum length of 35 characters." } } } }, "participant_video_files": { "type": "array", "title": "Recording file List", "description": "List of recording file.", "items": { "type": "object", "properties": { "id": { "type": "string", "description": "The recording file ID. Included in the response of general query." }, "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." }, "file_name": { "type": "string", "description": "Name of the file." }, "file_path": { "type": "string", "description": "The file path to the On-Premise account recording. \n\n**Note:** This API only returns this field for [Zoom On-Premise accounts](https://support.zoom.us/hc/en-us/articles/360034064852-Zoom-On-Premise-Deployment). It does **not** return the download_url field." }, "file_type": { "type": "string", "description": "The recording file type. The value of this field could be one of the following:
    \nMP4: Video file of the recording.", "enum": ["MP4"] }, "file_size": { "type": "number", "description": "The recording file size." }, "file_extension": { "type": "string", "description": "The archived file's file extension.", "enum": ["MP4"] }, "download_url": { "type": "string", "description": "The URL at which to download the the recording. \n\nTo access a private or password-protected cloud recording of a user in your account, use your [Video SDK API JWT](https://marketplace.zoom.us/docs/guides/build/video-sdk-app/#video-sdk-and-api-credentials). Pass the generated JWT as a Bearer token in the Authorization header of your HTTP request. For example: \n\n \ncurl --request GET \\\n --url {download_url} \\\n --header 'authorization: Bearer {JWT} \\\n --header 'content-type: application/json'\n" }, "status": { "type": "string", "description": "The recording status.", "enum": ["completed"] }, "recording_type": { "type": "string", "description": "The recording type. The value of this field can be one of the following:
    shared_screen_with_speaker_view(CC)
    shared_screen_with_speaker_view
    shared_screen_with_gallery_view
    speaker_view
    gallery_view
    shared_screen
    audio_only
    audio_transcript
    chat_file
    active_speaker
    poll
    timeline
    closed_caption", "enum": ["individual_user", "individual_shared_screen"] }, "user_id": { "type": "string", "description": "The participant's session user ID. This value is assigned to a participant upon joining a session and is only valid for the duration of the session." }, "user_key": { "type": "string", "description": "The participant's SDK identifier. Set with the user_identity key in the Video SDK JWT payload. This value can be alphanumeric, up to a maximum length of 35 characters." } } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_completed\",\n \"event_ts\": 1626230691572,\n \"download_token\": \"abJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwczovL2V2ZW50Lnpvb20udXMiLCJhY2NvdW50SWQiOiJNdDZzdjR1MFRBeVBrd2dzTDJseGlBIiwiYXVkIjoiaHR0cHM6Ly9vYXV0aC56b29tLnVzIiwibWlkIjoieFp3SEc0c3BRU2VuekdZWG16dnpiUT09IiwiZXhwIjoxNjI2MTM5NTA3LCJ1c2VySWQiOiJEWUhyZHBqclMzdWFPZjdkUGtrZzh3In0.a6KetiC6BlkDhf1dP4KBGUE1bb2brMeraoD45yhFx0eSSSTFdkHQnsKmlJQ-hdo9Zy-4vQw3rOxlyoHv583JyZ\",\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_files\": [\n {\n \"id\": \"ed6c2f27-2ae7-42f4-b3d0-835b493e4fa8\",\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\",\n \"recording_type\": \"audio_only\",\n \"file_type\": \"M4A\",\n \"file_size\": 246560,\n \"file_extension\": \"M4A\",\n \"download_url\": \"https://example.com/recording/download/Qg75t7xZBtEbAkjdlgbfdngBBBB\",\n \"status\": \"completed\",\n \"recording_type\": \"audio_only\"\n }\n ],\n \"participant_audio_files\": [\n {\n \"id\": \"ed6c2f27-2ae7-42f4-b3d0-835b493e4fa8\",\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\",\n \"file_type\": \"M4A\",\n \"file_name\": \"MyRecording\",\n \"file_size\": 246560,\n \"file_extension\": \"MP4\",\n \"download_url\": \"https://example.com/recording/download/Qg75t7xZBtEbAkjdlgbfdngAAAA\",\n \"status\": \"completed\",\n \"recording_type\": \"audio_only\",\n \"user_id\": \"16778240\",\n \"user_key\": \"key1\"\n }\n ],\n \"participant_video_files\": [\n {\n \"id\": \"0a564312-edf7-495e-b916-6873a7b32c50\",\n \"status\": \"completed\",\n \"recording_start\": \"2022-12-06T01:01:30Z\",\n \"recording_end\": \"2022-12-06T01:10:32Z\",\n \"file_type\": \"MP4\",\n \"file_size\": 1200500,\n \"download_url\": \"https://example.com/rec/download/cWfE3Ye3UUFgTxbBcii5t\",\n \"recording_type\": \"individual_shared_screen\",\n \"file_name\": \"Separated Share Video - user@example.com\",\n \"file_extension\": \"MP4\",\n \"user_id\": \"16778240\",\n \"user_key\": \"key1\"\n }\n ]\n }\n }\n}" } } } } } } } }, "session.recording_transcript_failed": { "post": { "tags": ["session"], "operationId": "session.recording_transcript_failed", "requestBody": { "description": "# session.recording_transcript_failed\n---\n\nEvent: `session.recording_transcript_failed`\n\n## Event description\n\nThe **Session recording transcript failed** event is triggered every time the transcript of the recording of a session generated failed.\n\nOnly a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details.\n\n## Prerequisites\n\n* Enable Cloud Recording on the Video SDK account.\n* Enable Event Subscriptions for your app with the following configurations:\n * A valid Event Notification Endpoint URL.\n * Enable session recording transcript completed subscription under the Recording event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_transcript_completed` event notification:\n\n\n\n**Event type**: `session.recording_transcript_failed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_transcript_failed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, when the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time when the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_transcript_completed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_transcript_failed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, when the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time when the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_transcript_completed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } } } } }, "session.recording_trashed": { "post": { "tags": ["session"], "operationId": "session.recording_trashed", "requestBody": { "description": "# session.recording_trashed\n---\n\nEvent: `session.recording_trashed`\n\n## Event description\n\nThe **Session recording deleted to trash** event is triggered every time one of your app users or account users temporarily delete a cloud recording.\n\nWhen a user initially deletes a recording, it is deleted to the trash. Recordings deleted to the trash can be recovered up to 30 days after deletion. Users can move a recording to the trash using:\n\n* The [Delete session's recording](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingDelete) API **with the trash query parameter** or\n* The Zoom web portal. See [Video SDK account](https://developers.zoom.us/docs/video-sdk/account/) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n\t* A valid Event Notification Endpoint URL.\n\t* **Session recording deleted to trash** subscription enabled under the **Recording** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_trashed` event notification:\n\n\n\n**Event type**: `session.recording_trashed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_trashed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "operator", "operator_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "operator": { "type": "string", "format": "email", "description": "The email address of the user who deleted the recording." }, "operator_id": { "type": "string", "description": "The user ID of the user who deleted the recording." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_trashed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n\t\"operator\" : \"user@example.com\",\n\t\"operator_id\" : \"I7zp-pYbTl22Z29H796Ixg\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_trashed"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "operator", "operator_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "operator": { "type": "string", "format": "email", "description": "The email address of the user who deleted the recording." }, "operator_id": { "type": "string", "description": "The user ID of the user who deleted the recording." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_trashed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n\t\"operator\" : \"user@example.com\",\n\t\"operator_id\" : \"I7zp-pYbTl22Z29H796Ixg\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } } } } }, "session.user_joined": { "post": { "tags": ["session"], "operationId": "session.user_joined", "requestBody": { "description": "# session.user_joined\n---\n\n\nThe Session User Joined event is triggered every time a user (including host and co-host) joins a session.\n\n## Prerequisites\nEvent Subscriptions must be enabled for your [Marketplace app](https://marketplace.zoom.us/user/build) with the following configurations:\n\n* A valid Event Notification Endpoint URL.\n* Session User Joined subscription enabled under the Video SDK event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.user_joined` event notification:\n\n\n\n**Event type**: `session.user_joined`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.user_joined"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "join_time", "participant_uuid"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "join_time": { "type": "string", "description": "The time at which the user joined the session.", "format": "date-time" }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "phone_number": { "type": "string", "description": "Phone number of participant joined via PSTN." }, "participant_uuid": { "type": "string", "description": "The participant's UUID. This value is assigned to a participant upon joining a session and is only valid for the session's duration." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_joined\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"account_id\": \"EFgHiJABC000DEfGHI\",\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"example\",\n \"join_time\": \"2021-07-16T17:19:11Z\",\n \"user_key\": \"ASD74dfDI854\",\n \"phone_number\": \"8615250064084\",\n \"participant_uuid\": \"55555AAAiAAAAAiAiAiiAii\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.user_joined"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": ["id", "session_id", "session_name", "user"], "properties": { "id": { "type": "string", "description": "The session ID." }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user": { "type": "object", "description": "Information about the user.", "required": ["id", "name", "join_time", "participant_uuid"], "properties": { "id": { "type": "string", "description": "The user's unique ID. This value is assigned to the user upon joining a session and is only valid for that session." }, "name": { "type": "string", "description": "The user's username." }, "join_time": { "type": "string", "description": "The time at which the user joined the session.", "format": "date-time" }, "user_key": { "type": "string", "description": "Another identifier for the user. Can be a number or characters." }, "phone_number": { "type": "string", "description": "Phone number of participant joined via PSTN." }, "participant_uuid": { "type": "string", "description": "The participant's UUID. This value is assigned to a participant upon joining a session and is only valid for the session's duration." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_joined\",\n \"event_ts\": 1626473951859,\n \"payload\": {\n \"account_id\": \"EFgHiJABC000DEfGHI\",\n \"object\": {\n \"id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user\": {\n \"id\": \"25508864\",\n \"name\": \"example\",\n \"join_time\": \"2021-07-16T17:19:11Z\",\n \"user_key\": \"ASD74dfDI854\",\n \"phone_number\": \"8615250064084\",\n \"participant_uuid\": \"55555AAAiAAAAAiAiAiiAii\"\n }\n }\n }\n}" } } } } } } } }, "session.stream_ingestion_started": { "post": { "tags": ["session"], "operationId": "session.stream_ingestion_started", "requestBody": { "description": "# session.stream_ingestion_started\nZoom triggers the **Session stream ingestion started** event every time a host starts sending an incoming live stream to a session. The session user can subscribe to it to see what's being streamed live into this session.\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Session stream ingestion started** subscription enabled under the **Video SDK** event.\n\n\n**Event type**: `session.stream_ingestion_started`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_started"], "description": "Event name." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_started\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_started"], "description": "Event name." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_started\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } } } } }, "session.stream_ingestion_connected": { "post": { "tags": ["session"], "operationId": "session.stream_ingestion_connected", "requestBody": { "description": "# session.stream_ingestion_connected\nZoom triggers the **Session stream ingestion connected** event every time live streaming software connects to the Zoom Video SDK session. This indicates that the Zoom streaming platform is receiving data from the streaming software, but the received Real-Time Messaging Protocol (RTMP) data is not sent to the session yet.\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Session stream ingestion connected** subscription enabled under the **Video SDK** event.\n\n\n**Event type**: `session.stream_ingestion_connected`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_connected"], "description": "Name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_connected\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_connected"], "description": "Name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_connected\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } } } } }, "session.stream_ingestion_disconnected": { "post": { "tags": ["session"], "operationId": "session.stream_ingestion_disconnected", "requestBody": { "description": "# session.stream_ingestion_disconnected\nZoom triggers the **Session stream ingestion disconnected** event every time a Real-Time Messaging Protocol (RTMP) software program disconnects.\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Session stream ingestion disconnected** subscription enabled under the **Video SDK** event.\n\n\n**Event type**: `session.stream_ingestion_disconnected`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_disconnected"], "description": "Name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_disconnected\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.stream_ingestion_disconnected"], "description": "Name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "Timestamp (in milliseconds since epoch) when the event occurred. The value of this field is returned in long (int64) format." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session.", "required": ["session_id", "session_name", "stream_ingestion"], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "stream_ingestion": { "type": "object", "description": "Information about the stream ingestion.", "required": [ "stream_id", "stream_name", "stream_key", "stream_url", "backup_stream_url" ], "properties": { "stream_id": { "type": "string", "description": "The stream ingestion ID." }, "stream_name": { "type": "string", "description": "The stream ingestion name." }, "stream_description": { "type": "string", "description": "The stream ingestion description." }, "stream_key": { "type": "string", "description": "The stream ingestion key." }, "stream_url": { "type": "string", "description": "The stream URL." }, "backup_stream_url": { "type": "string", "description": "The backup stream URL." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.stream_ingestion_disconnected\",\n \"event_ts\": 1627906965803,\n \"payload\": {\n \"account_id\": \"D8cJuqWVQ623CI4Q8yQK0Q\",\n \"object\": {\n \"session_id\": \"4567UVWxYZABCdEfGhiJkl==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"stream_ingestion\": {\n \"stream_id\": \"sfk/aOFJSJSYhGwk1hnxgw==\",\n \"stream_name\": \"stream ingestion1\",\n \"stream_description\": \"stream ingestion1\",\n \"stream_key\": \"ABCDEFG12345HIJ6789\",\n \"stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\",\n \"backup_stream_url\": \"rtmp://a.rtmp.zoomevent.com/live1\"\n }\n }\n }\n}" } } } } } } } }, "session.recording_recovered": { "post": { "tags": ["session"], "operationId": "session.recording_recovered", "requestBody": { "description": "# session.recording_recovered\n---\n\nEvent: `session.recording_recovered`\n\n## Event description\n\nThe **Session recording recovered** event is triggered every time one of your app users or account users recover a recording from the trash.\n\nZoom allows users to recover their cloud recordings from trash within 30 days of deletion. You can recover a deleted cloud recording with:\n\n* The tab in the Zoom web client. See [Video SDK recordings and reports](https://developers.zoom.us/docs/video-sdk/reports/) for details.\n* The [Recover a single recording](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingStatusUpdateOne) or [Recover session's recordings](https://developers.zoom.us/docs/api/rest/reference/video-sdk/methods/#operation/recordingStatusUpdate) API.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n\t* A valid Event Notification Endpoint URL.\n\t* \"**Session recording recovered**\" subscription enabled under the **Recording** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_recovered` event notification:\n\n\n\n**Event type**: `session.recording_recovered`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_recovered"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "operator", "operator_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "operator": { "type": "string", "format": "email", "description": "The email address of the user who deleted the recording." }, "operator_id": { "type": "string", "description": "The user ID of the user who deleted the recording." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_recovered\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n\t\"operator\" : \"user@example.com\",\n\t\"operator_id\" : \"I7zp-pYbTl22Z29H796Ixg\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_recovered"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "operator", "operator_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "operator": { "type": "string", "format": "email", "description": "The email address of the user who deleted the recording." }, "operator_id": { "type": "string", "description": "The user ID of the user who deleted the recording." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_recovered\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n\t\"operator\" : \"user@example.com\",\n\t\"operator_id\" : \"I7zp-pYbTl22Z29H796Ixg\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\"\n }\n }\n}" } } } } } } } }, "session.user_phone_callout_missed": { "post": { "tags": ["session"], "operationId": "session.user_phone_callout_missed", "requestBody": { "description": "# session.user_phone_callout_missed\n\nThe **Invited party missed a session invitation through phone (call out)** event is triggered every time an invitation to join a session through phone (call out) times out. Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Invited party missed a session invitation through phone (call out)** subscription enabled under the **Session** event.\n\n\n\n\n**Event type**: `session.user_phone_callout_missed`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited user.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_missed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited user.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_missed\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } } } } }, "session.user_phone_callout_rejected": { "post": { "tags": ["session"], "operationId": "session.user_phone_callout_rejected", "requestBody": { "description": "# session.user_phone_callout_rejected\n\nThe **Invited party rejected a session invitation through phone (call out)** event is triggered every time a user rejects an invitation to join a session through phone (call out). Video SDK call out operates in a similar manner as [Zoom meeting call out](https://support.zoom.com/hc/article?id=zm_kb&sysparm_article=KB0062038).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n * A valid **Event Notification Endpoint URL**.\n * The **Invited party rejected a session invitation through phone (call out)** subscription enabled under the **Session** event.\n\n\n\n\n**Event type**: `session.user_phone_callout_rejected`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited user.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_rejected\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "session_key", "user_key", "host_id", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "user_key": { "type": "string", "description": "Another identifier for the inviter. Can be a number or characters." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "participant": { "type": "object", "description": "Information about the invited user.", "required": ["invitee_name", "phone_number", "from_number"], "properties": { "invitee_name": { "type": "string", "description": "The user's name to display in the session." }, "phone_number": { "type": "integer", "format": "int64", "description": "The user's phone number." }, "from_number": { "type": "integer", "format": "int64", "description": "The number used to call out to the invited user." } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_phone_callout_rejected\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"session_key\": \"ABC36jaBI145\",\n \"user_key\": \"ASD74dfDI854\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"participant\": {\n \"invitee_name\": \"Jill Chill\",\n \"phone_number\": 15555550100,\n \"from_number\": 13167900000\n }\n }\n }\n}" } } } } } } } }, "session.user_room_system_callout_accepted": { "post": { "tags": ["session"], "operationId": "session.user_room_system_callout_accepted", "requestBody": { "description": "# session.user_room_system_callout_accepted\n\nThe **Invited party answered a session invitation through phone (call out) via Zoom room** event is triggered every time a user [joins a session through phone (call out) from a Zoom room](https://support.zoom.us/hc/en-us/articles/205369035).\n\n## Prerequisites\n\n* **Event Subscriptions** must be enabled for your app with the following configurations:\n* A valid **Event Notification Endpoint URL**.\n* The **Invited party answered a session invitation through phone (call out) via Zoom room** subscription enabled under the **Session** event.\n\n\n\n**Event type**: `session.user_room_system_callout_accepted`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_accepted\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "description": "The name of the event." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The account ID of the session host." }, "object": { "type": "object", "description": "Information about the session.", "required": [ "session_id", "session_name", "host_id", "message_id", "inviter_name", "participant" ], "properties": { "id": { "type": "integer", "format": "int64", "description": "The session ID.", "deprecated": true }, "uuid": { "type": "string", "description": "The session's universally unique identifier (UUID). Each session instance generates a session UUID.", "deprecated": true }, "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "host_id": { "type": "string", "description": "The user ID of the session host." }, "message_id": { "type": "string", "description": "The request unique identifier (UUID)." }, "inviter_name": { "type": "string", "description": "The user name of the event's trigger." }, "participant": { "type": "object", "description": "Information about the invited participant.", "required": ["call_type", "device_ip"], "properties": { "call_type": { "type": "string", "description": "The type of call out. Use a value of h323 or sip." }, "device_ip": { "type": "string", "description": "The user's device IP address." } }, "additionalProperties": true } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.user_room_system_callout_accepted\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"dzVA4QmMQfyISoRcpFO8CA\",\n \"object\": {\n \"id\": 713592696,\n \"uuid\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_id\": \"4444AAAiAAAAAiAiAiiAii==\",\n \"session_name\": \"My Session\",\n \"host_id\": \"ICuPoX4ERtikRcKqkVxunQ\",\n \"message_id\": \"atsXxhSEQWit9t+U02HXNQ==\",\n \"inviter_name\": \"Jill Chill\",\n \"participant\": {\n \"call_type\": \"h323\",\n \"device_ip\": \"10.100.111.237\"\n }\n }\n }\n}" } } } } } } } }, "session.recording_stopped": { "post": { "tags": ["session"], "operationId": "session.recording_stopped", "requestBody": { "description": "# session.recording_stopped\n---\n\nEvent: `session.recording_stopped`\n\n## Event description\n\nThe **Session recording stopped** event is triggered every time a previously paused recording of a session is resumed.\n\nOnly a session host or co-host can start, pause, resume, or stop a cloud recording. A recording is considered complete **after** the host or co-host ends the session. See [Enable cloud recording](https://developers.zoom.us/docs/video-sdk/account/#enable-cloud-recording) for details.\n\n## Prerequisites\n\n* Cloud Recording must be enabled on the Video SDK account.\n* Event Subscriptions must be enabled for your app with the following configurations:\n * A valid Event Notification Endpoint URL.\n * **Session recording stopped** subscription enabled under the **Recording** event.\n\nThe tabs below display the complete schema, payload with data types, and an example of the `session.recording_stopped` event notification:\n\n\n\n**Event type**: `session.recording_stopped`\n", "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_stopped"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_stopped\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["event", "event_ts", "payload"], "properties": { "event": { "type": "string", "enum": ["session.recording_stopped"], "description": "The event's name." }, "event_ts": { "type": "integer", "format": "int64", "description": "A timestamp, in milliseconds since epoch, at which the event occurred." }, "payload": { "type": "object", "required": ["account_id", "object"], "properties": { "account_id": { "type": "string", "description": "The Video SDK account ID." }, "object": { "type": "object", "description": "Information about the session. This object only returns updated properties.", "required": [ "session_id", "session_name", "session_key", "start_time", "timezone", "recording_file" ], "properties": { "session_id": { "type": "string", "description": "Unique session identifier. Each instance of the session will have its own session_id." }, "session_name": { "type": "string", "description": "Session name." }, "session_key": { "type": "string", "description": "The Video SDK custom session ID." }, "start_time": { "type": "string", "format": "date-time", "description": "The time at which the session started." }, "timezone": { "type": "string", "description": "The user's timezone." }, "recording_file": { "type": "object", "properties": { "recording_start": { "type": "string", "description": "The recording start time." }, "recording_end": { "type": "string", "description": "The recording end time. Response in general query." } } } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }, "examples": { "json-example": { "summary": "JSON example", "value": "{\n \"event\": \"session.recording_stopped\",\n \"event_ts\": 1626230691572,\n \"payload\": {\n \"account_id\": \"AAAAAABBBB\",\n \"object\": {\n \"session_id\": 1234567890,\n \"session_name\": \"My Personal Recording\",\n \"session_key\": \"ABC36jaBI145\",\n \"start_time\": \"2021-07-13T21:44:51Z\",\n \"timezone\": \"America/Los_Angeles\",\n \"recording_file\": {\n \"recording_start\": \"2021-03-23T22:14:57Z\",\n \"recording_end\": \"2021-03-23T23:15:41Z\"\n }\n }\n }\n}" } } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/ResolutionStep.v1_0_1.yaml ================================================ components: schemas: ResolutionStep_v1_0_1_ResolutionStep: type: object properties: ResolutionType: oneOf: - $ref: '#/components/schemas/ResolutionStep_v1_0_1_ResolutionType' ActionName: type: string description: Name of the action ResolutionStep_v1_0_1_ResolutionType: type: string enum: - ContactVendor - ResetToDefaults - RetryOperation description: Types of resolution actions ResolutionStep_v1_0_1_ActionParameters: type: object properties: ActionId: type: string ActionType: $ref: '#/components/schemas/ResolutionStep_v1_0_1_ResolutionType' ================================================ FILE: specs/json-schema-ref-parser/circular-ref-with-description.json ================================================ { "schemas": { "Foo": { "$ref": "#/schemas/Bar" }, "Bar": { "description": "ok", "$ref": "#/schemas/Foo" } } } ================================================ FILE: specs/json-schema-ref-parser/external-with-siblings.json ================================================ { "components": { "schemas": { "ResolutionStep": { "type": "object", "properties": { "ResolutionType": { "oneOf": [ { "$ref": "#/components/schemas/ResolutionType" } ] }, "ActionName": { "type": "string" } } }, "ResolutionType": { "type": "string", "enum": ["ContactVendor", "ResetToDefaults", "RetryOperation"] }, "ActionInfo": { "type": "object", "properties": { "ActionId": { "type": "string" } } } } } } ================================================ FILE: specs/json-schema-ref-parser/main-with-external-siblings.json ================================================ { "openapi": "3.0.0", "info": { "title": "Test API", "version": "1.0.0" }, "paths": { "/resolution": { "get": { "summary": "Get resolution step", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "external-with-siblings.json#/components/schemas/ResolutionStep" } } } } } } }, "/action": { "get": { "summary": "Get action info", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "external-with-siblings.json#/components/schemas/ActionInfo" } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/multiple-refs.json ================================================ { "paths": { "/test1/{pathId}": { "get": { "summary": "First endpoint using the same pathId schema", "parameters": [ { "$ref": "path-parameter.json#/components/parameters/pathId" } ], "responses": { "200": { "description": "Test 1 response" } } } }, "/test2/{pathId}": { "get": { "summary": "Second endpoint using the same pathId schema", "parameters": [ { "$ref": "path-parameter.json#/components/parameters/pathId" } ], "responses": { "200": { "description": "Test 2 response" } } } } } } ================================================ FILE: specs/json-schema-ref-parser/openapi-paths-ref.json ================================================ { "openapi": "3.1.0", "info": { "title": "Sample API", "version": "1.0.0" }, "paths": { "/foo": { "get": { "summary": "Get foo", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "bar": { "type": "string" } } } } } } } }, "post": { "summary": "Create foo", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/paths/~1foo/get/responses/200/content/application~1json/schema" } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/path-parameter.json ================================================ { "components": { "parameters": { "pathId": { "name": "pathId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid", "description": "Unique identifier for the path" } } } } } ================================================ FILE: specs/json-schema-ref-parser/redfish-like.yaml ================================================ openapi: 3.0.0 info: title: Redfish-like API version: '1.0.0' description: Test API simulating Redfish structure with versioned schemas paths: /redfish/v1/Systems: get: summary: Get Systems responses: '200': description: Success content: application/json: schema: $ref: 'ResolutionStep.v1_0_1.yaml#/components/schemas/ResolutionStep_v1_0_1_ResolutionStep' default: description: Error /redfish/v1/Actions: post: summary: Submit Action responses: '200': description: Success content: application/json: schema: $ref: 'ResolutionStep.v1_0_1.yaml#/components/schemas/ResolutionStep_v1_0_1_ActionParameters' ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-collision-other.json ================================================ { "components": { "schemas": { "OtherSchema": { "type": "object", "properties": { "code": { "$ref": "#/components/schemas/Status" } } }, "Status": { "type": "integer", "enum": [0, 1, 2] } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-collision-root.json ================================================ { "openapi": "3.1.0", "info": { "title": "Collision Test", "version": "1.0.0" }, "paths": { "/main": { "get": { "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$ref": "sibling-schema-collision-wrapper.json#/components/schemas/MainSchema" } } } } } } }, "/other": { "get": { "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$ref": "sibling-schema-collision-other.json#/components/schemas/OtherSchema" } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-collision-versioned.json ================================================ { "components": { "schemas": { "MainSchema": { "type": "object", "properties": { "status": { "$ref": "#/components/schemas/Status" } } }, "Status": { "type": "string", "enum": ["active", "inactive"] } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-collision-wrapper.json ================================================ { "components": { "schemas": { "MainSchema": { "$ref": "sibling-schema-collision-versioned.json#/components/schemas/MainSchema" } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-direct-root.json ================================================ { "openapi": "3.1.0", "info": { "title": "Direct Sibling Schema Test", "version": "1.0.0" }, "paths": { "/test": { "get": { "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$ref": "sibling-schema-versioned.json#/components/schemas/Versioned_Schema" } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-extended-root.json ================================================ { "openapi": "3.1.0", "info": { "title": "Extended Wrapper Sibling Schema Test", "version": "1.0.0" }, "paths": { "/test": { "get": { "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$ref": "sibling-schema-extended-wrapper.json#/components/schemas/Wrapper_Schema" } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-extended-wrapper.json ================================================ { "components": { "schemas": { "Wrapper_Schema": { "description": "Wrapper that extends the versioned schema", "$ref": "sibling-schema-versioned.json#/components/schemas/Versioned_Schema" } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-multi-root.json ================================================ { "openapi": "3.1.0", "info": { "title": "Multiple Siblings Test", "version": "1.0.0" }, "paths": { "/resource": { "get": { "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$ref": "sibling-schema-multi-wrapper.json#/components/schemas/Resource_Schema" } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-multi-versioned.json ================================================ { "components": { "schemas": { "Resource_v1_Schema": { "type": "object", "properties": { "status": { "$ref": "#/components/schemas/Resource_v1_StatusEnum" }, "health": { "$ref": "#/components/schemas/Resource_v1_HealthEnum" }, "name": { "type": "string" } } }, "Resource_v1_StatusEnum": { "type": "string", "enum": ["enabled", "disabled", "standby"] }, "Resource_v1_HealthEnum": { "type": "string", "enum": ["ok", "warning", "critical"] } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-multi-wrapper.json ================================================ { "components": { "schemas": { "Resource_Schema": { "description": "Wrapper with extra description", "$ref": "sibling-schema-multi-versioned.json#/components/schemas/Resource_v1_Schema" } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-root.json ================================================ { "openapi": "3.1.0", "info": { "title": "Sibling Schema Test", "version": "1.0.0" }, "paths": { "/test": { "get": { "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$ref": "sibling-schema-wrapper.json#/components/schemas/Wrapper_Schema" } } } } } } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-versioned.json ================================================ { "components": { "schemas": { "Versioned_Schema": { "type": "object", "properties": { "name": { "type": "string" }, "status": { "$ref": "#/components/schemas/Versioned_MyEnum" } } }, "Versioned_MyEnum": { "type": "string", "enum": ["active", "inactive", "pending"] } } } } ================================================ FILE: specs/json-schema-ref-parser/sibling-schema-wrapper.json ================================================ { "components": { "schemas": { "Wrapper_Schema": { "$ref": "sibling-schema-versioned.json#/components/schemas/Versioned_Schema" } } } } ================================================ FILE: specs/json-schema-ref-parser/test-siblings.yaml ================================================ components: schemas: MainSchema: type: object properties: typeField: $ref: '#/components/schemas/SiblingSchema' name: type: string SiblingSchema: type: string enum: - TypeA - TypeB ================================================ FILE: tsconfig.base.json ================================================ { "compilerOptions": { "declaration": true, "declarationMap": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true, "module": "ES2022", "moduleResolution": "Bundler", "noEmit": false, "noUncheckedIndexedAccess": true, "skipLibCheck": true, "sourceMap": true, "strict": true, "target": "ES2022", "verbatimModuleSyntax": true } } ================================================ FILE: tsconfig.json ================================================ { "files": [], "references": [ { "path": "./packages/codegen-core" }, { "path": "./packages/json-schema-ref-parser" }, { "path": "./packages/openapi-python" }, { "path": "./packages/openapi-ts" }, { "path": "./packages/shared" }, { "path": "./packages/types" } ] } ================================================ FILE: turbo.json ================================================ { "$schema": "./node_modules/turbo/schema.json", "tasks": { "build": { "dependsOn": ["^build"], "inputs": [ "src/**", "!src/**/*.test.ts", "package.json", "tsconfig.json", "tsdown.config.ts" ], "outputs": [ ".next/**", "!.next/cache/**", ".output/**", ".svelte-kit/**", ".vitepress/dist/**", "dist/**" ] }, "dev": { "cache": false, "persistent": true }, "lint": { "dependsOn": ["^build"], "inputs": ["src/**", "test/**", "*.config.*", "package.json"] }, "//#test": { "cache": true, "dependsOn": ["^build"], "inputs": ["src/**", "test/**", "*.config.*", "package.json", "vitest.config.ts"], "outputs": ["coverage/**"] }, "//#test:coverage": { "dependsOn": ["^build"], "inputs": ["src/**", "test/**", "*.config.*", "package.json", "vitest.config.ts"], "outputs": ["coverage/**"] }, "//#test:update": { "cache": false, "dependsOn": ["^build"] }, "//#test:watch": { "cache": false, "dependsOn": ["^build"], "persistent": true }, "typecheck": { "dependsOn": ["^build"], "inputs": [ "src/**", "test/**", "*.config.*", "package.json", "tsconfig.json", "pyproject.toml" ] } } } ================================================ FILE: vercel.json ================================================ { "$schema": "https://openapi.vercel.sh/vercel.json", "buildCommand": "pnpm --filter docs build", "cleanUrls": true, "devCommand": "pnpm --filter docs dev", "framework": "vitepress", "installCommand": "pnpm install --filter docs", "outputDirectory": "docs/.vitepress/dist", "redirects": [ { "source": "/openapi-ts", "destination": "/openapi-ts/get-started", "permanent": true }, { "source": "/openapi-ts/custom-plugin", "destination": "/openapi-ts/plugins/custom", "permanent": true }, { "source": "/openapi-ts/plugins", "destination": "/openapi-ts/core", "permanent": true }, { "source": "/openapi-ts/output/json-schema", "destination": "/openapi-ts/plugins/schemas", "permanent": true }, { "source": "/openapi-ts/output/sdk", "destination": "/openapi-ts/plugins/sdk", "permanent": true }, { "source": "/openapi-ts/transformers", "destination": "/openapi-ts/plugins/transformers", "permanent": true }, { "source": "/openapi-ts/output/typescript", "destination": "/openapi-ts/plugins/typescript", "permanent": true } ], "trailingSlash": false } ================================================ FILE: vitest.config.ts ================================================ import { platform } from 'node:os'; import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { coverage: { exclude: ['bin', 'dist', 'src/**/*.d.ts'], include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.vue'], provider: 'v8', }, globals: true, projects: [ 'examples/*/vitest.config.ts', { extends: true, test: { name: '@hey-api/codegen-core', root: 'packages/codegen-core', }, }, { extends: true, test: { globalSetup: ['./src/py-compiler/__tests__/globalTeardown.ts'], name: '@hey-api/openapi-python', root: 'packages/openapi-python', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { globalSetup: ['./src/ts-compiler/__tests__/globalTeardown.ts'], name: '@hey-api/openapi-ts', root: 'packages/openapi-ts', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@hey-api/shared', root: 'packages/shared', }, }, { extends: true, test: { name: '@hey-api/json-schema-ref-parser', root: 'packages/json-schema-ref-parser', }, }, { extends: true, test: { name: '@test/openapi-ts', root: 'packages/openapi-ts-tests/main', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@test/openapi-ts-nestjs-v11', root: 'packages/openapi-ts-tests/nestjs/v11', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { globalSetup: ['./test/globalTeardown.ts'], name: '@test/openapi-ts-orpc-v1', root: 'packages/openapi-ts-tests/orpc/v1', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@test/openapi-ts-sdks', root: 'packages/openapi-ts-tests/sdks', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@test/openapi-ts-valibot-v1', root: 'packages/openapi-ts-tests/valibot/v1', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@test/openapi-ts-zod-v3', root: 'packages/openapi-ts-tests/zod/v3', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@test/openapi-ts-zod-v4', root: 'packages/openapi-ts-tests/zod/v4', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@test/openapi-python-sdks', root: 'packages/openapi-python-tests/sdks', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@test/openapi-python-pydantic-v2', root: 'packages/openapi-python-tests/pydantic/v2', setupFiles: ['./vitest.setup.ts'], }, }, { extends: true, test: { name: '@hey-api/custom-client', root: 'packages/custom-client', }, }, ], testTimeout: platform() === 'win32' ? 10000 : 5000, }, });